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
package/src/cli.ts DELETED
@@ -1,4455 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * Minimal CLI for snow-flow - ServiceNow Multi-Agent Framework
4
- */
5
-
6
- import { Command } from 'commander';
7
- import dotenv from 'dotenv';
8
- import { promises as fs } from 'fs';
9
- import { join, dirname } from 'path';
10
- import { spawn, ChildProcess } from 'child_process';
11
- import * as os from 'os';
12
- import { existsSync } from 'fs';
13
- import { ServiceNowOAuth } from './utils/snow-oauth.js';
14
- import { ServiceNowClient } from './utils/servicenow-client.js';
15
- import { AgentDetector, TaskAnalysis } from './utils/agent-detector.js';
16
- import { getNotificationTemplateSysId } from './utils/servicenow-id-generator.js';
17
- import { VERSION } from './version.js';
18
- import { integrateSnowFlowCommands } from './cli/snow-flow-cli-integration.js';
19
- import { snowFlowSystem } from './snow-flow-system.js';
20
- import { Logger } from './utils/logger.js';
21
- import chalk from 'chalk';
22
-
23
- // Load environment variables
24
- dotenv.config();
25
-
26
- // Create CLI logger instance
27
- const cliLogger = new Logger('cli');
28
-
29
- const program = new Command();
30
-
31
- program
32
- .name('snow-flow')
33
- .description('ServiceNow Multi-Agent Development Framework')
34
- .version(VERSION);
35
-
36
- // Flow deprecation handler - check for flow-related commands
37
- function checkFlowDeprecation(command: string, objective?: string) {
38
- const flowKeywords = ['flow', 'create-flow', 'xml-flow', 'flow-designer'];
39
- const isFlowCommand = flowKeywords.some(keyword => command.includes(keyword));
40
- const isFlowObjective = objective && objective.toLowerCase().includes('flow') &&
41
- !objective.toLowerCase().includes('workflow') &&
42
- !objective.toLowerCase().includes('data flow') &&
43
- !objective.toLowerCase().includes('snow-flow');
44
-
45
- if (isFlowCommand || isFlowObjective) {
46
- console.error('❌ Flow creation has been removed from snow-flow v1.4.0+');
47
- console.error('');
48
- console.error('Please use ServiceNow Flow Designer directly:');
49
- console.error('1. Log into your ServiceNow instance');
50
- console.error('2. Navigate to: Flow Designer > Designer');
51
- console.error('3. Create flows using the visual interface');
52
- console.error('');
53
- console.error('Snow-flow continues to support:');
54
- console.error('- Widget development');
55
- console.error('- Update Set management');
56
- console.error('- Table/field discovery');
57
- console.error('- General ServiceNow operations');
58
- process.exit(1);
59
- }
60
- }
61
-
62
-
63
- // Swarm command - the main orchestration command with EVERYTHING
64
- program
65
- .command('swarm <objective>')
66
- .description('Execute multi-agent orchestration for a ServiceNow task - één command voor alles!')
67
- .option('--strategy <strategy>', 'Execution strategy (development, _analysis, research)', 'development')
68
- .option('--mode <mode>', 'Coordination mode (hierarchical, mesh, distributed)', 'hierarchical')
69
- .option('--max-agents <number>', 'Maximum number of agents', '5')
70
- .option('--parallel', 'Enable parallel execution')
71
- .option('--monitor', 'Enable real-time monitoring')
72
- .option('--auto-permissions', 'Automatic permission escalation when needed')
73
- .option('--smart-discovery', 'Smart artifact discovery and reuse (default: true)', true)
74
- .option('--no-smart-discovery', 'Disable smart artifact discovery')
75
- .option('--live-testing', 'Enable live testing during development (default: true)', true)
76
- .option('--no-live-testing', 'Disable live testing')
77
- .option('--auto-deploy', 'Automatic deployment when ready (default: true)', true)
78
- .option('--no-auto-deploy', 'Disable automatic deployment')
79
- .option('--auto-rollback', 'Automatic rollback on failures (default: true)', true)
80
- .option('--no-auto-rollback', 'Disable automatic rollback')
81
- .option('--shared-memory', 'Enable shared memory between agents (default: true)', true)
82
- .option('--no-shared-memory', 'Disable shared memory')
83
- .option('--progress-monitoring', 'Real-time progress monitoring (default: true)', true)
84
- .option('--no-progress-monitoring', 'Disable progress monitoring')
85
- .option('--xml-first', 'Use XML-first approach for flow creation (MOST RELIABLE!)')
86
- .option('--xml-output <path>', 'Save generated XML to specific path (with --xml-first)')
87
- .option('--autonomous-documentation', 'Enable autonomous documentation system (default: true)', true)
88
- .option('--no-autonomous-documentation', 'Disable autonomous documentation system')
89
- .option('--autonomous-cost-optimization', 'Enable autonomous cost optimization engine (default: true)', true)
90
- .option('--no-autonomous-cost-optimization', 'Disable autonomous cost optimization engine')
91
- .option('--autonomous-compliance', 'Enable autonomous compliance monitoring (default: true)', true)
92
- .option('--no-autonomous-compliance', 'Disable autonomous compliance monitoring')
93
- .option('--autonomous-healing', 'Enable autonomous self-healing capabilities (default: true)', true)
94
- .option('--no-autonomous-healing', 'Disable autonomous self-healing capabilities')
95
- .option('--autonomous-all', 'Force enable all autonomous systems (overrides individual --no- flags)')
96
- .option('--no-autonomous-all', 'Disable all autonomous systems (overrides individual settings)')
97
- .option('--verbose', 'Show detailed execution information')
98
- .action(async (objective: string, options) => {
99
- // Check for flow deprecation first
100
- checkFlowDeprecation('swarm', objective);
101
-
102
- // Always show essential info
103
- cliLogger.info(`\n🚀 Snow-Flow v${VERSION}`);
104
- cliLogger.info(`📋 Objective: ${objective}`);
105
-
106
- // Only show detailed config in verbose mode
107
- if (options.verbose) {
108
- cliLogger.info(`⚙️ Strategy: ${options.strategy} | Mode: ${options.mode} | Max Agents: ${options.maxAgents}`);
109
- cliLogger.info(`🔄 Parallel: ${options.parallel ? 'Yes' : 'No'} | Monitor: ${options.monitor ? 'Yes' : 'No'}`);
110
-
111
- // Show new intelligent features
112
- cliLogger.info(`\n🧠 Intelligent Features:`);
113
- cliLogger.info(` 🔐 Auto Permissions: ${options.autoPermissions ? '✅ Yes' : '❌ No'}`);
114
- cliLogger.info(` 🔍 Smart Discovery: ${options.smartDiscovery ? '✅ Yes' : '❌ No'}`);
115
- cliLogger.info(` 🧪 Live Testing: ${options.liveTesting ? '✅ Yes' : '❌ No'}`);
116
- cliLogger.info(` 🚀 Auto Deploy: ${options.autoDeploy ? '✅ DEPLOYMENT MODE - WILL CREATE REAL ARTIFACTS' : '❌ PLANNING MODE - ANALYSIS ONLY'}`);
117
- cliLogger.info(` 🔄 Auto Rollback: ${options.autoRollback ? '✅ Yes' : '❌ No'}`);
118
- cliLogger.info(` 💾 Shared Memory: ${options.sharedMemory ? '✅ Yes' : '❌ No'}`);
119
- cliLogger.info(` 📊 Progress Monitoring: ${options.progressMonitoring ? '✅ Yes' : '❌ No'}`);
120
-
121
- // Calculate actual autonomous system states (with override logic)
122
- // Commander.js converts --no-autonomous-all to autonomousAll: false
123
- const noAutonomousAll = options.autonomousAll === false;
124
- const forceAutonomousAll = options.autonomousAll === true;
125
-
126
- const autonomousDocActive = noAutonomousAll ? false :
127
- forceAutonomousAll ? true :
128
- options.autonomousDocumentation !== false;
129
-
130
- const autonomousCostActive = noAutonomousAll ? false :
131
- forceAutonomousAll ? true :
132
- options.autonomousCostOptimization !== false;
133
-
134
- const autonomousComplianceActive = noAutonomousAll ? false :
135
- forceAutonomousAll ? true :
136
- options.autonomousCompliance !== false;
137
-
138
- const autonomousHealingActive = noAutonomousAll ? false :
139
- forceAutonomousAll ? true :
140
- options.autonomousHealing !== false;
141
-
142
- const hasAutonomousSystems = autonomousDocActive || autonomousCostActive ||
143
- autonomousComplianceActive || autonomousHealingActive;
144
-
145
- cliLogger.info(`\n🤖 Autonomous Systems (DEFAULT ENABLED):`);
146
- cliLogger.info(` 📚 Documentation: ${autonomousDocActive ? '✅ ACTIVE' : '❌ Disabled'}`);
147
- cliLogger.info(` 💰 Cost Optimization: ${autonomousCostActive ? '✅ ACTIVE' : '❌ Disabled'}`);
148
- cliLogger.info(` 🔐 Compliance Monitoring: ${autonomousComplianceActive ? '✅ ACTIVE' : '❌ Disabled'}`);
149
- cliLogger.info(` 🏥 Self-Healing: ${autonomousHealingActive ? '✅ ACTIVE' : '❌ Disabled'}`);
150
- cliLogger.info('');
151
- } else {
152
- // In non-verbose mode, only show critical info
153
- if (options.autoDeploy) {
154
- cliLogger.info(`🚀 Auto-Deploy: ENABLED - Will create real artifacts in ServiceNow`);
155
- }
156
-
157
- // Calculate autonomous systems for non-verbose mode (same logic as verbose)
158
- const noAutonomousAll = options.autonomousAll === false;
159
- const forceAutonomousAll = options.autonomousAll === true;
160
-
161
- const autonomousDocActive = noAutonomousAll ? false :
162
- forceAutonomousAll ? true :
163
- options.autonomousDocumentation !== false;
164
-
165
- const autonomousCostActive = noAutonomousAll ? false :
166
- forceAutonomousAll ? true :
167
- options.autonomousCostOptimization !== false;
168
-
169
- const autonomousComplianceActive = noAutonomousAll ? false :
170
- forceAutonomousAll ? true :
171
- options.autonomousCompliance !== false;
172
-
173
- const autonomousHealingActive = noAutonomousAll ? false :
174
- forceAutonomousAll ? true :
175
- options.autonomousHealing !== false;
176
-
177
- // Show active autonomous systems
178
- const activeSystems = [];
179
- if (autonomousDocActive) activeSystems.push('📚 Documentation');
180
- if (autonomousCostActive) activeSystems.push('💰 Cost Optimization');
181
- if (autonomousComplianceActive) activeSystems.push('🔐 Compliance');
182
- if (autonomousHealingActive) activeSystems.push('🏥 Self-Healing');
183
-
184
- if (activeSystems.length > 0) {
185
- cliLogger.info(`🤖 Autonomous Systems: ${activeSystems.join(', ')}`);
186
- } else {
187
- cliLogger.info(`🤖 Autonomous Systems: ❌ All Disabled`);
188
- }
189
- }
190
-
191
- // Analyze the objective using intelligent agent detection
192
- const taskAnalysis = analyzeObjective(objective, parseInt(options.maxAgents));
193
-
194
- // Debug logging to understand task type detection
195
- if (process.env.DEBUG || options.verbose) {
196
- if (process.env.DEBUG) {
197
- cliLogger.info(`🔍 DEBUG - Detected artifacts: [${taskAnalysis.serviceNowArtifacts.join(', ')}]`);
198
- cliLogger.info(`🔍 DEBUG - Flow keywords in objective: ${objective.toLowerCase().includes('flow')}`);
199
- cliLogger.info(`🔍 DEBUG - Widget keywords in objective: ${objective.toLowerCase().includes('widget')}`);
200
- }
201
-
202
- cliLogger.info(`\n📊 Task Analysis:`);
203
- cliLogger.info(` 🎯 Task Type: ${taskAnalysis.taskType}`);
204
- cliLogger.info(` 🧠 Primary Agent: ${taskAnalysis.primaryAgent}`);
205
- cliLogger.info(` 👥 Supporting Agents: ${taskAnalysis.supportingAgents.join(', ')}`);
206
- cliLogger.info(` 📊 Complexity: ${taskAnalysis.complexity} | Estimated Agents: ${taskAnalysis.estimatedAgentCount}`);
207
- cliLogger.info(` 🔧 ServiceNow Artifacts: ${taskAnalysis.serviceNowArtifacts.join(', ')}`);
208
- cliLogger.info(` 📦 Auto Update Set: ${taskAnalysis.requiresUpdateSet ? '✅ Yes' : '❌ No'}`);
209
- cliLogger.info(` 🏗️ Auto Application: ${taskAnalysis.requiresApplication ? '✅ Yes' : '❌ No'}`);
210
- }
211
-
212
- // Show timeout configuration only in verbose mode
213
- const timeoutMinutes = process.env.SNOW_FLOW_TIMEOUT_MINUTES ? parseInt(process.env.SNOW_FLOW_TIMEOUT_MINUTES) : 60;
214
- if (options.verbose) {
215
- if (timeoutMinutes > 0) {
216
- cliLogger.info(`⏱️ Timeout: ${timeoutMinutes} minutes`);
217
- } else {
218
- cliLogger.info('⏱️ Timeout: Disabled (infinite execution time)');
219
- }
220
- }
221
-
222
- // Check ServiceNow authentication
223
- const oauth = new ServiceNowOAuth();
224
- const isAuthenticated = await oauth.isAuthenticated();
225
-
226
- if (options.verbose) {
227
- if (isAuthenticated) {
228
- cliLogger.info('🔗 ServiceNow connection: ✅ Authenticated');
229
-
230
- // Test ServiceNow connection
231
- const client = new ServiceNowClient();
232
- const testResult = await client.testConnection();
233
- if (testResult.success) {
234
- cliLogger.info(`👤 Connected as: ${testResult.data.name} (${testResult.data.user_name})`);
235
- }
236
- } else {
237
- cliLogger.warn('🔗 ServiceNow connection: ❌ Not authenticated');
238
- cliLogger.info('💡 Run "snow-flow auth login" to enable live ServiceNow integration');
239
- }
240
- } else if (!isAuthenticated) {
241
- // In non-verbose mode, only warn if not authenticated
242
- cliLogger.warn('⚠️ Not authenticated. Run "snow-flow auth login" for ServiceNow integration');
243
- }
244
-
245
- // Initialize Queen Agent memory system
246
- if (options.verbose) {
247
- cliLogger.info('\n💾 Initializing swarm memory system...');
248
- }
249
- const { QueenMemorySystem } = await import('./queen/queen-memory.js');
250
- const memorySystem = new QueenMemorySystem();
251
-
252
- // Generate swarm session ID
253
- const sessionId = `swarm_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
254
- cliLogger.info(`\n🔖 Session: ${sessionId}`);
255
-
256
- // Store swarm session in memory
257
- memorySystem.storeLearning(`session_${sessionId}`, {
258
- objective,
259
- taskAnalysis,
260
- options,
261
- started_at: new Date().toISOString(),
262
- is_authenticated: isAuthenticated
263
- });
264
-
265
- // Check if this is a Flow Designer flow request
266
- const isFlowDesignerTask = taskAnalysis.taskType === 'flow_development' ||
267
- taskAnalysis.primaryAgent === 'flow-builder' ||
268
- (objective.toLowerCase().includes('flow') &&
269
- !objective.toLowerCase().includes('workflow') &&
270
- !objective.toLowerCase().includes('data flow'));
271
-
272
- let xmlFlowResult: any = null;
273
-
274
- // Start real Claude Code orchestration
275
- try {
276
- // Generate the Queen Agent orchestration prompt
277
- const orchestrationPrompt = buildQueenAgentPrompt(objective, taskAnalysis, options, isAuthenticated, sessionId, isFlowDesignerTask);
278
-
279
- if (options.verbose) {
280
- cliLogger.info('\n👑 Initializing Queen Agent orchestration...');
281
- cliLogger.info('🎯 Queen Agent will coordinate the following:');
282
- cliLogger.info(` - Analyze objective: "${objective}"`);
283
- cliLogger.info(` - Spawn ${taskAnalysis.estimatedAgentCount} specialized agents`);
284
- cliLogger.info(` - Coordinate through shared memory (session: ${sessionId})`);
285
- cliLogger.info(` - Monitor progress and adapt strategy`);
286
- } else {
287
- cliLogger.info('\n👑 Launching Queen Agent...');
288
- }
289
-
290
- // Check if intelligent features are enabled
291
- const hasIntelligentFeatures = options.autoPermissions || options.smartDiscovery ||
292
- options.liveTesting || options.autoDeploy || options.autoRollback ||
293
- options.sharedMemory || options.progressMonitoring;
294
-
295
- if (options.verbose && hasIntelligentFeatures && isAuthenticated) {
296
- cliLogger.info('\n🧠 INTELLIGENT ORCHESTRATION MODE ENABLED!');
297
- cliLogger.info('✨ Queen Agent will use advanced features:');
298
-
299
- if (options.autoPermissions) {
300
- cliLogger.info(' 🔐 Automatic permission escalation');
301
- }
302
- if (options.smartDiscovery) {
303
- cliLogger.info(' 🔍 Smart artifact discovery and reuse');
304
- }
305
- if (options.liveTesting) {
306
- cliLogger.info(' 🧪 Real-time testing in ServiceNow');
307
- }
308
- if (options.autoDeploy) {
309
- cliLogger.info(' 🚀 Automatic deployment when ready');
310
- }
311
- if (options.autoRollback) {
312
- cliLogger.info(' 🔄 Automatic rollback on failures');
313
- }
314
- if (options.sharedMemory) {
315
- cliLogger.info(' 💾 Shared context across all agents');
316
- }
317
- if (options.progressMonitoring) {
318
- cliLogger.info(' 📊 Real-time progress monitoring');
319
- }
320
- }
321
-
322
- if (options.verbose) {
323
- if (isAuthenticated) {
324
- cliLogger.info('\n🔗 Live ServiceNow integration: ✅ Enabled');
325
- cliLogger.info('📝 Artifacts will be created directly in ServiceNow');
326
- } else {
327
- cliLogger.info('\n🔗 Live ServiceNow integration: ❌ Disabled');
328
- cliLogger.info('📝 Artifacts will be saved to servicenow/ directory');
329
- }
330
- }
331
-
332
- cliLogger.info('🚀 Launching Claude Code...');
333
-
334
- // Try to execute Claude Code directly with the prompt
335
- const success = await executeClaudeCode(orchestrationPrompt);
336
-
337
- if (success) {
338
- cliLogger.info('✅ Claude Code launched successfully!');
339
-
340
- if (options.verbose) {
341
- cliLogger.info('👑 Queen Agent is now coordinating your swarm');
342
- cliLogger.info(`💾 Monitor progress with session ID: ${sessionId}`);
343
-
344
- if (isAuthenticated && options.autoDeploy) {
345
- cliLogger.info('🚀 Real artifacts will be created in ServiceNow');
346
- } else {
347
- cliLogger.info('📋 Planning mode - _analysis and recommendations only');
348
- }
349
- }
350
-
351
- // Store successful launch in memory
352
- memorySystem.storeLearning(`launch_${sessionId}`, {
353
- success: true,
354
- launched_at: new Date().toISOString()
355
- });
356
- } else {
357
- if (options.verbose) {
358
- cliLogger.info('\n🚀 SNOW-FLOW ORCHESTRATION COMPLETE!');
359
- cliLogger.info('🤖 Now it\'s time for Claude Code agents to do the work...\n');
360
-
361
- cliLogger.info('👑 QUEEN AGENT ORCHESTRATION PROMPT FOR CLAUDE CODE:');
362
- cliLogger.info('=' .repeat(80));
363
- cliLogger.info(orchestrationPrompt);
364
- cliLogger.info('=' .repeat(80));
365
-
366
- cliLogger.info('\n✅ Snow-Flow has prepared the orchestration!');
367
- cliLogger.info('📊 CRITICAL NEXT STEPS:');
368
- cliLogger.info(' 1. Copy the ENTIRE prompt above');
369
- cliLogger.info(' 2. Paste it into Claude Code (the AI assistant)');
370
- cliLogger.info(' 3. Claude Code will spawn multiple specialized agents as workhorses');
371
- cliLogger.info(' 4. These agents will implement your flow with all required logic');
372
- cliLogger.info(' 5. Agents will enhance the basic XML template with real functionality');
373
-
374
- cliLogger.info('\n🎯 Remember:');
375
- cliLogger.info(' - Snow-Flow = Orchestrator (coordinates the work)');
376
- cliLogger.info(' - Claude Code = Workhorses (implement the solution)');
377
-
378
- if (xmlFlowResult) {
379
- cliLogger.info(`\n📁 XML template saved at: ${xmlFlowResult.filePath}`);
380
- cliLogger.info(' ⚠️ This is just a BASIC template - agents must enhance it!');
381
- }
382
-
383
- if (isAuthenticated && options.autoDeploy) {
384
- cliLogger.info('\n🚀 Deployment Mode: Agents will create REAL artifacts in ServiceNow');
385
- } else {
386
- cliLogger.info('\n📋 Planning Mode: Analysis and recommendations only');
387
- }
388
- cliLogger.info(`\n💾 Session ID for monitoring: ${sessionId}`);
389
- } else {
390
- // Non-verbose mode - just show the essential info
391
- cliLogger.info('\n📋 Manual Claude Code execution required');
392
- cliLogger.info('💡 Run with --verbose to see the full orchestration prompt');
393
-
394
- if (xmlFlowResult) {
395
- cliLogger.info(`📁 XML generated: ${xmlFlowResult.filePath}`);
396
- }
397
- }
398
- }
399
-
400
- } catch (error) {
401
- cliLogger.error('❌ Failed to execute Queen Agent orchestration:', error instanceof Error ? error.message : String(error));
402
-
403
- // Store error in memory for learning
404
- memorySystem.storeLearning(`error_${sessionId}`, {
405
- error: error instanceof Error ? error.message : String(error),
406
- failed_at: new Date().toISOString()
407
- });
408
- }
409
- });
410
-
411
-
412
- // Helper function to execute Claude Code directly
413
- async function executeClaudeCode(prompt: string): Promise<boolean> {
414
- cliLogger.info('🤖 Preparing Claude Code agent orchestration...');
415
-
416
- try {
417
- // Check if Claude CLI is available
418
- const { execSync } = require('child_process');
419
- try {
420
- execSync('which claude', { stdio: 'ignore' });
421
- } catch {
422
- cliLogger.warn('⚠️ Claude Code CLI not found in PATH');
423
- cliLogger.info('📋 Please install Claude Desktop or copy the prompt manually');
424
- return false;
425
- }
426
-
427
-
428
- // Check for MCP config
429
- const mcpConfigPath = join(process.cwd(), '.mcp.json');
430
- const hasMcpConfig = existsSync(mcpConfigPath);
431
-
432
- // Launch Claude Code with MCP config and skip permissions to avoid raw mode issues
433
- const claudeArgs = hasMcpConfig
434
- ? ['--mcp-config', '.mcp.json', '.', '--dangerously-skip-permissions']
435
- : ['--dangerously-skip-permissions'];
436
-
437
- cliLogger.info('🚀 Launching Claude Code automatically...');
438
- if (hasMcpConfig) {
439
- cliLogger.info('🔧 Starting Claude Code with ServiceNow MCP servers...');
440
- }
441
-
442
- // Start Claude Code process in interactive mode with stdin piping
443
- const claudeProcess = spawn('claude', claudeArgs, {
444
- stdio: ['pipe', 'inherit', 'inherit'], // pipe stdin, inherit stdout/stderr
445
- cwd: process.cwd(),
446
- env: { ...process.env }
447
- });
448
-
449
- // Send the prompt via stdin
450
- cliLogger.info('📝 Sending orchestration prompt to Claude Code...');
451
- cliLogger.info('🚀 Claude Code interface opening...\n');
452
-
453
- // Write prompt to stdin
454
- claudeProcess.stdin.write(prompt);
455
- claudeProcess.stdin.end();
456
-
457
- // Set up process monitoring
458
- return new Promise((resolve) => {
459
- claudeProcess.on('close', async (code) => {
460
-
461
- if (code === 0) {
462
- cliLogger.info('\n✅ Claude Code session completed successfully!');
463
- resolve(true);
464
- } else {
465
- cliLogger.warn(`\n⚠️ Claude Code session ended with code: ${code}`);
466
- resolve(false);
467
- }
468
- });
469
-
470
- claudeProcess.on('error', (error) => {
471
- cliLogger.error(`❌ Failed to start Claude Code: ${error.message}`);
472
- resolve(false);
473
- });
474
-
475
- // Set timeout (configurable via environment variable)
476
- const timeoutMinutes = parseInt(process.env.SNOW_FLOW_TIMEOUT_MINUTES || '0');
477
- if (timeoutMinutes > 0) {
478
- setTimeout(() => {
479
- cliLogger.warn(`⏱️ Claude Code session timeout (${timeoutMinutes} minutes), terminating...`);
480
- claudeProcess.kill('SIGTERM');
481
- resolve(false);
482
- }, timeoutMinutes * 60 * 1000);
483
- }
484
- });
485
-
486
- } catch (error) {
487
- cliLogger.error('❌ Error launching Claude Code:', error instanceof Error ? error.message : String(error));
488
- cliLogger.info('📋 Claude Code prompt generated - please copy and paste manually');
489
- return false;
490
- }
491
- }
492
-
493
- // Real-time monitoring dashboard for Claude Code process
494
- function startMonitoringDashboard(claudeProcess: ChildProcess): NodeJS.Timeout {
495
- let iterations = 0;
496
- const startTime = Date.now();
497
-
498
- // Show initial dashboard only once
499
- cliLogger.info(`┌─────────────────────────────────────────────────────────────┐`);
500
- cliLogger.info(`│ 🚀 Snow-Flow Dashboard v${VERSION} │`);
501
- cliLogger.info(`├─────────────────────────────────────────────────────────────┤`);
502
- cliLogger.info(`│ 🤖 Claude Code Status: ✅ Starting │`);
503
- cliLogger.info(`│ 📊 Process ID: ${claudeProcess.pid || 'N/A'} │`);
504
- cliLogger.info(`│ ⏱️ Session Time: 00:00 │`);
505
- cliLogger.info(`│ 🔄 Monitoring Cycles: 0 │`);
506
- cliLogger.info('└─────────────────────────────────────────────────────────────┘');
507
-
508
- // Silent monitoring - only log to file or memory, don't interfere with Claude Code UI
509
- const monitoringInterval = setInterval(() => {
510
- iterations++;
511
- const uptime = Math.floor((Date.now() - startTime) / 1000);
512
-
513
- // Silent monitoring - check files but don't output to console
514
- try {
515
- const serviceNowDir = join(process.cwd(), 'servicenow');
516
- fs.readdir(serviceNowDir).then(files => {
517
- // Files are being generated - could log to file if needed
518
- // console.log(`\n📁 Generated Files: ${files.length} artifacts in servicenow/`);
519
- }).catch(() => {
520
- // Directory doesn't exist yet, that's normal
521
- });
522
- } catch (error) {
523
- // Ignore errors
524
- }
525
-
526
- }, 5000); // Check every 5 seconds silently
527
-
528
- return monitoringInterval;
529
- }
530
-
531
- async function executeWithClaude(claudeCommand: string, prompt: string, resolve: (value: boolean) => void): Promise<void> {
532
- cliLogger.info('🚀 Starting Claude Code execution...');
533
-
534
- // Write prompt to temporary file for large prompts
535
- const tempFile = join(process.cwd(), '.snow-flow-prompt.tmp');
536
- await fs.writeFile(tempFile, prompt);
537
-
538
- // Check if .mcp.json exists in current directory
539
- const mcpConfigPath = join(process.cwd(), '.mcp.json');
540
- let hasMcpConfig = false;
541
- try {
542
- await fs.access(mcpConfigPath);
543
- hasMcpConfig = true;
544
- cliLogger.info('✅ Found MCP configuration in current directory');
545
- } catch {
546
- cliLogger.warn('⚠️ No MCP configuration found. Run "snow-flow init" to set up MCP servers');
547
- }
548
-
549
- const claudeArgs = hasMcpConfig
550
- ? ['--mcp-config', '.mcp.json', '.', '--dangerously-skip-permissions']
551
- : ['--dangerously-skip-permissions'];
552
-
553
- if (hasMcpConfig) {
554
- cliLogger.info('🔧 Starting Claude Code with ServiceNow MCP servers...');
555
- }
556
-
557
- // Start Claude Code process in interactive mode
558
- const claudeProcess = spawn(claudeCommand, claudeArgs, {
559
- stdio: ['pipe', 'inherit', 'inherit'], // inherit stdout/stderr for interactive mode
560
- cwd: process.cwd()
561
- });
562
-
563
- // Send the prompt via stdin
564
- cliLogger.info('📝 Sending orchestration prompt to Claude Code...');
565
- cliLogger.info('🚀 Claude Code interactive interface opening...\n');
566
-
567
- claudeProcess.stdin.write(prompt);
568
- claudeProcess.stdin.end();
569
-
570
- // Start silent monitoring dashboard (doesn't interfere with Claude Code UI)
571
- const monitoringInterval = startMonitoringDashboard(claudeProcess);
572
-
573
- claudeProcess.on('close', (code) => {
574
- clearInterval(monitoringInterval);
575
- if (code === 0) {
576
- cliLogger.info('\n✅ Claude Code session completed successfully!');
577
- resolve(true);
578
- } else {
579
- cliLogger.warn(`\n❌ Claude Code session ended with code: ${code}`);
580
- resolve(false);
581
- }
582
- });
583
-
584
- claudeProcess.on('error', (error) => {
585
- clearInterval(monitoringInterval);
586
- cliLogger.error(`❌ Failed to start Claude Code: ${error.message}`);
587
- resolve(false);
588
- });
589
-
590
- // Set timeout for Claude Code execution (configurable via environment variable)
591
- const timeoutMinutes = process.env.SNOW_FLOW_TIMEOUT_MINUTES ? parseInt(process.env.SNOW_FLOW_TIMEOUT_MINUTES) : 60;
592
- const timeoutMs = timeoutMinutes * 60 * 1000;
593
-
594
- cliLogger.info(`⏱️ Claude Code timeout set to ${timeoutMinutes} minutes (configure with SNOW_FLOW_TIMEOUT_MINUTES=0 for no timeout)`);
595
-
596
- let timeout: NodeJS.Timeout | null = null;
597
-
598
- // Only set timeout if not disabled (0 = no timeout)
599
- if (timeoutMinutes > 0) {
600
- timeout = setTimeout(() => {
601
- clearInterval(monitoringInterval);
602
- cliLogger.warn(`⏱️ Claude Code session timeout (${timeoutMinutes} minutes), terminating...`);
603
- claudeProcess.kill('SIGTERM');
604
-
605
- // Force kill if it doesn't respond
606
- setTimeout(() => {
607
- claudeProcess.kill('SIGKILL');
608
- }, 2000);
609
-
610
- resolve(false);
611
- }, timeoutMs);
612
- }
613
-
614
- claudeProcess.on('close', () => {
615
- if (timeout) {
616
- clearTimeout(timeout);
617
- }
618
- });
619
- }
620
-
621
- // Helper function to build Queen Agent orchestration prompt
622
- function buildQueenAgentPrompt(objective: string, taskAnalysis: TaskAnalysis, options: any, isAuthenticated: boolean = false, sessionId: string, isFlowDesignerTask: boolean = false): string {
623
- // Check if intelligent features are enabled
624
- const hasIntelligentFeatures = options.autoPermissions || options.smartDiscovery ||
625
- options.liveTesting || options.autoDeploy || options.autoRollback ||
626
- options.sharedMemory || options.progressMonitoring;
627
-
628
- // Calculate actual autonomous system states (with override logic)
629
- const noAutonomousAll = options.autonomousAll === false;
630
- const forceAutonomousAll = options.autonomousAll === true;
631
-
632
- const autonomousDocActive = noAutonomousAll ? false :
633
- forceAutonomousAll ? true :
634
- options.autonomousDocumentation !== false;
635
-
636
- const autonomousCostActive = noAutonomousAll ? false :
637
- forceAutonomousAll ? true :
638
- options.autonomousCostOptimization !== false;
639
-
640
- const autonomousComplianceActive = noAutonomousAll ? false :
641
- forceAutonomousAll ? true :
642
- options.autonomousCompliance !== false;
643
-
644
- const autonomousHealingActive = noAutonomousAll ? false :
645
- forceAutonomousAll ? true :
646
- options.autonomousHealing !== false;
647
-
648
- const hasAutonomousSystems = autonomousDocActive || autonomousCostActive ||
649
- autonomousComplianceActive || autonomousHealingActive;
650
-
651
- const prompt = `# 👑 Snow-Flow Queen Agent Orchestration
652
-
653
- ## 🎯 Mission Brief
654
- You are the Queen Agent, master coordinator of the Snow-Flow hive-mind. Your mission is to orchestrate a swarm of specialized agents to complete the following ServiceNow development objective:
655
-
656
- **Objective**: ${objective}
657
- **Session ID**: ${sessionId}
658
-
659
- ## 🧠 Task Analysis Summary
660
- - **Task Type**: ${taskAnalysis.taskType}
661
- - **Complexity**: ${taskAnalysis.complexity}
662
- - **Primary Agent Required**: ${taskAnalysis.primaryAgent}
663
- - **Supporting Agents**: ${taskAnalysis.supportingAgents.join(', ')}
664
- - **Estimated Total Agents**: ${taskAnalysis.estimatedAgentCount}
665
- - **ServiceNow Artifacts**: ${taskAnalysis.serviceNowArtifacts.join(', ')}
666
-
667
- ${isFlowDesignerTask ? `## 🔧 Flow Designer Task Detected - Using ENHANCED XML-First Approach!
668
- 🚀 **FULLY AUTOMATED FLOW DEPLOYMENT v2.0** - ALL features working correctly!
669
-
670
- **MANDATORY: Use this exact approach for Flow Designer tasks:**
671
-
672
- \`\`\`javascript
673
- // ✅ ENHANCED v2.0: Complete flow generation with ALL features
674
- await snow_create_flow({
675
- instruction: "your natural language flow description",
676
- deploy_immediately: true, // 🔥 Automatically deploys to ServiceNow!
677
- return_metadata: true // 📊 Returns complete deployment metadata
678
- });
679
- \`\`\`
680
-
681
- 🎯 **What this does automatically (ENHANCED v1.3.28+):**
682
- - ✅ Uses CompleteFlowXMLGenerator for PROPER flow structure
683
- - ✅ Generates with v2 tables (sys_hub_action_instance_v2, sys_hub_trigger_instance_v2)
684
- - ✅ Applies Base64+gzip encoding for action values
685
- - ✅ Includes comprehensive label_cache structure
686
- - ✅ Imports XML to ServiceNow as remote update set
687
- - ✅ Automatic tool name resolution with MCPToolRegistry
688
- - ✅ Complete metadata extraction (sys_id, URLs, endpoints)
689
- - ✅ Performance _analysis and recommendations
690
- - ✅ 100% of requested features deploy correctly!
691
-
692
- 🚫 **FORBIDDEN APPROACHES:**
693
- - ❌ DO NOT use old API-only approach without XML generation
694
- - ❌ DO NOT use manual \`snow-flow deploy-xml\` commands
695
- - ❌ DO NOT generate XML without auto-deployment
696
- - ❌ DO NOT use v1 tables (they create empty flows!)
697
-
698
- 💡 **Why Enhanced XML-First v2.0?**
699
- - Fixes ALL critical issues from beta testing
700
- - Flows deploy with 100% of requested features working
701
- - Complete metadata always returned (no more null sys_id)
702
- - Tool names resolve correctly across all MCP providers
703
- - Zero chance of empty flows or missing features!
704
-
705
- ` : ''}
706
- - **Recommended Team**: ${getTeamRecommendation(taskAnalysis.taskType)}
707
-
708
- ## 📊 Table Discovery Intelligence
709
-
710
- The Queen Agent will automatically discover and validate table schemas based on the objective. This ensures agents use correct field names and table structures.
711
-
712
- **Table Detection Examples:**
713
- - "create widget for incident records" → Discovers: incident, sys_user, sys_user_group
714
- - "build approval flow for u_equipment_request" → Discovers: u_equipment_request, sys_user, sysapproval_approver
715
- - "portal showing catalog items" → Discovers: sc_cat_item, sc_category, sc_request
716
- - "dashboard with CMDB assets" → Discovers: cmdb_ci, cmdb_rel_ci, sys_user
717
- - "report on problem tickets" → Discovers: problem, incident, sys_user
718
-
719
- **Discovery Process:**
720
- 1. Extracts table names from objective (standard tables, u_ custom tables, explicit mentions)
721
- 2. Discovers actual table schemas with field names, types, and relationships
722
- 3. Stores schemas in memory for all agents to use
723
- 4. Agents MUST use exact field names from schemas (e.g., 'short_description' not 'desc')
724
-
725
- ## 👑 Your Queen Agent Responsibilities
726
-
727
- ### 1. CRITICAL: Initialize Memory FIRST (Before Everything!)
728
- **THIS MUST BE YOUR VERY FIRST ACTION - Initialize the swarm memory session:**
729
- \`\`\`javascript
730
- // 🚨 EXECUTE THIS IMMEDIATELY - DO NOT SKIP OR DELAY!
731
- mcp__servicenow-memory__memory_store({
732
- key: "swarm_session_${sessionId}",
733
- value: JSON.stringify({
734
- objective: "${objective}",
735
- status: "initializing",
736
- started_at: new Date().toISOString(),
737
- queen_agent_id: "queen_${sessionId}",
738
- task__analysis: ${JSON.stringify(taskAnalysis, null, 2)},
739
- configuration: {
740
- strategy: "${options.strategy}",
741
- mode: "${options.mode}",
742
- max_agents: ${parseInt(options.maxAgents)},
743
- parallel_execution: ${options.parallel ? 'true' : 'false'},
744
- monitoring_enabled: ${options.monitor ? 'true' : 'false'},
745
- auth_required: ${!isAuthenticated}
746
- }
747
- }),
748
- namespace: "swarm_${sessionId}"
749
- });
750
-
751
- // Agent coordination namespace handled automatically by ServiceNow memory system
752
- \`\`\`
753
-
754
- ### 2. MANDATORY MCP-FIRST Workflow Steps
755
- **Execute these steps IN ORDER before spawning agents:**
756
-
757
- \`\`\`javascript
758
- // Step 2.1: Validate ServiceNow authentication
759
- const authCheck = await mcp__servicenow-intelligent__snow_validate_live_connection({
760
- test_level: "permissions",
761
- include_performance: false
762
- });
763
-
764
- if (!authCheck.connection_status === "success") {
765
- throw new Error("Authentication failed! Run: snow-flow auth login");
766
- }
767
-
768
- // Step 2.2: Check for existing artifacts (DRY principle)
769
- const existingArtifacts = await mcp__servicenow-intelligent__snow_comprehensive_search({
770
- query: "${objective}",
771
- include_inactive: false
772
- });
773
-
774
- // Store discovery results in memory for agents
775
- await mcp__servicenow-memory__memory_store({
776
- key: "existing_artifacts_${sessionId}",
777
- value: JSON.stringify(existingArtifacts),
778
- namespace: "swarm_${sessionId}"
779
- });
780
-
781
- // Step 2.3: Create isolated Update Set for this objective
782
- const updateSetName = "Snow-Flow: ${objective.substring(0, 50)}... - ${new Date().toISOString().split('T')[0]}";
783
- const updateSet = await mcp__servicenow-update-set__snow_update_set_create({
784
- name: updateSetName,
785
- description: "Automated creation for: ${objective}\\n\\nSession: ${sessionId}",
786
- auto_switch: true
787
- });
788
-
789
- // Store Update Set info in memory
790
- await mcp__servicenow-memory__memory_store({
791
- key: "update_set_${sessionId}",
792
- value: JSON.stringify(updateSet),
793
- namespace: "swarm_${sessionId}"
794
- });
795
-
796
- // Step 2.4: Discover tables mentioned in objective
797
- // Extract potential table names from the objective
798
- const tablePatterns = [
799
- /\b(incident|problem|change_request|sc_request|sc_req_item|task|cmdb_ci|sys_user|sys_user_group)\b/gi,
800
- /\b(u_\w+)\b/g, // Custom tables starting with u_
801
- /\b(\w+_table)\b/gi, // Tables ending with _table
802
- /\bfrom\s+(\w+)\b/gi, // SQL-like "from table_name"
803
- /\btable[:\s]+(\w+)\b/gi, // "table: xyz" or "table xyz"
804
- /\b(\w+)\s+records?\b/gi, // "xyz records"
805
- ];
806
-
807
- const detectedTables = new Set();
808
- // Always include common tables for context
809
- ['incident', 'sc_request', 'sys_user'].forEach(t => detectedTables.add(t));
810
-
811
- // Search for tables in objective
812
- for (const pattern of tablePatterns) {
813
- const matches = "${objective}".matchAll(pattern);
814
- for (const match of matches) {
815
- if (match[1]) {
816
- detectedTables.add(match[1].toLowerCase());
817
- }
818
- }
819
- }
820
-
821
- // Also check for common data needs based on objective type
822
- if ("${objective}".toLowerCase().includes('catalog')) {
823
- detectedTables.add('sc_cat_item');
824
- detectedTables.add('sc_category');
825
- }
826
- if ("${objective}".toLowerCase().includes('user')) {
827
- detectedTables.add('sys_user');
828
- detectedTables.add('sys_user_group');
829
- }
830
- if ("${objective}".toLowerCase().includes('cmdb') || "${objective}".toLowerCase().includes('asset')) {
831
- detectedTables.add('cmdb_ci');
832
- }
833
- if ("${objective}".toLowerCase().includes('knowledge')) {
834
- detectedTables.add('kb_knowledge');
835
- }
836
-
837
- cliLogger.info(\`🔍 Detected tables to discover: \${Array.from(detectedTables).join(', ')}\`);
838
-
839
- // Discover schemas for all detected tables
840
- const tableSchemas = {};
841
- for (const tableName of detectedTables) {
842
- try {
843
- const schema = await mcp__servicenow-platform-development__snow_table_schema_discovery({
844
- tableName: tableName,
845
- includeRelated: true,
846
- includeIndexes: false,
847
- maxDepth: 1 // Don't go too deep to avoid timeout
848
- });
849
-
850
- if (schema && schema.fields) {
851
- tableSchemas[tableName] = {
852
- name: tableName,
853
- label: schema.label || tableName,
854
- fields: schema.fields,
855
- field_count: schema.fields.length,
856
- key_fields: schema.fields.filter(f => f.primary || f.reference).map(f => f.name)
857
- };
858
- cliLogger.info(\`✅ Discovered table '\${tableName}' with \${schema.fields.length} fields\`);
859
- }
860
- } catch (e) {
861
- cliLogger.warn(\`⚠️ Table '\${tableName}' not found or inaccessible\`);
862
- }
863
- }
864
-
865
- // Store discovered table schemas in memory
866
- await mcp__servicenow-memory__memory_store({
867
- key: "table_schemas_${sessionId}",
868
- value: JSON.stringify({
869
- discovered_at: new Date().toISOString(),
870
- objective: "${objective}",
871
- tables: tableSchemas,
872
- table_names: Object.keys(tableSchemas)
873
- }),
874
- namespace: "swarm_${sessionId}"
875
- });
876
- \`\`\`
877
-
878
- ### 3. Create Master Task List
879
- After completing MCP-FIRST steps, create task breakdown:
880
- \`\`\`javascript
881
- TodoWrite([
882
- {
883
- id: "mcp_workflow_complete",
884
- content: "✅ MCP-FIRST workflow: Auth, Discovery, Update Set, Tables",
885
- status: "completed",
886
- priority: "high"
887
- },
888
- {
889
- id: "analyze_requirements",
890
- content: "Analyze user requirements: ${objective}",
891
- status: "in_progress",
892
- priority: "high"
893
- },
894
- {
895
- id: "spawn_agents",
896
- content: "Spawn ${taskAnalysis.estimatedAgentCount} specialized agents",
897
- status: "pending",
898
- priority: "high"
899
- },
900
- {
901
- id: "coordinate_development",
902
- content: "Coordinate agent activities for ${taskAnalysis.taskType}",
903
- status: "pending",
904
- priority: "high"
905
- },
906
- {
907
- id: "validate_solution",
908
- content: "Validate and test the complete solution",
909
- status: "pending",
910
- priority: "medium"
911
- }
912
- ]);
913
- \`\`\`
914
-
915
- ### 4. Spawn Specialized Agents
916
- Based on the task _analysis, spawn the following agents using the Task tool:
917
-
918
- **Primary Agent**: ${taskAnalysis.primaryAgent}
919
- \`\`\`javascript
920
- // Spawn primary agent
921
- Task("${taskAnalysis.primaryAgent}", \`
922
- You are the primary ${taskAnalysis.primaryAgent} agent for this swarm.
923
-
924
- Objective: ${objective}
925
- Session: ${sessionId}
926
- Task Type: ${taskAnalysis.taskType}
927
-
928
- Instructions:
929
- 1. FIRST: Read ALL shared context from memory:
930
- - mcp__servicenow-memory__memory_get({key: "swarm_session_${sessionId}", namespace: "swarm_${sessionId}"})
931
- - mcp__servicenow-memory__memory_get({key: "existing_artifacts_${sessionId}", namespace: "swarm_${sessionId}"})
932
- - mcp__servicenow-memory__memory_get({key: "update_set_${sessionId}", namespace: "swarm_${sessionId}"})
933
- - mcp__servicenow-memory__memory_get({key: "table_schemas_${sessionId}", namespace: "swarm_${sessionId}"})
934
-
935
- 2. 🔍 CRITICAL: Use discovered table schemas:
936
- - The table_schemas contain actual field names, types, and relationships
937
- - ALWAYS use the exact field names from the schema (e.g., 'short_description' not 'description')
938
- - Check key_fields for primary keys and references
939
- - If you need a table that wasn't discovered, use snow_table_schema_discovery first
940
-
941
- 3. Check existing_artifacts to avoid duplication - reuse or extend existing ones
942
- 4. ALL deployments MUST use the Update Set stored in memory
943
- 5. Begin implementing the core ${taskAnalysis.taskType} requirements
944
- 6. Store all work progress with: mcp__servicenow-memory__memory_store({key: "agent_${taskAnalysis.primaryAgent}_progress", value: "...", namespace: "agents_${sessionId}"})
945
- 7. Update TodoWrite items as you complete tasks
946
- 8. Read other agents' progress from namespace "agents_${sessionId}"
947
-
948
- 🔐 AUTHENTICATION: Already validated by Queen. Use MCP tools directly.
949
- 📦 UPDATE SET: Use the one from memory - DO NOT create a new one!
950
- 📊 TABLES: Use exact field names from discovered schemas!
951
- \`);
952
- \`\`\`
953
-
954
- **Supporting Agents**:
955
- ${taskAnalysis.supportingAgents.map((agent, index) => `
956
- Agent ${index + 2}: ${agent}
957
- \`\`\`javascript
958
- // Spawn ${agent}
959
- Task("${agent}", \`
960
- You are a supporting ${agent} agent in this swarm.
961
-
962
- Role: ${agent}
963
- Session: ${sessionId}
964
- Primary Agent: ${taskAnalysis.primaryAgent}
965
-
966
- Instructions:
967
- 1. FIRST: Read ALL shared context from memory (same as primary agent):
968
- - mcp__servicenow-memory__memory_get({key: "swarm_session_${sessionId}", namespace: "swarm_${sessionId}"})
969
- - mcp__servicenow-memory__memory_get({key: "existing_artifacts_${sessionId}", namespace: "swarm_${sessionId}"})
970
- - mcp__servicenow-memory__memory_get({key: "update_set_${sessionId}", namespace: "swarm_${sessionId}"})
971
- - mcp__servicenow-memory__memory_get({key: "table_schemas_${sessionId}", namespace: "swarm_${sessionId}"})
972
-
973
- 2. 🔍 CRITICAL: Use discovered table schemas:
974
- - The table_schemas contain actual field names, types, and relationships
975
- - ALWAYS use the exact field names from the schema (e.g., 'short_description' not 'description')
976
- - Check key_fields for primary keys and references
977
- - If you need a table that wasn't discovered, use snow_table_schema_discovery first
978
-
979
- 3. Monitor primary agent's progress: mcp__servicenow-memory__memory_search({pattern: "agent_${taskAnalysis.primaryAgent}_*", namespace: "agents_${sessionId}"})
980
- 4. Wait for primary agent to establish base structure before major changes
981
- 5. Enhance/support with your ${agent} expertise
982
- 6. Store your progress: mcp__servicenow-memory__memory_store({key: "agent_${agent}_progress", value: "...", namespace: "agents_${sessionId}"})
983
- 7. Update relevant TodoWrite items
984
-
985
- 🔐 AUTHENTICATION: Already validated by Queen. Use MCP tools directly.
986
- 📦 UPDATE SET: Use the one from memory - DO NOT create a new one!
987
- 📊 TABLES: Use exact field names from discovered schemas!
988
-
989
- 🔐 AUTHENTICATION REQUIREMENTS:
990
- - ALWAYS use MCP tools first - inherit auth status from primary agent
991
- - If auth fails, contribute to the PLANNING documentation
992
- - Store all plans in Memory for future deployment
993
- \`);
994
- \`\`\``).join('\n')}
995
-
996
- ### 4. Memory Coordination Pattern
997
- All agents MUST use this memory coordination pattern:
998
-
999
- \`\`\`javascript
1000
- // Agent initialization
1001
- const session = Memory.get("swarm_session_${sessionId}");
1002
- const agentId = \`agent_\${agentType}_${sessionId}\`;
1003
-
1004
- // Agent stores progress
1005
- Memory.store(\`\${agentId}_progress\`, {
1006
- status: "working",
1007
- current_task: "description of current work",
1008
- completion_percentage: 45,
1009
- last_update: new Date().toISOString()
1010
- });
1011
-
1012
- // Agent reads other agent's work
1013
- const primaryWork = Memory.get("agent_${taskAnalysis.primaryAgent}_output");
1014
-
1015
- // Agent signals completion
1016
- Memory.store(\`\${agentId}_complete\`, {
1017
- completed_at: new Date().toISOString(),
1018
- outputs: { /* agent deliverables */ },
1019
- artifacts_created: [ /* list of created artifacts */ ]
1020
- });
1021
- \`\`\`
1022
-
1023
- ## 🧠 Intelligent Features Configuration
1024
- ${hasIntelligentFeatures ? `✅ **INTELLIGENT MODE ACTIVE** - The following features are enabled:
1025
-
1026
- - **🔐 Auto Permissions**: ${options.autoPermissions ? '✅ Will escalate permissions automatically' : '❌ Manual permission handling'}
1027
- - **🔍 Smart Discovery**: ${options.smartDiscovery ? '✅ Will discover and reuse existing artifacts' : '❌ Create all new artifacts'}
1028
- - **🧪 Live Testing**: ${options.liveTesting ? '✅ Will test in real ServiceNow instance' : '❌ Local testing only'}
1029
- - **🚀 Auto Deploy**: ${options.autoDeploy ? '⚠️ WILL DEPLOY TO SERVICENOW AUTOMATICALLY' : '✅ Planning mode - no deployment'}
1030
- - **🔄 Auto Rollback**: ${options.autoRollback ? '✅ Will rollback on any failures' : '❌ No automatic rollback'}
1031
- - **💾 Shared Memory**: ${options.sharedMemory ? '✅ Agents share context via Memory' : '❌ Isolated agent execution'}
1032
- - **📊 Progress Monitoring**: ${options.progressMonitoring ? '✅ Real-time progress tracking' : '❌ No progress monitoring'}` : '❌ **STANDARD MODE** - Use manual coordination patterns'}
1033
-
1034
- ## 🎯 ServiceNow Execution Strategy
1035
-
1036
- ### 🚀 MANDATORY: Live ServiceNow Development First!
1037
-
1038
- **CRITICAL RULE**: All agents MUST attempt to use ServiceNow MCP tools first, regardless of authentication status.
1039
-
1040
- ${hasIntelligentFeatures ? `#### 🧠 Intelligent Orchestration Available
1041
- Use the unified orchestration tool for complete automation:
1042
-
1043
- \`\`\`javascript
1044
- // Queen Agent uses this for intelligent orchestration
1045
- snow_orchestrate_development({
1046
- objective: "${objective}",
1047
- auto_permissions: ${options.autoPermissions},
1048
- smart_discovery: ${options.smartDiscovery},
1049
- live_testing: ${options.liveTesting},
1050
- auto_deploy: ${options.autoDeploy},
1051
- auto_rollback: ${options.autoRollback},
1052
- shared_memory: ${options.sharedMemory},
1053
- progress_monitoring: ${options.progressMonitoring}
1054
- });
1055
- \`\`\`
1056
-
1057
- ## 🧠 REVOLUTIONARY: Intelligent Gap Analysis Engine (v1.1.88)
1058
- **AUTOMATIC BEYOND-MCP CONFIGURATION DETECTION**
1059
-
1060
- The Queen Agent now includes the revolutionary **Intelligent Gap Analysis Engine** that automatically detects and resolves ALL ServiceNow configurations needed beyond standard MCP tools.
1061
-
1062
- **What Gap Analysis Does:**
1063
- - **🔍 Analyzes Requirements**: AI-powered parsing of objectives to identify 60+ types of ServiceNow configurations
1064
- - **📊 MCP Coverage Analysis**: Maps what current MCP tools can handle vs manual setup requirements
1065
- - **🤖 Auto-Resolution Engine**: Attempts automatic configuration via ServiceNow APIs for safe operations
1066
- - **📚 Manual Guide Generation**: Creates detailed step-by-step guides with role requirements and risk assessment
1067
- - **🛡️ Risk Assessment**: Evaluates complexity and safety of each configuration
1068
- - **🌍 Environment Awareness**: Provides dev/test/prod specific guidance and warnings
1069
-
1070
- **60+ Configuration Types Covered:**
1071
- - **🔐 Authentication**: LDAP, SAML, OAuth providers, SSO, MFA configurations
1072
- - **🗄️ Database**: Indexes, views, partitioning, performance analytics, system properties
1073
- - **🧭 Navigation**: Application menus, modules, form layouts, UI actions, policies
1074
- - **📧 Integration**: Email templates, web services, import sets, transform maps
1075
- - **🔄 Workflow**: Activities, transitions, SLA definitions, escalation rules
1076
- - **🛡️ Security**: ACL rules, data policies, audit rules, compliance configurations
1077
- - **📊 Reporting**: Custom reports, dashboards, KPIs, performance analytics
1078
-
1079
- **Example Output:**
1080
- \`\`\`
1081
- 🧠 Step 4: Running Intelligent Gap Analysis...
1082
- 📊 Gap Analysis Complete:
1083
- • Total Requirements: 12
1084
- • MCP Coverage: 67%
1085
- • Automated: 6 configurations
1086
- • Manual Work: 4 items
1087
-
1088
- ✅ Automatically Configured:
1089
- • System property: glide.ui.incident_management created
1090
- • Navigation module: Incident Management added to Service Desk
1091
- • Email template: incident_notification configured
1092
- • Database index: incident.priority_state for performance
1093
-
1094
- 📋 Manual Configuration Required:
1095
- • LDAP authentication setup (high-risk operation)
1096
- • SSO configuration with Active Directory
1097
-
1098
- 📚 Detailed Manual Guides Available:
1099
- 📖 Configure LDAP Authentication - 25 minutes
1100
- Risk: high | Roles: security_admin, admin
1101
- \`\`\`
1102
-
1103
- **The Gap Analysis Engine automatically runs as part of Queen Agent execution - no additional commands needed!**
1104
-
1105
- ` : ''}
1106
-
1107
- #### ServiceNow MCP Tools (ALWAYS TRY THESE FIRST!)
1108
- ${isAuthenticated ? '✅ Authentication detected - full deployment capabilities' : '⚠️ No authentication detected - MCP tools will provide specific instructions if auth needed'}
1109
-
1110
- Your agents MUST use these MCP tools IN THIS ORDER:
1111
-
1112
- 🔍 **PRE-FLIGHT CHECKS** (Always do first!):
1113
- 1. \`snow_find_artifact\` with a simple query to test authentication
1114
- 2. If auth fails, the tool provides specific instructions
1115
- 3. Continue with appropriate strategy based on auth status
1116
-
1117
- 📦 **CORE DEVELOPMENT TOOLS**:
1118
- 1. **Deployment Tools** (servicenow-deployment-mcp)
1119
- - \`snow_deploy\` - Unified deployment for all artifact types
1120
- - \`snow_preview_widget\` - Preview widgets before deployment
1121
- - \`snow_widget_test\` - Test widget functionality
1122
-
1123
- 2. **Discovery Tools** (servicenow-intelligent-mcp)
1124
- - \`snow_find_artifact\` - Natural language artifact search
1125
- - \`snow_catalog_item_search\` - Find catalog items with fuzzy matching
1126
- - \`snow_get_by_sysid\` - Direct sys_id lookup
1127
-
1128
- 3. **Update Set Management** (servicenow-update-set-mcp)
1129
- - \`snow_update_set_create\` - Create new update sets
1130
- - \`snow_update_set_add_artifact\` - Track artifacts
1131
- - \`snow_update_set_complete\` - Complete update sets
1132
-
1133
- 🚀 **14 ADVANCED SERVICENOW INTELLIGENCE TOOLS** - NEW v1.4.9!
1134
-
1135
- **Performance & Optimization (Features 1-4)**:
1136
- 4. **Smart Batch API Operations** (\`snow_batch_api\`)
1137
- - 80% API call reduction through intelligent batching
1138
- - Parallel execution with transaction support
1139
- - Query optimization and result caching
1140
- - Real-time performance monitoring
1141
-
1142
- 5. **Table Relationship Mapping** (\`snow_get_table_relationships\`)
1143
- - Deep relationship discovery across table hierarchies
1144
- - Visual relationship diagrams (Mermaid format)
1145
- - Impact analysis for schema changes
1146
- - Performance optimization recommendations
1147
-
1148
- 6. **Query Performance Analyzer** (\`snow_analyze_query\`)
1149
- - Query execution analysis with bottleneck detection
1150
- - Index recommendations for performance optimization
1151
- - Alternative query suggestions with risk assessment
1152
- - Execution time prediction
1153
-
1154
- 7. **Field Usage Intelligence** (\`snow_analyze_field_usage\`)
1155
- - Comprehensive field usage analysis across all ServiceNow components
1156
- - Unused field detection with deprecation recommendations
1157
- - Technical debt scoring and optimization opportunities
1158
- - Cross-component impact analysis
1159
-
1160
- **Migration & Architecture (Features 5-7)**:
1161
- 8. **Migration Helper** (\`snow_create_migration_plan\`)
1162
- - Automated migration planning with risk assessment
1163
- - Data transformation scripts generation
1164
- - Performance impact estimation and rollback strategy creation
1165
-
1166
- 9. **Deep Table Analysis** (\`snow_analyze_table_deep\`)
1167
- - Multi-dimensional table analysis (structure, data quality, performance)
1168
- - Security and compliance assessment
1169
- - Usage pattern analysis and optimization recommendations
1170
-
1171
- 10. **Code Pattern Detector** (\`snow_detect_code_patterns\`)
1172
- - Advanced pattern recognition across all script types
1173
- - Performance anti-pattern detection and security vulnerability scanning
1174
- - Maintainability scoring with refactoring suggestions
1175
-
1176
- **AI-Powered Intelligence (Features 8-10)**:
1177
- 11. **Predictive Impact Analysis** (\`snow_predict_change_impact\`)
1178
- - AI-powered change impact prediction with confidence scoring
1179
- - Risk assessment and dependency chain analysis
1180
- - Rollback requirement prediction
1181
-
1182
- 12. **Auto Documentation Generator** (\`snow_generate_documentation\`)
1183
- - Intelligent documentation generation from code and configuration
1184
- - Multiple output formats (Markdown, HTML, PDF)
1185
- - Relationship diagrams and architecture documentation
1186
-
1187
- 13. **Intelligent Refactoring** (\`snow_refactor_code\`)
1188
- - AI-driven code refactoring with performance optimization
1189
- - Modern JavaScript patterns and best practices
1190
- - Security hardening and error handling improvements
1191
-
1192
- **Process Mining & Workflow (Features 11-14)**:
1193
- 14. **Process Mining Engine** (\`snow_discover_process\`)
1194
- - Real process discovery from ServiceNow event logs
1195
- - Process variant analysis and bottleneck identification
1196
- - Compliance checking with ROI calculation
1197
-
1198
- 15. **Workflow Reality Analyzer** (\`snow_analyze_workflow_execution\`)
1199
- - Real workflow execution analysis vs. designed processes
1200
- - Performance bottleneck identification and SLA compliance monitoring
1201
-
1202
- 16. **Cross Table Process Discovery** (\`snow_discover_cross_table_process\`)
1203
- - Multi-table process flow discovery
1204
- - Data lineage and transformation tracking
1205
- - Integration point analysis
1206
-
1207
- 17. **Real Time Process Monitoring** (\`snow_monitor_process\`)
1208
- - Live process monitoring with real-time alerts
1209
- - Anomaly detection using machine learning
1210
- - Performance trend analysis and predictive failure detection
1211
-
1212
- 💯 **ZERO MOCK DATA GUARANTEE**: All 14 advanced tools work with 100% real ServiceNow API integration!
1213
-
1214
- 📊 **PERFORMANCE METRICS & BENEFITS**:
1215
- - **80% API Call Reduction** through intelligent batching and optimization
1216
- - **60% Faster Analysis** with parallel processing and caching
1217
- - **90% Task Automation** of manual ServiceNow analysis workflows
1218
- - **100% Real Data** accuracy - no mocks, placeholders, or demo data
1219
- - **Zero Configuration** - works with any ServiceNow instance
1220
-
1221
- 🎯 **USAGE EXAMPLES FOR AGENTS**:
1222
-
1223
- **Performance Analysis:**
1224
- \`\`\`javascript
1225
- // Analyze incident table performance issues
1226
- await snow_analyze_table_deep({
1227
- table_name: "incident",
1228
- analysis_scope: ["structure", "data_quality", "performance"],
1229
- generate_recommendations: true
1230
- });
1231
-
1232
- // Optimize frequently used queries
1233
- await snow_analyze_query({
1234
- query: "state=1^priority<=2",
1235
- table: "incident",
1236
- analyze_indexes: true,
1237
- suggest_optimizations: true
1238
- });
1239
- \`\`\`
1240
-
1241
- **Batch Operations:**
1242
- \`\`\`javascript
1243
- // Execute multiple operations with 80% API reduction
1244
- await snow_batch_api({
1245
- operations: [
1246
- {operation: "query", table: "incident", query: "state=1"},
1247
- {operation: "update", table: "incident", sys_id: "xxx", data: {urgency: "1"}}
1248
- ],
1249
- parallel: true,
1250
- transactional: true
1251
- });
1252
- \`\`\`
1253
-
1254
- **Process Mining:**
1255
- \`\`\`javascript
1256
- // Discover real incident management processes
1257
- await snow_discover_process({
1258
- process_type: "incident_management",
1259
- analysis_period: "30d",
1260
- include_variants: true
1261
- });
1262
-
1263
- // Monitor processes in real-time
1264
- await snow_monitor_process({
1265
- process_name: "incident_resolution",
1266
- tables_to_monitor: ["incident", "task"],
1267
- monitoring_duration: "24h"
1268
- });
1269
- \`\`\`
1270
-
1271
- **Intelligence & Automation:**
1272
- \`\`\`javascript
1273
- // AI-powered impact prediction
1274
- await snow_predict_change_impact({
1275
- change_type: "field_change",
1276
- target_object: "incident",
1277
- change_details: {field_changes: ["urgency"]},
1278
- include_dependencies: true
1279
- });
1280
-
1281
- // Auto-generate documentation
1282
- await snow_generate_documentation({
1283
- documentation_scope: ["tables", "workflows"],
1284
- output_format: "markdown",
1285
- include_diagrams: true
1286
- });
1287
- \`\`\`
1288
-
1289
- 🚨 **ERROR RECOVERY PATTERNS**:
1290
- - Auth Error → Document complete solution → Store in Memory → Guide user
1291
- - Permission Error → Try global scope → Document if fails
1292
- - Not Found → Create new → Track in Update Set
1293
- - Any Error → Provide SPECIFIC next steps, not generic messages
1294
-
1295
- ${options.autoDeploy ? `
1296
- #### ⚠️ AUTO-DEPLOYMENT ACTIVE ⚠️
1297
- - Real artifacts will be created in ServiceNow
1298
- - All changes tracked in Update Sets
1299
- - Rollback available if needed
1300
- ` : `
1301
- #### 📋 Planning Mode Active
1302
- - No real artifacts will be created
1303
- - Analysis and recommendations only
1304
- - Use --auto-deploy to enable deployment
1305
- `}
1306
- ${!isAuthenticated ? `### ❌ ServiceNow Integration Disabled
1307
-
1308
- #### Planning Mode (Auth Required)
1309
- When authentication is not available, agents will:
1310
- 1. Document the COMPLETE solution architecture
1311
- 2. Create detailed implementation guides
1312
- 3. Store all plans in Memory for future deployment
1313
- 4. Provide SPECIFIC instructions: "Run snow-flow auth login"
1314
-
1315
- ⚠️ IMPORTANT: This is a FALLBACK mode only!
1316
- Agents must ALWAYS try MCP tools first!` : ''}
1317
-
1318
- ## 👑 Queen Agent Coordination Instructions
1319
-
1320
- ### 5. Snow-Flow Memory Synchronization Pattern
1321
- Implement continuous memory synchronization for real-time coordination:
1322
-
1323
- \`\`\`javascript
1324
- // Initialize coordination heartbeat (Snow-Flow pattern)
1325
- const coordinationInterval = setInterval(async () => {
1326
- // Sync agent states across namespace
1327
- const agentStates = await mcp__servicenow-memory__memory_search({
1328
- pattern: "agent_*_progress",
1329
- namespace: "agents_${sessionId}",
1330
- limit: 50
1331
- });
1332
-
1333
- // Update swarm coordination state with TTL for freshness
1334
- await mcp__servicenow-memory__memory_store({
1335
- key: "swarm_coordination_${sessionId}",
1336
- value: JSON.stringify({
1337
- timestamp: new Date().toISOString(),
1338
- active_agents: agentStates.length,
1339
- completion_status: TodoRead().filter(t => t.status === 'completed').length,
1340
- memory_sync: true,
1341
- discovered_artifacts: agentStates.filter(s => s.includes("deployed")).length
1342
- }),
1343
- namespace: "swarm_${sessionId}",
1344
- ttl: 300 // 5 minute TTL for coordination data
1345
- });
1346
-
1347
- // Detect and resolve conflicts between agents
1348
- if (agentStates.some(s => s.includes("conflict") || s.includes("duplicate"))) {
1349
- await mcp__servicenow-memory__memory_store({
1350
- key: "conflict_resolution_needed",
1351
- value: JSON.stringify({
1352
- agents: agentStates.filter(s => s.includes("conflict")),
1353
- timestamp: new Date().toISOString()
1354
- }),
1355
- namespace: "swarm_${sessionId}"
1356
- });
1357
- }
1358
-
1359
- // Track deployed artifacts in Update Set automatically
1360
- const deployedArtifacts = [];
1361
- for (const state of agentStates) {
1362
- if (state.includes("deployed") && state.includes("sys_id")) {
1363
- try {
1364
- const artifact = JSON.parse(state);
1365
- if (artifact.sys_id && !artifact.tracked_in_update_set) {
1366
- deployedArtifacts.push(artifact);
1367
- }
1368
- } catch (e) {
1369
- // Not valid JSON, skip
1370
- }
1371
- }
1372
- }
1373
-
1374
- // Add all deployed artifacts to Update Set
1375
- for (const artifact of deployedArtifacts) {
1376
- await mcp__servicenow-update-set__snow_update_set_add_artifact({
1377
- type: artifact.type,
1378
- sys_id: artifact.sys_id,
1379
- name: artifact.name
1380
- });
1381
-
1382
- // Mark as tracked
1383
- artifact.tracked_in_update_set = true;
1384
- await mcp__servicenow-memory__memory_store({
1385
- key: \`agent_\${artifact.agent}_deployed_\${artifact.sys_id}\`,
1386
- value: JSON.stringify(artifact),
1387
- namespace: "agents_${sessionId}"
1388
- });
1389
- }
1390
-
1391
- // Monitor individual agent progress
1392
- const agents = [${[taskAnalysis.primaryAgent, ...taskAnalysis.supportingAgents].map(a => `"${a}"`).join(', ')}];
1393
- for (const agent of agents) {
1394
- const progress = agentStates.find(s => s.includes(\`agent_\${agent}_progress\`));
1395
- cliLogger.info(\`Agent \${agent}: \${progress ? 'active' : 'waiting'}\`);
1396
- }
1397
- }, 10000); // Every 10 seconds
1398
-
1399
- // Also update main session state
1400
- await mcp__servicenow-memory__memory_store({
1401
- key: "swarm_session_${sessionId}",
1402
- value: JSON.stringify({
1403
- status: "agents_working",
1404
- last_check: new Date().toISOString()
1405
- }),
1406
- namespace: "swarm_${sessionId}"
1407
- });
1408
- \`\`\`
1409
-
1410
- ### 6. Coordinate Agent Handoffs
1411
- Ensure smooth transitions between agents:
1412
-
1413
- \`\`\`javascript
1414
- // Primary agent signals readiness for support
1415
- Memory.store("agent_${taskAnalysis.primaryAgent}_ready_for_support", {
1416
- base_structure_complete: true,
1417
- ready_for: [${taskAnalysis.supportingAgents.map(a => `"${a}"`).join(', ')}],
1418
- timestamp: new Date().toISOString()
1419
- });
1420
-
1421
- // Supporting agents check readiness
1422
- const canProceed = Memory.get("agent_${taskAnalysis.primaryAgent}_ready_for_support");
1423
- if (canProceed?.base_structure_complete) {
1424
- // Begin supporting work
1425
- }
1426
- \`\`\`
1427
-
1428
- ### 7. Final Validation and Completion
1429
- Once all agents complete their work:
1430
-
1431
- \`\`\`javascript
1432
- // Collect all agent outputs
1433
- const agentOutputs = {};
1434
- [${[taskAnalysis.primaryAgent, ...taskAnalysis.supportingAgents].map(a => `"${a}"`).join(', ')}].forEach(agent => {
1435
- const output = Memory.get(\`agent_\${agent}_complete\`);
1436
- if (output) {
1437
- agentOutputs[agent] = output;
1438
- }
1439
- });
1440
-
1441
- // Store final swarm results
1442
- Memory.store("swarm_session_${sessionId}_results", {
1443
- objective: "${objective}",
1444
- completed_at: new Date().toISOString(),
1445
- agent_outputs: agentOutputs,
1446
- artifacts_created: Object.values(agentOutputs)
1447
- .flatMap(output => output.artifacts_created || []),
1448
- success: true
1449
- });
1450
-
1451
- // Update final TodoWrite status
1452
- TodoWrite([
1453
- {
1454
- id: "swarm_completion",
1455
- content: "Swarm successfully completed: ${objective}",
1456
- status: "completed",
1457
- priority: "high"
1458
- }
1459
- ]);
1460
- \`\`\`
1461
-
1462
- ## 📊 Progress Monitoring Pattern
1463
-
1464
- ${options.progressMonitoring ? `### Real-Time Progress Monitoring Enabled
1465
- Monitor swarm progress using these patterns:
1466
-
1467
- \`\`\`javascript
1468
- // Regular progress checks
1469
- setInterval(() => {
1470
- const session = Memory.get("swarm_session_${sessionId}");
1471
- const todos = TodoRead();
1472
-
1473
- cliLogger.info(\`Swarm Status: \${session.status}\`);
1474
- cliLogger.info(\`Tasks Completed: \${todos.filter(t => t.status === 'completed').length}/\${todos.length}\`);
1475
-
1476
- // Check individual agent progress
1477
- checkAgentProgress();
1478
- }, 30000); // Check every 30 seconds
1479
- \`\`\`
1480
- ` : '### Manual Progress Checking\nUse TodoRead and Memory tools to check progress periodically.'}
1481
-
1482
- ## 🎯 Success Criteria
1483
-
1484
- Your Queen Agent orchestration is successful when:
1485
- 1. ✅ All agents have been spawned and initialized
1486
- 2. ✅ Swarm session is tracked in Memory
1487
- 3. ✅ Agents are coordinating through shared Memory
1488
- 4. ✅ TodoWrite is being used for task tracking
1489
- 5. ✅ Progress is being monitored
1490
- 6. ✅ ${taskAnalysis.taskType} requirements are met
1491
- 7. ✅ All artifacts are created/deployed successfully
1492
-
1493
- ## 💡 Queen Agent Best Practices
1494
-
1495
- 1. **Spawn agents concurrently** when tasks are independent
1496
- 2. **Use Memory prefixes** to avoid key collisions
1497
- 3. **Update TodoWrite** frequently for visibility
1498
- 4. **Monitor agent health** and restart if needed
1499
- 5. **Validate outputs** before marking complete
1500
- 6. **Store all decisions** in Memory for audit trail
1501
-
1502
- ## 📋 Agent-Specific Authentication & Discovery Workflows
1503
-
1504
- ### 🛠️ Widget Creator Agent
1505
- \`\`\`javascript
1506
- // Pre-flight check
1507
- const authCheck = await snow_find_artifact({ query: "test auth", type: "widget" });
1508
- if (authCheck.error?.includes("OAuth")) {
1509
- // Switch to planning mode
1510
- Memory.store("widget_plan", {
1511
- html_template: "<!-- Complete HTML structure -->",
1512
- server_script: "// Complete server logic",
1513
- client_script: "// Complete client controller",
1514
- css_styles: "/* Complete styles */",
1515
- deployment_instructions: "Run snow-flow auth login, then use snow_deploy"
1516
- });
1517
- TodoWrite([{ content: "Widget plan ready - auth required for deployment", status: "completed" }]);
1518
- } else {
1519
- // Continue with live development
1520
- const existing = await snow_comprehensive_search({ query: "similar widget" });
1521
- // ... proceed with snow_deploy
1522
- }
1523
- \`\`\`
1524
-
1525
- ### 🔄 Flow Builder Agent
1526
- \`\`\`javascript
1527
- // Check existing flows first
1528
- const flows = await snow_discover_existing_flows({ flow_purpose: "objective" });
1529
- if (flows.error?.includes("OAuth")) {
1530
- // Document flow architecture
1531
- Memory.store("flow_plan", {
1532
- trigger: "When record created on [table]",
1533
- steps: ["Step 1: Validate data", "Step 2: Process", "Step 3: Notify"],
1534
- natural_language: "Complete flow instruction for snow_create_flow",
1535
- deployment_command: "snow_create_flow with deploy_immediately: true"
1536
- });
1537
- } else {
1538
- // Create flow directly using XML-first approach
1539
- await snow_create_flow({
1540
- instruction: "natural language description",
1541
- deploy_immediately: true
1542
- });
1543
- }
1544
- \`\`\`
1545
-
1546
- ### 📝 Script Writer Agent
1547
- \`\`\`javascript
1548
- // Verify permissions
1549
- const permCheck = await snow_get_by_sysid({
1550
- sys_id: "test", // Example sys_id - replace with actual value
1551
- table: "sys_script_include"
1552
- });
1553
- if (permCheck.error?.includes("OAuth")) {
1554
- // Complete script documentation
1555
- Memory.store("script_solution", {
1556
- script_type: "Business Rule/Script Include/etc",
1557
- code: "// Complete implementation",
1558
- when: "before/after/async",
1559
- table: "target_table",
1560
- deployment_ready: true
1561
- });
1562
- }
1563
- \`\`\`
1564
-
1565
- ### 🧪 Tester Agent
1566
- \`\`\`javascript
1567
- // Tester can start with mock (always works)
1568
- const mockTest = await snow_test_flow_with_mock({
1569
- flow_id: "flow_name",
1570
- test_inputs: { /* test data */ }
1571
- });
1572
- // Then try comprehensive if authenticated
1573
- // 🔧 TEST-001 FIX: Skip live test if no valid flow sys_id is available
1574
- // Only run live test if we have a real sys_id from previous flow creation
1575
- let liveTest: any = { error: "No valid flow_sys_id available for live testing" };
1576
-
1577
- // In practice, this would get the sys_id from a previously created flow:
1578
- // if (Memory.get("last_created_flow_sys_id")) {
1579
- // liveTest = await snow_comprehensive_flow_test({
1580
- // flow_sys_id: Memory.get("last_created_flow_sys_id")
1581
- // });
1582
- // }
1583
-
1584
- if (liveTest.error) {
1585
- // Document test results from mock only
1586
- Memory.store("test_results", mockTest);
1587
- }
1588
- \`\`\`
1589
-
1590
- ## 🚀 Begin Orchestration
1591
-
1592
- Now execute this Queen Agent orchestration plan:
1593
- 1. Initialize the swarm session in Memory
1594
- 2. Create the master task list with TodoWrite
1595
- 3. Spawn all required agents using Task
1596
- 4. Monitor progress and coordinate
1597
- 5. Validate and complete the objective
1598
-
1599
- Remember: You are the Queen Agent - the master coordinator. Your role is to ensure all agents work harmoniously to achieve the objective: "${objective}"
1600
-
1601
- ${hasAutonomousSystems ? `
1602
-
1603
- ## 🤖 AUTONOMOUS SYSTEMS INTEGRATION
1604
-
1605
- **CRITICAL: The following autonomous systems have been enabled and MUST be initialized:**
1606
-
1607
- ${autonomousDocActive ? `
1608
- ### 📚 Self-Documenting System
1609
- **MANDATORY**: Initialize and start autonomous documentation:
1610
- \`\`\`javascript
1611
- // Start continuous documentation monitoring
1612
- await snow_start_continuous_documentation({
1613
- auto_commit: true,
1614
- include_diagrams: true,
1615
- scope: "full"
1616
- });
1617
-
1618
- // Store status in memory
1619
- await mcp__servicenow-memory__memory_store({
1620
- key: "autonomous_documentation_${sessionId}",
1621
- value: JSON.stringify({
1622
- status: "active",
1623
- started_at: new Date().toISOString(),
1624
- auto_commit: true
1625
- }),
1626
- namespace: "swarm_${sessionId}"
1627
- });
1628
- \`\`\`
1629
- ` : ''}
1630
-
1631
- ${autonomousCostActive ? `
1632
- ### 💰 Cost Optimization Engine
1633
- **MANDATORY**: Initialize and start autonomous cost optimization:
1634
- \`\`\`javascript
1635
- // Start autonomous cost optimization
1636
- await snow_start_autonomous_cost_optimization({
1637
- target_savings: 30,
1638
- auto_implement: true,
1639
- monitor_real_time: true
1640
- });
1641
-
1642
- // Store status in memory
1643
- await mcp__servicenow-memory__memory_store({
1644
- key: "autonomous_cost_optimization_${sessionId}",
1645
- value: JSON.stringify({
1646
- status: "active",
1647
- started_at: new Date().toISOString(),
1648
- target_savings: 30,
1649
- auto_implement: true
1650
- }),
1651
- namespace: "swarm_${sessionId}"
1652
- });
1653
- \`\`\`
1654
- ` : ''}
1655
-
1656
- ${autonomousComplianceActive ? `
1657
- ### 🔐 Advanced Compliance System
1658
- **MANDATORY**: Initialize and start autonomous compliance monitoring:
1659
- \`\`\`javascript
1660
- // Start compliance monitoring
1661
- await snow_start_compliance_monitoring({
1662
- frameworks: ["GDPR", "SOX", "HIPAA"],
1663
- auto_remediate: true,
1664
- continuous_monitoring: true
1665
- });
1666
-
1667
- // Store status in memory
1668
- await mcp__servicenow-memory__memory_store({
1669
- key: "autonomous_compliance_${sessionId}",
1670
- value: JSON.stringify({
1671
- status: "active",
1672
- started_at: new Date().toISOString(),
1673
- frameworks: ["GDPR", "SOX", "HIPAA"],
1674
- auto_remediate: true
1675
- }),
1676
- namespace: "swarm_${sessionId}"
1677
- });
1678
- \`\`\`
1679
- ` : ''}
1680
-
1681
- ${autonomousHealingActive ? `
1682
- ### 🏥 Self-Healing System
1683
- **MANDATORY**: Initialize and start autonomous self-healing:
1684
- \`\`\`javascript
1685
- // Start self-healing system
1686
- await snow_start_autonomous_healing({
1687
- preventive: true,
1688
- auto_heal: true,
1689
- learn_patterns: true
1690
- });
1691
-
1692
- // Store status in memory
1693
- await mcp__servicenow-memory__memory_store({
1694
- key: "autonomous_healing_${sessionId}",
1695
- value: JSON.stringify({
1696
- status: "active",
1697
- started_at: new Date().toISOString(),
1698
- preventive: true,
1699
- auto_heal: true
1700
- }),
1701
- namespace: "swarm_${sessionId}"
1702
- });
1703
- \`\`\`
1704
- ` : ''}
1705
-
1706
- **🎯 ORCHESTRATOR SHOWCASE:** These autonomous systems operate without manual intervention, demonstrating true orchestration capabilities. They will:
1707
- - Monitor continuously in the background
1708
- - Make intelligent decisions automatically
1709
- - Adapt and learn from patterns
1710
- - Provide real-time dashboards and insights
1711
- - Execute actions autonomously when needed
1712
-
1713
- **Integration with Main Objective:** All autonomous systems will coordinate with your main objective ("${objective}") by providing:
1714
- - Automatic documentation of created artifacts
1715
- - Cost optimization of operations performed
1716
- - Compliance validation of all changes
1717
- - Self-healing of any issues that arise
1718
-
1719
- ` : ''}
1720
-
1721
- Session ID for this swarm: ${sessionId}`;
1722
-
1723
- return prompt;
1724
- }
1725
-
1726
- function getTeamRecommendation(taskType: string): string {
1727
- switch (taskType) {
1728
- case 'widget_development':
1729
- return 'Widget Development Team (Frontend + Backend + UI/UX + Platform + QA)';
1730
- case 'flow_development':
1731
- return 'Flow Development Team (Process + Trigger + Data + Integration + Security)';
1732
- case 'application_development':
1733
- return 'Application Development Team (Database + Business Logic + Interface + Security + Performance)';
1734
- case 'integration':
1735
- return 'Individual Integration Specialist or Adaptive Team';
1736
- case 'security_review':
1737
- return 'Individual Security Specialist';
1738
- case 'performance_optimization':
1739
- return 'Individual Backend Specialist or Adaptive Team';
1740
- default:
1741
- return 'Adaptive Team (dynamically assembled based on requirements)';
1742
- }
1743
- }
1744
-
1745
- function getServiceNowInstructions(taskType: string): string {
1746
- const taskTitle = taskType.split('_').map(word =>
1747
- word.charAt(0).toUpperCase() + word.slice(1)
1748
- ).join(' ');
1749
-
1750
- return `**${taskTitle} Process:**
1751
- The team-based SPARC architecture will handle the complete development process.
1752
- Refer to CLAUDE.md for detailed instructions and best practices specific to ${taskType}.`;
1753
- }
1754
-
1755
- function getExpectedDeliverables(taskType: string, isAuthenticated: boolean = false): string {
1756
- const taskTitle = taskType.split('_').map(word =>
1757
- word.charAt(0).toUpperCase() + word.slice(1)
1758
- ).join(' ');
1759
-
1760
- if (isAuthenticated) {
1761
- return `The team will deliver a complete ${taskTitle.toLowerCase()} solution directly to ServiceNow.
1762
- All artifacts will be created in your ServiceNow instance with proper Update Set tracking.
1763
- Refer to CLAUDE.md for specific deliverables based on your task type.`;
1764
- } else {
1765
- return `The team will create ${taskTitle.toLowerCase()} artifacts as local files.
1766
- Files will be organized in the servicenow/ directory for easy import.
1767
- Refer to CLAUDE.md for specific deliverables based on your task type.`;
1768
- }
1769
- }
1770
-
1771
- // Helper function to analyze objectives using intelligent agent detection
1772
- function analyzeObjective(objective: string, userMaxAgents?: number): TaskAnalysis {
1773
- return AgentDetector.analyzeTask(objective, userMaxAgents);
1774
- }
1775
-
1776
- function extractName(objective: string, type: string): string {
1777
- const words = objective.split(' ');
1778
- const typeIndex = words.findIndex(w => w.toLowerCase().includes(type));
1779
- if (typeIndex >= 0 && typeIndex < words.length - 1) {
1780
- return words.slice(typeIndex + 1).join(' ').replace(/['"]/g, '');
1781
- }
1782
- return `Generated ${type}`;
1783
- }
1784
-
1785
- // Swarm status command - monitor running swarms
1786
- program
1787
- .command('swarm-status [sessionId]')
1788
- .description('Check the status of a running swarm session')
1789
- .option('--watch', 'Continuously monitor the swarm progress')
1790
- .option('--interval <seconds>', 'Watch interval in seconds', '5')
1791
- .action(async (sessionId: string | undefined, options) => {
1792
- cliLogger.info('\n🔍 Checking swarm status...\n');
1793
-
1794
- try {
1795
- const { QueenMemorySystem } = await import('./queen/queen-memory.js');
1796
- const memorySystem = new QueenMemorySystem();
1797
-
1798
- if (!sessionId) {
1799
- // List all recent swarm sessions
1800
- cliLogger.info('📋 Recent swarm sessions:');
1801
- cliLogger.info('(Provide a session ID to see detailed status)\n');
1802
-
1803
- // Get all session keys from learnings
1804
- const sessionKeys: string[] = [];
1805
- // Note: This is a simplified approach - in production, you'd query the database directly
1806
- cliLogger.info('💡 Use: snow-flow swarm-status <sessionId> to see details');
1807
- cliLogger.info('💡 Session IDs are displayed when you start a swarm\n');
1808
- return;
1809
- }
1810
-
1811
- // Get specific session data
1812
- const sessionData = memorySystem.getLearning(`session_${sessionId}`);
1813
- const launchData = memorySystem.getLearning(`launch_${sessionId}`);
1814
- const errorData = memorySystem.getLearning(`error_${sessionId}`);
1815
-
1816
- if (!sessionData) {
1817
- console.error(`❌ No swarm session found with ID: ${sessionId}`);
1818
- cliLogger.info('💡 Make sure to use the exact session ID displayed when starting the swarm');
1819
- return;
1820
- }
1821
-
1822
- cliLogger.info(`👑 Swarm Session: ${sessionId}`);
1823
- cliLogger.info(`📋 Objective: ${sessionData.objective}`);
1824
- cliLogger.info(`🕐 Started: ${sessionData.started_at}`);
1825
- cliLogger.info(`📊 Task Type: ${sessionData.taskAnalysis.taskType}`);
1826
- cliLogger.info(`🤖 Agents: ${sessionData.taskAnalysis.estimatedAgentCount} total`);
1827
- cliLogger.info(` - Primary: ${sessionData.taskAnalysis.primaryAgent}`);
1828
- cliLogger.info(` - Supporting: ${sessionData.taskAnalysis.supportingAgents.join(', ')}`);
1829
-
1830
- if (launchData && launchData.success) {
1831
- cliLogger.info(`\n✅ Status: Claude Code launched successfully`);
1832
- cliLogger.info(`🚀 Launched at: ${launchData.launched_at}`);
1833
- } else if (errorData) {
1834
- cliLogger.error(`\n❌ Status: Error occurred`);
1835
- cliLogger.error(`💥 Error: ${errorData.error}`);
1836
- cliLogger.error(`🕐 Failed at: ${errorData.failed_at}`);
1837
- } else {
1838
- cliLogger.info(`\n⏳ Status: Awaiting manual Claude Code execution`);
1839
- }
1840
-
1841
- cliLogger.info('\n💡 Tips:');
1842
- cliLogger.info(' - Check Claude Code for real-time agent progress');
1843
- cliLogger.info(' - Use Memory.get("swarm_session_' + sessionId + '") in Claude Code');
1844
- cliLogger.info(' - Monitor TodoRead for task completion status');
1845
-
1846
- if (options.watch) {
1847
- cliLogger.info(`\n👀 Watching for updates every ${options.interval} seconds...`);
1848
- cliLogger.info('(Press Ctrl+C to stop)\n');
1849
-
1850
- const watchInterval = setInterval(async () => {
1851
- // In a real implementation, this would query Claude Code's memory
1852
- cliLogger.info(`[${new Date().toLocaleTimeString()}] Checking for updates...`);
1853
-
1854
- // Re-fetch session data to check for updates
1855
- const updatedSession = memorySystem.getLearning(`session_${sessionId}`);
1856
- if (updatedSession) {
1857
- cliLogger.info(' Status: Active - Check Claude Code for details');
1858
- }
1859
- }, parseInt(options.interval) * 1000);
1860
-
1861
- // Handle graceful shutdown
1862
- process.on('SIGINT', () => {
1863
- clearInterval(watchInterval);
1864
- cliLogger.info('\n\n✋ Stopped watching swarm status');
1865
- process.exit(0);
1866
- });
1867
- }
1868
-
1869
- } catch (error) {
1870
- console.error('❌ Failed to check swarm status:', error instanceof Error ? error.message : String(error));
1871
- }
1872
- });
1873
-
1874
- // Spawn agent command
1875
- program
1876
- .command('spawn <type>')
1877
- .description('Spawn a specific agent type')
1878
- .option('--name <name>', 'Custom agent name')
1879
- .action(async (type: string, options) => {
1880
- cliLogger.info(`🤖 Spawning ${type} agent${options.name ? ` with name "${options.name}"` : ''}...`);
1881
- cliLogger.info(`✅ Agent spawned successfully`);
1882
- cliLogger.info(`📋 Agent capabilities:`);
1883
-
1884
- if (type === 'widget-builder') {
1885
- cliLogger.info(' ├── Service Portal widget creation');
1886
- cliLogger.info(' ├── HTML/CSS template generation');
1887
- cliLogger.info(' ├── Client script development');
1888
- cliLogger.info(' └── Server script implementation');
1889
- } else if (type === 'workflow-designer') {
1890
- cliLogger.info(' ├── Flow Designer workflow creation');
1891
- cliLogger.info(' ├── Process automation');
1892
- cliLogger.info(' ├── Approval routing');
1893
- cliLogger.info(' └── Integration orchestration');
1894
- } else {
1895
- cliLogger.info(' ├── Generic ServiceNow development');
1896
- cliLogger.info(' ├── Script generation');
1897
- cliLogger.info(' ├── Configuration management');
1898
- cliLogger.info(' └── API integration');
1899
- }
1900
- });
1901
-
1902
- // Status command
1903
- program
1904
- .command('status')
1905
- .description('Show orchestrator status')
1906
- .action(async () => {
1907
- cliLogger.info('\n🔍 ServiceNow Multi-Agent Orchestrator Status');
1908
- cliLogger.info('=============================================');
1909
- cliLogger.info('📊 System Status: ✅ Online');
1910
- cliLogger.info('🤖 Available Agents: 5');
1911
- cliLogger.info('📋 Queue Status: Empty');
1912
- cliLogger.info('🔗 ServiceNow Connection: Not configured');
1913
- cliLogger.info('💾 Memory Usage: 45MB');
1914
- cliLogger.info('🕒 Uptime: 00:05:23');
1915
-
1916
- cliLogger.info('\n🤖 Agent Types:');
1917
- cliLogger.info(' ├── widget-builder: Available');
1918
- cliLogger.info(' ├── workflow-designer: Available');
1919
- cliLogger.info(' ├── script-generator: Available');
1920
- cliLogger.info(' ├── ui-builder: Available');
1921
- cliLogger.info(' └── app-creator: Available');
1922
-
1923
- cliLogger.info('\n⚙️ Configuration:');
1924
- cliLogger.info(' ├── Instance: Not set');
1925
- cliLogger.info(' ├── Authentication: Not configured');
1926
- cliLogger.info(' └── Mode: Development');
1927
- });
1928
-
1929
- // Monitor command - real-time dashboard
1930
- program
1931
- .command('monitor')
1932
- .description('Show real-time monitoring dashboard')
1933
- .option('--duration <seconds>', 'Duration to monitor (default: 60)', '60')
1934
- .action(async (options) => {
1935
- const duration = parseInt(options.duration) * 1000;
1936
- cliLogger.info('🚀 Starting Snow-Flow Real-Time Monitor...\n');
1937
-
1938
- let iterations = 0;
1939
- const startTime = Date.now();
1940
-
1941
- const monitoringInterval = setInterval(() => {
1942
- iterations++;
1943
- const uptime = Math.floor((Date.now() - startTime) / 1000);
1944
- const minutes = Math.floor(uptime / 60);
1945
- const seconds = uptime % 60;
1946
-
1947
- // Clear previous lines and show dashboard
1948
- if (iterations > 1) {
1949
- process.stdout.write('\x1B[12A'); // Move cursor up 12 lines
1950
- process.stdout.write('\x1B[2K'); // Clear line
1951
- }
1952
-
1953
- cliLogger.info('┌─────────────────────────────────────────────────────────────┐');
1954
- console.log(`│ 🚀 Snow-Flow Monitor v${VERSION} │`);
1955
- console.log('├─────────────────────────────────────────────────────────────┤');
1956
- console.log(`│ 📊 System Status: ✅ Online │`);
1957
- console.log(`│ ⏱️ Monitor Time: ${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')} │`);
1958
- console.log(`│ 🔄 Update Cycles: ${iterations} │`);
1959
- console.log(`│ 🤖 Available Agents: 5 │`);
1960
- console.log(`│ 💾 Memory Usage: ~45MB │`);
1961
- console.log('├─────────────────────────────────────────────────────────────┤');
1962
- console.log('│ 📋 Recent Activity: │');
1963
- console.log(`│ • ${new Date().toLocaleTimeString()} - System monitoring active │`);
1964
- cliLogger.info('└─────────────────────────────────────────────────────────────┘');
1965
-
1966
- // Check for active Claude Code processes
1967
- try {
1968
- const { execSync } = require('child_process');
1969
- const processes = execSync('ps aux | grep "claude" | grep -v grep', { encoding: 'utf8' }).toString();
1970
- if (processes.trim()) {
1971
- cliLogger.info('\n🤖 Active Claude Code Processes:');
1972
- const lines = processes.trim().split('\n');
1973
- lines.forEach((line: string, index: number) => {
1974
- if (index < 3) { // Show max 3 processes
1975
- const parts = line.split(/\s+/);
1976
- const pid = parts[1];
1977
- const cpu = parts[2];
1978
- const mem = parts[3];
1979
- cliLogger.info(` Process ${pid}: CPU ${cpu}%, Memory ${mem}%`);
1980
- }
1981
- });
1982
- }
1983
- } catch (error) {
1984
- // No active processes or error occurred
1985
- }
1986
-
1987
- // Check generated files
1988
- try {
1989
- const serviceNowDir = join(process.cwd(), 'servicenow');
1990
- fs.readdir(serviceNowDir).then(files => {
1991
- if (files.length > 0) {
1992
- cliLogger.info(`\n📁 Generated Artifacts: ${files.length} files in servicenow/`);
1993
- files.slice(0, 3).forEach(file => {
1994
- cliLogger.info(` • ${file}`);
1995
- });
1996
- if (files.length > 3) {
1997
- cliLogger.info(` ... and ${files.length - 3} more files`);
1998
- }
1999
- }
2000
- }).catch(() => {
2001
- // Directory doesn't exist yet
2002
- });
2003
- } catch (error) {
2004
- // Ignore errors
2005
- }
2006
-
2007
- }, 2000); // Update every 2 seconds
2008
-
2009
- // Stop monitoring after duration
2010
- setTimeout(() => {
2011
- clearInterval(monitoringInterval);
2012
- cliLogger.info('\n✅ Monitoring completed. Use --duration <seconds> to monitor longer.');
2013
- }, duration);
2014
- });
2015
-
2016
- // Memory commands
2017
- program
2018
- .command('memory <action> [key] [value]')
2019
- .description('Memory operations (store, get, list)')
2020
- .action(async (action: string, key?: string, value?: string) => {
2021
- cliLogger.info(`💾 Memory ${action}${key ? `: ${key}` : ''}`);
2022
-
2023
- if (action === 'store' && key && value) {
2024
- cliLogger.info(`✅ Stored: ${key} = ${value}`);
2025
- } else if (action === 'get' && key) {
2026
- cliLogger.info(`📖 Retrieved: ${key} = [simulated value]`);
2027
- } else if (action === 'list') {
2028
- cliLogger.info('📚 Memory contents:');
2029
- cliLogger.info(' ├── last_widget: incident_management_widget');
2030
- cliLogger.info(' ├── last_workflow: approval_process');
2031
- cliLogger.info(' └── session_id: snow-flow-session-123');
2032
- } else {
2033
- cliLogger.error('❌ Invalid memory operation');
2034
- }
2035
- });
2036
-
2037
- // Auth command - OAuth implementation
2038
- program
2039
- .command('auth <action>')
2040
- .description('Authentication management (login, logout, status)')
2041
- .option('--instance <instance>', 'ServiceNow instance (e.g., dev12345.service-now.com)')
2042
- .option('--client-id <clientId>', 'OAuth Client ID')
2043
- .option('--client-secret <clientSecret>', 'OAuth Client Secret')
2044
- .action(async (action: string, options) => {
2045
- const oauth = new ServiceNowOAuth();
2046
-
2047
- if (action === 'login') {
2048
- cliLogger.info('🔑 Starting ServiceNow OAuth authentication...');
2049
-
2050
- // Get credentials from options or environment
2051
- const instance = options.instance || process.env.SNOW_INSTANCE;
2052
- const clientId = options.clientId || process.env.SNOW_CLIENT_ID;
2053
- const clientSecret = options.clientSecret || process.env.SNOW_CLIENT_SECRET;
2054
-
2055
- if (!instance || !clientId || !clientSecret) {
2056
- console.error('❌ Missing required OAuth credentials');
2057
- cliLogger.info('\n📝 Please provide:');
2058
- cliLogger.info(' --instance: ServiceNow instance (e.g., dev12345.service-now.com)');
2059
- cliLogger.info(' --client-id: OAuth Client ID');
2060
- cliLogger.info(' --client-secret: OAuth Client Secret');
2061
- cliLogger.info('\n💡 Or set environment variables:');
2062
- cliLogger.info(' export SNOW_INSTANCE=your-instance.service-now.com');
2063
- cliLogger.info(' export SNOW_CLIENT_ID=your-client-id');
2064
- cliLogger.info(' export SNOW_CLIENT_SECRET=your-client-secret');
2065
- return;
2066
- }
2067
-
2068
- // Start OAuth flow
2069
- const result = await oauth.authenticate(instance, clientId, clientSecret);
2070
-
2071
- if (result.success) {
2072
- cliLogger.info('\n✅ Authentication successful!');
2073
- cliLogger.info('🎉 Snow-Flow is now connected to ServiceNow!');
2074
- cliLogger.info('\n📋 Next steps:');
2075
- cliLogger.info(' 1. Test connection: snow-flow auth status');
2076
- cliLogger.info(' 2. Start development: snow-flow swarm "create a widget for incident management"');
2077
-
2078
- // Test connection
2079
- const client = new ServiceNowClient();
2080
- const testResult = await client.testConnection();
2081
- if (testResult.success) {
2082
- cliLogger.info(`\n🔍 Connection test successful!`);
2083
- cliLogger.info(`👤 Logged in as: ${testResult.data.name} (${testResult.data.user_name})`);
2084
- }
2085
- } else {
2086
- console.error(`\n❌ Authentication failed: ${result.error}`);
2087
- process.exit(1);
2088
- }
2089
-
2090
- } else if (action === 'logout') {
2091
- cliLogger.info('🔓 Logging out...');
2092
- await oauth.logout();
2093
-
2094
- } else if (action === 'status') {
2095
- cliLogger.info('📊 Authentication Status:');
2096
-
2097
- const isAuthenticated = await oauth.isAuthenticated();
2098
- const credentials = await oauth.loadCredentials();
2099
-
2100
- if (isAuthenticated && credentials) {
2101
- console.log(' ├── Status: ✅ Authenticated');
2102
- console.log(` ├── Instance: ${credentials.instance}`);
2103
- console.log(' ├── Method: OAuth 2.0');
2104
- console.log(` ├── Client ID: ${credentials.clientId}`);
2105
-
2106
- if (credentials.expiresAt) {
2107
- const expiresAt = new Date(credentials.expiresAt);
2108
- console.log(` └── Token expires: ${expiresAt.toLocaleString()}`);
2109
- }
2110
-
2111
- // Test connection
2112
- const client = new ServiceNowClient();
2113
- const testResult = await client.testConnection();
2114
- if (testResult.success) {
2115
- console.log(`\n🔍 Connection test: ✅ Success`);
2116
- if (testResult.data.message) {
2117
- console.log(` ${testResult.data.message}`);
2118
- }
2119
- console.log(`🌐 Instance: ${testResult.data.email || credentials.instance}`);
2120
- } else {
2121
- console.log(`\n🔍 Connection test: ❌ Failed`);
2122
- console.log(` Error: ${testResult.error}`);
2123
- }
2124
- } else {
2125
- console.log(' ├── Status: ❌ Not authenticated');
2126
- console.log(' ├── Instance: Not configured');
2127
- console.log(' └── Method: Not set');
2128
- console.log('\n💡 Run "snow-flow auth login" to authenticate');
2129
- }
2130
- } else {
2131
- console.log('❌ Invalid action. Use: login, logout, or status');
2132
- }
2133
- });
2134
-
2135
-
2136
- // Initialize Snow-Flow project
2137
- program
2138
- .command('init')
2139
- .description('Initialize a Snow-Flow project with full AI-powered environment')
2140
- .option('--sparc', '[Deprecated] SPARC is now included by default', true)
2141
- .option('--skip-mcp', 'Skip MCP server activation prompt')
2142
- .option('--force', 'Overwrite existing files without prompting')
2143
- .action(async (options) => {
2144
- console.log(chalk.blue.bold(`\n🚀 Initializing Snow-Flow Project v${VERSION}...`));
2145
- console.log('='.repeat(60));
2146
-
2147
- const targetDir = process.cwd();
2148
-
2149
- try {
2150
- // Check for .snow-flow migration
2151
- const { migrationUtil } = await import('./utils/migrate-snow-flow.js');
2152
- if (await migrationUtil.checkMigrationNeeded()) {
2153
- console.log('\n🔄 Detected .snow-flow directory, migrating to .snow-flow...');
2154
- await migrationUtil.migrate();
2155
- }
2156
-
2157
- // Create directory structure
2158
- console.log('\n📁 Creating project structure...');
2159
- await createDirectoryStructure(targetDir, options.force);
2160
-
2161
- // Create .env file
2162
- console.log('🔐 Creating environment configuration...');
2163
- await createEnvFile(targetDir, options.force);
2164
-
2165
- // Create MCP configuration - always included now (SPARC is default)
2166
- console.log('🔧 Setting up MCP servers for Claude Code...');
2167
- await createMCPConfig(targetDir, options.force);
2168
-
2169
- // Copy CLAUDE.md file
2170
- console.log('📚 Creating documentation files...');
2171
- await copyCLAUDEmd(targetDir, options.force);
2172
-
2173
- // Create README files
2174
- await createReadmeFiles(targetDir, options.force);
2175
-
2176
- console.log(chalk.green.bold('\n✅ Snow-Flow project initialized successfully!'));
2177
- console.log('\n📋 Created files and directories:');
2178
- console.log(' ✓ .claude/ - Claude Code configuration');
2179
- console.log(' ✓ .swarm/ - Swarm session management');
2180
- console.log(' ✓ .snow-flow/ - Snow-Flow project data (Queen, memory, tests)');
2181
- console.log(' ✓ memory/ - Persistent memory storage');
2182
- console.log(' ✓ .env - ServiceNow OAuth configuration');
2183
- console.log(' ✓ .mcp.json - MCP server configuration');
2184
- console.log(' ✓ CLAUDE.md - Development documentation');
2185
- console.log(' ✓ README.md - Project documentation');
2186
-
2187
- if (!options.skipMcp) {
2188
- // Start MCP servers automatically
2189
- console.log(chalk.yellow.bold('\n🚀 Starting MCP servers in the background...'));
2190
-
2191
- try {
2192
- const { MCPServerManager } = await import('./utils/mcp-server-manager.js');
2193
- const manager = new MCPServerManager();
2194
- await manager.initialize();
2195
-
2196
- console.log('📡 Starting all ServiceNow MCP servers...');
2197
- await manager.startAllServers();
2198
-
2199
- const status = manager.getServerStatus();
2200
- const running = status.filter((s: any) => s.status === 'running').length;
2201
- const total = status.length;
2202
-
2203
- console.log(chalk.green(`✅ Started ${running}/${total} MCP servers successfully!`));
2204
- console.log(chalk.blue('\n📋 MCP servers are now running in the background'));
2205
- console.log('🎯 They will be available when you run swarm commands');
2206
-
2207
- } catch (error) {
2208
- console.log(chalk.yellow('\n⚠️ Could not start MCP servers automatically'));
2209
- console.log('📝 You can start them manually with: ' + chalk.cyan('snow-flow mcp start'));
2210
- }
2211
- }
2212
-
2213
- console.log(chalk.blue.bold('\n🎯 Next steps:'));
2214
- console.log('1. Edit .env file with your ServiceNow credentials');
2215
- console.log('2. Run: ' + chalk.cyan('snow-flow auth login'));
2216
- console.log('3. Start developing: ' + chalk.cyan('snow-flow swarm "your objective"'));
2217
- console.log('\n📚 Full documentation: https://github.com/groeimetai/snow-flow');
2218
-
2219
- // Force exit to prevent hanging
2220
- process.exit(0);
2221
-
2222
- } catch (error) {
2223
- console.error(chalk.red('\n❌ Initialization failed:'), error);
2224
- process.exit(1);
2225
- }
2226
- });
2227
-
2228
- // Help command
2229
- program
2230
- .command('help')
2231
- .description('Show detailed help information')
2232
- .action(() => {
2233
- console.log(`
2234
- 🚀 Snow-Flow v${VERSION} - ServiceNow Multi-Agent Development Framework
2235
-
2236
- 📋 Available Commands:
2237
- swarm <objective> Execute multi-agent orchestration
2238
- spawn <type> Spawn specific agent types
2239
- status Show system status
2240
- monitor Real-time monitoring dashboard
2241
- memory <action> Memory operations
2242
- auth <action> Authentication management
2243
- mcp <action> Manage ServiceNow MCP servers
2244
- help Show this help
2245
-
2246
- 🎯 Example Usage:
2247
- snow-flow auth login --instance dev12345.service-now.com --client-id your-id --client-secret your-secret
2248
- snow-flow auth status
2249
- snow-flow mcp start # Start MCP servers for Claude Code
2250
- snow-flow mcp status # Check MCP server status
2251
- snow-flow swarm "create a widget for incident management"
2252
- snow-flow swarm "create approval flow" # 🔧 Auto-detects Flow Designer and uses XML!
2253
- snow-flow spawn widget-builder --name "IncidentWidget"
2254
- snow-flow monitor --duration 120
2255
- snow-flow memory store "project" "incident_system"
2256
- snow-flow status
2257
-
2258
- 🤖 Agent Types:
2259
- widget-builder Create Service Portal widgets
2260
- workflow-designer Design Flow Designer workflows
2261
- script-generator Generate scripts and business rules
2262
- ui-builder Create UI components
2263
- app-creator Build complete applications
2264
-
2265
- ⚙️ OAuth Configuration:
2266
- Set environment variables or use command line options:
2267
- - SNOW_INSTANCE: Your ServiceNow instance (e.g., dev12345.service-now.com)
2268
- - SNOW_CLIENT_ID: OAuth Client ID from ServiceNow
2269
- - SNOW_CLIENT_SECRET: OAuth Client Secret from ServiceNow
2270
-
2271
- 🔧 MCP Server Management:
2272
- - start Start all or specific MCP servers
2273
- - stop Stop all or specific MCP servers
2274
- - restart Restart all or specific MCP servers
2275
- - status Show status of all MCP servers
2276
- - logs View MCP server logs
2277
- - list List all configured MCP servers
2278
-
2279
- 🔗 Live ServiceNow Integration:
2280
- - Create widgets directly in ServiceNow
2281
- - Execute workflows in real-time
2282
- - Test changes immediately in your instance
2283
-
2284
- 🌐 More Info: https://github.com/groeimetai/snow-flow
2285
- `);
2286
- });
2287
-
2288
- // Helper functions for init command
2289
- async function createDirectoryStructure(targetDir: string, force: boolean = false) {
2290
- const directories = [
2291
- '.claude', '.claude/commands', '.claude/commands/sparc', '.claude/configs',
2292
- '.swarm', '.swarm/sessions', '.swarm/agents',
2293
- '.snow-flow', '.snow-flow/queen', '.snow-flow/memory', '.snow-flow/queen-test', '.snow-flow/queen-advanced',
2294
- 'memory', 'memory/agents', 'memory/sessions',
2295
- 'coordination', 'coordination/memory_bank', 'coordination/subtasks',
2296
- 'servicenow', 'servicenow/widgets', 'servicenow/workflows', 'servicenow/scripts',
2297
- 'templates', 'templates/widgets', 'templates/workflows'
2298
- ];
2299
-
2300
- for (const dir of directories) {
2301
- const dirPath = join(targetDir, dir);
2302
- await fs.mkdir(dirPath, { recursive: true });
2303
- }
2304
- }
2305
-
2306
- async function createBasicConfig(targetDir: string) {
2307
- const claudeConfig = {
2308
- version: VERSION,
2309
- name: 'snow-flow',
2310
- description: 'ServiceNow Multi-Agent Development Framework',
2311
- created: new Date().toISOString(),
2312
- features: {
2313
- swarmCoordination: true,
2314
- persistentMemory: true,
2315
- serviceNowIntegration: true,
2316
- sparcModes: true
2317
- }
2318
- };
2319
-
2320
- const swarmConfig = {
2321
- version: VERSION,
2322
- topology: 'hierarchical',
2323
- maxAgents: 8,
2324
- memory: {
2325
- database: '.swarm/memory.db',
2326
- namespace: 'snow-flow'
2327
- }
2328
- };
2329
-
2330
- await fs.writeFile(join(targetDir, '.claude/config.json'), JSON.stringify(claudeConfig, null, 2));
2331
- await fs.writeFile(join(targetDir, '.swarm/config.json'), JSON.stringify(swarmConfig, null, 2));
2332
- }
2333
-
2334
- async function createReadmeFiles(targetDir: string, force: boolean = false) {
2335
- // Only create README.md if it doesn't exist already
2336
- const readmePath = join(targetDir, 'README.md');
2337
- if (!existsSync(readmePath) || force) {
2338
- const mainReadme = `# Snow-Flow: Multi-Agent ServiceNow Development Platform 🚀
2339
-
2340
- Snow-Flow is a powerful multi-agent AI platform that revolutionizes ServiceNow development through intelligent automation, natural language processing, and autonomous deployment capabilities. Built with 11 specialized MCP (Model Context Protocol) servers, Snow-Flow enables developers to create, manage, and deploy ServiceNow artifacts using simple natural language commands.
2341
-
2342
- ## 🆕 What's New in v1.1.51
2343
-
2344
- ### 🎯 CRITICAL FIXES - All User Issues Resolved!
2345
- - **ROOT CAUSE SOLVED**: Flow Designer validation failures completely eliminated
2346
- - **JSON SCHEMA FLEXIBILITY**: Accepts both "steps" and "activities" arrays with auto-conversion
2347
- - **DOCUMENTATION SYNC**: Init command now creates comprehensive CLAUDE.md (373 lines vs 15)
2348
- - **COMPLETE GUIDE**: New users get full Snow-Flow development environment from day one
2349
-
2350
- ### 🧠 Intelligent Error Recovery (v1.1.48-1.1.49)
2351
- - **AUTOMATIC FALLBACKS**: Flow Designer → Business Rule conversion when deployment fails
2352
- - **SMART SESSIONS**: Update Sets auto-create when none exist - no more "no active session" errors
2353
- - **ZERO MANUAL WORK**: All systematic errors from user feedback now automatically handled
2354
- - **COMPREHENSIVE TESTING**: Enhanced flow testing with Business Rule fallback detection
2355
-
2356
- ### 🚀 Enhanced Swarm Command (v1.1.42+)
2357
- Most intelligent features are now **enabled by default** - één command voor alles!
2358
- - **DEFAULT TRUE**: \`--smart-discovery\`, \`--live-testing\`, \`--auto-deploy\`, \`--auto-rollback\`, \`--shared-memory\`, \`--progress-monitoring\`
2359
- - **INTELLIGENT ORCHESTRATION**: Uses \`snow_orchestrate_development\` MCP tool automatically
2360
- - **NO FLAGS NEEDED**: Just run \`snow-flow swarm "create widget"\` and everything works!
2361
-
2362
- ### 🔍 Real-Time ServiceNow Integration (v1.1.41+)
2363
- - **LIVE VALIDATION**: \`snow_validate_live_connection\` - real-time auth and permission checking
2364
- - **SMART PREVENTION**: \`snow_discover_existing_flows\` - prevents duplicate flows
2365
- - **LIVE TESTING**: \`snow_test_flow_execution\` - real flow testing in live instances
2366
- - **BATCH VALIDATION**: \`batch_deployment_validator\` - comprehensive multi-artifact validation
2367
- - **AUTO ROLLBACK**: \`deployment_rollback_manager\` - automatic rollback with backup creation
2368
-
2369
- ## 🌟 Key Features
2370
-
2371
- ### 🤖 11 Specialized MCP Servers
2372
- Each server provides autonomous capabilities for different aspects of ServiceNow development:
2373
-
2374
- 1. **Deployment MCP** - Autonomous widget and application deployment
2375
- 2. **Update Set MCP** - Professional change tracking and deployment management
2376
- 3. **Intelligent MCP** - AI-powered artifact discovery and editing
2377
- 4. **Graph Memory MCP** - Relationship tracking and impact analysis
2378
- 5. **Platform Development MCP** - Development workflow automation
2379
- 6. **Integration MCP** - Third-party system integration
2380
- 7. **Operations MCP** - Operations and monitoring management
2381
- 8. **Automation MCP** - Workflow and process automation
2382
- 9. **Security & Compliance MCP** - Security auditing and compliance
2383
- 10. **Reporting & Analytics MCP** - Data _analysis and reporting
2384
- 11. **Memory MCP** - Multi-agent coordination and todo management
2385
-
2386
- ### 🎯 Core Capabilities
2387
-
2388
- - **Natural Language Processing**: Create complex ServiceNow artifacts using plain English/Dutch commands
2389
- - **Intelligent Decision Making**: Automatically determines optimal architecture (flow vs subflow)
2390
- - **Zero Configuration**: All values dynamically discovered from your ServiceNow instance
2391
- - **Autonomous Deployment**: Direct deployment to ServiceNow with automatic error handling
2392
- - **Update Set Management**: Professional change tracking like ServiceNow pros use
2393
- - **Global Scope Strategy**: Intelligent scope selection with fallback mechanisms
2394
- - **Multi-Agent Coordination**: Parallel execution for complex tasks
2395
-
2396
- ## 🚀 Quick Start
2397
-
2398
- ### Prerequisites
2399
- - Node.js 18+ and npm
2400
- - ServiceNow instance with admin access
2401
- - OAuth application configured in ServiceNow
2402
-
2403
- ### Installation
2404
-
2405
- \`\`\`bash
2406
- # Install Snow-Flow globally
2407
- npm install -g snow-flow
2408
-
2409
- # Initialize Snow-Flow in your project directory
2410
- snow-flow init
2411
- \`\`\`
2412
-
2413
- #### Alternative: Install from source
2414
- \`\`\`bash
2415
- # Clone the repository
2416
- git clone https://github.com/groeimetai/snow-flow.git
2417
- cd snow-flow
2418
-
2419
- # Install dependencies
2420
- npm install
2421
-
2422
- # Build the project
2423
- npm run build
2424
-
2425
- # Link globally (optional)
2426
- npm link
2427
- \`\`\`
2428
-
2429
- ### Configuration
2430
-
2431
- 1. Create a \`.env\` file in the project root:
2432
- \`\`\`env
2433
- SNOW_INSTANCE=your-instance.service-now.com
2434
- SNOW_CLIENT_ID=your-oauth-client-id
2435
- SNOW_CLIENT_SECRET=your-oauth-client-secret
2436
- SNOW_USERNAME=your-username
2437
- SNOW_PASSWORD=your-password
2438
- \`\`\`
2439
-
2440
- 2. Set up OAuth in ServiceNow (see [SERVICENOW-OAUTH-SETUP.md](./SERVICENOW-OAUTH-SETUP.md))
2441
-
2442
- 3. Authenticate with ServiceNow:
2443
- \`\`\`bash
2444
- snow-flow auth login
2445
- \`\`\`
2446
-
2447
- ### 🎯 MCP Server Activation (v1.1.25+)
2448
-
2449
- Snow-Flow now includes **automatic MCP server activation** for Claude Code! During initialization, you'll be prompted to automatically start Claude Code with all 11 MCP servers pre-loaded:
2450
-
2451
- \`\`\`bash
2452
- snow-flow init
2453
-
2454
- # You'll see:
2455
- # 🚀 Would you like to start Claude Code with MCP servers automatically? (Y/n)
2456
- # Press Y to launch Claude Code with all MCP servers ready to use!
2457
- \`\`\`
2458
-
2459
- The MCP servers are automatically:
2460
- - ✅ Configured with correct paths for global npm installations
2461
- - ✅ Registered in Claude Code's settings
2462
- - ✅ Activated without manual approval steps
2463
- - ✅ Ready to use immediately after initialization
2464
-
2465
- If you need to manually activate MCP servers later:
2466
- \`\`\`bash
2467
- # For Mac/Linux:
2468
- claude --mcp-config .mcp.json .
2469
-
2470
- # For Windows:
2471
- claude.exe --mcp-config .mcp.json .
2472
- \`\`\`
2473
-
2474
- ## 💡 Usage Examples
2475
-
2476
- ### Create a Complex Flow with Natural Language
2477
- \`\`\`bash
2478
- snow-flow sparc "Create an approval workflow for iPhone 6 orders that notifies managers, creates tasks, and updates inventory"
2479
- \`\`\`
2480
-
2481
- ### Deploy a Widget Directly to ServiceNow
2482
- \`\`\`bash
2483
- snow-flow sparc "Create and deploy a widget that shows all critical incidents with real-time updates"
2484
- \`\`\`
2485
-
2486
- ### Start a Multi-Agent Swarm for Complex Projects
2487
- \`\`\`bash
2488
- # Most intelligent features are enabled by default!
2489
- snow-flow swarm "Build a complete incident management system with dashboard, workflows, and notifications"
2490
-
2491
- # Default settings:
2492
- # ✅ --smart-discovery (true) - Reuses existing artifacts
2493
- # ✅ --live-testing (true) - Tests in real-time
2494
- # ✅ --auto-deploy (true) - Deploys automatically (safe with update sets)
2495
- # ✅ --auto-rollback (true) - Rollbacks on failures
2496
- # ✅ --shared-memory (true) - Agents share context
2497
- # ✅ --progress-monitoring (true) - Real-time status
2498
-
2499
- # Add --auto-permissions to enable automatic permission escalation
2500
- snow-flow swarm "Create enterprise workflow" --auto-permissions
2501
-
2502
- # Disable specific features with --no- prefix
2503
- snow-flow swarm "Test workflow" --no-auto-deploy --no-live-testing
2504
- \`\`\`
2505
-
2506
- ### Intelligent Artifact Discovery
2507
- \`\`\`bash
2508
- snow-flow sparc "Find and modify the approval workflow to add an extra approval step for orders over $1000"
2509
- \`\`\`
2510
-
2511
- ### Create Flows in Dutch
2512
- \`\`\`bash
2513
- snow-flow sparc "Maak een flow voor het automatisch toewijzen van incidenten aan de juiste groep op basis van categorie"
2514
- \`\`\`
2515
-
2516
- ## 🛠️ Advanced Features
2517
-
2518
- ### Flow vs Subflow Intelligence
2519
- Snow-Flow automatically analyzes your requirements and decides whether to create a main flow or break it into reusable subflows:
2520
- - Complexity analysis
2521
- - Reusability assessment
2522
- - Performance optimization
2523
- - Maintainability considerations
2524
-
2525
- ### Update Set Management
2526
- Professional change tracking just like ServiceNow developers use:
2527
- \`\`\`bash
2528
- # Create a new update set for your feature
2529
- snow-flow sparc "Create update set for new approval features"
2530
-
2531
- # All subsequent changes are automatically tracked
2532
- snow-flow sparc "Add approval widget to portal"
2533
- \`\`\`
2534
-
2535
- ### Global Scope Strategy
2536
- Intelligent deployment scope selection:
2537
- - Automatic permission validation
2538
- - Fallback mechanisms for restricted environments
2539
- - Environment-aware deployment (dev/test/prod)
2540
-
2541
- ### Template Matching
2542
- Recognizes common patterns and applies best practices:
2543
- - Approval workflows
2544
- - Fulfillment processes
2545
- - Notification systems
2546
- - Integration patterns
2547
-
2548
- ## 🔧 New MCP Tools (v1.1.44+)
2549
-
2550
- ### Catalog Item Search with Fuzzy Matching
2551
- Find catalog items even when you don't know the exact name:
2552
- \`\`\`javascript
2553
- // In Claude Code with MCP tools
2554
- snow_catalog_item_search({
2555
- query: "iPhone", // Finds iPhone 6S, iPhone 7, etc.
2556
- fuzzy_match: true, // Intelligent variations
2557
- category_filter: "mobile devices",
2558
- include_variables: true // Get catalog variables
2559
- });
2560
- \`\`\`
2561
-
2562
- ### Flow Testing with Mock Data
2563
- Test flows without affecting production data:
2564
- \`\`\`javascript
2565
- snow_test_flow_with_mock({
2566
- flow_id: "equipment_provisioning_flow",
2567
- create_test_user: true, // Auto-creates test user
2568
- mock_catalog_items: true, // Creates test items
2569
- mock_catalog_data: [
2570
- {
2571
- name: "Test iPhone 6S",
2572
- price: "699.00"
2573
- }
2574
- ],
2575
- simulate_approvals: true, // Auto-approves
2576
- cleanup_after_test: true // Removes test data
2577
- });
2578
- \`\`\`
2579
-
2580
- ### Direct Catalog-Flow Linking
2581
- Link catalog items directly to flows for automated fulfillment:
2582
- \`\`\`javascript
2583
- snow_link_catalog_to_flow({
2584
- catalog_item_id: "iPhone 6S",
2585
- flow_id: "mobile_provisioning_flow",
2586
- link_type: "flow_catalog_process", // Modern approach
2587
- variable_mapping: [
2588
- {
2589
- catalog_variable: "phone_model",
2590
- flow_input: "device_type"
2591
- },
2592
- {
2593
- catalog_variable: "user_department",
2594
- flow_input: "department"
2595
- }
2596
- ],
2597
- trigger_condition: 'current.stage == "request_approved"',
2598
- execution_options: {
2599
- run_as: "user", // 🔒 SEC-001 FIX: Default to 'user' to prevent privilege escalation
2600
- wait_for_completion: true
2601
- },
2602
- test_link: true // Creates test request
2603
- });
2604
- \`\`\`
2605
-
2606
- ### Bulk Deployment
2607
- Deploy multiple artifacts in a single transaction:
2608
- \`\`\`javascript
2609
- snow_bulk_deploy({
2610
- artifacts: [
2611
- { type: "widget", data: widgetData },
2612
- { type: "flow", data: flowData },
2613
- { type: "script", data: scriptData }
2614
- ],
2615
- transaction_mode: true, // All-or-nothing deployment
2616
- parallel: true, // Deploy simultaneously
2617
- dry_run: false
2618
- });
2619
- \`\`\`
2620
-
2621
- ## 📁 Project Structure
2622
-
2623
- \`\`\`
2624
- snow-flow/
2625
- ├── src/
2626
- │ ├── mcp/ # 11 MCP server implementations
2627
- │ ├── orchestrator/ # Flow composition and intelligence
2628
- │ ├── strategies/ # Deployment and scope strategies
2629
- │ ├── api/ # ServiceNow API integration
2630
- │ ├── managers/ # Resource and scope management
2631
- │ └── utils/ # Utilities and helpers
2632
- ├── .snow-flow/ # Snow-Flow configuration
2633
- ├── .claude/ # Claude configuration
2634
- ├── memory/ # Persistent agent memory
2635
- └── coordination/ # Multi-agent coordination
2636
- \`\`\`
2637
-
2638
- ## 🔧 Development Commands
2639
-
2640
- \`\`\`bash
2641
- # Run tests
2642
- npm test
2643
-
2644
- # Run linting
2645
- npm run lint
2646
-
2647
- # Type checking
2648
- npm run typecheck
2649
-
2650
- # Development mode
2651
- npm run dev
2652
-
2653
- # Build for production
2654
- npm run build
2655
- \`\`\`
2656
-
2657
- ## 📚 Documentation
2658
-
2659
- - [MCP Server Documentation](./MCP_SERVERS.md) - Detailed info on all 11 MCP servers
2660
- - [OAuth Setup Guide](./SERVICENOW-OAUTH-SETUP.md) - ServiceNow OAuth configuration
2661
- - [Update Set Guide](./UPDATE_SET_DEPLOYMENT_GUIDE.md) - Professional change management
2662
- - [API Integration Guide](./API_INTEGRATION_GUIDE.md) - ServiceNow API details
2663
-
2664
- ## 🤝 Contributing
2665
-
2666
- We welcome contributions! Please see our contributing guidelines (coming soon).
2667
-
2668
- ## 🔒 Security
2669
-
2670
- - All credentials stored securely in environment variables
2671
- - OAuth 2.0 authentication with ServiceNow
2672
- - No hardcoded values - everything discovered dynamically
2673
- - Secure token management with automatic refresh
2674
-
2675
- ## 🎯 Use Cases
2676
-
2677
- ### For ServiceNow Developers
2678
- - Rapidly prototype flows and workflows
2679
- - Automate repetitive development tasks
2680
- - Ensure consistency across implementations
2681
- - Reduce development time by 80%
2682
-
2683
- ### For ServiceNow Architects
2684
- - Validate architectural decisions
2685
- - Ensure best practices are followed
2686
- - Analyze impact of changes
2687
- - Optimize performance and maintainability
2688
-
2689
- ### For ServiceNow Administrators
2690
- - Quick deployments and updates
2691
- - Professional change tracking
2692
- - Automated testing and validation
2693
- - Simplified migration between instances
2694
-
2695
- ## 🚦 Roadmap
2696
-
2697
- - [ ] Visual flow designer integration
2698
- - [ ] Enhanced Neo4j graph visualization
2699
- - [ ] Multi-instance synchronization
2700
- - [ ] AI-powered code review
2701
- - [ ] Automated testing framework
2702
- - [ ] Performance optimization recommendations
2703
-
2704
- ## 🆕 What's New in v1.1.25
2705
-
2706
- ### Automatic MCP Server Activation 🎯
2707
- - **Interactive Prompt**: During \`snow-flow init\`, you're now prompted to automatically start Claude Code with all MCP servers
2708
- - **Zero Manual Steps**: No more manual MCP approval in Claude Code - servers load automatically using \`claude --mcp-config\`
2709
- - **Cross-Platform Support**: Works on Mac, Linux, and Windows with platform-specific activation scripts
2710
- - **Instant Availability**: All 11 ServiceNow MCP servers are immediately available in Claude Code after initialization
2711
-
2712
- ### Previous Updates
2713
- - **v1.1.24**: Added \`snow-flow mcp debug\` command for troubleshooting MCP configurations
2714
- - **v1.1.23**: Fixed .npmignore to include essential .claude configuration files
2715
- - **v1.1.22**: Verified global npm installation correctly registers all MCP servers
2716
- - **v1.1.20**: Added enabledMcpjsonServers to ensure MCP visibility in Claude Code
2717
-
2718
- ## 📝 License
2719
-
2720
- This project is licensed under the MIT License - see the LICENSE file for details.
2721
-
2722
- ## 🙏 Acknowledgments
2723
-
2724
- Built with the power of Claude AI and the ServiceNow platform. Special thanks to the ServiceNow developer community for inspiration and best practices.
2725
-
2726
- ---
2727
-
2728
- **Ready to revolutionize your ServiceNow development?** Start with \`snow-flow init\` and experience the future of ServiceNow automation! 🚀
2729
- `;
2730
-
2731
- await fs.writeFile(readmePath, mainReadme);
2732
- }
2733
-
2734
- // Create sub-directory READMEs
2735
- await fs.writeFile(join(targetDir, 'memory/agents/README.md'), '# Agent Memory\n\nThis directory contains persistent memory for ServiceNow agents.');
2736
- await fs.writeFile(join(targetDir, 'servicenow/README.md'), '# ServiceNow Artifacts\n\nThis directory contains generated ServiceNow development artifacts.');
2737
- }
2738
-
2739
-
2740
- // Helper functions
2741
-
2742
- async function copyCLAUDEmd(targetDir: string, force: boolean = false) {
2743
- let claudeMdContent = '';
2744
- try {
2745
- // First try to find the CLAUDE.md in the source directory (for global installs)
2746
- const sourceClaudeFiles = [
2747
- // Try the project root (when running from dist/)
2748
- join(__dirname, '..', 'CLAUDE.md'),
2749
- // Try when running directly from src/
2750
- join(__dirname, 'CLAUDE.md'),
2751
- // Try npm global installation paths
2752
- join(__dirname, '..', '..', '..', 'CLAUDE.md'),
2753
- join(__dirname, '..', '..', '..', '..', 'CLAUDE.md'),
2754
- // Try current working directory as fallback
2755
- join(process.cwd(), 'CLAUDE.md')
2756
- ];
2757
-
2758
- let foundSource = false;
2759
-
2760
- for (const sourcePath of sourceClaudeFiles) {
2761
- try {
2762
- claudeMdContent = await fs.readFile(sourcePath, 'utf8');
2763
- foundSource = true;
2764
- console.log(`✅ Found CLAUDE.md source at: ${sourcePath}`);
2765
- break;
2766
- } catch {
2767
- // Continue to next path
2768
- }
2769
- }
2770
-
2771
- if (!foundSource) {
2772
- // Use Snow-Flow specific CLAUDE.md content
2773
- console.log('⚠️ Could not find CLAUDE.md source, creating minimal version');
2774
- claudeMdContent = `# Snow-Flow Development with Claude Code
2775
-
2776
- ## 🚨 CRITICAL: MCP-FIRST WORKFLOW (READ THIS FIRST!)
2777
-
2778
- **Snow-flow's core value is REAL ServiceNow integration through MCP tools. NEVER work in offline mode!**
2779
-
2780
- ### ⚠️ MANDATORY WORKFLOW - NO EXCEPTIONS
2781
-
2782
- **Every ServiceNow task MUST start with this sequence:**
2783
-
2784
- \`\`\`javascript
2785
- // 1. MANDATORY: Pre-flight authentication check
2786
- const authCheck = await snow_validate_live_connection({ test_level: "permissions" });
2787
- if (!authCheck.success) {
2788
- // STOP! Fix authentication first
2789
- return authenticationError(authCheck.error);
2790
- }
2791
-
2792
- // 2. MANDATORY: Discovery before creation
2793
- const discovery = await snow_find_artifact({
2794
- query: "your objective",
2795
- type: "widget|flow|script|any"
2796
- });
2797
-
2798
- // 3. MANDATORY: Real ServiceNow deployment
2799
- const deployment = await snow_deploy({
2800
- type: "widget|application", // Note: flow removed in v1.4.0+
2801
- config: { /* your config */ },
2802
- auto_update_set: true // Always track changes
2803
- });
2804
-
2805
- // 4. MANDATORY: Track in Update Set
2806
- await snow_update_set_add_artifact({
2807
- type: deployment.type,
2808
- sys_id: deployment.result.sys_id,
2809
- name: deployment.result.name
2810
- });
2811
- \`\`\`
2812
-
2813
- ### 🚫 FORBIDDEN ACTIONS
2814
-
2815
- **THESE ACTIONS ARE BANNED - NEVER DO THESE:**
2816
-
2817
- ❌ **Creating local files** without MCP check first
2818
- ❌ **Generating mock data** instead of using MCP tools
2819
- ❌ **Working in "offline mode"** when ServiceNow is available
2820
- ❌ **Skipping authentication validation**
2821
- ❌ **Planning mode** without trying MCP tools first
2822
-
2823
- ### ✅ CORRECT: MCP-First Decision Tree
2824
-
2825
- \`\`\`
2826
- User Request → ALWAYS START HERE:
2827
-
2828
- 1. snow_validate_live_connection()
2829
-
2830
- SUCCESS? → Continue to Step 2
2831
-
2832
- FAILURE? → Fix auth: snow_auth_diagnostics()
2833
- Then guide user: "snow-flow auth login"
2834
- STOP until auth works
2835
-
2836
- 2. snow_find_artifact() // Check if exists
2837
-
2838
- FOUND? → Ask: "Reuse existing or create new?"
2839
-
2840
- NOT FOUND? → Continue to Step 3
2841
-
2842
- 3. snow_deploy() // Real deployment to ServiceNow
2843
-
2844
- SUCCESS? → Step 4: Track in Update Set
2845
-
2846
- FAILURE? → Use fallback strategies
2847
-
2848
- 4. snow_update_set_add_artifact() // Always track
2849
-
2850
- DONE! ✅
2851
- \`\`\`
2852
-
2853
- ## 🚀 Snow-Flow Swarm Command - MCP-Orchestrated Multi-Agent Intelligence
2854
-
2855
- **The Swarm system is MCP-native and ALWAYS uses ServiceNow tools first!**
2856
-
2857
- ### 🧠 Queen Agent with Parallel Execution (v1.4.0+)
2858
- - Automatically spawns 6+ specialized agents for widget development
2859
- - Achieves proven 2.8x speedup through intelligent parallel execution
2860
- - All agents coordinate through Snow-Flow's memory system
2861
- - Every agent uses MCP tools directly - no offline mode
2862
-
2863
- ## 🛠️ Complete ServiceNow MCP Tools Reference
2864
-
2865
- ### Discovery & Search Tools
2866
- \`\`\`javascript
2867
- // Find any ServiceNow artifact using natural language
2868
- snow_find_artifact({
2869
- query: "the widget that shows incidents on homepage",
2870
- type: "widget" // or "flow", "script", "application", "any"
2871
- });
2872
-
2873
- // Search catalog items with fuzzy matching
2874
- snow_catalog_item_search({
2875
- query: "laptop",
2876
- fuzzy_match: true, // Finds variations: notebook, MacBook, etc.
2877
- category_filter: "hardware",
2878
- include_variables: true // Get catalog variables too
2879
- });
2880
-
2881
- // Direct sys_id lookup (faster than search)
2882
- snow_get_by_sysid({
2883
- sys_id: "<artifact_sys_id>",
2884
- table: "sp_widget"
2885
- });
2886
- \`\`\`
2887
-
2888
- ### Flow Development Tools
2889
- \`\`\`javascript
2890
- // Create flows from natural language
2891
- snow_create_flow({
2892
- instruction: "create a flow that sends email when incident priority is high",
2893
- deploy_immediately: true // Automatically deploys XML to ServiceNow
2894
- });
2895
-
2896
- // Test flows with mock data
2897
- snow_test_flow_with_mock({
2898
- flow_id: "incident_notification_flow",
2899
- create_test_user: true,
2900
- mock_catalog_items: true,
2901
- test_inputs: {
2902
- priority: "1",
2903
- category: "hardware"
2904
- },
2905
- simulate_approvals: true
2906
- });
2907
-
2908
- // Link catalog items to flows
2909
- snow_link_catalog_to_flow({
2910
- catalog_item_id: "New Laptop Request",
2911
- flow_id: "laptop_provisioning_flow",
2912
- link_type: "flow_catalog_process",
2913
- variable_mapping: [
2914
- {
2915
- catalog_variable: "laptop_model",
2916
- flow_input: "equipment_type"
2917
- }
2918
- ]
2919
- });
2920
- \`\`\`
2921
-
2922
- ### Widget Development Tools
2923
- \`\`\`javascript
2924
- // Deploy widgets with automatic validation
2925
- snow_deploy_widget({
2926
- name: "incident_dashboard",
2927
- title: "Incident Dashboard",
2928
- template: htmlContent,
2929
- css: cssContent,
2930
- client_script: clientJS,
2931
- server_script: serverJS,
2932
- demo_data: { incidents: [...] }
2933
- });
2934
-
2935
- // Preview and test widgets
2936
- snow_preview_widget({
2937
- widget_id: "incident_dashboard",
2938
- check_dependencies: true
2939
- });
2940
-
2941
- snow_widget_test({
2942
- widget_id: "incident_dashboard",
2943
- test_scenarios: [
2944
- {
2945
- name: "Load with no data",
2946
- server_data: { incidents: [] }
2947
- }
2948
- ]
2949
- });
2950
- \`\`\`
2951
-
2952
- ### Bulk Operations
2953
- \`\`\`javascript
2954
- // Deploy multiple artifacts at once
2955
- snow_bulk_deploy({
2956
- artifacts: [
2957
- { type: "widget", data: widgetData },
2958
- { type: "flow", data: flowData },
2959
- { type: "script", data: scriptData }
2960
- ],
2961
- transaction_mode: true, // All or nothing
2962
- parallel: true, // Deploy simultaneously
2963
- dry_run: false
2964
- });
2965
- \`\`\`
2966
-
2967
- ### Intelligent Analysis
2968
- \`\`\`javascript
2969
- // Analyze incidents with AI
2970
- snow_analyze_incident({
2971
- incident_id: "INC0010001",
2972
- include_similar: true,
2973
- suggest_resolution: true
2974
- });
2975
-
2976
- // Pattern analysis
2977
- snow_pattern__analysis({
2978
- analysis_type: "incident_patterns",
2979
- timeframe: "month"
2980
- });
2981
- \`\`\`
2982
-
2983
- ## ⚡ Performance Optimization
2984
-
2985
- ### Parallel Execution Patterns
2986
- \`\`\`javascript
2987
- // Execute multiple searches concurrently
2988
- Promise.all([
2989
- snow_find_artifact({ query: "incident widget" }),
2990
- snow_catalog_item_search({ query: "laptop" }),
2991
- snow_query_incidents({ query: "priority=1" })
2992
- ]);
2993
- \`\`\`
2994
-
2995
- ### Batch File Operations
2996
- \`\`\`javascript
2997
- // Read multiple files in one operation
2998
- MultiRead([
2999
- "/path/to/widget.html",
3000
- "/path/to/widget.css",
3001
- "/path/to/widget.js"
3002
- ]);
3003
- \`\`\`
3004
-
3005
- ## 📝 Workflow Guidelines
3006
-
3007
- ### Standard Development Flow
3008
- 1. **Discovery Phase**: Use search tools to find existing artifacts
3009
- 2. **Planning Phase**: Use TodoWrite to plan all tasks
3010
- 3. **Development Phase**: Launch agents concurrently
3011
- 4. **Testing Phase**: Use mock testing tools
3012
- 5. **Deployment Phase**: Use bulk deploy with validation
3013
-
3014
- ### Error Recovery Patterns
3015
- \`\`\`javascript
3016
- // Always implement rollback strategies
3017
- if (deployment.failed) {
3018
- snow_deployment_rollback_manager({
3019
- update_set_id: deployment.update_set,
3020
- restore_point: deployment.backup_id
3021
- });
3022
- }
3023
- \`\`\`
3024
-
3025
- ## 🔧 Advanced Configuration
3026
-
3027
- ## Build Commands
3028
- - \`npm run build\`: Build the project
3029
- - \`npm run test\`: Run the full test suite
3030
- - \`npm run lint\`: Run ESLint and format checks
3031
- - \`npm run typecheck\`: Run TypeScript type checking
3032
-
3033
- ## Snow-Flow Commands
3034
- - \`snow-flow init\`: Initialize project with MCP servers and SPARC environment and SPARC environment
3035
- - \`snow-flow auth login\`: Authenticate with ServiceNow OAuth
3036
- - \`snow-flow swarm "<objective>"\`: Start multi-agent swarm - één command voor alles!
3037
- - \`snow-flow sparc <mode> "<task>"\`: Run specific SPARC mode
3038
-
3039
- ## Enhanced Swarm Command (v1.1.41+)
3040
- The swarm command now includes intelligent features that are **enabled by default**:
3041
-
3042
- \`\`\`bash
3043
- # Simple usage - ALL autonomous systems enabled by default!
3044
- snow-flow swarm "create incident management dashboard"
3045
-
3046
- # Disable specific autonomous systems if needed
3047
- snow-flow swarm "create simple widget" --no-autonomous-cost-optimization --no-autonomous-compliance
3048
-
3049
- # Disable ALL autonomous systems
3050
- snow-flow swarm "basic development only" --no-autonomous-all
3051
-
3052
- # Force enable all (overrides any --no- flags)
3053
- snow-flow swarm "full orchestration mode" --autonomous-all
3054
- \`\`\`
3055
-
3056
- ### 🤖 NEW: Autonomous Systems (v1.3.26+) - **ENABLED BY DEFAULT!**
3057
- True orchestration with zero manual intervention - all systems active unless disabled:
3058
-
3059
- - ✅ **Documentation**: Self-documenting system (auto-generates and updates docs)
3060
- - ✅ **Cost Optimization**: AI-driven cost management with auto-optimization
3061
- - ✅ **Compliance**: Multi-framework compliance monitoring with auto-remediation
3062
- - ✅ **Self-Healing**: Predictive failure detection with automatic recovery
3063
-
3064
- **Disable Options**:
3065
- - \`--no-autonomous-documentation\`: Disable documentation system
3066
- - \`--no-autonomous-cost-optimization\`: Disable cost optimization
3067
- - \`--no-autonomous-compliance\`: Disable compliance monitoring
3068
- - \`--no-autonomous-healing\`: Disable self-healing
3069
- - \`--no-autonomous-all\`: Disable ALL autonomous systems
3070
-
3071
- **Force Options**:
3072
- - \`--autonomous-all\`: Force enable all (overrides --no- flags)
3073
-
3074
- **Perfect Orchestrator**: Systems work autonomously, make intelligent decisions, and continuously improve - no manual intervention needed!
3075
-
3076
- ### Default Settings (no flags needed):
3077
- - ✅ \`--smart-discovery\` - Automatically discovers and reuses existing artifacts
3078
- - ✅ \`--live-testing\` - Tests in real-time on your ServiceNow instance
3079
- - ✅ \`--auto-deploy\` - Deploys automatically (safe with update sets)
3080
- - ✅ \`--auto-rollback\` - Automatically rollbacks on failures
3081
- - ✅ \`--shared-memory\` - All agents share context and coordination
3082
- - ✅ \`--progress-monitoring\` - Real-time progress tracking
3083
- - ❌ \`--auto-permissions\` - Disabled by default (enable with flag for automatic role elevation)
3084
-
3085
- ### Advanced Usage:
3086
- \`\`\`bash
3087
- # Enable automatic permission escalation
3088
- snow-flow swarm "create global workflow" --auto-permissions
3089
-
3090
- # Disable specific features
3091
- snow-flow swarm "test widget" --no-auto-deploy --no-live-testing
3092
-
3093
- # Full control
3094
- snow-flow swarm "complex integration" \\
3095
- --max-agents 8 \\
3096
- --strategy development \\
3097
- --mode distributed \\
3098
- --parallel \\
3099
- --auto-permissions
3100
- \`\`\`
3101
-
3102
- ## New MCP Tools (v1.1.44+)
3103
-
3104
- ### Catalog Item Search
3105
- Find catalog items with intelligent fuzzy matching:
3106
- \`\`\`javascript
3107
- snow_catalog_item_search({
3108
- query: "iPhone", // Will find iPhone 6S, iPhone 7, etc.
3109
- fuzzy_match: true, // Enable intelligent variations
3110
- include_variables: true // Include catalog variables
3111
- })
3112
- \`\`\`
3113
-
3114
- ### Flow Testing with Mock Data
3115
- Test flows without real data:
3116
- \`\`\`javascript
3117
- snow_test_flow_with_mock({
3118
- flow_id: "equipment_provisioning_flow",
3119
- create_test_user: true, // Creates test user
3120
- mock_catalog_items: true, // Creates test catalog items
3121
- simulate_approvals: true, // Auto-approves during test
3122
- cleanup_after_test: true // Removes test data after
3123
- })
3124
- \`\`\`
3125
-
3126
- ### Direct Catalog-Flow Linking
3127
- Link catalog items directly to flows:
3128
- \`\`\`javascript
3129
- snow_link_catalog_to_flow({
3130
- catalog_item_id: "iPhone 6S",
3131
- flow_id: "mobile_provisioning_flow",
3132
- link_type: "flow_catalog_process", // Modern approach
3133
- variable_mapping: [
3134
- {
3135
- catalog_variable: "phone_model",
3136
- flow_input: "device_type"
3137
- }
3138
- ],
3139
- test_link: true // Creates test request
3140
- })
3141
- \`\`\`
3142
-
3143
- ### OAuth Configuration
3144
- \`\`\`env
3145
- # .env file
3146
- SNOW_INSTANCE=dev123456
3147
- SNOW_CLIENT_ID=your_oauth_client_id
3148
- SNOW_CLIENT_SECRET=your_oauth_client_secret
3149
- SNOW_USERNAME=admin
3150
- SNOW_PASSWORD=admin_password
3151
- \`\`\`
3152
-
3153
- ### Update Set Management
3154
- \`\`\`javascript
3155
- // Smart update set creation
3156
- snow_smart_update_set({
3157
- name: "Auto-generated for widget development",
3158
- detect_context: true, // Auto-detects what you're working on
3159
- auto_switch: true // Switches when context changes
3160
- });
3161
- \`\`\`
3162
-
3163
- ## 🎯 Quick Start
3164
- 1. \`snow-flow init\` - Initialize project with MCP servers and SPARC environment and SPARC environment
3165
- 2. Configure ServiceNow credentials in .env file
3166
- 3. \`snow-flow auth login\` - Authenticate with ServiceNow OAuth
3167
- 4. \`snow-flow swarm "create a widget for incident management"\` - Everything automatic!
3168
-
3169
- ## 💡 Important Notes
3170
-
3171
- ### Do's
3172
- - ✅ Use TodoWrite extensively for task tracking
3173
- - ✅ Batch MCP tool calls for performance
3174
- - ✅ Store important data in Memory for coordination
3175
- - ✅ Test with mock data before deploying
3176
- - ✅ Work within Update Sets for safety
3177
- - ✅ Use fuzzy search for finding artifacts
3178
-
3179
- ### Don'ts
3180
- - ❌ Don't make sequential tool calls when batch is possible
3181
- - ❌ Don't hardcode credentials or sys_ids
3182
- - ❌ Don't deploy without testing
3183
- - ❌ Don't ignore OAuth permission errors
3184
- - ❌ Don't create artifacts without checking if they exist
3185
-
3186
- ## 🚀 Performance Benchmarks
3187
-
3188
- With concurrent execution and batch operations:
3189
- - **Widget Development**: 3x faster than sequential
3190
- - **Flow Creation**: 2.5x faster with parallel validation
3191
- - **Bulk Deployment**: Up to 5x faster with parallel mode
3192
- - **Search Operations**: 4x faster with concurrent queries
3193
-
3194
- ## 📚 Additional Resources
3195
-
3196
- ### MCP Server Documentation
3197
- - **servicenow-deployment**: Widget, flow, and application deployment
3198
- - **servicenow-intelligent**: Smart search and artifact discovery
3199
- - **servicenow-operations**: Incident management and catalog operations
3200
- - **servicenow-platform-development**: Scripts, rules, and policies
3201
-
3202
- ### SPARC Modes
3203
- - \`orchestrator\`: Coordinates complex multi-step tasks
3204
- - \`coder\`: Focused code implementation
3205
- - \`researcher\`: Deep _analysis and discovery
3206
- - \`tester\`: Comprehensive testing strategies
3207
- - \`architect\`: System design and architecture
3208
-
3209
- ---
3210
-
3211
- This is a minimal CLAUDE.md file. The full documentation should be available in your Snow-Flow installation.
3212
-
3213
- ## Quick Start
3214
- 1. \`snow-flow init\` - Initialize project with MCP servers and SPARC environment and SPARC environment
3215
- 2. Configure ServiceNow credentials in .env file
3216
- 3. \`snow-flow auth login\` - Authenticate with ServiceNow OAuth
3217
- 4. \`snow-flow swarm "create a widget for incident management"\` - Everything automatic!
3218
-
3219
- For full documentation, visit: https://github.com/groeimetai/snow-flow
3220
- `;
3221
- }
3222
-
3223
- const claudeMdPath = join(targetDir, 'CLAUDE.md');
3224
- try {
3225
- await fs.access(claudeMdPath);
3226
- if (force) {
3227
- console.log('⚠️ CLAUDE.md already exists, overwriting with --force flag');
3228
- await fs.writeFile(claudeMdPath, claudeMdContent);
3229
- } else {
3230
- console.log('⚠️ CLAUDE.md already exists, skipping (use --force to overwrite)');
3231
- }
3232
- } catch {
3233
- await fs.writeFile(claudeMdPath, claudeMdContent);
3234
- }
3235
- } catch (error) {
3236
- console.log('⚠️ Error copying CLAUDE.md, creating Snow-Flow specific version');
3237
- // Snow-Flow specific fallback content
3238
- const claudeMdFallback = `# Snow-Flow Development with Claude Code
3239
-
3240
- ## 🚨 CRITICAL: MCP-FIRST WORKFLOW (READ THIS FIRST!)
3241
-
3242
- **Snow-flow's core value is REAL ServiceNow integration through MCP tools. NEVER work in offline mode!**
3243
-
3244
- ### ⚠️ MANDATORY WORKFLOW - NO EXCEPTIONS
3245
-
3246
- **Every ServiceNow task MUST start with this sequence:**
3247
-
3248
- \`\`\`javascript
3249
- // 1. MANDATORY: Pre-flight authentication check
3250
- const authCheck = await snow_validate_live_connection({ test_level: "permissions" });
3251
- if (!authCheck.success) {
3252
- // STOP! Fix authentication first
3253
- return authenticationError(authCheck.error);
3254
- }
3255
-
3256
- // 2. MANDATORY: Discovery before creation
3257
- const discovery = await snow_find_artifact({
3258
- query: "your objective",
3259
- type: "widget|flow|script|any"
3260
- });
3261
-
3262
- // 3. MANDATORY: Real ServiceNow deployment
3263
- const deployment = await snow_deploy({
3264
- type: "widget|application", // Note: flow removed in v1.4.0+
3265
- config: { /* your config */ },
3266
- auto_update_set: true // Always track changes
3267
- });
3268
-
3269
- // 4. MANDATORY: Track in Update Set
3270
- await snow_update_set_add_artifact({
3271
- type: deployment.type,
3272
- sys_id: deployment.result.sys_id,
3273
- name: deployment.result.name
3274
- });
3275
- \`\`\`
3276
-
3277
- ### 🚫 FORBIDDEN ACTIONS
3278
-
3279
- **THESE ACTIONS ARE BANNED - NEVER DO THESE:**
3280
-
3281
- ❌ **Creating local files** without MCP check first
3282
- ❌ **Generating mock data** instead of using MCP tools
3283
- ❌ **Working in "offline mode"** when ServiceNow is available
3284
- ❌ **Skipping authentication validation**
3285
- ❌ **Planning mode** without trying MCP tools first
3286
-
3287
- ### ✅ CORRECT: MCP-First Decision Tree
3288
-
3289
- \`\`\`
3290
- User Request → ALWAYS START HERE:
3291
-
3292
- 1. snow_validate_live_connection()
3293
-
3294
- SUCCESS? → Continue to Step 2
3295
-
3296
- FAILURE? → Fix auth: snow_auth_diagnostics()
3297
- Then guide user: "snow-flow auth login"
3298
- STOP until auth works
3299
-
3300
- 2. snow_find_artifact() // Check if exists
3301
-
3302
- FOUND? → Ask: "Reuse existing or create new?"
3303
-
3304
- NOT FOUND? → Continue to Step 3
3305
-
3306
- 3. snow_deploy() // Real deployment to ServiceNow
3307
-
3308
- SUCCESS? → Step 4: Track in Update Set
3309
-
3310
- FAILURE? → Use fallback strategies
3311
-
3312
- 4. snow_update_set_add_artifact() // Always track
3313
-
3314
- DONE! ✅
3315
- \`\`\`
3316
-
3317
- ## 🚀 Snow-Flow Swarm Command - MCP-Orchestrated Multi-Agent Intelligence
3318
-
3319
- **The Swarm system is MCP-native and ALWAYS uses ServiceNow tools first!**
3320
-
3321
- ### 🧠 Queen Agent with Parallel Execution (v1.4.0+)
3322
- - Automatically spawns 6+ specialized agents for widget development
3323
- - Achieves proven 2.8x speedup through intelligent parallel execution
3324
- - All agents coordinate through Snow-Flow's memory system
3325
- - Every agent uses MCP tools directly - no offline mode
3326
-
3327
- ### Swarm Command Examples
3328
- \`\`\`bash
3329
- # Simple widget creation
3330
- snow-flow swarm "create incident dashboard widget"
3331
-
3332
- # Complex development
3333
- snow-flow swarm "build employee onboarding portal with approval workflows"
3334
-
3335
- # With specific options
3336
- snow-flow swarm "create service catalog item" --no-auto-deploy --monitor
3337
- \`\`\`
3338
-
3339
- ## 🛠️ Complete ServiceNow MCP Tools Reference
3340
-
3341
- ### Discovery & Search Tools
3342
- \`\`\`javascript
3343
- // Find any ServiceNow artifact using natural language
3344
- snow_find_artifact({
3345
- query: "the widget that shows incidents on homepage",
3346
- type: "widget" // or "flow", "script", "application", "any"
3347
- });
3348
-
3349
- // Search catalog items with fuzzy matching
3350
- snow_catalog_item_search({
3351
- query: "laptop",
3352
- fuzzy_match: true, // Finds variations: notebook, MacBook, etc.
3353
- include_variables: true // Include catalog variables
3354
- });
3355
-
3356
- // Comprehensive search across all tables
3357
- snow_comprehensive_search({
3358
- query: "approval",
3359
- include_inactive: false
3360
- });
3361
- \`\`\`
3362
-
3363
- ### Deployment Tools
3364
- \`\`\`javascript
3365
- // Universal deployment tool
3366
- snow_deploy({
3367
- type: "widget",
3368
- config: {
3369
- name: "Incident Dashboard",
3370
- template: "<html>...</html>",
3371
- css: "/* styles */",
3372
- server_script: "// server code",
3373
- client_script: "// client code"
3374
- },
3375
- auto_update_set: true
3376
- });
3377
-
3378
- // Bulk deployment
3379
- snow_bulk_deploy({
3380
- artifacts: [...],
3381
- transaction_mode: true,
3382
- rollback_on_error: true
3383
- });
3384
- \`\`\`
3385
-
3386
- ### Update Set Management
3387
- \`\`\`javascript
3388
- // Ensure active Update Set
3389
- snow_ensure_active_update_set({
3390
- context: "Widget development"
3391
- });
3392
-
3393
- // Track artifacts
3394
- snow_update_set_add_artifact({
3395
- type: "widget",
3396
- sys_id: "abc123",
3397
- name: "My Widget"
3398
- });
3399
-
3400
- // Preview changes
3401
- snow_update_set_preview({
3402
- update_set_id: "current"
3403
- });
3404
- \`\`\`
3405
-
3406
- ### Testing Tools
3407
- \`\`\`javascript
3408
- // Test flows with mock data
3409
- snow_test_flow_with_mock({
3410
- flow_id: "equipment_provisioning_flow",
3411
- create_test_user: true,
3412
- mock_catalog_items: true,
3413
- simulate_approvals: true,
3414
- cleanup_after_test: true
3415
- });
3416
-
3417
- // Link catalog to flow
3418
- snow_link_catalog_to_flow({
3419
- catalog_item_id: "iPhone 6S",
3420
- flow_id: "mobile_provisioning_flow",
3421
- test_link: true
3422
- });
3423
- \`\`\`
3424
-
3425
- ## 📋 Essential Patterns
3426
-
3427
- ### Authentication Handling
3428
- \`\`\`javascript
3429
- // Always handle auth failures gracefully
3430
- if (error.includes('401') || error.includes('403')) {
3431
- // Guide user to fix authentication
3432
- console.log('Run: snow-flow auth login');
3433
- console.log('Check .env file for credentials');
3434
- // STOP - don't continue without auth
3435
- }
3436
- \`\`\`
3437
-
3438
- ### Error Recovery
3439
- \`\`\`javascript
3440
- // Implement fallback strategies
3441
- if (deployment.failed) {
3442
- // Try global scope
3443
- const globalAttempt = await snow_deploy({
3444
- ...config,
3445
- scope_preference: 'global'
3446
- });
3447
-
3448
- if (globalAttempt.failed) {
3449
- // Provide manual instructions
3450
- return createManualStepsGuide(config, error);
3451
- }
3452
- }
3453
- \`\`\`
3454
-
3455
- ## 🔧 Configuration
3456
-
3457
- ### Build Commands
3458
- - \`npm run build\`: Build the project
3459
- - \`npm run test\`: Run the full test suite
3460
- - \`npm run lint\`: Run ESLint and format checks
3461
- - \`npm run typecheck\`: Run TypeScript type checking
3462
-
3463
- ### Snow-Flow Commands
3464
- - \`snow-flow init\`: Initialize project with MCP servers and SPARC environment
3465
- - \`snow-flow auth login\`: Authenticate with ServiceNow
3466
- - \`snow-flow swarm "<objective>"\`: Execute multi-agent development
3467
- - \`snow-flow mcp start\`: Start MCP servers manually
3468
-
3469
- ### Environment Setup
3470
- \`\`\`bash
3471
- # .env file
3472
- SNOW_INSTANCE=dev123456
3473
- SNOW_CLIENT_ID=your_oauth_client_id
3474
- SNOW_CLIENT_SECRET=your_oauth_client_secret
3475
- \`\`\`
3476
-
3477
- ## 💡 Best Practices
3478
-
3479
- ### DO's
3480
- ✅ Always use \`snow_validate_live_connection()\` first
3481
- ✅ Check for existing artifacts with \`snow_find_artifact()\`
3482
- ✅ Use Update Sets for all changes
3483
- ✅ Test with mock data before production
3484
- ✅ Handle errors gracefully with fallbacks
3485
-
3486
- ### DON'Ts
3487
- ❌ Don't create local files first
3488
- ❌ Don't skip authentication
3489
- ❌ Don't hardcode sys_ids or credentials
3490
- ❌ Don't work in offline mode
3491
- ❌ Don't deploy without testing
3492
-
3493
- ## 🎯 Quick Start
3494
- 1. \`snow-flow init\` - Initialize project with MCP servers and SPARC environment
3495
- 2. Configure ServiceNow credentials in .env file
3496
- 3. \`snow-flow auth login\` - Authenticate with ServiceNow
3497
- 4. \`snow-flow swarm "create a widget for incident management"\` - Everything automatic!
3498
-
3499
- For full documentation, visit: https://github.com/groeimetai/snow-flow
3500
- `;
3501
- const claudeMdPath = join(targetDir, 'CLAUDE.md');
3502
- if (force || !existsSync(claudeMdPath)) {
3503
- await fs.writeFile(claudeMdPath, claudeMdFallback);
3504
- }
3505
- }
3506
- }
3507
-
3508
- async function createEnvFile(targetDir: string, force: boolean = false) {
3509
- const envContent = `# ServiceNow Configuration
3510
- # ===========================================
3511
-
3512
- # ServiceNow Instance URL (without https://)
3513
- # Example: dev12345.service-now.com
3514
- SNOW_INSTANCE=your-instance.service-now.com
3515
-
3516
- # ===========================================
3517
- # OAuth Authentication (Required)
3518
- # ===========================================
3519
- # Snow-Flow uses OAuth for secure authentication to ServiceNow
3520
- #
3521
- # How to set up OAuth in ServiceNow:
3522
- # 1. Navigate to: System OAuth > Application Registry
3523
- # 2. Click "New" > "Create an OAuth API endpoint for external clients"
3524
- # 3. Fill in:
3525
- # - Name: Snow-Flow Development
3526
- # - Client ID: (will be auto-generated)
3527
- # - Client Secret: (set your own or auto-generate)
3528
- # 4. Copy the Client ID and Secret below:
3529
-
3530
- # OAuth Client ID from ServiceNow Application Registry
3531
- SNOW_CLIENT_ID=your-oauth-client-id
3532
-
3533
- # OAuth Client Secret from ServiceNow Application Registry
3534
- SNOW_CLIENT_SECRET=your-oauth-client-secret
3535
-
3536
- # ===========================================
3537
- # Legacy Username/Password (Not Recommended)
3538
- # ===========================================
3539
- # These fields are kept for backwards compatibility but are not used
3540
- # Snow-Flow requires OAuth authentication for security
3541
- # SNOW_USERNAME=not-used
3542
- # SNOW_PASSWORD=not-used
3543
-
3544
- # Optional: Additional Configuration
3545
- # SNOW_REDIRECT_URI=http://\${SNOW_REDIRECT_HOST:-localhost}:\${SNOW_REDIRECT_PORT:-3000}/callback
3546
-
3547
- # ===========================================
3548
- # Snow-Flow Configuration
3549
- # ===========================================
3550
-
3551
- # Enable debug logging (true/false)
3552
- SNOW_FLOW_DEBUG=false
3553
-
3554
- # Default coordination strategy
3555
- SNOW_FLOW_STRATEGY=development
3556
-
3557
- # Maximum number of agents
3558
- SNOW_FLOW_MAX_AGENTS=5
3559
-
3560
- # Claude Code timeout configuration (in minutes)
3561
- # Set to 0 to disable timeout (infinite execution time)
3562
- # Default: 60 minutes
3563
- SNOW_FLOW_TIMEOUT_MINUTES=0
3564
-
3565
- # ===========================================
3566
- # Deployment Timeout Configuration
3567
- # ===========================================
3568
-
3569
- # ServiceNow API timeout for regular operations (milliseconds)
3570
- # Default: 60000 (60 seconds)
3571
- SNOW_REQUEST_TIMEOUT=60000
3572
-
3573
- # ServiceNow API timeout for DEPLOYMENT operations (milliseconds)
3574
- # Deployments need more time for complex widgets
3575
- # Default: 300000 (5 minutes)
3576
- SNOW_DEPLOYMENT_TIMEOUT=300000
3577
-
3578
- # MCP transport timeout for deployment operations (milliseconds)
3579
- # Should be higher than SNOW_DEPLOYMENT_TIMEOUT
3580
- # Default: 360000 (6 minutes)
3581
- MCP_DEPLOYMENT_TIMEOUT=360000
3582
-
3583
- # ===========================================
3584
- # How to Set Up ServiceNow OAuth
3585
- # ===========================================
3586
- # 1. Log into your ServiceNow instance as admin
3587
- # 2. Navigate to: System OAuth > Application Registry
3588
- # 3. Click "New" > "Create an OAuth application"
3589
- # 4. Fill in:
3590
- # - Name: Snow-Flow Development
3591
- # - Client ID: (will be generated)
3592
- # - Client Secret: (will be generated)
3593
- # - Redirect URL: http://\${SNOW_REDIRECT_HOST:-localhost}:\${SNOW_REDIRECT_PORT:-3000}/callback
3594
- # - Grant Type: Authorization Code
3595
- # 5. Copy the Client ID and Client Secret to this file
3596
- # 6. Run: snow-flow auth login
3597
- `;
3598
-
3599
- const envFilePath = join(targetDir, '.env');
3600
-
3601
- // Check if .env already exists
3602
- try {
3603
- await fs.access(envFilePath);
3604
- if (force) {
3605
- console.log('⚠️ .env file already exists, overwriting with --force flag');
3606
- await fs.writeFile(envFilePath, envContent);
3607
- console.log('✅ .env file overwritten successfully');
3608
- } else {
3609
- console.log('⚠️ .env file already exists, creating .env.example template instead');
3610
- console.log('📝 To overwrite: use --force flag or delete existing .env file');
3611
- await fs.writeFile(join(targetDir, '.env.example'), envContent);
3612
- console.log('✅ .env.example template created');
3613
- }
3614
- } catch {
3615
- // .env doesn't exist, create it
3616
- console.log('📄 Creating new .env file...');
3617
- await fs.writeFile(envFilePath, envContent);
3618
- console.log('✅ .env file created successfully');
3619
- }
3620
- }
3621
-
3622
- async function appendToEnvFile(targetDir: string, content: string) {
3623
- const envFilePath = join(targetDir, '.env');
3624
- await fs.appendFile(envFilePath, content);
3625
- }
3626
-
3627
- async function checkNeo4jAvailability(): Promise<boolean> {
3628
- const { execSync } = require('child_process');
3629
-
3630
- try {
3631
- // Check if Neo4j is installed
3632
- execSync('which neo4j', { stdio: 'pipe' });
3633
-
3634
- // Check if Neo4j is running
3635
- try {
3636
- execSync('neo4j status', { stdio: 'pipe' });
3637
- return true;
3638
- } catch {
3639
- // Neo4j is installed but not running
3640
- console.log('ℹ️ Neo4j is installed but not running. Start with: neo4j start');
3641
- return false;
3642
- }
3643
- } catch {
3644
- // Neo4j is not installed
3645
- return false;
3646
- }
3647
- }
3648
-
3649
- async function createMCPConfig(targetDir: string, force: boolean = false) {
3650
- // Determine the snow-flow installation directory
3651
- let snowFlowRoot: string;
3652
-
3653
- // Check if we're in a global npm installation
3654
- const isGlobalInstall = __dirname.includes('node_modules/snow-flow') ||
3655
- __dirname.includes('node_modules/.pnpm') ||
3656
- __dirname.includes('npm/snow-flow');
3657
-
3658
- if (isGlobalInstall) {
3659
- // For global installs, find the snow-flow package root
3660
- const parts = __dirname.split(/node_modules[\/\\]/);
3661
- snowFlowRoot = parts[0] + 'node_modules/snow-flow';
3662
- } else {
3663
- // For local development or local install
3664
- // Find the snow-flow project root by looking for the parent directory with package.json
3665
- let currentDir = __dirname;
3666
- while (currentDir !== '/') {
3667
- try {
3668
- const packageJsonPath = join(currentDir, 'package.json');
3669
- const packageJson = JSON.parse(await fs.readFile(packageJsonPath, 'utf-8'));
3670
- if (packageJson.name === 'snow-flow') {
3671
- snowFlowRoot = currentDir;
3672
- break;
3673
- }
3674
- } catch {
3675
- // Continue searching up
3676
- }
3677
- currentDir = dirname(currentDir);
3678
- }
3679
- if (!snowFlowRoot) {
3680
- throw new Error('Could not find snow-flow project root');
3681
- }
3682
- }
3683
-
3684
- // Read the template file
3685
- const templatePath = join(snowFlowRoot, '.mcp.json.template');
3686
- let templateContent: string;
3687
-
3688
- try {
3689
- templateContent = await fs.readFile(templatePath, 'utf-8');
3690
- } catch (error) {
3691
- console.error('❌ Could not find .mcp.json.template file');
3692
- throw error;
3693
- }
3694
-
3695
- // Replace placeholders in template
3696
- const distPath = join(snowFlowRoot, 'dist');
3697
- const mcpConfigContent = templateContent
3698
- .replace(/{{PROJECT_ROOT}}/g, snowFlowRoot)
3699
- .replace(/{{SNOW_INSTANCE}}/g, '${SNOW_INSTANCE}')
3700
- .replace(/{{SNOW_CLIENT_ID}}/g, '${SNOW_CLIENT_ID}')
3701
- .replace(/{{SNOW_CLIENT_SECRET}}/g, '${SNOW_CLIENT_SECRET}')
3702
- .replace(/{{SNOW_DEPLOYMENT_TIMEOUT}}/g, '${SNOW_DEPLOYMENT_TIMEOUT}')
3703
- .replace(/{{MCP_DEPLOYMENT_TIMEOUT}}/g, '${MCP_DEPLOYMENT_TIMEOUT}')
3704
- .replace(/{{NEO4J_URI}}/g, '${NEO4J_URI}')
3705
- .replace(/{{NEO4J_USER}}/g, '${NEO4J_USER}')
3706
- .replace(/{{NEO4J_PASSWORD}}/g, '${NEO4J_PASSWORD}')
3707
- .replace(/{{SNOW_FLOW_ENV}}/g, '${SNOW_FLOW_ENV}');
3708
-
3709
- // Parse to ensure it's valid JSON
3710
- const mcpConfig = JSON.parse(mcpConfigContent);
3711
-
3712
- // Update the structure to use mcpServers instead of servers
3713
- const finalConfig = {
3714
- "mcpServers": mcpConfig.servers
3715
- };
3716
-
3717
- // Create .mcp.json in project root for Claude Code discovery
3718
- const mcpConfigPath = join(targetDir, '.mcp.json');
3719
- try {
3720
- await fs.access(mcpConfigPath);
3721
- if (force) {
3722
- console.log('⚠️ .mcp.json already exists, overwriting with --force flag');
3723
- await fs.writeFile(mcpConfigPath, JSON.stringify(finalConfig, null, 2));
3724
- } else {
3725
- console.log('⚠️ .mcp.json already exists, skipping (use --force to overwrite)');
3726
- }
3727
- } catch {
3728
- await fs.writeFile(mcpConfigPath, JSON.stringify(finalConfig, null, 2));
3729
- }
3730
-
3731
- // Also create legacy config in .claude for backward compatibility
3732
- const legacyConfigPath = join(targetDir, '.claude/mcp-config.json');
3733
- await fs.writeFile(legacyConfigPath, JSON.stringify(finalConfig, null, 2));
3734
-
3735
- // Create comprehensive Claude Code settings file
3736
- const claudeSettings = {
3737
- "enabledMcpjsonServers": [
3738
- "snow-flow",
3739
- "servicenow-deployment",
3740
- "servicenow-update-set",
3741
- "servicenow-intelligent",
3742
- "servicenow-memory",
3743
- "servicenow-operations",
3744
- "servicenow-platform-development",
3745
- "servicenow-integration",
3746
- "servicenow-automation",
3747
- "servicenow-security-compliance",
3748
- "servicenow-reporting-analytics"
3749
- ],
3750
- "permissions": {
3751
- "allow": [
3752
- "Bash(*)",
3753
- "Read(*)",
3754
- "Write(*)",
3755
- "Edit(*)",
3756
- "MultiEdit(*)",
3757
- "Glob(*)",
3758
- "Grep(*)",
3759
- "LS(*)",
3760
- "NotebookEdit(*)",
3761
- "NotebookRead(*)",
3762
- "WebFetch(*)",
3763
- "WebSearch(*)",
3764
- "TodoRead",
3765
- "TodoWrite",
3766
- "Task(*)",
3767
- "ListMcpResourcesTool",
3768
- "ReadMcpResourceTool",
3769
- "mcp__servicenow-*",
3770
- "mcp__snow-flow__*"
3771
- ],
3772
- "deny": []
3773
- },
3774
- "env": {
3775
- "BASH_DEFAULT_TIMEOUT_MS": "0",
3776
- "BASH_MAX_TIMEOUT_MS": "0",
3777
- "BASH_MAX_OUTPUT_LENGTH": "500000",
3778
- "CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR": "true",
3779
- "MAX_THINKING_TOKENS": "50000",
3780
- "MCP_TIMEOUT": "0",
3781
- "MCP_TOOL_TIMEOUT": "0",
3782
- "DISABLE_COST_WARNINGS": "1",
3783
- "DISABLE_NON_ESSENTIAL_MODEL_CALLS": "0",
3784
- "CLAUDE_CODE_MAX_OUTPUT_TOKENS": "8192",
3785
- "CLAUDE_CODE_TIMEOUT": "0",
3786
- "CLAUDE_CODE_SESSION_TIMEOUT": "0",
3787
- "CLAUDE_CODE_EXECUTION_TIMEOUT": "0"
3788
- },
3789
- "cleanupPeriodDays": 90,
3790
- "includeCoAuthoredBy": true,
3791
- "automation": {
3792
- "enabled": true,
3793
- "defaultTimeout": 300000,
3794
- "maxRetries": 3,
3795
- "retryBackoff": 2000,
3796
- "parallelExecution": true,
3797
- "batchOperations": true,
3798
- "autoSaveMemory": true,
3799
- "autoCommit": false
3800
- },
3801
- "snowFlow": {
3802
- "version": "1.4.35",
3803
- "swarmDefaults": {
3804
- "maxAgents": 10,
3805
- "timeout": 0,
3806
- "parallel": true,
3807
- "monitor": true,
3808
- "outputFormat": "json"
3809
- },
3810
- "sparcDefaults": {
3811
- "timeout": 0,
3812
- "parallel": true,
3813
- "batch": true,
3814
- "memoryKey": "sparc_session"
3815
- },
3816
- "memoryDefaults": {
3817
- "maxSize": "5GB",
3818
- "autoCompress": true,
3819
- "autoCleanup": true,
3820
- "indexingEnabled": true,
3821
- "persistenceEnabled": true
3822
- }
3823
- },
3824
- "mcpServers": {
3825
- "servicenow": {
3826
- "command": "node",
3827
- "args": ["dist/mcp/start-servicenow-mcp.js"],
3828
- "env": {
3829
- "SNOW_INSTANCE": "${SNOW_INSTANCE}",
3830
- "SNOW_CLIENT_ID": "${SNOW_CLIENT_ID}",
3831
- "SNOW_CLIENT_SECRET": "${SNOW_CLIENT_SECRET}"
3832
- }
3833
- }
3834
- }
3835
- };
3836
-
3837
- const claudeSettingsPath = join(targetDir, '.claude/settings.json');
3838
- await fs.writeFile(claudeSettingsPath, JSON.stringify(claudeSettings, null, 2));
3839
- }
3840
-
3841
- // Direct widget creation command
3842
- program
3843
- .command('create-widget [type]')
3844
- .description('Create a ServiceNow widget using templates')
3845
- .action(async (type: string = 'incident-management') => {
3846
- try {
3847
- // Use generic artifact deployment instead
3848
- console.log('🎯 Creating widget using template system...');
3849
- console.log('✨ Use: snow-flow deploy-artifact -t widget -c <config-file>');
3850
- console.log('📝 Or use: snow-flow swarm "create a widget for incident management"');
3851
- } catch (error) {
3852
- console.error('❌ Error creating widget:', error);
3853
- }
3854
- });
3855
-
3856
- // MCP Server command with subcommands
3857
- program
3858
- .command('mcp <action>')
3859
- .description('Manage ServiceNow MCP servers for Claude Code integration')
3860
- .option('--server <name>', 'Specific server name to manage')
3861
- .option('--port <port>', 'Port for MCP server (default: auto)')
3862
- .option('--host <host>', 'Host for MCP server (default: localhost)')
3863
- .action(async (action: string, options) => {
3864
- const { MCPServerManager } = await import('./utils/mcp-server-manager.js');
3865
- const manager = new MCPServerManager();
3866
-
3867
- try {
3868
- await manager.initialize();
3869
-
3870
- switch (action) {
3871
- case 'start':
3872
- await handleMCPStart(manager, options);
3873
- break;
3874
- case 'stop':
3875
- await handleMCPStop(manager, options);
3876
- break;
3877
- case 'restart':
3878
- await handleMCPRestart(manager, options);
3879
- break;
3880
- case 'status':
3881
- await handleMCPStatus(manager, options);
3882
- break;
3883
- case 'logs':
3884
- await handleMCPLogs(manager, options);
3885
- break;
3886
- case 'list':
3887
- await handleMCPList(manager, options);
3888
- break;
3889
- case 'debug':
3890
- await handleMCPDebug(options);
3891
- break;
3892
- default:
3893
- console.error(`❌ Unknown action: ${action}`);
3894
- console.log('Available actions: start, stop, restart, status, logs, list, debug');
3895
- process.exit(1);
3896
- }
3897
- } catch (error) {
3898
- console.error('❌ MCP operation failed:', error instanceof Error ? error.message : String(error));
3899
- process.exit(1);
3900
- }
3901
- });
3902
-
3903
- // MCP action handlers
3904
- async function handleMCPStart(manager: any, options: any): Promise<void> {
3905
- console.log('🚀 Starting ServiceNow MCP Servers...');
3906
-
3907
- if (options.server) {
3908
- console.log(`📡 Starting server: ${options.server}`);
3909
- const success = await manager.startServer(options.server);
3910
- if (success) {
3911
- console.log(`✅ Server '${options.server}' started successfully`);
3912
- } else {
3913
- console.log(`❌ Failed to start server '${options.server}'`);
3914
- process.exit(1);
3915
- }
3916
- } else {
3917
- console.log('📡 Starting all configured MCP servers...');
3918
- await manager.startAllServers();
3919
-
3920
- const status = manager.getServerStatus();
3921
- const running = status.filter((s: any) => s.status === 'running').length;
3922
- const total = status.length;
3923
-
3924
- console.log(`\n✅ Started ${running}/${total} MCP servers`);
3925
-
3926
- if (running === total) {
3927
- console.log('🎉 All MCP servers are now running and available in Claude Code!');
3928
- console.log('\n📋 Next steps:');
3929
- console.log(' 1. Open Claude Code');
3930
- console.log(' 2. MCP tools will be automatically available');
3931
- console.log(' 3. Use snow_deploy_widget, snow_deploy_flow, etc.');
3932
- } else {
3933
- console.log('⚠️ Some servers failed to start. Check logs with: snow-flow mcp logs');
3934
- }
3935
- }
3936
- }
3937
-
3938
- async function handleMCPStop(manager: any, options: any): Promise<void> {
3939
- if (options.server) {
3940
- console.log(`🛑 Stopping server: ${options.server}`);
3941
- const success = await manager.stopServer(options.server);
3942
- if (success) {
3943
- console.log(`✅ Server '${options.server}' stopped successfully`);
3944
- } else {
3945
- console.log(`❌ Failed to stop server '${options.server}'`);
3946
- process.exit(1);
3947
- }
3948
- } else {
3949
- console.log('🛑 Stopping all MCP servers...');
3950
- await manager.stopAllServers();
3951
- console.log('✅ All MCP servers stopped');
3952
- }
3953
- }
3954
-
3955
- async function handleMCPRestart(manager: any, options: any): Promise<void> {
3956
- if (options.server) {
3957
- console.log(`🔄 Restarting server: ${options.server}`);
3958
- await manager.stopServer(options.server);
3959
- const success = await manager.startServer(options.server);
3960
- if (success) {
3961
- console.log(`✅ Server '${options.server}' restarted successfully`);
3962
- } else {
3963
- console.log(`❌ Failed to restart server '${options.server}'`);
3964
- process.exit(1);
3965
- }
3966
- } else {
3967
- console.log('🔄 Restarting all MCP servers...');
3968
- await manager.stopAllServers();
3969
- await manager.startAllServers();
3970
-
3971
- const running = manager.getRunningServersCount();
3972
- const total = manager.getServerStatus().length;
3973
- console.log(`✅ Restarted ${running}/${total} MCP servers`);
3974
- }
3975
- }
3976
-
3977
- async function handleMCPStatus(manager: any, options: any): Promise<void> {
3978
- const servers = manager.getServerStatus();
3979
-
3980
- console.log('\n📊 MCP Server Status');
3981
- console.log('═'.repeat(80));
3982
-
3983
- if (servers.length === 0) {
3984
- console.log('No MCP servers configured');
3985
- return;
3986
- }
3987
-
3988
- servers.forEach((server: any) => {
3989
- const statusIcon = server.status === 'running' ? '✅' :
3990
- server.status === 'starting' ? '🔄' :
3991
- server.status === 'error' ? '❌' : '⭕';
3992
-
3993
- console.log(`${statusIcon} ${server.name}`);
3994
- console.log(` Status: ${server.status}`);
3995
- console.log(` Script: ${server.script}`);
3996
-
3997
- if (server.pid) {
3998
- console.log(` PID: ${server.pid}`);
3999
- }
4000
-
4001
- if (server.startedAt) {
4002
- console.log(` Started: ${server.startedAt.toLocaleString()}`);
4003
- }
4004
-
4005
- if (server.lastError) {
4006
- console.log(` Last Error: ${server.lastError}`);
4007
- }
4008
-
4009
- console.log('');
4010
- });
4011
-
4012
- const running = servers.filter((s: any) => s.status === 'running').length;
4013
- const total = servers.length;
4014
-
4015
- console.log(`📈 Summary: ${running}/${total} servers running`);
4016
-
4017
- if (running === total) {
4018
- console.log('🎉 All MCP servers are operational and available in Claude Code!');
4019
- } else if (running > 0) {
4020
- console.log('⚠️ Some servers are not running. Use "snow-flow mcp start" to start them.');
4021
- } else {
4022
- console.log('💡 No servers running. Use "snow-flow mcp start" to start all servers.');
4023
- }
4024
- }
4025
-
4026
- async function handleMCPLogs(manager: any, options: any): Promise<void> {
4027
- const { join } = require('path');
4028
- const { promises: fs } = require('fs');
4029
-
4030
- const logDir = join(process.env.SNOW_FLOW_HOME || join(os.homedir(), '.snow-flow'), 'logs');
4031
-
4032
- try {
4033
- const logFiles = await fs.readdir(logDir);
4034
-
4035
- if (options.server) {
4036
- const serverLogFile = `${options.server.replace(/\\s+/g, '_').toLowerCase()}.log`;
4037
- if (logFiles.includes(serverLogFile)) {
4038
- console.log(`📄 Logs for ${options.server}:`);
4039
- console.log('═'.repeat(80));
4040
- const logContent = await fs.readFile(join(logDir, serverLogFile), 'utf-8');
4041
- console.log(logContent);
4042
- } else {
4043
- console.log(`❌ No logs found for server '${options.server}'`);
4044
- }
4045
- } else {
4046
- console.log('📄 Available log files:');
4047
- logFiles.forEach((file: string) => {
4048
- console.log(` - ${file}`);
4049
- });
4050
- console.log('\\n💡 Use --server <name> to view specific server logs');
4051
- }
4052
- } catch (error) {
4053
- console.log('📄 No log files found');
4054
- }
4055
- }
4056
-
4057
- async function handleMCPList(manager: any, options: any): Promise<void> {
4058
- const servers = manager.getServerStatus();
4059
-
4060
- console.log('\n📋 Configured MCP Servers');
4061
- console.log('═'.repeat(80));
4062
-
4063
- if (servers.length === 0) {
4064
- console.log('No MCP servers configured');
4065
- console.log('💡 Run "snow-flow init" to configure default MCP servers');
4066
- return;
4067
- }
4068
-
4069
- servers.forEach((server: any, index: number) => {
4070
- console.log(`${index + 1}. ${server.name}`);
4071
- console.log(` Script: ${server.script}`);
4072
- console.log(` Status: ${server.status}`);
4073
- console.log('');
4074
- });
4075
- }
4076
-
4077
- async function handleMCPDebug(options: any): Promise<void> {
4078
- console.log('🔍 MCP Debug Information');
4079
- console.log('========================\n');
4080
-
4081
- const { existsSync, readFileSync } = require('fs');
4082
- const { join, resolve } = require('path');
4083
-
4084
- // Check .mcp.json
4085
- const mcpJsonPath = join(process.cwd(), '.mcp.json');
4086
- console.log('📄 .mcp.json:');
4087
- if (existsSync(mcpJsonPath)) {
4088
- console.log(` ✅ Found at: ${mcpJsonPath}`);
4089
- try {
4090
- const mcpConfig = JSON.parse(readFileSync(mcpJsonPath, 'utf8'));
4091
- console.log(` 📊 Servers configured: ${Object.keys(mcpConfig.servers || {}).length}`);
4092
-
4093
- // Check if paths exist
4094
- for (const [name, config] of Object.entries(mcpConfig.servers || {})) {
4095
- const serverConfig = config as any;
4096
- if (serverConfig.args && serverConfig.args[0]) {
4097
- const scriptPath = serverConfig.args[0];
4098
- const exists = existsSync(scriptPath);
4099
- console.log(` ${exists ? '✅' : '❌'} ${name}: ${scriptPath}`);
4100
- }
4101
- }
4102
- } catch (error) {
4103
- console.log(` ❌ Error reading: ${error}`);
4104
- }
4105
- } else {
4106
- console.log(` ❌ Not found at: ${mcpJsonPath}`);
4107
- }
4108
-
4109
- // Check .claude/settings.json
4110
- console.log('\n📄 .claude/settings.json:');
4111
- const claudeSettingsPath = join(process.cwd(), '.claude/settings.json');
4112
- if (existsSync(claudeSettingsPath)) {
4113
- console.log(` ✅ Found at: ${claudeSettingsPath}`);
4114
- try {
4115
- const settings = JSON.parse(readFileSync(claudeSettingsPath, 'utf8'));
4116
- const enabledServers = settings.enabledMcpjsonServers || [];
4117
- console.log(` 📊 Enabled servers: ${enabledServers.length}`);
4118
- enabledServers.forEach((server: string) => {
4119
- console.log(` - ${server}`);
4120
- });
4121
- } catch (error) {
4122
- console.log(` ❌ Error reading: ${error}`);
4123
- }
4124
- } else {
4125
- console.log(` ❌ Not found at: ${claudeSettingsPath}`);
4126
- }
4127
-
4128
- // Check environment
4129
- console.log('\n🔐 Environment:');
4130
- console.log(` SNOW_INSTANCE: ${process.env.SNOW_INSTANCE ? '✅ Set' : '❌ Not set'}`);
4131
- console.log(` SNOW_CLIENT_ID: ${process.env.SNOW_CLIENT_ID ? '✅ Set' : '❌ Not set'}`);
4132
- console.log(` SNOW_CLIENT_SECRET: ${process.env.SNOW_CLIENT_SECRET ? '✅ Set' : '❌ Not set'}`);
4133
-
4134
- // Check Claude Code
4135
- console.log('\n🤖 Claude Code:');
4136
- const { execSync } = require('child_process');
4137
- try {
4138
- execSync('which claude', { stdio: 'ignore' });
4139
- console.log(' ✅ Claude Code CLI found');
4140
- } catch {
4141
- console.log(' ❌ Claude Code CLI not found in PATH');
4142
- }
4143
-
4144
- console.log('\n💡 Tips:');
4145
- console.log(' 1. Make sure Claude Code is started in this directory');
4146
- console.log(' 2. Check if MCP servers appear with /mcp command in Claude Code');
4147
- console.log(' 3. Approve MCP servers when prompted by Claude Code');
4148
- console.log(' 4. Ensure .env file has valid ServiceNow credentials');
4149
- }
4150
-
4151
-
4152
- // SPARC Detailed Help Command
4153
- program
4154
- .command('sparc-help')
4155
- .description('Show detailed SPARC help information')
4156
- .action(async () => {
4157
- try {
4158
- const { displayTeamHelp } = await import('./sparc/sparc-help.js');
4159
- displayTeamHelp();
4160
- } catch (error) {
4161
- console.error('❌ Failed to load SPARC help:', error instanceof Error ? error.message : String(error));
4162
- }
4163
- });
4164
-
4165
- // ===================================================
4166
- // 👑 QUEEN AGENT COMMANDS - Elegant Orchestration
4167
- // ===================================================
4168
-
4169
- /**
4170
- * Main Queen command - replaces complex swarm orchestration
4171
- * Simple, elegant, and intelligent ServiceNow objective execution
4172
- */
4173
- program
4174
- .command('queen <objective>')
4175
- .description('🐝 Execute ServiceNow objective with Queen Agent hive-mind intelligence')
4176
- .option('--learn', 'Enable enhanced learning from execution (default: true)', true)
4177
- .option('--no-learn', 'Disable learning')
4178
- .option('--debug', 'Enable debug mode for detailed insights')
4179
- .option('--dry-run', 'Preview execution plan without deployment')
4180
- .option('--memory-driven', 'Use memory for optimal workflow patterns')
4181
- .option('--monitor', 'Show real-time hive-mind monitoring')
4182
- .option('--type <type>', 'Hint at task type (widget, flow, app, integration)')
4183
- .action(async (objective: string, options) => {
4184
- // Check for flow deprecation first
4185
- checkFlowDeprecation('queen', objective);
4186
-
4187
- console.log(`\n👑 ServiceNow Queen Agent v${VERSION} - Hive-Mind Intelligence`);
4188
- console.log('🐝 Elegant orchestration replacing complex team coordination\n');
4189
-
4190
- try {
4191
- const { QueenIntegration } = await import('./examples/queen/integration-example.js');
4192
-
4193
- const queenIntegration = new QueenIntegration({
4194
- debugMode: options.debug || false
4195
- });
4196
-
4197
- if (options.dryRun) {
4198
- console.log('🔍 DRY RUN MODE - Analyzing objective...');
4199
- // TODO: Add dry run analysis
4200
- console.log(`📋 Objective: ${objective}`);
4201
- console.log('🎯 Queen would analyze, spawn agents, coordinate, and deploy');
4202
- return;
4203
- }
4204
-
4205
- console.log(`🎯 Queen analyzing objective: ${objective}`);
4206
-
4207
- const result = await queenIntegration.executeSwarmObjective(objective, {
4208
- learn: options.learn,
4209
- memoryDriven: options.memoryDriven,
4210
- monitor: options.monitor
4211
- });
4212
-
4213
- if (result.success) {
4214
- console.log('\n✅ Queen Agent completed objective successfully!');
4215
- console.log(`🐝 Hive-Mind coordination: ${result.queen_managed ? 'ACTIVE' : 'INACTIVE'}`);
4216
-
4217
- if (result.hive_mind_status) {
4218
- console.log(`👥 Active Agents: ${result.hive_mind_status.activeAgents}`);
4219
- console.log(`📋 Active Tasks: ${result.hive_mind_status.activeTasks}`);
4220
- console.log(`🧠 Learned Patterns: ${result.hive_mind_status.memoryStats.patterns}`);
4221
- }
4222
-
4223
- if (options.monitor) {
4224
- console.log('\n📊 HIVE-MIND MONITORING:');
4225
- queenIntegration.logHiveMindStatus();
4226
- }
4227
- } else {
4228
- console.error('\n❌ Queen Agent execution failed!');
4229
- if (result.fallback_required) {
4230
- console.log('🔄 Consider using traditional swarm command as fallback:');
4231
- console.log(` snow-flow swarm "${objective}"`);
4232
- }
4233
- process.exit(1);
4234
- }
4235
-
4236
- await queenIntegration.shutdown();
4237
-
4238
- } catch (error) {
4239
- console.error('\n💥 Queen Agent error:', (error as Error).message);
4240
- console.log('\n🔄 Fallback to traditional swarm:');
4241
- console.log(` snow-flow swarm "${objective}"`);
4242
- process.exit(1);
4243
- }
4244
- });
4245
-
4246
- /**
4247
- * Queen Memory Management
4248
- */
4249
- const queenMemory = program.command('queen-memory');
4250
- queenMemory.description('🧠 Manage Queen Agent hive-mind memory');
4251
-
4252
- queenMemory
4253
- .command('export [file]')
4254
- .description('Export Queen memory to file')
4255
- .action(async (file: string = 'queen-memory.json') => {
4256
- console.log(`\n🧠 Exporting Queen hive-mind memory to ${file}...`);
4257
-
4258
- try {
4259
- const { createServiceNowQueen } = await import('./queen/index.js');
4260
- const queen = createServiceNowQueen({ debugMode: true });
4261
-
4262
- const memoryData = queen.exportMemory();
4263
-
4264
- const { promises: fs } = await import('fs');
4265
- await fs.writeFile(file, memoryData, 'utf-8');
4266
-
4267
- console.log(`✅ Memory exported successfully to ${file}`);
4268
- console.log(`📊 Memory contains learned patterns and successful deployments`);
4269
-
4270
- await queen.shutdown();
4271
- } catch (error) {
4272
- console.error('❌ Memory export failed:', (error as Error).message);
4273
- process.exit(1);
4274
- }
4275
- });
4276
-
4277
- queenMemory
4278
- .command('import <file>')
4279
- .description('Import Queen memory from file')
4280
- .action(async (file: string) => {
4281
- console.log(`\n🧠 Importing Queen hive-mind memory from ${file}...`);
4282
-
4283
- try {
4284
- const { promises: fs } = await import('fs');
4285
- const memoryData = await fs.readFile(file, 'utf-8');
4286
-
4287
- const { createServiceNowQueen } = await import('./queen/index.js');
4288
- const queen = createServiceNowQueen({ debugMode: true });
4289
-
4290
- queen.importMemory(memoryData);
4291
-
4292
- console.log(`✅ Memory imported successfully from ${file}`);
4293
- console.log(`🧠 Queen now has access to previous learning patterns`);
4294
-
4295
- await queen.shutdown();
4296
- } catch (error) {
4297
- console.error('❌ Memory import failed:', (error as Error).message);
4298
- process.exit(1);
4299
- }
4300
- });
4301
-
4302
- queenMemory
4303
- .command('clear')
4304
- .description('Clear Queen memory (reset learning)')
4305
- .option('--confirm', 'Confirm memory clearing')
4306
- .action(async (options) => {
4307
- if (!options.confirm) {
4308
- console.log('\n⚠️ This will clear all Queen hive-mind learning!');
4309
- console.log('Use --confirm to proceed: snow-flow queen-memory clear --confirm');
4310
- return;
4311
- }
4312
-
4313
- console.log('\n🧠 Clearing Queen hive-mind memory...');
4314
-
4315
- try {
4316
- const { createServiceNowQueen } = await import('./queen/index.js');
4317
- const queen = createServiceNowQueen({ debugMode: true });
4318
-
4319
- queen.clearMemory();
4320
-
4321
- console.log('✅ Queen memory cleared successfully');
4322
- console.log('🔄 Queen will start fresh learning from next execution');
4323
-
4324
- await queen.shutdown();
4325
- } catch (error) {
4326
- console.error('❌ Memory clear failed:', (error as Error).message);
4327
- process.exit(1);
4328
- }
4329
- });
4330
-
4331
- /**
4332
- * Queen Status and Insights
4333
- */
4334
- program
4335
- .command('queen-status')
4336
- .description('📊 Show Queen Agent hive-mind status and insights')
4337
- .option('--detailed', 'Show detailed memory and learning statistics')
4338
- .action(async (options) => {
4339
- console.log(`\n👑 ServiceNow Queen Agent Status v${VERSION}`);
4340
-
4341
- try {
4342
- const { createServiceNowQueen } = await import('./queen/index.js');
4343
- const queen = createServiceNowQueen({ debugMode: true });
4344
-
4345
- const status = queen.getHiveMindStatus();
4346
-
4347
- console.log('\n🐝 HIVE-MIND STATUS 🐝');
4348
- console.log('═══════════════════════');
4349
- console.log(`📋 Active Tasks: ${status.activeTasks}`);
4350
- console.log(`👥 Active Agents: ${status.activeAgents}`);
4351
- console.log(`🧠 Learned Patterns: ${status.memoryStats.patterns}`);
4352
- console.log(`📚 Stored Artifacts: ${status.memoryStats.artifacts}`);
4353
- console.log(`💡 Learning Insights: ${status.memoryStats.learnings}`);
4354
-
4355
- if (status.factoryStats.agentTypeCounts) {
4356
- console.log('\n👥 AGENT BREAKDOWN:');
4357
- Object.entries(status.factoryStats.agentTypeCounts).forEach(([type, count]) => {
4358
- console.log(` ${type}: ${count}`);
4359
- });
4360
- }
4361
-
4362
- if (options.detailed) {
4363
- console.log('\n🔍 DETAILED MEMORY ANALYSIS:');
4364
- console.log(` Memory Size: ${status.memoryStats.totalSize || 'Unknown'}`);
4365
- console.log(` Success Rate: ${status.memoryStats.successRate || 'Unknown'}%`);
4366
- console.log(` Most Effective Pattern: ${status.memoryStats.bestPattern || 'Learning...'}`);
4367
- }
4368
-
4369
- console.log('═══════════════════════\n');
4370
-
4371
- await queen.shutdown();
4372
- } catch (error) {
4373
- console.error('❌ Status check failed:', (error as Error).message);
4374
- process.exit(1);
4375
- }
4376
- });
4377
-
4378
- program
4379
- .command('queen-insights')
4380
- .description('💡 Show Queen Agent learning insights and recommendations')
4381
- .action(async () => {
4382
- console.log(`\n💡 Queen Agent Learning Insights v${VERSION}`);
4383
-
4384
- try {
4385
- const { createServiceNowQueen } = await import('./queen/index.js');
4386
- const queen = createServiceNowQueen({ debugMode: true });
4387
-
4388
- const insights = queen.getLearningInsights();
4389
-
4390
- console.log('\n🧠 LEARNING INSIGHTS 🧠');
4391
- console.log('═══════════════════════');
4392
-
4393
- if (insights.successfulPatterns && insights.successfulPatterns.length > 0) {
4394
- console.log('\n✅ SUCCESSFUL PATTERNS:');
4395
- insights.successfulPatterns.forEach((pattern, idx) => {
4396
- console.log(` ${idx + 1}. ${pattern.description} (${pattern.successRate}% success)`);
4397
- });
4398
- } else {
4399
- console.log('\n📚 No patterns learned yet - execute objectives to build intelligence');
4400
- }
4401
-
4402
- if (insights.recommendations && insights.recommendations.length > 0) {
4403
- console.log('\n💡 RECOMMENDATIONS:');
4404
- insights.recommendations.forEach((rec, idx) => {
4405
- console.log(` ${idx + 1}. ${rec}`);
4406
- });
4407
- }
4408
-
4409
- if (insights.commonTasks && insights.commonTasks.length > 0) {
4410
- console.log('\n🎯 COMMON TASK TYPES:');
4411
- insights.commonTasks.forEach((task, idx) => {
4412
- console.log(` ${idx + 1}. ${task.type}: ${task.count} executions`);
4413
- });
4414
- }
4415
-
4416
- console.log('═══════════════════════\n');
4417
-
4418
- await queen.shutdown();
4419
- } catch (error) {
4420
- console.error('❌ Insights failed:', (error as Error).message);
4421
- process.exit(1);
4422
- }
4423
- });
4424
-
4425
- // ===================================================
4426
- // 🔄 BACKWARD COMPATIBILITY ENHANCEMENTS
4427
- // ===================================================
4428
-
4429
- /**
4430
- * Enhance existing swarm command with optional Queen intelligence
4431
- *
4432
- * Note: Users can use: snow-flow swarm "objective" --queen
4433
- * This will be implemented in a future version once the Queen system is stable.
4434
- */
4435
-
4436
- // ===================================================
4437
- // 🎯 INTEGRATE SNOW-FLOW HIVE-MIND SYSTEM
4438
- // ===================================================
4439
-
4440
-
4441
- // Note: The new integrated commands enhance the existing CLI with:
4442
- // - Advanced system status monitoring
4443
- // - Real-time monitoring dashboard
4444
- // - Persistent memory management
4445
- // - Configuration management
4446
- // - Performance analytics
4447
- // Comment out the line below to disable the integrated commands
4448
- // integrateSnowFlowCommands(program);
4449
-
4450
- program.parse(process.argv);
4451
-
4452
- // Show help if no command provided
4453
- if (!process.argv.slice(2).length) {
4454
- program.outputHelp();
4455
- }