UNPKG

snow-flow

Version:

Snow-Flow v3.2.0: Complete ServiceNow Enterprise Suite with 180+ MCP Tools. ATF Testing, Knowledge Management, Service Catalog, Change Management with CAB scheduling, Virtual Agent chatbots with NLU, Performance Analytics KPIs, Flow Designer automation, A

1,056 lines (988 loc) โ€ข 188 kB
#!/usr/bin/env node "use strict"; /** * Minimal CLI for snow-flow - ServiceNow Multi-Agent Framework */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const commander_1 = require("commander"); const dotenv_1 = __importDefault(require("dotenv")); const fs_1 = require("fs"); const path_1 = require("path"); const child_process_1 = require("child_process"); const os = __importStar(require("os")); const fs_2 = require("fs"); const snow_oauth_js_1 = require("./utils/snow-oauth.js"); const servicenow_client_js_1 = require("./utils/servicenow-client.js"); const agent_detector_js_1 = require("./utils/agent-detector.js"); const version_js_1 = require("./version.js"); const logger_js_1 = require("./utils/logger.js"); const chalk_1 = __importDefault(require("chalk")); // Load environment variables dotenv_1.default.config(); // Create CLI logger instance const cliLogger = new logger_js_1.Logger('cli'); const program = new commander_1.Command(); program .name('snow-flow') .description('ServiceNow Multi-Agent Development Framework') .version(version_js_1.VERSION); // Flow deprecation handler - check for flow-related commands function checkFlowDeprecation(command, objective) { const flowKeywords = ['flow', 'create-flow', 'xml-flow', 'flow-designer']; const isFlowCommand = flowKeywords.some(keyword => command.includes(keyword)); const isFlowObjective = objective && objective.toLowerCase().includes('flow') && !objective.toLowerCase().includes('workflow') && !objective.toLowerCase().includes('data flow') && !objective.toLowerCase().includes('snow-flow'); if (isFlowCommand || isFlowObjective) { console.error('โŒ Flow creation has been removed from snow-flow v1.4.0+'); console.error(''); console.error('Please use ServiceNow Flow Designer directly:'); console.error('1. Log into your ServiceNow instance'); console.error('2. Navigate to: Flow Designer > Designer'); console.error('3. Create flows using the visual interface'); console.error(''); console.error('Snow-flow continues to support:'); console.error('- Widget development'); console.error('- Update Set management'); console.error('- Table/field discovery'); console.error('- General ServiceNow operations'); process.exit(1); } } // Swarm command - the main orchestration command with EVERYTHING program .command('swarm <objective>') .description('Execute multi-agent orchestration for a ServiceNow task - รฉรฉn command voor alles!') .option('--strategy <strategy>', 'Execution strategy (development, _analysis, research)', 'development') .option('--mode <mode>', 'Coordination mode (hierarchical, mesh, distributed)', 'hierarchical') .option('--max-agents <number>', 'Maximum number of agents', '5') .option('--parallel', 'Enable parallel execution') .option('--monitor', 'Enable real-time monitoring') .option('--auto-permissions', 'Automatic permission escalation when needed') .option('--smart-discovery', 'Smart artifact discovery and reuse (default: true)', true) .option('--no-smart-discovery', 'Disable smart artifact discovery') .option('--live-testing', 'Enable live testing during development (default: true)', true) .option('--no-live-testing', 'Disable live testing') .option('--auto-deploy', 'Automatic deployment when ready (default: true)', true) .option('--no-auto-deploy', 'Disable automatic deployment') .option('--auto-rollback', 'Automatic rollback on failures (default: true)', true) .option('--no-auto-rollback', 'Disable automatic rollback') .option('--shared-memory', 'Enable shared memory between agents (default: true)', true) .option('--no-shared-memory', 'Disable shared memory') .option('--progress-monitoring', 'Real-time progress monitoring (default: true)', true) .option('--no-progress-monitoring', 'Disable progress monitoring') .option('--xml-first', 'Use XML-first approach for flow creation (MOST RELIABLE!)') .option('--xml-output <path>', 'Save generated XML to specific path (with --xml-first)') .option('--autonomous-documentation', 'Enable autonomous documentation system (default: true)', true) .option('--no-autonomous-documentation', 'Disable autonomous documentation system') .option('--autonomous-cost-optimization', 'Enable autonomous cost optimization engine (default: true)', true) .option('--no-autonomous-cost-optimization', 'Disable autonomous cost optimization engine') .option('--autonomous-compliance', 'Enable autonomous compliance monitoring (default: true)', true) .option('--no-autonomous-compliance', 'Disable autonomous compliance monitoring') .option('--autonomous-healing', 'Enable autonomous self-healing capabilities (default: true)', true) .option('--no-autonomous-healing', 'Disable autonomous self-healing capabilities') .option('--autonomous-all', 'Force enable all autonomous systems (overrides individual --no- flags)') .option('--no-autonomous-all', 'Disable all autonomous systems (overrides individual settings)') .option('--verbose', 'Show detailed execution information') .action(async (objective, options) => { // Check for flow deprecation first checkFlowDeprecation('swarm', objective); // Always show essential info cliLogger.info(`\n๐Ÿš€ Snow-Flow v${version_js_1.VERSION}`); cliLogger.info(`๐Ÿ“‹ Objective: ${objective}`); // Only show detailed config in verbose mode if (options.verbose) { cliLogger.info(`โš™๏ธ Strategy: ${options.strategy} | Mode: ${options.mode} | Max Agents: ${options.maxAgents}`); cliLogger.info(`๐Ÿ”„ Parallel: ${options.parallel ? 'Yes' : 'No'} | Monitor: ${options.monitor ? 'Yes' : 'No'}`); // Show new intelligent features cliLogger.info(`\n๐Ÿง  Intelligent Features:`); cliLogger.info(` ๐Ÿ” Auto Permissions: ${options.autoPermissions ? 'โœ… Yes' : 'โŒ No'}`); cliLogger.info(` ๐Ÿ” Smart Discovery: ${options.smartDiscovery ? 'โœ… Yes' : 'โŒ No'}`); cliLogger.info(` ๐Ÿงช Live Testing: ${options.liveTesting ? 'โœ… Yes' : 'โŒ No'}`); cliLogger.info(` ๐Ÿš€ Auto Deploy: ${options.autoDeploy ? 'โœ… DEPLOYMENT MODE - WILL CREATE REAL ARTIFACTS' : 'โŒ PLANNING MODE - ANALYSIS ONLY'}`); cliLogger.info(` ๐Ÿ”„ Auto Rollback: ${options.autoRollback ? 'โœ… Yes' : 'โŒ No'}`); cliLogger.info(` ๐Ÿ’พ Shared Memory: ${options.sharedMemory ? 'โœ… Yes' : 'โŒ No'}`); cliLogger.info(` ๐Ÿ“Š Progress Monitoring: ${options.progressMonitoring ? 'โœ… Yes' : 'โŒ No'}`); // Calculate actual autonomous system states (with override logic) // Commander.js converts --no-autonomous-all to autonomousAll: false const noAutonomousAll = options.autonomousAll === false; const forceAutonomousAll = options.autonomousAll === true; const autonomousDocActive = noAutonomousAll ? false : forceAutonomousAll ? true : options.autonomousDocumentation !== false; const autonomousCostActive = noAutonomousAll ? false : forceAutonomousAll ? true : options.autonomousCostOptimization !== false; const autonomousComplianceActive = noAutonomousAll ? false : forceAutonomousAll ? true : options.autonomousCompliance !== false; const autonomousHealingActive = noAutonomousAll ? false : forceAutonomousAll ? true : options.autonomousHealing !== false; const hasAutonomousSystems = autonomousDocActive || autonomousCostActive || autonomousComplianceActive || autonomousHealingActive; cliLogger.info(`\n๐Ÿค– Autonomous Systems (DEFAULT ENABLED):`); cliLogger.info(` ๐Ÿ“š Documentation: ${autonomousDocActive ? 'โœ… ACTIVE' : 'โŒ Disabled'}`); cliLogger.info(` ๐Ÿ’ฐ Cost Optimization: ${autonomousCostActive ? 'โœ… ACTIVE' : 'โŒ Disabled'}`); cliLogger.info(` ๐Ÿ” Compliance Monitoring: ${autonomousComplianceActive ? 'โœ… ACTIVE' : 'โŒ Disabled'}`); cliLogger.info(` ๐Ÿฅ Self-Healing: ${autonomousHealingActive ? 'โœ… ACTIVE' : 'โŒ Disabled'}`); cliLogger.info(''); } else { // In non-verbose mode, only show critical info if (options.autoDeploy) { cliLogger.info(`๐Ÿš€ Auto-Deploy: ENABLED - Will create real artifacts in ServiceNow`); } // Calculate autonomous systems for non-verbose mode (same logic as verbose) const noAutonomousAll = options.autonomousAll === false; const forceAutonomousAll = options.autonomousAll === true; const autonomousDocActive = noAutonomousAll ? false : forceAutonomousAll ? true : options.autonomousDocumentation !== false; const autonomousCostActive = noAutonomousAll ? false : forceAutonomousAll ? true : options.autonomousCostOptimization !== false; const autonomousComplianceActive = noAutonomousAll ? false : forceAutonomousAll ? true : options.autonomousCompliance !== false; const autonomousHealingActive = noAutonomousAll ? false : forceAutonomousAll ? true : options.autonomousHealing !== false; // Show active autonomous systems const activeSystems = []; if (autonomousDocActive) activeSystems.push('๐Ÿ“š Documentation'); if (autonomousCostActive) activeSystems.push('๐Ÿ’ฐ Cost Optimization'); if (autonomousComplianceActive) activeSystems.push('๐Ÿ” Compliance'); if (autonomousHealingActive) activeSystems.push('๐Ÿฅ Self-Healing'); if (activeSystems.length > 0) { cliLogger.info(`๐Ÿค– Autonomous Systems: ${activeSystems.join(', ')}`); } else { cliLogger.info(`๐Ÿค– Autonomous Systems: โŒ All Disabled`); } } // Analyze the objective using intelligent agent detection const taskAnalysis = analyzeObjective(objective, parseInt(options.maxAgents)); // Debug logging to understand task type detection if (process.env.DEBUG || options.verbose) { if (process.env.DEBUG) { cliLogger.info(`๐Ÿ” DEBUG - Detected artifacts: [${taskAnalysis.serviceNowArtifacts.join(', ')}]`); cliLogger.info(`๐Ÿ” DEBUG - Flow keywords in objective: ${objective.toLowerCase().includes('flow')}`); cliLogger.info(`๐Ÿ” DEBUG - Widget keywords in objective: ${objective.toLowerCase().includes('widget')}`); } cliLogger.info(`\n๐Ÿ“Š Task Analysis:`); cliLogger.info(` ๐ŸŽฏ Task Type: ${taskAnalysis.taskType}`); cliLogger.info(` ๐Ÿง  Primary Agent: ${taskAnalysis.primaryAgent}`); cliLogger.info(` ๐Ÿ‘ฅ Supporting Agents: ${taskAnalysis.supportingAgents.join(', ')}`); cliLogger.info(` ๐Ÿ“Š Complexity: ${taskAnalysis.complexity} | Estimated Agents: ${taskAnalysis.estimatedAgentCount}`); cliLogger.info(` ๐Ÿ”ง ServiceNow Artifacts: ${taskAnalysis.serviceNowArtifacts.join(', ')}`); cliLogger.info(` ๐Ÿ“ฆ Auto Update Set: ${taskAnalysis.requiresUpdateSet ? 'โœ… Yes' : 'โŒ No'}`); cliLogger.info(` ๐Ÿ—๏ธ Auto Application: ${taskAnalysis.requiresApplication ? 'โœ… Yes' : 'โŒ No'}`); } // Show timeout configuration only in verbose mode const timeoutMinutes = process.env.SNOW_FLOW_TIMEOUT_MINUTES ? parseInt(process.env.SNOW_FLOW_TIMEOUT_MINUTES) : 60; if (options.verbose) { if (timeoutMinutes > 0) { cliLogger.info(`โฑ๏ธ Timeout: ${timeoutMinutes} minutes`); } else { cliLogger.info('โฑ๏ธ Timeout: Disabled (infinite execution time)'); } } // Check ServiceNow authentication const oauth = new snow_oauth_js_1.ServiceNowOAuth(); const isAuthenticated = await oauth.isAuthenticated(); if (options.verbose) { if (isAuthenticated) { cliLogger.info('๐Ÿ”— ServiceNow connection: โœ… Authenticated'); // Test ServiceNow connection const client = new servicenow_client_js_1.ServiceNowClient(); const testResult = await client.testConnection(); if (testResult.success) { cliLogger.info(`๐Ÿ‘ค Connected as: ${testResult.data.name} (${testResult.data.user_name})`); } } else { cliLogger.warn('๐Ÿ”— ServiceNow connection: โŒ Not authenticated'); cliLogger.info('๐Ÿ’ก Run "snow-flow auth login" to enable live ServiceNow integration'); } } else if (!isAuthenticated) { // In non-verbose mode, only warn if not authenticated cliLogger.warn('โš ๏ธ Not authenticated. Run "snow-flow auth login" for ServiceNow integration'); } // Initialize Queen Agent memory system if (options.verbose) { cliLogger.info('\n๐Ÿ’พ Initializing swarm memory system...'); } const { QueenMemorySystem } = await Promise.resolve().then(() => __importStar(require('./queen/queen-memory.js'))); const memorySystem = new QueenMemorySystem(); // Generate swarm session ID const sessionId = `swarm_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`; cliLogger.info(`\n๐Ÿ”– Session: ${sessionId}`); // Store swarm session in memory memorySystem.storeLearning(`session_${sessionId}`, { objective, taskAnalysis, options, started_at: new Date().toISOString(), is_authenticated: isAuthenticated }); // Check if this is a Flow Designer flow request const isFlowDesignerTask = taskAnalysis.taskType === 'flow_development' || taskAnalysis.primaryAgent === 'flow-builder' || (objective.toLowerCase().includes('flow') && !objective.toLowerCase().includes('workflow') && !objective.toLowerCase().includes('data flow')); let xmlFlowResult = null; // Start real Claude Code orchestration try { // Generate the Queen Agent orchestration prompt const orchestrationPrompt = buildQueenAgentPrompt(objective, taskAnalysis, options, isAuthenticated, sessionId, isFlowDesignerTask); if (options.verbose) { cliLogger.info('\n๐Ÿ‘‘ Initializing Queen Agent orchestration...'); cliLogger.info('๐ŸŽฏ Queen Agent will coordinate the following:'); cliLogger.info(` - Analyze objective: "${objective}"`); cliLogger.info(` - Spawn ${taskAnalysis.estimatedAgentCount} specialized agents`); cliLogger.info(` - Coordinate through shared memory (session: ${sessionId})`); cliLogger.info(` - Monitor progress and adapt strategy`); } else { cliLogger.info('\n๐Ÿ‘‘ Launching Queen Agent...'); } // Check if intelligent features are enabled const hasIntelligentFeatures = options.autoPermissions || options.smartDiscovery || options.liveTesting || options.autoDeploy || options.autoRollback || options.sharedMemory || options.progressMonitoring; if (options.verbose && hasIntelligentFeatures && isAuthenticated) { cliLogger.info('\n๐Ÿง  INTELLIGENT ORCHESTRATION MODE ENABLED!'); cliLogger.info('โœจ Queen Agent will use advanced features:'); if (options.autoPermissions) { cliLogger.info(' ๐Ÿ” Automatic permission escalation'); } if (options.smartDiscovery) { cliLogger.info(' ๐Ÿ” Smart artifact discovery and reuse'); } if (options.liveTesting) { cliLogger.info(' ๐Ÿงช Real-time testing in ServiceNow'); } if (options.autoDeploy) { cliLogger.info(' ๐Ÿš€ Automatic deployment when ready'); } if (options.autoRollback) { cliLogger.info(' ๐Ÿ”„ Automatic rollback on failures'); } if (options.sharedMemory) { cliLogger.info(' ๐Ÿ’พ Shared context across all agents'); } if (options.progressMonitoring) { cliLogger.info(' ๐Ÿ“Š Real-time progress monitoring'); } } if (options.verbose) { if (isAuthenticated) { cliLogger.info('\n๐Ÿ”— Live ServiceNow integration: โœ… Enabled'); cliLogger.info('๐Ÿ“ Artifacts will be created directly in ServiceNow'); } else { cliLogger.info('\n๐Ÿ”— Live ServiceNow integration: โŒ Disabled'); cliLogger.info('๐Ÿ“ Artifacts will be saved to servicenow/ directory'); } } cliLogger.info('๐Ÿš€ Launching Claude Code...'); // Try to execute Claude Code directly with the prompt const success = await executeClaudeCode(orchestrationPrompt); if (success) { cliLogger.info('โœ… Claude Code launched successfully!'); if (options.verbose) { cliLogger.info('๐Ÿ‘‘ Queen Agent is now coordinating your swarm'); cliLogger.info(`๐Ÿ’พ Monitor progress with session ID: ${sessionId}`); if (isAuthenticated && options.autoDeploy) { cliLogger.info('๐Ÿš€ Real artifacts will be created in ServiceNow'); } else { cliLogger.info('๐Ÿ“‹ Planning mode - _analysis and recommendations only'); } } // Store successful launch in memory memorySystem.storeLearning(`launch_${sessionId}`, { success: true, launched_at: new Date().toISOString() }); } else { if (options.verbose) { cliLogger.info('\n๐Ÿš€ SNOW-FLOW ORCHESTRATION COMPLETE!'); cliLogger.info('๐Ÿค– Now it\'s time for Claude Code agents to do the work...\n'); cliLogger.info('๐Ÿ‘‘ QUEEN AGENT ORCHESTRATION PROMPT FOR CLAUDE CODE:'); cliLogger.info('='.repeat(80)); cliLogger.info(orchestrationPrompt); cliLogger.info('='.repeat(80)); cliLogger.info('\nโœ… Snow-Flow has prepared the orchestration!'); cliLogger.info('๐Ÿ“Š CRITICAL NEXT STEPS:'); cliLogger.info(' 1. Copy the ENTIRE prompt above'); cliLogger.info(' 2. Paste it into Claude Code (the AI assistant)'); cliLogger.info(' 3. Claude Code will spawn multiple specialized agents as workhorses'); cliLogger.info(' 4. These agents will implement your flow with all required logic'); cliLogger.info(' 5. Agents will enhance the basic XML template with real functionality'); cliLogger.info('\n๐ŸŽฏ Remember:'); cliLogger.info(' - Snow-Flow = Orchestrator (coordinates the work)'); cliLogger.info(' - Claude Code = Workhorses (implement the solution)'); if (xmlFlowResult) { cliLogger.info(`\n๐Ÿ“ XML template saved at: ${xmlFlowResult.filePath}`); cliLogger.info(' โš ๏ธ This is just a BASIC template - agents must enhance it!'); } if (isAuthenticated && options.autoDeploy) { cliLogger.info('\n๐Ÿš€ Deployment Mode: Agents will create REAL artifacts in ServiceNow'); } else { cliLogger.info('\n๐Ÿ“‹ Planning Mode: Analysis and recommendations only'); } cliLogger.info(`\n๐Ÿ’พ Session ID for monitoring: ${sessionId}`); } else { // Non-verbose mode - just show the essential info cliLogger.info('\n๐Ÿ“‹ Manual Claude Code execution required'); cliLogger.info('๐Ÿ’ก Run with --verbose to see the full orchestration prompt'); if (xmlFlowResult) { cliLogger.info(`๐Ÿ“ XML generated: ${xmlFlowResult.filePath}`); } } } } catch (error) { cliLogger.error('โŒ Failed to execute Queen Agent orchestration:', error instanceof Error ? error.message : String(error)); // Store error in memory for learning memorySystem.storeLearning(`error_${sessionId}`, { error: error instanceof Error ? error.message : String(error), failed_at: new Date().toISOString() }); } }); // Helper function to execute Claude Code directly async function executeClaudeCode(prompt) { cliLogger.info('๐Ÿค– Preparing Claude Code agent orchestration...'); try { // Check if Claude CLI is available const { execSync } = require('child_process'); try { execSync('which claude', { stdio: 'ignore' }); } catch { cliLogger.warn('โš ๏ธ Claude Code CLI not found in PATH'); cliLogger.info('๐Ÿ“‹ Please install Claude Desktop or copy the prompt manually'); return false; } // Check for MCP config const mcpConfigPath = (0, path_1.join)(process.cwd(), '.mcp.json'); const hasMcpConfig = (0, fs_2.existsSync)(mcpConfigPath); // Auto-start MCP servers if they're not running if (hasMcpConfig) { cliLogger.info('๐Ÿ”ง Checking MCP server status...'); try { const { MCPServerManager } = await Promise.resolve().then(() => __importStar(require('./utils/mcp-server-manager.js'))); const manager = new MCPServerManager(); await manager.initialize(); const systemStatus = manager.getSystemStatus(); if (systemStatus.running === 0) { cliLogger.info('๐Ÿš€ Starting MCP servers automatically for swarm operation...'); await manager.startAllServers(); const newStatus = manager.getSystemStatus(); cliLogger.info(`โœ… Started ${newStatus.running}/${newStatus.total} MCP servers`); } else if (systemStatus.running < systemStatus.total) { cliLogger.info(`โš ๏ธ Only ${systemStatus.running}/${systemStatus.total} MCP servers running`); cliLogger.info('๐Ÿ”„ Starting remaining servers...'); await manager.startAllServers(); const newStatus = manager.getSystemStatus(); cliLogger.info(`โœ… All ${newStatus.running}/${newStatus.total} MCP servers running`); } else { cliLogger.info(`โœ… All ${systemStatus.running} MCP servers already running`); } } catch (error) { cliLogger.warn('โš ๏ธ Could not auto-start MCP servers:', error instanceof Error ? error.message : error); cliLogger.info('๐Ÿ’ก You may need to run "npm run mcp:start" manually'); } } // Launch Claude Code with MCP config and skip permissions to avoid raw mode issues const claudeArgs = hasMcpConfig ? ['--mcp-config', '.mcp.json', '.', '--dangerously-skip-permissions'] : ['--dangerously-skip-permissions']; cliLogger.info('๐Ÿš€ Launching Claude Code automatically...'); if (hasMcpConfig) { cliLogger.info('๐Ÿ”ง Starting Claude Code with ServiceNow MCP servers...'); } // Start Claude Code process in interactive mode with stdin piping const claudeProcess = (0, child_process_1.spawn)('claude', claudeArgs, { stdio: ['pipe', 'inherit', 'inherit'], // pipe stdin, inherit stdout/stderr cwd: process.cwd(), env: { ...process.env } }); // Send the prompt via stdin cliLogger.info('๐Ÿ“ Sending orchestration prompt to Claude Code...'); cliLogger.info('๐Ÿš€ Claude Code interface opening...\n'); // Write prompt to stdin claudeProcess.stdin.write(prompt); claudeProcess.stdin.end(); // Set up process monitoring return new Promise((resolve) => { claudeProcess.on('close', async (code) => { if (code === 0) { cliLogger.info('\nโœ… Claude Code session completed successfully!'); resolve(true); } else { cliLogger.warn(`\nโš ๏ธ Claude Code session ended with code: ${code}`); resolve(false); } }); claudeProcess.on('error', (error) => { cliLogger.error(`โŒ Failed to start Claude Code: ${error.message}`); resolve(false); }); // Set timeout (configurable via environment variable) const timeoutMinutes = parseInt(process.env.SNOW_FLOW_TIMEOUT_MINUTES || '0'); if (timeoutMinutes > 0) { setTimeout(() => { cliLogger.warn(`โฑ๏ธ Claude Code session timeout (${timeoutMinutes} minutes), terminating...`); claudeProcess.kill('SIGTERM'); resolve(false); }, timeoutMinutes * 60 * 1000); } }); } catch (error) { cliLogger.error('โŒ Error launching Claude Code:', error instanceof Error ? error.message : String(error)); cliLogger.info('๐Ÿ“‹ Claude Code prompt generated - please copy and paste manually'); return false; } } // Real-time monitoring dashboard for Claude Code process function startMonitoringDashboard(claudeProcess) { let iterations = 0; const startTime = Date.now(); // Show initial dashboard only once cliLogger.info(`โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”`); cliLogger.info(`โ”‚ ๐Ÿš€ Snow-Flow Dashboard v${version_js_1.VERSION} โ”‚`); cliLogger.info(`โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค`); cliLogger.info(`โ”‚ ๐Ÿค– Claude Code Status: โœ… Starting โ”‚`); cliLogger.info(`โ”‚ ๐Ÿ“Š Process ID: ${claudeProcess.pid || 'N/A'} โ”‚`); cliLogger.info(`โ”‚ โฑ๏ธ Session Time: 00:00 โ”‚`); cliLogger.info(`โ”‚ ๐Ÿ”„ Monitoring Cycles: 0 โ”‚`); cliLogger.info('โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜'); // Silent monitoring - only log to file or memory, don't interfere with Claude Code UI const monitoringInterval = setInterval(() => { iterations++; const uptime = Math.floor((Date.now() - startTime) / 1000); // Silent monitoring - check files but don't output to console try { const serviceNowDir = (0, path_1.join)(process.cwd(), 'servicenow'); fs_1.promises.readdir(serviceNowDir).then(files => { // Files are being generated - could log to file if needed // console.log(`\n๐Ÿ“ Generated Files: ${files.length} artifacts in servicenow/`); }).catch(() => { // Directory doesn't exist yet, that's normal }); } catch (error) { // Ignore errors } }, 5000); // Check every 5 seconds silently return monitoringInterval; } async function executeWithClaude(claudeCommand, prompt, resolve) { cliLogger.info('๐Ÿš€ Starting Claude Code execution...'); // Write prompt to temporary file for large prompts const tempFile = (0, path_1.join)(process.cwd(), '.snow-flow-prompt.tmp'); await fs_1.promises.writeFile(tempFile, prompt); // Check if .mcp.json exists in current directory const mcpConfigPath = (0, path_1.join)(process.cwd(), '.mcp.json'); let hasMcpConfig = false; try { await fs_1.promises.access(mcpConfigPath); hasMcpConfig = true; cliLogger.info('โœ… Found MCP configuration in current directory'); } catch { cliLogger.warn('โš ๏ธ No MCP configuration found. Run "snow-flow init" to set up MCP servers'); } const claudeArgs = hasMcpConfig ? ['--mcp-config', '.mcp.json', '.', '--dangerously-skip-permissions'] : ['--dangerously-skip-permissions']; if (hasMcpConfig) { cliLogger.info('๐Ÿ”ง Starting Claude Code with ServiceNow MCP servers...'); } // Start Claude Code process in interactive mode const claudeProcess = (0, child_process_1.spawn)(claudeCommand, claudeArgs, { stdio: ['pipe', 'inherit', 'inherit'], // inherit stdout/stderr for interactive mode cwd: process.cwd() }); // Send the prompt via stdin cliLogger.info('๐Ÿ“ Sending orchestration prompt to Claude Code...'); cliLogger.info('๐Ÿš€ Claude Code interactive interface opening...\n'); claudeProcess.stdin.write(prompt); claudeProcess.stdin.end(); // Start silent monitoring dashboard (doesn't interfere with Claude Code UI) const monitoringInterval = startMonitoringDashboard(claudeProcess); claudeProcess.on('close', (code) => { clearInterval(monitoringInterval); if (code === 0) { cliLogger.info('\nโœ… Claude Code session completed successfully!'); resolve(true); } else { cliLogger.warn(`\nโŒ Claude Code session ended with code: ${code}`); resolve(false); } }); claudeProcess.on('error', (error) => { clearInterval(monitoringInterval); cliLogger.error(`โŒ Failed to start Claude Code: ${error.message}`); resolve(false); }); // Set timeout for Claude Code execution (configurable via environment variable) const timeoutMinutes = process.env.SNOW_FLOW_TIMEOUT_MINUTES ? parseInt(process.env.SNOW_FLOW_TIMEOUT_MINUTES) : 60; const timeoutMs = timeoutMinutes * 60 * 1000; cliLogger.info(`โฑ๏ธ Claude Code timeout set to ${timeoutMinutes} minutes (configure with SNOW_FLOW_TIMEOUT_MINUTES=0 for no timeout)`); let timeout = null; // Only set timeout if not disabled (0 = no timeout) if (timeoutMinutes > 0) { timeout = setTimeout(() => { clearInterval(monitoringInterval); cliLogger.warn(`โฑ๏ธ Claude Code session timeout (${timeoutMinutes} minutes), terminating...`); claudeProcess.kill('SIGTERM'); // Force kill if it doesn't respond setTimeout(() => { claudeProcess.kill('SIGKILL'); }, 2000); resolve(false); }, timeoutMs); } claudeProcess.on('close', () => { if (timeout) { clearTimeout(timeout); } }); } // Helper function to build Queen Agent orchestration prompt function buildQueenAgentPrompt(objective, taskAnalysis, options, isAuthenticated = false, sessionId, isFlowDesignerTask = false) { // Check if intelligent features are enabled const hasIntelligentFeatures = options.autoPermissions || options.smartDiscovery || options.liveTesting || options.autoDeploy || options.autoRollback || options.sharedMemory || options.progressMonitoring; // Calculate actual autonomous system states (with override logic) const noAutonomousAll = options.autonomousAll === false; const forceAutonomousAll = options.autonomousAll === true; const autonomousDocActive = noAutonomousAll ? false : forceAutonomousAll ? true : options.autonomousDocumentation !== false; const autonomousCostActive = noAutonomousAll ? false : forceAutonomousAll ? true : options.autonomousCostOptimization !== false; const autonomousComplianceActive = noAutonomousAll ? false : forceAutonomousAll ? true : options.autonomousCompliance !== false; const autonomousHealingActive = noAutonomousAll ? false : forceAutonomousAll ? true : options.autonomousHealing !== false; const hasAutonomousSystems = autonomousDocActive || autonomousCostActive || autonomousComplianceActive || autonomousHealingActive; const prompt = `# ๐Ÿ‘‘ Snow-Flow Queen Agent Orchestration ## ๐ŸŽฏ Mission Brief 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: **Objective**: ${objective} **Session ID**: ${sessionId} ## ๐Ÿง  Task Analysis Summary - **Task Type**: ${taskAnalysis.taskType} - **Complexity**: ${taskAnalysis.complexity} - **Primary Agent Required**: ${taskAnalysis.primaryAgent} - **Supporting Agents**: ${taskAnalysis.supportingAgents.join(', ')} - **Estimated Total Agents**: ${taskAnalysis.estimatedAgentCount} - **ServiceNow Artifacts**: ${taskAnalysis.serviceNowArtifacts.join(', ')} ## โšก CRITICAL: Task Intent Analysis **BEFORE PROCEEDING**, analyze the user's ACTUAL intent: 1. **Data Generation Request?** (e.g., "create 5000 incidents", "generate test data") โ†’ Focus on CREATING DATA, not building systems โ†’ Use simple scripts or bulk operations to generate the data โ†’ Skip complex architectures unless explicitly asked 2. **System Building Request?** (e.g., "build a widget", "create an ML system") โ†’ Follow full development workflow โ†’ Build proper architecture and components 3. **Simple Operation Request?** (e.g., "update field X", "delete records") โ†’ Execute the operation directly โ†’ Skip unnecessary complexity **For this objective**: Analyze if the user wants data generation, system building, or a simple operation. ${isFlowDesignerTask ? `## ๐Ÿ”ง Flow Designer Task Detected - Using ENHANCED XML-First Approach! ๐Ÿš€ **FULLY AUTOMATED FLOW DEPLOYMENT v2.0** - ALL features working correctly! **MANDATORY: Use this exact approach for Flow Designer tasks:** \`\`\`javascript // โœ… ENHANCED v2.0: Complete flow generation with ALL features await snow_create_flow({ instruction: "your natural language flow description", deploy_immediately: true, // ๐Ÿ”ฅ Automatically deploys to ServiceNow! return_metadata: true // ๐Ÿ“Š Returns complete deployment metadata }); \`\`\` ๐ŸŽฏ **What this does automatically (ENHANCED v1.3.28+):** - โœ… Uses CompleteFlowXMLGenerator for PROPER flow structure - โœ… Generates with v2 tables (sys_hub_action_instance_v2, sys_hub_trigger_instance_v2) - โœ… Applies Base64+gzip encoding for action values - โœ… Includes comprehensive label_cache structure - โœ… Imports XML to ServiceNow as remote update set - โœ… Automatic tool name resolution with MCPToolRegistry - โœ… Complete metadata extraction (sys_id, URLs, endpoints) - โœ… Performance _analysis and recommendations - โœ… 100% of requested features deploy correctly! ๐Ÿšซ **FORBIDDEN APPROACHES:** - โŒ DO NOT use old API-only approach without XML generation - โŒ DO NOT use manual \`snow-flow deploy-xml\` commands - โŒ DO NOT generate XML without auto-deployment - โŒ DO NOT use v1 tables (they create empty flows!) ๐Ÿ’ก **Why Enhanced XML-First v2.0?** - Fixes ALL critical issues from beta testing - Flows deploy with 100% of requested features working - Complete metadata always returned (no more null sys_id) - Tool names resolve correctly across all MCP providers - Zero chance of empty flows or missing features! ` : ''} - **Recommended Team**: ${getTeamRecommendation(taskAnalysis.taskType)} ## ๐Ÿ“Š Table Discovery Intelligence The Queen Agent will automatically discover and validate table schemas based on the objective. This ensures agents use correct field names and table structures. **Table Detection Examples:** - "create widget for incident records" โ†’ Discovers: incident, sys_user, sys_user_group - "build approval flow for u_equipment_request" โ†’ Discovers: u_equipment_request, sys_user, sysapproval_approver - "portal showing catalog items" โ†’ Discovers: sc_cat_item, sc_category, sc_request - "dashboard with CMDB assets" โ†’ Discovers: cmdb_ci, cmdb_rel_ci, sys_user - "report on problem tickets" โ†’ Discovers: problem, incident, sys_user **Discovery Process:** 1. Extracts table names from objective (standard tables, u_ custom tables, explicit mentions) 2. Discovers actual table schemas with field names, types, and relationships 3. Stores schemas in memory for all agents to use 4. Agents MUST use exact field names from schemas (e.g., 'short_description' not 'desc') ## ๐Ÿ‘‘ Your Queen Agent Responsibilities ## ๐Ÿ“Š Data Generation Specific Instructions If the task is identified as DATA GENERATION (e.g., "create 5000 incidents"): 1. **DO NOT** build complex export/import systems 2. **DO NOT** create APIs, UI Actions, or workflows 3. **DO** focus on: - Creating a simple script to generate the data - Using ServiceNow's REST API or direct table operations - Ensuring realistic data distribution for ML training - Adding variety in categories, priorities, descriptions, etc. **Example approach for "create 5000 incidents":** \`\`\`javascript // Simple batch creation script for (let i = 0; i < 5000; i += 100) { // Create 100 incidents at a time to avoid timeouts const batch = generateRealisticIncidentBatch(100); await createIncidentsBatch(batch); } \`\`\` ### 1. CRITICAL: Initialize Memory FIRST (Before Everything!) **THIS MUST BE YOUR VERY FIRST ACTION - Initialize the swarm memory session:** \`\`\`javascript // ๐Ÿšจ EXECUTE THIS IMMEDIATELY - DO NOT SKIP OR DELAY! mcp__snow-flow__memory_usage({ key: "swarm_session_${sessionId}", value: JSON.stringify({ objective: "${objective}", status: "initializing", started_at: new Date().toISOString(), queen_agent_id: "queen_${sessionId}", task_analysis: ${JSON.stringify(taskAnalysis, null, 2)}, configuration: { strategy: "${options.strategy}", mode: "${options.mode}", max_agents: ${parseInt(options.maxAgents)}, parallel_execution: ${options.parallel ? 'true' : 'false'}, monitoring_enabled: ${options.monitor ? 'true' : 'false'}, auth_required: ${!isAuthenticated} } }), namespace: "swarm_${sessionId}" }); // Agent coordination namespace handled automatically by ServiceNow memory system \`\`\` ### 2. MANDATORY MCP-FIRST Workflow Steps **Execute these steps IN ORDER before spawning agents:** \`\`\`javascript // Step 2.1: Validate ServiceNow authentication const authCheck = await mcp__servicenow-intelligent__snow_validate_live_connection({ test_level: "permissions", include_performance: false }); if (!authCheck.connection_status === "success") { throw new Error("Authentication failed! Run: snow-flow auth login"); } // Step 2.2: Check for existing artifacts (DRY principle) const existingArtifacts = await mcp__servicenow-intelligent__snow_comprehensive_search({ query: "${objective}", include_inactive: false }); // Store discovery results in memory for agents await mcp__snow-flow__memory_usage({ key: "existing_artifacts_${sessionId}", value: JSON.stringify(existingArtifacts), namespace: "swarm_${sessionId}" }); // Step 2.3: Create isolated Update Set for this objective const updateSetName = "Snow-Flow: ${objective.substring(0, 50)}... - ${new Date().toISOString().split('T')[0]}"; const updateSet = await mcp__servicenow-update-set__snow_update_set_create({ name: updateSetName, description: "Automated creation for: ${objective}\\n\\nSession: ${sessionId}", auto_switch: true }); // Store Update Set info in memory await mcp__snow-flow__memory_usage({ key: "update_set_${sessionId}", value: JSON.stringify(updateSet), namespace: "swarm_${sessionId}" }); // Step 2.4: Discover tables mentioned in objective // Extract potential table names from the objective const tablePatterns = [ /\b(incident|problem|change_request|sc_request|sc_req_item|task|cmdb_ci|sys_user|sys_user_group)\b/gi, /\b(u_\w+)\b/g, // Custom tables starting with u_ /\b(\w+_table)\b/gi, // Tables ending with _table /\bfrom\s+(\w+)\b/gi, // SQL-like "from table_name" /\btable[:\s]+(\w+)\b/gi, // "table: xyz" or "table xyz" /\b(\w+)\s+records?\b/gi, // "xyz records" ]; const detectedTables = new Set(); // Always include common tables for context ['incident', 'sc_request', 'sys_user'].forEach(t => detectedTables.add(t)); // Search for tables in objective for (const pattern of tablePatterns) { const matches = "${objective}".matchAll(pattern); for (const match of matches) { if (match[1]) { detectedTables.add(match[1].toLowerCase()); } } } // Also check for common data needs based on objective type if ("${objective}".toLowerCase().includes('catalog')) { detectedTables.add('sc_cat_item'); detectedTables.add('sc_category'); } if ("${objective}".toLowerCase().includes('user')) { detectedTables.add('sys_user'); detectedTables.add('sys_user_group'); } if ("${objective}".toLowerCase().includes('cmdb') || "${objective}".toLowerCase().includes('asset')) { detectedTables.add('cmdb_ci'); } if ("${objective}".toLowerCase().includes('knowledge')) { detectedTables.add('kb_knowledge'); } cliLogger.info(\`๐Ÿ” Detected tables to discover: \${Array.from(detectedTables).join(', ')}\`); // Discover schemas for all detected tables const tableSchemas = {}; for (const tableName of detectedTables) { try { const schema = await mcp__servicenow-platform-development__snow_table_schema_discovery({ tableName: tableName, includeRelated: true, includeIndexes: false, maxDepth: 1 // Don't go too deep to avoid timeout }); if (schema && schema.fields) { tableSchemas[tableName] = { name: tableName, label: schema.label || tableName, fields: schema.fields, field_count: schema.fields.length, key_fields: schema.fields.filter(f => f.primary || f.reference).map(f => f.name) }; cliLogger.info(\`โœ… Discovered table '\${tableName}' with \${schema.fields.length} fields\`); } } catch (e) { cliLogger.warn(\`โš ๏ธ Table '\${tableName}' not found or inaccessible\`); } } // Store discovered table schemas in memory await mcp__snow-flow__memory_usage({ action: "store", key: "table_schemas_${sessionId}", value: JSON.stringify({ discovered_at: new Date().toISOString(), objective: "${objective}", tables: tableSchemas, table_names: Object.keys(tableSchemas) }), namespace: "swarm_${sessionId}" }); \`\`\` ### 3. Create Master Task List After completing MCP-FIRST steps, create task breakdown: \`\`\`javascript TodoWrite([ { id: "mcp_workflow_complete", content: "โœ… MCP-FIRST workflow: Auth, Discovery, Update Set, Tables", status: "completed", priority: "high" }, { id: "analyze_requirements", content: "Analyze user requirements: ${objective}", status: "in_progress", priority: "high" }, { id: "spawn_agents", content: "Spawn ${taskAnalysis.estimatedAgentCount} specialized agents", status: "pending", priority: "high" }, { id: "coordinate_development", content: "Coordinate agent activities for ${taskAnalysis.taskType}", status: "pending", priority: "high" }, { id: "validate_solution", content: "Validate and test the complete solution", status: "pending", priority: "medium" } ]); \`\`\` ### 4. Intelligent Agent Spawning with Dependency-Based Batching โšก **CRITICAL: Spawn agents in SMART BATCHES based on dependencies!** Based on the task analysis, we need to spawn ${taskAnalysis.estimatedAgentCount} agents. ${getAgentSpawnStrategy(taskAnalysis)} ### 5. Memory Coordination Pattern All agents MUST use this memory coordination pattern: \`\`\`javascript // Agent initialization const session = Memory.get("swarm_session_${sessionId}"); const agentId = \`agent_\${agentType}_${sessionId}\`; // Agent stores progress Memory.store(\`\${agentId}_progress\`, { status: "working", current_task: "description of current work", completion_percentage: 45, last_update: new Date().toISOString() }); // Agent reads other agent's work const primaryWork = Memory.get("agent_${taskAnalysis.primaryAgent}_output"); // Agent signals completion Memory.store(\`\${agentId}_complete\`, { completed_at: new Date().toISOString(), outputs: { /* agent deliverables */ }, artifacts_created: [ /* list of created artifacts */ ] }); \`\`\` ## ๐Ÿง  Intelligent Features Configuration ${hasIntelligentFeatures ? `โœ… **INTELLIGENT MODE ACTIVE** - The following features are enabled: - **๐Ÿ” Auto Permissions**: ${options.autoPermissions ? 'โœ… Will escalate permissions automatically' : 'โŒ Manual permission handling'} - **๐Ÿ” Smart Discovery**: ${options.smartDiscovery ? 'โœ… Will discover and reuse existing artifacts' : 'โŒ Create all new artifacts'} - **๐Ÿงช Live Testing**: ${options.liveTesting ? 'โœ… Will test in real ServiceNow instance' : 'โŒ Local testing only'} - **๐Ÿš€ Auto Deploy**: ${options.autoDeploy ? 'โš ๏ธ WILL DEPLOY TO SERVICENOW AUTOMATICALLY' : 'โœ… Planning mode - no deployment'} - **๐Ÿ”„ Auto Rollback**: ${options.autoRollback ? 'โœ… Will rollback on any failures' : 'โŒ No automatic rollback'} - **๐Ÿ’พ Shared Memory**: ${options.sharedMemory ? 'โœ… Agents share context via Memory' : 'โŒ Isolated agent execution'} - **๐Ÿ“Š Progress Monitoring**: ${options.progressMonitoring ? 'โœ… Real-time progress tracking' : 'โŒ No progress monitoring'}` : 'โŒ **STANDARD MODE** - Use manual coordination patterns'} ## ๐ŸŽฏ ServiceNow Execution Strategy ### ๐Ÿš€ MANDATORY: Live ServiceNow Development First! **CRITICAL RULE**: All agents MUST attempt to use ServiceNow MCP tools first, regardless of authentication status. ${hasIntelligentFeatures ? `#### ๐Ÿง  Intelligent Orchestration Available Use the unified orchestration tool for complete automation: \`\`\`javascript // Queen Agent uses this for intelligent orchestration snow_orchestrate_development({ objective: "${objective}", auto_permissions: ${options.autoPermissions}, smart_discovery: ${options.smartDiscovery}, live_testing: ${options.liveTesting}, auto_deploy: ${options.autoDeploy}, auto_rollback: ${options.autoRollback}, shared_memory: ${options.sharedMemory}, progress_monitoring: ${options.progressMonitoring} }); \`\`\` ## ๐Ÿง  REVOLUTIONARY: Intelligent Gap Analysis Engine (v1.1.88) **AUTOMATIC BEYOND-MCP CONFIGURATION DETECTION** The Queen Agent now includes the revolutionary **Intelligent Gap Analysis Engine** that automatically detects and resolves ALL ServiceNow configurations needed beyond standard MCP tools. **What Gap Analysis Does:** - **๐Ÿ” Analyzes Requirements**: AI-powered parsing of objectives to identify 60+ types of ServiceNow configurations - **๐Ÿ“Š MCP Coverage Analysis**: Maps what current MCP tools can handle vs manual setup requirements - **๐Ÿค– Auto-Resolution Engine**: Attempts automatic configuration via ServiceNow APIs for safe operations - **๐Ÿ“š Manual Guide Generation**: Creates detailed step-by-step guides with role requirements and risk assessment - **๐Ÿ›ก๏ธ Risk Assessment**: Evaluates complexity and safety of each configuration - **๐ŸŒ Environment Awareness**: Provides dev/test/prod specific guidance and warnings **60+ Configuration Types Covered:** - **๐Ÿ” Authentication**: LDAP, SAML, OAuth providers, SSO, MFA configurations - **๐Ÿ—„๏ธ Database**: Indexes, views, partitioning, performance analytics, system properties - **๐Ÿงญ Navigation**: Application menus, modules, form layouts, UI actions, policies - **๐Ÿ“ง Integration**: Email templates, web services, import sets, transform maps - **๐Ÿ”„ Workflow**: Activities, transitions, SLA definitions, escalation rules - **๐Ÿ›ก๏ธ Security**: ACL rules, data policies, audit rules, compliance configurations - **๐Ÿ“Š Reporting**: Custom reports, dashboards, KPIs, performance analytics **Example Output:** \`\`\` ๐Ÿง  Step 4: Running Intelligent Gap Analysis... ๐Ÿ“Š Gap Analysis Complete: โ€ข Total Requirements: 12 โ€ข MCP Coverage: 67% โ€ข Automated: 6 configurations โ€ข Manual Work: 4 items โœ… Automatically Configured: โ€ข System property: glide.ui.incident_management created โ€ข Navigation module: Incident Management added to Service Desk โ€ข Email template: incident_notification configured โ€ข Database index: incident.priority_state for performance ๐Ÿ“‹ Manual Configuration Required: โ€ข LDAP authentication setup (high-risk operation) โ€ข SSO configuration with Active Directory ๐Ÿ“š Detailed Manual Guides Available: ๐Ÿ“– Configure LDAP Authentication - 25 minutes Risk: high | Roles: security_admin, admin \`\`\` **The Gap Analysis Engine automatically runs as part of Queen Agent execution - no additional commands needed!** ` : ''} #### ServiceNow MCP Tools (ALWAYS TRY T