snow-flow 4.6.2 → 4.6.6

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.
@@ -1,420 +0,0 @@
1
- // Helper function to build Queen Agent orchestration prompt - CLEANED UP VERSION
2
- function buildQueenAgentPrompt(objective, taskAnalysis, options, isAuthenticated = false, sessionId, isFlowDesignerTask = false) {
3
- // Check if intelligent features are enabled
4
- const hasIntelligentFeatures = options.autoPermissions || options.smartDiscovery ||
5
- options.liveTesting || options.autoDeploy || options.autoRollback ||
6
- options.sharedMemory || options.progressMonitoring;
7
- const prompt = `# 👑 Snow-Flow Queen Agent Orchestration
8
-
9
- ## 🎯 Mission Brief
10
- 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:
11
-
12
- **Objective**: ${objective}
13
- **Session ID**: ${sessionId}
14
-
15
- ## 🧠 Task Analysis Summary
16
- - **Task Type**: ${taskAnalysis.taskType}
17
- - **Complexity**: ${taskAnalysis.complexity}
18
- - **Primary Agent Required**: ${taskAnalysis.primaryAgent}
19
- - **Supporting Agents**: ${taskAnalysis.supportingAgents.join(', ')}
20
- - **Estimated Total Agents**: ${taskAnalysis.estimatedAgentCount}
21
- - **ServiceNow Artifacts**: ${taskAnalysis.serviceNowArtifacts.join(', ')}
22
-
23
- ## ⚡ CRITICAL: Task Intent Analysis
24
- **BEFORE PROCEEDING**, analyze the user's ACTUAL intent:
25
-
26
- 1. **Data Generation Request?** (e.g., "create 5000 incidents", "generate test data")
27
- → Focus on CREATING DATA, not building systems
28
- → Use simple scripts or bulk operations to generate the data
29
- → Skip complex architectures unless explicitly asked
30
-
31
- 2. **System Building Request?** (e.g., "build a widget", "create an ML system")
32
- → Follow full development workflow
33
- → Build proper architecture and components
34
-
35
- 3. **Simple Operation Request?** (e.g., "update field X", "delete records")
36
- → Execute the operation directly
37
- → Skip unnecessary complexity
38
-
39
- **For this objective**: Analyze if the user wants data generation, system building, or a simple operation.
40
-
41
- ${isFlowDesignerTask ? `## 🔧 Flow Designer Task Detected - Using Enhanced Flow Creation!
42
-
43
- **MANDATORY: Use this exact approach for Flow Designer tasks:**
44
-
45
- \`\`\`javascript
46
- // ✅ Complete flow generation with ALL features
47
- await snow_create_flow({
48
- instruction: "your natural language flow description",
49
- deploy_immediately: true, // 🔥 Automatically deploys to ServiceNow!
50
- return_metadata: true // 📊 Returns complete deployment metadata
51
- });
52
- \`\`\`
53
-
54
- 🎯 **What this does automatically:**
55
- - ✅ Generates proper flow structure with all components
56
- - ✅ Uses correct ServiceNow tables and relationships
57
- - ✅ Deploys directly to your ServiceNow instance
58
- - ✅ Returns complete metadata (sys_id, URLs, endpoints)
59
- - ✅ Includes all requested features and logic
60
-
61
- ` : ''}
62
-
63
- ## 📊 Table Discovery Intelligence
64
-
65
- The Queen Agent will automatically discover and validate table schemas based on the objective. This ensures agents use correct field names and table structures.
66
-
67
- **Table Detection Examples:**
68
- - "create widget for incident records" → Discovers: incident, sys_user, sys_user_group
69
- - "build approval flow for u_equipment_request" → Discovers: u_equipment_request, sys_user, sysapproval_approver
70
- - "portal showing catalog items" → Discovers: sc_cat_item, sc_category, sc_request
71
- - "dashboard with CMDB assets" → Discovers: cmdb_ci, cmdb_rel_ci, sys_user
72
- - "report on problem tickets" → Discovers: problem, incident, sys_user
73
-
74
- **Discovery Process:**
75
- 1. Extracts table names from objective (standard tables, u_ custom tables, explicit mentions)
76
- 2. Discovers actual table schemas with field names, types, and relationships
77
- 3. Stores schemas in memory for all agents to use
78
- 4. Agents MUST use exact field names from schemas (e.g., 'short_description' not 'desc')
79
-
80
- ## 👑 Your Queen Agent Responsibilities
81
-
82
- ## 📊 Data Generation Specific Instructions
83
- If the task is identified as DATA GENERATION (e.g., "create 5000 incidents"):
84
-
85
- 1. **DO NOT** build complex export/import systems
86
- 2. **DO NOT** create APIs, UI Actions, or workflows
87
- 3. **DO** focus on:
88
- - Creating a simple script to generate the data
89
- - Using ServiceNow's REST API or direct table operations
90
- - Ensuring realistic data distribution for ML training
91
- - Adding variety in categories, priorities, descriptions, etc.
92
-
93
- **Example approach for "create 5000 incidents":**
94
- \`\`\`javascript
95
- // Simple batch creation script
96
- for (let i = 0; i < 5000; i += 100) {
97
- // Create 100 incidents at a time to avoid timeouts
98
- const batch = generateRealisticIncidentBatch(100);
99
- await createIncidentsBatch(batch);
100
- }
101
- \`\`\`
102
-
103
- ### 1. Initialize Memory & Session (Required First Step)
104
- **THIS MUST BE YOUR VERY FIRST ACTION:**
105
- \`\`\`javascript
106
- // Initialize swarm memory session
107
- Memory.store("swarm_session_${sessionId}", JSON.stringify({
108
- objective: "${objective}",
109
- status: "initializing",
110
- started_at: new Date().toISOString(),
111
- task_analysis: ${JSON.stringify(taskAnalysis, null, 2)},
112
- configuration: {
113
- strategy: "${options.strategy}",
114
- mode: "${options.mode}",
115
- max_agents: ${parseInt(options.maxAgents)},
116
- authenticated: ${isAuthenticated}
117
- }
118
- }));
119
- \`\`\`
120
-
121
- ### 2. Validate ServiceNow Connection
122
- **Execute these steps IN ORDER:**
123
-
124
- \`\`\`javascript
125
- // Step 2.1: Test ServiceNow authentication
126
- const authCheck = await snow_auth_diagnostics();
127
- if (!authCheck.success) {
128
- throw new Error("Authentication failed! Run: snow-flow auth login");
129
- }
130
-
131
- // Step 2.2: Create Update Set for tracking changes
132
- const updateSetName = "Snow-Flow: ${objective.substring(0, 50)}... - ${new Date().toISOString().split('T')[0]}";
133
- const updateSet = await snow_update_set_create({
134
- name: updateSetName,
135
- description: "Automated creation for: ${objective}\\n\\nSession: ${sessionId}",
136
- auto_switch: true
137
- });
138
-
139
- // Store Update Set info in memory
140
- Memory.store("update_set_${sessionId}", JSON.stringify(updateSet));
141
- \`\`\`
142
-
143
- ### 3. Create Master Task List
144
- After completing setup steps, create task breakdown:
145
- \`\`\`javascript
146
- TodoWrite([
147
- {
148
- id: "setup_complete",
149
- content: "✅ Setup: Auth, Update Set, Memory initialized",
150
- status: "completed",
151
- priority: "high"
152
- },
153
- {
154
- id: "analyze_requirements",
155
- content: "Analyze user requirements: ${objective}",
156
- status: "in_progress",
157
- priority: "high"
158
- },
159
- {
160
- id: "spawn_agents",
161
- content: "Spawn ${taskAnalysis.estimatedAgentCount} specialized agents",
162
- status: "pending",
163
- priority: "high"
164
- },
165
- {
166
- id: "coordinate_development",
167
- content: "Coordinate agent activities for ${taskAnalysis.taskType}",
168
- status: "pending",
169
- priority: "high"
170
- },
171
- {
172
- id: "validate_solution",
173
- content: "Validate and test the complete solution",
174
- status: "pending",
175
- priority: "medium"
176
- }
177
- ]);
178
- \`\`\`
179
-
180
- ### 4. Agent Spawning Strategy
181
- Based on the task analysis, spawn ${taskAnalysis.estimatedAgentCount} agents in smart batches:
182
-
183
- **Agent Spawn Order:**
184
- 1. **Primary Agent**: Spawn ${taskAnalysis.primaryAgent} first
185
- 2. **Supporting Agents**: Spawn ${taskAnalysis.supportingAgents.join(', ')} after primary is established
186
- 3. **Use Task tool**: \`Task("agent description", "agent prompt")\` for each agent
187
-
188
- ### 5. Memory Coordination Pattern
189
- All agents MUST use this simple memory coordination:
190
-
191
- \`\`\`javascript
192
- // Agent initialization
193
- const agentId = \`agent_\${agentType}_${sessionId}\`;
194
-
195
- // Agent stores progress
196
- Memory.store(\`\${agentId}_progress\`, JSON.stringify({
197
- status: "working",
198
- current_task: "description of current work",
199
- completion_percentage: 45,
200
- last_update: new Date().toISOString()
201
- }));
202
-
203
- // Agent reads other agent's work when needed
204
- const primaryWork = Memory.get("agent_${taskAnalysis.primaryAgent}_output");
205
-
206
- // Agent signals completion
207
- Memory.store(\`\${agentId}_complete\`, JSON.stringify({
208
- completed_at: new Date().toISOString(),
209
- outputs: { /* agent deliverables */ },
210
- artifacts_created: [ /* list of created artifacts */ ]
211
- }));
212
- \`\`\`
213
-
214
- ## 🧠 Intelligent Features Configuration
215
- ${hasIntelligentFeatures ? `✅ **INTELLIGENT MODE ACTIVE** - The following features are enabled:
216
-
217
- - **🔐 Auto Permissions**: ${options.autoPermissions ? '✅ Will escalate permissions automatically' : '❌ Manual permission handling'}
218
- - **🔍 Smart Discovery**: ${options.smartDiscovery ? '✅ Will discover and reuse existing artifacts' : '❌ Create all new artifacts'}
219
- - **🧪 Live Testing**: ${options.liveTesting ? '✅ Will test in real ServiceNow instance' : '❌ Local testing only'}
220
- - **🚀 Auto Deploy**: ${options.autoDeploy ? '⚠️ WILL DEPLOY TO SERVICENOW AUTOMATICALLY' : '✅ Planning mode - no deployment'}
221
- - **🔄 Auto Rollback**: ${options.autoRollback ? '✅ Will rollback on any failures' : '❌ No automatic rollback'}
222
- - **💾 Shared Memory**: ${options.sharedMemory ? '✅ Agents share context via Memory' : '❌ Isolated agent execution'}
223
- - **📊 Progress Monitoring**: ${options.progressMonitoring ? '✅ Real-time progress tracking' : '❌ No progress monitoring'}` : '❌ **STANDARD MODE** - Use manual coordination patterns'}
224
-
225
- ## 🎯 ServiceNow Execution Strategy
226
-
227
- ### 🚀 MANDATORY: Live ServiceNow Development First!
228
-
229
- **CRITICAL RULE**: All agents MUST attempt to use ServiceNow MCP tools first, regardless of authentication status.
230
-
231
- #### Current MCP Tools Available (Snow-Flow v3.3.4)
232
- ${isAuthenticated ? '✅ Authentication detected - full deployment capabilities' : '⚠️ No authentication detected - MCP tools will provide specific instructions if auth needed'}
233
-
234
- Your agents MUST use these MCP tools IN THIS ORDER:
235
-
236
- 🔍 **PRE-FLIGHT CHECKS** (Always do first!):
237
- 1. \`snow_auth_diagnostics\` - Test authentication and permissions
238
- 2. If auth fails, the tool provides specific instructions
239
- 3. Continue with appropriate strategy based on auth status
240
-
241
- 🎯 **Core Development Tools**:
242
- 1. **Universal Query Tool**: \`snow_query_table\` - Works with ALL ServiceNow tables
243
- - Count-only: \`{table: "incident", query: "state!=7"}\` → Memory efficient
244
- - Specific fields: \`{table: "sc_request", fields: ["number", "state"]}\` → Only needed data
245
- - Full content: \`{table: "change_request", include_content: true}\` → When all data needed
246
-
247
- 2. **Deployment Tools**:
248
- - \`snow_deploy\` - Universal deployment for NEW artifacts (16+ types supported!)
249
- - \`snow_update\` - Update EXISTING artifacts by name or sys_id
250
-
251
- 3. **Discovery Tools**:
252
- - \`snow_discover_table_fields\` - Get exact field names and types
253
- - \`snow_table_schema_discovery\` - Complete table structure
254
-
255
- 4. **Update Set Management**:
256
- - \`snow_update_set_create\` - Create new update sets
257
- - \`snow_update_set_add_comment\` - Track progress
258
- - \`snow_update_set_retrieve\` - Get update set XML
259
-
260
- ## 🔧 NEW: Expanded Artifact Support (v3.3.4)
261
-
262
- Snow-Flow now supports **16+ different ServiceNow artifact types**:
263
-
264
- | Type | Table | Deploy | Update | Natural Language |
265
- |------|-------|--------|---------|------------------|
266
- | widget | sp_widget | ✅ | ✅ | ✅ |
267
- | business_rule | sys_script | ✅ | ✅ | ✅ |
268
- | script_include | sys_script_include | ✅ | ✅ | ✅ |
269
- | ui_page | sys_ui_page | ✅ | ✅ | ✅ |
270
- | client_script | sys_script_client | ✅ | ✅ | ✅ |
271
- | ui_action | sys_ui_action | ✅ | ✅ | ✅ |
272
- | ui_policy | sys_ui_policy | ✅ | ✅ | ✅ |
273
- | acl | sys_security_acl | ✅ | ✅ | ✅ |
274
- | table | sys_db_object | ✅ | ✅ | ✅ |
275
- | field | sys_dictionary | ✅ | ✅ | ✅ |
276
- | workflow | wf_workflow | ✅ | ✅ | ✅ |
277
- | flow | sys_hub_flow | ✅ | ✅ | ✅ |
278
- | notification | sysevent_email_action | ✅ | ✅ | ✅ |
279
- | scheduled_job | sysauto_script | ✅ | ✅ | ✅ |
280
-
281
- **Usage Examples:**
282
- \`\`\`javascript
283
- // Deploy NEW artifacts
284
- await snow_deploy({
285
- type: 'business_rule',
286
- name: 'Auto Assignment Rule',
287
- table: 'incident',
288
- when: 'before',
289
- script: 'if (current.priority == "1") current.assigned_to = "admin";'
290
- });
291
-
292
- // Update EXISTING artifacts (natural language supported!)
293
- await snow_update({
294
- type: 'ui_action',
295
- identifier: 'close_incident',
296
- instruction: 'Change label to "Close with Resolution" and add validation'
297
- });
298
- \`\`\`
299
-
300
- ${options.autoDeploy ? `
301
- #### ⚠️ AUTO-DEPLOYMENT ACTIVE ⚠️
302
- - Real artifacts will be created in ServiceNow
303
- - All changes tracked in Update Sets
304
- - Rollback available if needed
305
- ` : `
306
- #### 📋 Planning Mode Active
307
- - No real artifacts will be created
308
- - Analysis and recommendations only
309
- - Use --auto-deploy to enable deployment
310
- `}
311
-
312
- ${!isAuthenticated ? `### ❌ ServiceNow Integration Disabled
313
-
314
- #### Planning Mode (Auth Required)
315
- When authentication is not available, agents will:
316
- 1. Document the COMPLETE solution architecture
317
- 2. Create detailed implementation guides
318
- 3. Store all plans in Memory for future deployment
319
- 4. Provide SPECIFIC instructions: "Run snow-flow auth login"
320
-
321
- ⚠️ IMPORTANT: This is a FALLBACK mode only!
322
- Agents must ALWAYS try MCP tools first!` : ''}
323
-
324
- ## 👑 Queen Agent Coordination Instructions
325
-
326
- ### 6. Agent Coordination & Handoffs
327
- Ensure smooth transitions between agents:
328
-
329
- \`\`\`javascript
330
- // Primary agent signals readiness for support
331
- Memory.store("agent_${taskAnalysis.primaryAgent}_ready_for_support", JSON.stringify({
332
- base_structure_complete: true,
333
- ready_for: [${taskAnalysis.supportingAgents.map(a => `"${a}"`).join(', ')}],
334
- timestamp: new Date().toISOString()
335
- }));
336
-
337
- // Supporting agents check readiness
338
- const canProceed = JSON.parse(Memory.get("agent_${taskAnalysis.primaryAgent}_ready_for_support") || "{}");
339
- if (canProceed?.base_structure_complete) {
340
- // Begin supporting work
341
- }
342
- \`\`\`
343
-
344
- ### 7. Final Validation and Completion
345
- Once all agents complete their work:
346
-
347
- \`\`\`javascript
348
- // Collect all agent outputs
349
- const agentOutputs = {};
350
- [${[taskAnalysis.primaryAgent, ...taskAnalysis.supportingAgents].map(a => `"${a}"`).join(', ')}].forEach(agent => {
351
- const output = Memory.get(\`agent_\${agent}_complete\`);
352
- if (output) {
353
- agentOutputs[agent] = JSON.parse(output);
354
- }
355
- });
356
-
357
- // Store final swarm results
358
- Memory.store("swarm_session_${sessionId}_results", JSON.stringify({
359
- objective: "${objective}",
360
- completed_at: new Date().toISOString(),
361
- agent_outputs: agentOutputs,
362
- artifacts_created: Object.values(agentOutputs)
363
- .flatMap(output => output.artifacts_created || []),
364
- success: true
365
- }));
366
-
367
- // Update final TodoWrite status
368
- TodoWrite([
369
- {
370
- id: "swarm_completion",
371
- content: "Swarm successfully completed: ${objective}",
372
- status: "completed",
373
- priority: "high"
374
- }
375
- ]);
376
- \`\`\`
377
-
378
- ## 🎯 Success Criteria
379
-
380
- Your Queen Agent orchestration is successful when:
381
- 1. ✅ All agents have been spawned and initialized
382
- 2. ✅ Swarm session is tracked in Memory
383
- 3. ✅ Agents are coordinating through shared Memory
384
- 4. ✅ TodoWrite is being used for task tracking
385
- 5. ✅ ${taskAnalysis.taskType} requirements are met
386
- 6. ✅ All artifacts are created/deployed successfully
387
-
388
- ## 💡 Queen Agent Best Practices
389
-
390
- 1. **Spawn agents concurrently** when tasks are independent
391
- 2. **Use Memory with JSON.stringify/parse** to avoid key collisions
392
- 3. **Update TodoWrite** frequently for visibility
393
- 4. **Monitor agent health** and restart if needed
394
- 5. **Validate outputs** before marking complete
395
- 6. **Store all decisions** in Memory for audit trail
396
-
397
- ## 🚀 Begin Orchestration
398
-
399
- Now execute this Queen Agent orchestration plan:
400
- 1. Initialize the swarm session in Memory
401
- 2. Create the master task list with TodoWrite
402
- 3. Spawn all required agents using Task
403
- 4. Monitor progress and coordinate
404
- 5. Validate and complete the objective
405
-
406
- Remember: You are the Queen Agent - the master coordinator. Your role is to ensure all agents work harmoniously to achieve the objective: "${objective}"
407
-
408
- ## 📊 Session Information
409
- - **Session ID**: ${sessionId}
410
- - **Snow-Flow Version**: v3.3.4
411
- - **Authentication**: ${isAuthenticated ? 'Active' : 'Required'}
412
- - **Deployment Mode**: ${options.autoDeploy ? 'Live deployment enabled' : 'Planning mode'}
413
- - **Estimated Agents**: ${taskAnalysis.estimatedAgentCount}
414
- - **Primary Agent**: ${taskAnalysis.primaryAgent}
415
-
416
- 🎯 **Ready to begin orchestration!**
417
- `;
418
- return prompt;
419
- }
420
- //# sourceMappingURL=cli-new-prompt.js.map
@@ -1,11 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * ⚠️ DEPRECATED: Legacy MCP Server Starter
4
- *
5
- * This script is DEPRECATED and will be removed in v3.0.0
6
- * Use MCPServerManager instead for proper server management.
7
- *
8
- * Migration: Use scripts/start-mcp-proper.js or MCPServerManager directly
9
- */
10
- export {};
11
- //# sourceMappingURL=start-all-mcp-servers.d.ts.map
@@ -1,77 +0,0 @@
1
- #!/usr/bin/env node
2
- "use strict";
3
- /**
4
- * ⚠️ DEPRECATED: Legacy MCP Server Starter
5
- *
6
- * This script is DEPRECATED and will be removed in v3.0.0
7
- * Use MCPServerManager instead for proper server management.
8
- *
9
- * Migration: Use scripts/start-mcp-proper.js or MCPServerManager directly
10
- */
11
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
12
- if (k2 === undefined) k2 = k;
13
- var desc = Object.getOwnPropertyDescriptor(m, k);
14
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
15
- desc = { enumerable: true, get: function() { return m[k]; } };
16
- }
17
- Object.defineProperty(o, k2, desc);
18
- }) : (function(o, m, k, k2) {
19
- if (k2 === undefined) k2 = k;
20
- o[k2] = m[k];
21
- }));
22
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
23
- Object.defineProperty(o, "default", { enumerable: true, value: v });
24
- }) : function(o, v) {
25
- o["default"] = v;
26
- });
27
- var __importStar = (this && this.__importStar) || (function () {
28
- var ownKeys = function(o) {
29
- ownKeys = Object.getOwnPropertyNames || function (o) {
30
- var ar = [];
31
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
32
- return ar;
33
- };
34
- return ownKeys(o);
35
- };
36
- return function (mod) {
37
- if (mod && mod.__esModule) return mod;
38
- var result = {};
39
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
40
- __setModuleDefault(result, mod);
41
- return result;
42
- };
43
- })();
44
- Object.defineProperty(exports, "__esModule", { value: true });
45
- const logger_js_1 = require("../utils/logger.js");
46
- const logger = new logger_js_1.Logger('DeprecatedMCPLauncher');
47
- async function startAllServers() {
48
- logger.warn('⚠️ DEPRECATED: This start-all-mcp-servers.ts script is deprecated!');
49
- logger.warn(' Please use MCPServerManager or scripts/start-mcp-proper.js instead');
50
- logger.warn(' This provides proper process management and singleton protection');
51
- console.error('\n🔄 Redirecting to proper MCPServerManager...\n');
52
- try {
53
- // Redirect to proper approach
54
- const { MCPServerManager } = await Promise.resolve().then(() => __importStar(require('../utils/mcp-server-manager.js')));
55
- const manager = new MCPServerManager();
56
- await manager.initialize();
57
- await manager.startAllServers();
58
- logger.info('✅ Servers started using proper MCPServerManager');
59
- }
60
- catch (error) {
61
- logger.error('❌ Failed to start servers:', error.message);
62
- logger.info('💡 Consider migrating to: scripts/start-mcp-proper.js');
63
- process.exit(1);
64
- }
65
- // If we get here, MCPServerManager started successfully
66
- logger.info('🎉 Migration successful! Using proper MCPServerManager now.');
67
- // Keep process alive to monitor servers (handled by MCPServerManager)
68
- process.on('SIGINT', () => {
69
- logger.info('👋 Shutting down...');
70
- process.exit(0);
71
- });
72
- }
73
- startAllServers().catch(error => {
74
- logger.error('Failed to start MCP servers:', error);
75
- process.exit(1);
76
- });
77
- //# sourceMappingURL=start-all-mcp-servers.js.map
@@ -1,3 +0,0 @@
1
- export declare const CLAUDE_MD_TEMPLATE = "# Snow-Flow Configuration & Best Practices\n\nThis document provides comprehensive instructions for Snow-Flow, an advanced ServiceNow development and orchestration framework powered by Claude AI.\n\n## \uD83D\uDEA8 ABSOLUTE RULE #1: NO MOCK DATA, NO PLACEHOLDERS, NO SHORTCUTS! \uD83D\uDEA8\n\n### **EVERYTHING MUST BE REAL, COMPLETE, AND PRODUCTION-READY**\n\n**\u26D4 ABSOLUTELY FORBIDDEN:**\n- \u274C NO mock data, test data, or demo data\n- \u274C NO placeholder code or stub implementations\n- \u274C NO \"TODO\" comments or incomplete sections\n- \u274C NO simulated responses or fake results\n- \u274C NO shortcuts, quick fixes, or temporary solutions\n- \u274C NO \"this would normally...\" explanations\n- \u274C NO partial implementations or \"proof of concepts\"\n- \u274C NO hardcoded test values or example data\n\n**\u2705 MANDATORY REQUIREMENTS:**\n- \u2705 EVERY implementation must be COMPLETE and FUNCTIONAL\n- \u2705 ALL code must be PRODUCTION-READY\n- \u2705 TAKE THE TIME to write EVERYTHING properly\n- \u2705 IMPLEMENT all error handling, validation, and edge cases\n- \u2705 CREATE actual working solutions, not demonstrations\n- \u2705 BUILD real integrations, not simulations\n- \u2705 DEVELOP complete features, not prototypes\n- \u2705 DELIVER finished products, not drafts\n\n**\uD83D\uDCDD Quality Standards:**\n1. **Complete Implementation** - Every feature fully implemented with all functionality\n2. **Real Data Operations** - Actual ServiceNow API calls with real responses\n3. **Comprehensive Error Handling** - All edge cases covered, all errors handled\n4. **Production-Grade Code** - Clean, maintainable, documented, tested\n5. **Full Validation** - Input validation, data verification, coherence checking\n6. **Actual Integration** - Real connections to ServiceNow, no mocked services\n7. **Thorough Testing** - Complete test coverage, not just happy path\n8. **Professional Documentation** - Detailed, accurate, complete documentation\n\n**\uD83C\uDFAF The Snow-Flow Commitment:**\nWhen implementing ANY feature, no matter how complex or time-consuming:\n- INVEST the time to do it RIGHT\n- WRITE every line of code needed\n- IMPLEMENT every validation required\n- HANDLE every possible error\n- CREATE comprehensive solutions\n- BUILD production-ready systems\n- DELIVER professional results\n\n**Remember:** Users depend on Snow-Flow for REAL production ServiceNow environments. \nThere is NO room for shortcuts, placeholders, or incomplete implementations.\nEvery line of code matters. Every feature must work. Every implementation must be complete.\n\n**TAKE THE TIME. DO IT RIGHT. NO EXCEPTIONS.**\n\n---\n\n## Table of Contents\n1. [Core Philosophy](#core-philosophy)\n2. [Fundamental Rules](#fundamental-rules)\n3. [ServiceNow Development Standards](#servicenow-development-standards)\n4. [MCP Server Capabilities](#mcp-server-capabilities)\n5. [Debugging Best Practices](#debugging-best-practices)\n6. [Command Reference](#command-reference)\n7. [Workflow Guidelines](#workflow-guidelines)\n\n## CRITICAL: Widget Debugging Must Use Local Sync\n\n### \uD83D\uDD34 When User Reports Widget Issues, ALWAYS Use `snow_pull_artifact` FIRST!\n\n**Common scenarios that REQUIRE Local Sync:**\n- \"Widget skips questions\" \u2192 `snow_pull_artifact`\n- \"Form doesn't submit properly\" \u2192 `snow_pull_artifact`\n- \"Data not displaying\" \u2192 `snow_pull_artifact`\n- \"Button doesn't work\" \u2192 `snow_pull_artifact`\n- \"Debug this widget\" \u2192 `snow_pull_artifact`\n- \"Fix widget issue\" \u2192 `snow_pull_artifact`\n\n**DO NOT use `snow_query_table` for widget debugging!** It will hit token limits and you can't use native search/edit tools.\n\n## Core Philosophy\n\n### The Prime Directive: Verify, Don't Assume\n\nSnow-Flow operates on evidence-based development. Never make assumptions about what exists or doesn't exist in a ServiceNow environment. Every environment is unique with custom tables, fields, integrations, and configurations that you cannot predict.\n\n**Cardinal Rules:**\n1. If code references something, it probably exists\n2. Test before declaring something broken\n3. Verify before modifying\n4. Fix only what's confirmed broken\n5. Respect existing configurations\n\n### The Verification-First Approach\n\n```javascript\n// Before claiming anything doesn't work or exist:\n// Step 1: Test the actual implementation - COMPLETE TEST, NO MOCK\nconst verify = await snow_execute_script_with_output({\n script: `\n // REAL verification code - NO placeholders\n var gr = new GlideRecord('actual_table_name');\n gr.addQuery('active', true);\n gr.query();\n var count = 0;\n while (gr.next()) {\n count++;\n gs.info('Record found: ' + gr.getDisplayValue());\n }\n gs.info('Total records: ' + count);\n `\n});\n\n// Step 2: Check if resources exist - ACTUAL CHECK, NO ASSUMPTIONS\nconst tableCheck = await snow_discover_table_fields({\n table_name: 'potentially_custom_table'\n});\n\n// Step 3: Validate configurations - REAL VALIDATION\nconst propertyCheck = await snow_property_manager({\n action: 'get',\n name: 'system.property'\n});\n\n// Step 4: Only then make informed decisions based on REAL DATA\n```\n\n### \uD83D\uDD04 CRITICAL: Sync User Modifications Before Working\n\n**When a user mentions they've modified an artifact directly in ServiceNow, ALWAYS fetch the latest version first!**\n\nIf a user says any of these:\n- \"I've updated the widget in ServiceNow\"\n- \"I made some changes to the flow\"\n- \"I modified the script\"\n- \"I adjusted the configuration\"\n- \"Ik heb het zelf aangepast\" (Dutch: I adjusted it myself)\n\n**YOU MUST:**\n\n1. **Immediately fetch the current version from ServiceNow:**\n```javascript\n// For any artifact the user has modified\nconst currentVersion = await snow_query_table({\n table: 'artifact_table_name',\n query: `sys_id=${artifact_sys_id}`,\n fields: ['*'], // Get all fields\n limit: 1\n});\n\n// Or for widgets specifically\nconst widgetData = await snow_query_table({\n table: 'sp_widget',\n query: `sys_id=${widget_sys_id}`,\n fields: ['name', 'template', 'client_script', 'script', 'css', 'option_schema'],\n limit: 1\n});\n\n// Or use snow_get_by_sysid for comprehensive retrieval\nconst artifact = await snow_get_by_sysid({\n table: 'table_name',\n sys_id: 'the_sys_id'\n});\n```\n\n2. **Analyze the user's modifications:**\n - Review what they changed\n - Understand their intent\n - Preserve their modifications\n\n3. **Build upon their changes:**\n - Don't overwrite their work\n - Integrate new features with their modifications\n - Maintain their code style and patterns\n\n4. **Inform the user:**\n - Acknowledge that you've fetched their latest changes\n - Summarize what modifications you found\n - Explain how you'll build upon their work\n\n**Example Workflow:**\n```javascript\n// User: \"I've updated the widget to add a loading spinner\"\n// Snow-Flow response:\n\n// 1. Fetch current version\nconst widget = await snow_query_table({\n table: 'sp_widget',\n query: `sys_id=${widgetSysId}`,\n fields: ['*'],\n limit: 1\n});\n\n// 2. Analyze changes\nconsole.log(\"\u2705 Fetched your latest widget version from ServiceNow\");\nconsole.log(\"\uD83D\uDCDD I see you've added a loading spinner in the template\");\n\n// 3. Work with the updated version\n// ... make additional changes based on user's modifications ...\n```\n\n**Why This Matters:**\n- User modifications are not tracked locally\n- Working with outdated versions causes conflicts\n- User's work could be lost if not synced\n- Builds trust by respecting user's contributions\n- Ensures coherent development flow\n\n## Fundamental Rules\n\n### Rule 1: \uD83D\uDEA8 ES5 JavaScript ONLY in ServiceNow - NO EXCEPTIONS!\n\n**\u26A0\uFE0F CRITICAL WARNING: ServiceNow uses Rhino engine - ES6/ES7/ES8+ WILL FAIL!**\n\nServiceNow's server-side JavaScript runs on Mozilla Rhino which **ONLY supports ES5 (2009)**. Any modern JavaScript syntax will cause **RUNTIME ERRORS**.\n\n**\u274C THESE WILL CRASH SERVICENOW (DO NOT USE):**\n```javascript\n// \u274C ES6+ features that BREAK ServiceNow:\nconst data = []; // SyntaxError: missing ; after for-loop initializer\nlet items = []; // SyntaxError: missing ; after for-loop initializer \nconst fn = () => {}; // SyntaxError: syntax error\nvar msg = `Hello ${name}`; // SyntaxError: syntax error\nfor (let item of items){} // SyntaxError: missing ; after for-loop initializer\nvar {name, id} = user; // SyntaxError: destructuring declaration not supported\narray.forEach(x => {}); // SyntaxError: syntax error \narray.map(x => x.id); // SyntaxError: syntax error\nfunction test(param = 'default') {} // SyntaxError: syntax error\nclass MyClass {} // SyntaxError: missing ; after for-loop initializer\n```\n\n**\u2705 ONLY USE ES5 SYNTAX (THIS WORKS):**\n```javascript\n// \u2705 ES5 compatible code that WORKS in ServiceNow:\nvar data = [];\nvar items = [];\nfunction fn() { return 'result'; }\nvar msg = 'Hello ' + name;\nfor (var i = 0; i < items.length; i++) {\n var item = items[i];\n}\nvar name = user.name;\nvar id = user.id;\nfor (var j = 0; j < array.length; j++) {\n // Process array[j]\n}\nfunction test(param) {\n if (typeof param === 'undefined') param = 'default';\n}\n```\n\n**\uD83D\uDD25 COMMON MISTAKES THAT BREAK SERVICENOW:**\n1. **Arrow Functions**: `() => {}` \u2192 Use `function() {}`\n2. **Template Literals**: `` `${var}` `` \u2192 Use `'text ' + var`\n3. **Let/Const**: `let x` \u2192 Use `var x`\n4. **Destructuring**: `{a, b} = obj` \u2192 Use `obj.a`, `obj.b`\n5. **For...of**: `for (x of arr)` \u2192 Use `for (var i=0; i<arr.length; i++)`\n6. **Default Parameters**: `fn(x='default')` \u2192 Use `typeof x === 'undefined'`\n7. **Array Methods with Arrows**: `.map(x => x)` \u2192 Use `.map(function(x) { return x; })`\n\n### Rule 2: Background Scripts for Verification Only (Not Widget Updates!)\n\n**CRITICAL DISTINCTION:**\n- \u2705 Use background scripts for TESTING and VERIFICATION \n- \u274C Do NOT use background scripts to UPDATE widget fields\n- \u2705 Use `snow_update` to directly modify widget records\n- \u274C Do NOT try to import server scripts into client scripts via background scripts\n\n**\uD83D\uDEA8 ES5 ENFORCEMENT FOR BACKGROUND SCRIPTS:**\nBackground scripts run on ServiceNow's server-side Rhino engine. **EVERY background script MUST be ES5-only or it will fail.**\n\n**Quick ES5 Validation Checklist:**\n- [ ] No `const` or `let` (only `var`)\n- [ ] No arrow functions `() => {}` (only `function() {}`)\n- [ ] No template literals `` `${var}` `` (only string concatenation)\n- [ ] No destructuring `{a, b} = obj` (only explicit `obj.a`)\n- [ ] No `for...of` loops (only traditional `for` loops)\n- [ ] No default parameters (use `typeof` checks)\n- [ ] No modern array methods with arrows (use traditional functions)\n\nBackground scripts are excellent for verification and debugging, but widget updates must go through proper MCP tools.\n\n**NEW: Auto-Confirm Mode for Background Scripts (v3.4.10+)**\nYou can now skip the human-in-the-loop confirmation for trusted scripts:\n\n```javascript\n// Standard mode - requires user confirmation (ES5 ONLY!)\nsnow_execute_background_script({\n script: \"var gr = new GlideRecord('incident'); gr.query();\", // \u2705 ES5 syntax\n description: \"Query incidents\",\n allowDataModification: false\n});\n\n// Auto-confirm mode - executes immediately \u26A0\uFE0F USE WITH CAUTION!\nsnow_execute_background_script({\n script: \"var gr = new GlideRecord('incident'); gr.query();\", // \u2705 ES5 syntax\n description: \"Query incidents\",\n allowDataModification: false,\n autoConfirm: true // \u26A0\uFE0F Bypasses user confirmation!\n});\n\n// \u274C WRONG - This will FAIL in ServiceNow:\n// script: \"const gr = new GlideRecord('incident'); gr.query();\", // SyntaxError!\n// script: \"incidents.forEach(i => console.log(i.number));\", // SyntaxError!\n```\n\n**\uD83D\uDEA8 ES5 Validation Required:**\nBefore using any background script tool, validate your script is ES5-only:\n- No `const`/`let` (use `var`)\n- No arrow functions (use `function()`)\n- No template literals (use string concatenation)\n- No destructuring (use explicit property access)\n\n**\u26A0\uFE0F Security Warning:**\n- Only use `autoConfirm: true` for verified, safe scripts\n- High-risk operations will still be logged\n- All auto-executions are tracked with audit IDs\n- Default behavior (without autoConfirm) remains unchanged\n\n## \uD83D\uDEA8 CRITICAL: Common ES5 Mistakes That Break ServiceNow\n\nServiceNow developers frequently use modern JavaScript that fails on the Rhino engine. Here are the most common mistakes:\n\n### \uD83D\uDD25 Top ES5 Violations (Fix These Immediately!)\n\n**1. Arrow Functions with Array Methods**\n```javascript\n// \u274C BREAKS ServiceNow:\nvar activeIncidents = incidents.filter(inc => inc.active);\nvar numbers = activeIncidents.map(inc => inc.number);\n\n// \u2705 WORKS in ServiceNow:\nvar activeIncidents = [];\nfor (var i = 0; i < incidents.length; i++) {\n if (incidents[i].active) {\n activeIncidents.push(incidents[i]);\n }\n}\nvar numbers = [];\nfor (var j = 0; j < activeIncidents.length; j++) {\n numbers.push(activeIncidents[j].number);\n}\n```\n\n**2. Template Literals for String Building**\n```javascript\n// \u274C BREAKS ServiceNow:\nvar message = `Incident ${incident.number} assigned to ${user.name}`;\n\n// \u2705 WORKS in ServiceNow:\nvar message = 'Incident ' + incident.number + ' assigned to ' + user.name;\n```\n\n**3. Const/Let Variable Declarations**\n```javascript\n// \u274C BREAKS ServiceNow:\nconst MAX_RETRIES = 3;\nlet currentUser = gs.getUser();\n\n// \u2705 WORKS in ServiceNow:\nvar MAX_RETRIES = 3;\nvar currentUser = gs.getUser();\n```\n\n**4. Object Destructuring**\n```javascript\n// \u274C BREAKS ServiceNow:\nvar {name, email, department} = user;\nvar {sys_id: id, short_description: desc} = incident;\n\n// \u2705 WORKS in ServiceNow:\nvar name = user.name;\nvar email = user.email;\nvar department = user.department;\nvar id = incident.sys_id;\nvar desc = incident.short_description;\n```\n\n**5. For...of Loops**\n```javascript\n// \u274C BREAKS ServiceNow:\nfor (let incident of incidents) {\n gs.info('Processing: ' + incident.number);\n}\n\n// \u2705 WORKS in ServiceNow:\nfor (var i = 0; i < incidents.length; i++) {\n gs.info('Processing: ' + incidents[i].number);\n}\n```\n\n**6. Default Function Parameters**\n```javascript\n// \u274C BREAKS ServiceNow:\nfunction processIncident(incident, priority = 3, assignee = 'unassigned') {\n // Process incident\n}\n\n// \u2705 WORKS in ServiceNow:\nfunction processIncident(incident, priority, assignee) {\n if (typeof priority === 'undefined') priority = 3;\n if (typeof assignee === 'undefined') assignee = 'unassigned';\n // Process incident\n}\n```\n\n### \uD83C\uDFAF Quick ES5 Conversion Guide\n| Modern (ES6+) | ES5 Equivalent |\n|---------------|----------------|\n| `const x = 5;` | `var x = 5;` |\n| `let items = [];` | `var items = [];` |\n| `() => {}` | `function() {}` |\n| `` `Hello ${name}` `` | `'Hello ' + name` |\n| `{a, b} = obj` | `var a = obj.a; var b = obj.b;` |\n| `for (item of items)` | `for (var i = 0; i < items.length; i++)` |\n| `func(x = 'default')` | `if (typeof x === 'undefined') x = 'default';` |\n| `arr.map(x => x.id)` | `arr.map(function(x) { return x.id; })` |\n\n```javascript\n// Universal verification pattern - COMPLETE IMPLEMENTATION REQUIRED\nconst verify = await snow_execute_script_with_output({\n script: `\n gs.info('=== VERIFICATION TEST ===');\n \n // Test ACTUAL table existence - NO PLACEHOLDERS\n var incidentTable = new GlideRecord('incident');\n gs.info('Incident table valid: ' + incidentTable.isValid());\n \n // Count REAL records\n incidentTable.addQuery('active', true);\n incidentTable.query();\n var count = 0;\n while (incidentTable.next() && count < 10) {\n count++;\n gs.info('Found: ' + incidentTable.number + ' - ' + incidentTable.short_description);\n }\n gs.info('Total active incidents: ' + incidentTable.getRowCount());\n \n // Test ACTUAL property - use real property names\n var instanceName = gs.getProperty('instance_name');\n var glideVersion = gs.getProperty('glide.version');\n gs.info('Instance: ' + instanceName);\n gs.info('Version: ' + glideVersion);\n \n // Test COMPLETE user code - NO STUBS\n try {\n // REAL implementation - not placeholder\n var userGr = new GlideRecord('sys_user');\n userGr.addQuery('active', true);\n userGr.addQuery('user_name', gs.getUserName());\n userGr.query();\n if (userGr.next()) {\n gs.info('Current user: ' + userGr.name + ' (' + userGr.email + ')');\n gs.info('Roles: ' + userGr.roles.toString());\n }\n \n // Test ACTUAL business logic\n var taskGr = new GlideRecord('task');\n taskGr.addQuery('assigned_to', gs.getUserID());\n taskGr.addQuery('active', true);\n taskGr.query();\n gs.info('Active tasks assigned to me: ' + taskGr.getRowCount());\n \n gs.info('=== VERIFICATION COMPLETE ===');\n } catch(e) {\n gs.error('ERROR: ' + e.message);\n gs.error('Stack: ' + e.stack);\n }\n `\n});\n```\n\n### Rule 3: Widget Coherence - Critical Client-Server Communication\n\nServiceNow widgets MUST have perfect communication between client and server scripts. This is not optional - widgets fail when these components don't talk to each other correctly.\n\n**The Three-Way Contract:**\n\n**Server Script Must:**\n- Initialize all `data` properties that HTML will reference\n- Handle every `input.action` that client sends\n- Return data in the format client expects\n\n**Client Script Must:**\n- Implement every method that HTML calls via `ng-click`\n- Use `c.server.get({action: 'name'})` for server communication\n- Update `c.data` when server responds\n\n**HTML Template Must:**\n- Only reference `data` properties that server provides\n- Only call methods that client implements\n- Use correct Angular directives and bindings\n\n**Critical Communication Points:**\n\n1. **Server \u2192 Client Data Flow**\n - Server sets `data.property`\n - Client receives via `c.data.property`\n - HTML displays with `{{data.property}}`\n\n2. **Client \u2192 Server Requests**\n - Client sends `c.server.get({action: 'name'})`\n - Server receives via `input.action`\n - Server processes and returns updated `data`\n\n3. **HTML \u2192 Client Method Calls**\n - HTML has `ng-click=\"methodName()\"`\n - Client must have `$scope.methodName = function()`\n - Method typically calls server with `c.server.get()`\n\n**Common Failures to Avoid:**\n- Action name mismatches between client and server\n- Method name mismatches between HTML and client \n- Property name mismatches between server and HTML\n- Missing handlers for client requests\n- Orphaned data properties or methods\n\n**Coherence Validation Checklist:**\n- [ ] Every `data.property` in server is used in HTML/client\n- [ ] Every `ng-click` in HTML has matching `$scope.method` in client\n- [ ] Every `c.server.get({action})` in client has matching `if(input.action)` in server\n- [ ] Data flows correctly: Server \u2192 HTML \u2192 Client \u2192 Server\n- [ ] No orphaned methods or unused data properties\n\n### Rule 4: Use Local Sync for Widget Debugging - NOT snow_query_table!\n\n**CRITICAL: When debugging widgets, ALWAYS use `snow_pull_artifact` first!**\n\n```javascript\n// \u2705 CORRECT - Use Local Sync for widget debugging\nsnow_pull_artifact({ \n sys_id: 'widget_sys_id',\n table: 'sp_widget' \n});\n// Now use Claude Code native search, multi-file edit, etc.\n\n// \u274C WRONG - Don't use snow_query_table for debugging widgets\nsnow_query_table({ \n table: 'sp_widget',\n query: 'sys_id=...',\n fields: ['template', 'script', 'client_script'] \n});\n// This hits token limits and can't use native tools!\n```\n\n**Why Local Sync for Widget Debugging:**\n- **No token limits** - Handle widgets of ANY size\n- **Native search** - Find issues across all files instantly\n- **Multi-file view** - See relationships between components\n- **Better debugging** - Trace data flow, find missing methods\n- **Coherence checking** - Validate all parts work together\n\n**Widget Debugging Workflow:**\n1. User reports issue \u2192 `snow_pull_artifact`\n2. Search for error patterns across files\n3. Fix using multi-file edit\n4. Validate coherence \u2192 `snow_validate_artifact_coherence`\n5. Push fixes back \u2192 `snow_push_artifact`\n\n**IMPORTANT: Use Local Sync Instead of Query for Large Widgets**\n\nWhen you see \"exceeds maximum allowed tokens\" errors, don't try to fetch fields separately with `snow_query_table`. Use Local Sync instead:\n\n```javascript\n// \u274C WRONG - Don't do this when debugging:\nsnow_query_table({ table: 'sp_widget', fields: ['name'] });\nsnow_query_table({ table: 'sp_widget', fields: ['script'] });\nsnow_query_table({ table: 'sp_widget', fields: ['client_script'] });\n// This is inefficient and can't use native tools!\n\n// \u2705 CORRECT - Use Local Sync:\nsnow_pull_artifact({ \n sys_id: '01d01d6983176a502a7ea130ceaad376' \n});\n// All files available locally with NO token limits!\n```\n\n**Local Sync Benefits:**\n- Handles widgets of ANY size automatically\n- All files available for native tool usage\n- Maintains relationships between components\n- Enables powerful search and refactoring\n\n### Rule 5: Evidence-Based Debugging\n\nFollow this systematic approach for all debugging:\n\n1. **Reproduce** - Run the exact failing code\n2. **Inventory** - List all dependencies\n3. **Verify** - Test each dependency exists\n4. **Fix** - Correct only confirmed issues\n\n**Fix only:**\n- \u2705 Confirmed syntax errors\n- \u2705 Verified null references\n- \u2705 Missing dependencies (after verification)\n- \u2705 Real type mismatches\n\n**Never change:**\n- \u274C Unverified resources\n- \u274C Configurations that \"seem wrong\"\n- \u274C APIs you haven't tested\n- \u274C Working code that could be \"better\"\n\n## ServiceNow Development Standards\n\n### Table Operations\n- Always verify table existence before operations\n- Use proper field types and references\n- Check for ACLs and permissions\n- Handle large datasets with pagination\n\n### Script Development\n- Use Script Includes for reusable code\n- Implement proper error handling\n- Add meaningful logging with gs.info/warn/error\n- Test in scoped applications when applicable\n- **NEVER use background scripts to update widget fields - use `snow_update` instead**\n\n### Widget Development\n\n**\uD83D\uDEA8 NO MOCK WIDGETS - EVERY WIDGET MUST BE COMPLETE AND FUNCTIONAL**\n\n**CRITICAL: Direct Widget Updates (Not Background Scripts!)**\n- Use `snow_update({ type: 'widget', identifier: 'widget_name', config: { /* COMPLETE fields */ }})` \n- Updates widget fields DIRECTLY on the widget record\n- Do NOT use background scripts to update widget fields\n- Do NOT try to import server scripts into client scripts\n\n**Widget Coherence Requirements:**\n- Ensure HTML/Client/Server scripts communicate properly\n- Use Angular providers correctly \n- Implement proper data binding\n- Test across different themes and portals\n- **NO PLACEHOLDER CONTENT - Every widget must be production-ready**\n\n**Creating New Widgets - COMPLETE IMPLEMENTATION REQUIRED:**\n```javascript\n// \u274C WRONG - Mock/placeholder widget\nsnow_deploy({\n type: 'widget',\n config: {\n name: 'test_widget',\n template: '<div>TODO: Add content</div>', // NO!\n script: '// TODO: Add logic', // NO!\n client_script: '// Placeholder' // NO!\n }\n})\n\n// \u2705 CORRECT - Complete, functional widget\nsnow_deploy({\n type: 'widget',\n config: {\n name: 'incident_dashboard_widget',\n title: 'Incident Dashboard',\n template: `\n <div class=\"incident-dashboard\">\n <div class=\"dashboard-header\">\n <h2>{{data.title}}</h2>\n <span class=\"refresh-time\">{{data.lastRefresh}}</span>\n </div>\n <div class=\"stats-container\">\n <div class=\"stat-card\" ng-repeat=\"stat in data.stats\">\n <div class=\"stat-value\">{{stat.value}}</div>\n <div class=\"stat-label\">{{stat.label}}</div>\n </div>\n </div>\n <div class=\"incident-list\">\n <table class=\"table\">\n <thead>\n <tr>\n <th>Number</th>\n <th>Short Description</th>\n <th>Priority</th>\n <th>Assigned To</th>\n </tr>\n </thead>\n <tbody>\n <tr ng-repeat=\"incident in data.incidents\" ng-click=\"c.openIncident(incident.sys_id)\">\n <td>{{incident.number}}</td>\n <td>{{incident.short_description}}</td>\n <td><span class=\"priority-{{incident.priority}}\">{{incident.priority}}</span></td>\n <td>{{incident.assigned_to}}</td>\n </tr>\n </tbody>\n </table>\n </div>\n </div>\n `,\n script: `\n // COMPLETE server-side implementation\n (function() {\n data.title = 'Incident Dashboard';\n data.lastRefresh = new GlideDateTime().getDisplayValue();\n \n // Get incident statistics\n data.stats = [];\n \n var totalGr = new GlideAggregate('incident');\n totalGr.addQuery('active', true);\n totalGr.addAggregate('COUNT');\n totalGr.query();\n if (totalGr.next()) {\n data.stats.push({\n value: totalGr.getAggregate('COUNT'),\n label: 'Total Active'\n });\n }\n \n var criticalGr = new GlideAggregate('incident');\n criticalGr.addQuery('active', true);\n criticalGr.addQuery('priority', '1');\n criticalGr.addAggregate('COUNT');\n criticalGr.query();\n if (criticalGr.next()) {\n data.stats.push({\n value: criticalGr.getAggregate('COUNT'),\n label: 'Critical'\n });\n }\n \n // Get recent incidents\n data.incidents = [];\n var incGr = new GlideRecord('incident');\n incGr.addQuery('active', true);\n incGr.orderByDesc('sys_created_on');\n incGr.setLimit(10);\n incGr.query();\n \n while (incGr.next()) {\n data.incidents.push({\n sys_id: incGr.getUniqueValue(),\n number: incGr.getValue('number'),\n short_description: incGr.getValue('short_description'),\n priority: incGr.getValue('priority'),\n assigned_to: incGr.assigned_to.getDisplayValue()\n });\n }\n \n // Handle server actions\n if (input && input.action === 'refresh') {\n // Refresh logic\n data.lastRefresh = new GlideDateTime().getDisplayValue();\n }\n })();\n `,\n client_script: `\n function($scope, $window, spModal) {\n var c = this;\n \n // Initialize client controller\n c.refreshInterval = null;\n \n // Open incident in new window\n c.openIncident = function(sysId) {\n var url = '/nav_to.do?uri=incident.do?sys_id=' + sysId;\n $window.open(url, '_blank');\n };\n \n // Refresh data\n c.refresh = function() {\n c.server.get({\n action: 'refresh'\n }).then(function(response) {\n console.log('Dashboard refreshed');\n });\n };\n \n // Auto-refresh every 30 seconds\n c.startAutoRefresh = function() {\n c.refreshInterval = setInterval(function() {\n $scope.$apply(function() {\n c.refresh();\n });\n }, 30000);\n };\n \n // Clean up on destroy\n $scope.$on('$destroy', function() {\n if (c.refreshInterval) {\n clearInterval(c.refreshInterval);\n }\n });\n \n // Start auto-refresh\n c.startAutoRefresh();\n }\n `,\n css: `\n .incident-dashboard {\n padding: 20px;\n background: #f5f5f5;\n }\n \n .dashboard-header {\n display: flex;\n justify-content: space-between;\n margin-bottom: 20px;\n }\n \n .stats-container {\n display: flex;\n gap: 15px;\n margin-bottom: 20px;\n }\n \n .stat-card {\n flex: 1;\n background: white;\n padding: 15px;\n border-radius: 8px;\n box-shadow: 0 2px 4px rgba(0,0,0,0.1);\n text-align: center;\n }\n \n .stat-value {\n font-size: 32px;\n font-weight: bold;\n color: #333;\n }\n \n .stat-label {\n font-size: 14px;\n color: #666;\n margin-top: 5px;\n }\n \n .incident-list {\n background: white;\n border-radius: 8px;\n padding: 15px;\n }\n \n .incident-list tr {\n cursor: pointer;\n }\n \n .incident-list tr:hover {\n background: #f0f0f0;\n }\n \n .priority-1 { color: #d9534f; font-weight: bold; }\n .priority-2 { color: #f0ad4e; }\n .priority-3 { color: #5bc0de; }\n .priority-4 { color: #5cb85c; }\n .priority-5 { color: #777; }\n `,\n option_schema: [\n {\n name: 'refresh_interval',\n label: 'Refresh Interval (seconds)',\n type: 'integer',\n default: 30\n },\n {\n name: 'max_incidents',\n label: 'Maximum Incidents to Display',\n type: 'integer',\n default: 10\n }\n ]\n }\n})\n```\n\n**Updating Existing Widgets:**\n```javascript\nsnow_update({\n type: 'widget',\n identifier: 'my_widget', // Name or sys_id\n config: {\n template: '<div>Updated HTML</div>', // Only update what changes\n script: 'data.updated = true;' // ServiceNow uses 'script' field\n }\n})\n```\n\n### Flow Development\n- Use proper trigger conditions\n- Implement error handling paths\n- Add appropriate logging actions\n- Test with various data scenarios\n\n## MCP Server Capabilities\n\nSnow-Flow includes 16+ specialized MCP servers with over 200 tools for comprehensive ServiceNow integration:\n\n### 1. ServiceNow Deployment Server\n**Purpose:** Widget and artifact deployment with coherence validation\n\n**Key Tools:**\n- `snow_deploy` - Create NEW artifacts (widgets, pages, etc.) - use with `type: 'widget'`\n- `snow_update` - UPDATE existing artifacts - use for widget field updates\n- `snow_validate_deployment` - Validate deployed artifacts\n- `snow_rollback_deployment` - Rollback failed deployments\n- `snow_preview_widget` - Preview widget before deployment\n- `snow_widget_test` - Test widget functionality\n\n**Special Features:**\n- Automatic widget coherence validation\n- Data flow contract verification\n- Method implementation checking\n- CSS class validation\n\n### 2. ServiceNow Operations Server\n**Purpose:** Core ServiceNow operations and queries\n\n**Key Tools:**\n- `snow_query_table` - Universal table querying with pagination\n- `snow_query_incidents` - Query and analyze incidents\n- `snow_cmdb_search` - Search Configuration Management Database\n- `snow_user_lookup` - Find and manage users\n- `snow_operational_metrics` - Get operational metrics\n- `snow_knowledge_search` - Search knowledge base\n\n**Features:**\n- Full CRUD operations on any table\n- Advanced query capabilities\n- Field discovery and validation\n- Relationship navigation\n\n### 3. ServiceNow Automation Server\n**Purpose:** Script execution and automation\n\n**\uD83D\uDEA8 CRITICAL: ALL SCRIPTS MUST BE ES5 ONLY!**\nServiceNow runs on Rhino engine - ES6+ syntax will cause SyntaxError and script failure.\n\n**Key Tools:**\n- `snow_execute_background_script` - Execute background scripts (**ES5 ONLY!** with optional autoConfirm)\n- `snow_confirm_script_execution` - Confirm script execution after user approval\n- `snow_execute_script_with_output` - Execute scripts with output capture (**ES5 ONLY!**)\n- `snow_get_script_output` - Retrieve script execution history\n- `snow_execute_script_sync` - Synchronous script execution (**ES5 ONLY!**)\n- `snow_get_logs` - Access system logs\n- `snow_test_rest_connection` - Test REST integrations\n- `snow_trace_execution` - Trace script execution (**ES5 ONLY!**)\n- `snow_schedule_job` - Create scheduled jobs\n- `snow_create_event` - Trigger system events\n\n**Remember:** Use `var`, `function(){}`, string concatenation, traditional for loops only!\n\n**Features:**\n- Full output capture (gs.print/info/warn/error)\n- Execution history tracking\n- System log access\n- REST message testing\n- Performance tracing\n\n### 4. ServiceNow Platform Development Server\n**Purpose:** Platform development artifacts\n\n**Key Tools:**\n- `snow_create_ui_page` - Create UI pages\n- `snow_create_script_include` - Create reusable scripts\n- `snow_create_business_rule` - Create business rules\n- `snow_create_client_script` - Create client-side scripts\n- `snow_create_ui_policy` - Create UI policies\n- `snow_create_ui_action` - Create UI actions\n\n**Features:**\n- Full artifact creation\n- Proper scoping support\n- Condition builder integration\n- Script validation\n\n### 5. ServiceNow Integration Server\n**Purpose:** Integration and data management\n\n**Key Tools:**\n- `snow_create_rest_message` - Create REST integrations\n- `snow_create_transform_map` - Create data transformation maps\n- `snow_create_import_set` - Manage import sets\n- `snow_test_web_service` - Test web services\n- `snow_configure_email` - Configure email settings\n\n**Features:**\n- REST/SOAP integration\n- Data transformation\n- Import/Export capabilities\n- Email configuration\n\n### 6. ServiceNow System Properties Server\n**Purpose:** System property management\n\n**Key Tools:**\n- `snow_property_get` - Retrieve property values\n- `snow_property_set` - Set property values\n- `snow_property_list` - List properties by pattern\n- `snow_property_delete` - Remove properties\n- `snow_property_bulk_update` - Bulk operations\n- `snow_property_export` - Export to JSON\n- `snow_property_import` - Import from JSON\n\n**Features:**\n- Full CRUD on sys_properties\n- Bulk operations\n- Import/Export capabilities\n- Property validation\n\n### 7. ServiceNow Update Set Server\n**Purpose:** Change management and deployment\n\n**Key Tools:**\n- `snow_update_set_create` - Create new update sets\n- `snow_update_set_switch` - Switch active update set\n- `snow_update_set_current` - Get current update set\n- `snow_update_set_complete` - Mark as complete\n- `snow_update_set_export` - Export as XML\n- `snow_ensure_active_update_set` - Ensure update set is active\n\n**Features:**\n- Full update set lifecycle\n- Change tracking\n- XML export/import\n- Conflict detection\n\n### 8. ServiceNow Development Assistant Server\n**Purpose:** Intelligent artifact search, editing and development assistance\n\n**Key Tools:**\n- `snow_find_artifact` - Find any ServiceNow artifact by name/type\n- `snow_edit_artifact` - Edit existing artifacts intelligently\n- `snow_get_by_sysid` - Get artifact by sys_id\n- `snow_analyze_artifact` - Analyze artifact structure and dependencies\n- `snow_comprehensive_search` - Deep search across all tables\n- `snow_analyze_requirements` - Analyze development requirements\n\n**Features:**\n- Pattern-based code generation\n- Best practice enforcement\n- Performance optimization\n- Security review\n\n### 9. ServiceNow Security & Compliance Server\n**Purpose:** Security and compliance management\n\n**Key Tools:**\n- `snow_create_security_policy` - Create security policies\n- `snow_audit_compliance` - Compliance auditing\n- `snow_scan_vulnerabilities` - Vulnerability scanning\n- `snow_assess_risk` - Risk assessment\n- `snow_review_access_control` - ACL review\n\n**Features:**\n- SOX/GDPR/HIPAA compliance\n- Security policy management\n- Vulnerability assessment\n- Access control validation\n\n### 10. ServiceNow Reporting & Analytics Server\n**Purpose:** Reporting and data visualization\n\n**Key Tools:**\n- `snow_create_report` - Create reports\n- `snow_create_dashboard` - Create dashboards\n- `snow_define_kpi` - Define KPIs\n- `snow_schedule_report` - Schedule report delivery\n- `snow_analyze_data_quality` - Data quality analysis\n\n**Features:**\n- Advanced reporting\n- Dashboard creation\n- KPI management\n- Scheduled delivery\n\n### 11. ServiceNow Machine Learning Server\n**Purpose:** AI/ML capabilities with TensorFlow.js and native ML integration\n\n**Key Tools:**\n- `ml_train_incident_classifier` - Train incident classifier with LSTM neural networks\n- `ml_predict_change_risk` - Predict change risks\n- `ml_detect_anomalies` - Anomaly detection\n- `ml_forecast_incidents` - Incident forecasting with time series\n- `ml_performance_analytics` - Native Performance Analytics ML\n- `ml_hybrid_recommendation` - Hybrid ML recommendations\n\n**Features:**\n- Predictive analytics\n- Pattern recognition\n- Anomaly detection\n- Process optimization\n\n### 12. ServiceNow Local Development Server\n**Purpose:** Bridge between ServiceNow artifacts and Claude Code's native development tools\n\n**Key Tools:**\n- `snow_pull_artifact` - Pull any ServiceNow artifact to local files\n- `snow_push_artifact` - Push local changes back with validation\n- `snow_validate_artifact_coherence` - Validate artifact relationships\n- `snow_list_supported_artifacts` - List all supported artifact types\n- `snow_sync_status` - Check sync status of local artifacts\n- `snow_sync_cleanup` - Clean up local files after sync\n- `snow_convert_to_es5` - Convert modern JavaScript to ES5\n\n**Features:**\n- Supports 12+ artifact types dynamically\n- Smart field chunking for large artifacts\n- ES5 validation for server-side scripts\n- Coherence validation for widgets\n- Full Claude Code native tool integration\n\n**Supported Artifact Types:**\n- Service Portal Widgets (`sp_widget`)\n- Flow Designer Flows (`sys_hub_flow`)\n- Script Includes (`sys_script_include`)\n- Business Rules (`sys_script`)\n- UI Pages (`sys_ui_page`)\n- Client Scripts (`sys_script_client`)\n- UI Policies (`sys_ui_policy`)\n- REST Messages (`sys_rest_message`)\n- Transform Maps (`sys_transform_map`)\n- Scheduled Jobs (`sysauto_script`)\n- Fix Scripts (`sys_script_fix`)\n\n### 13. Snow-Flow Orchestration Server\n**Purpose:** Multi-agent coordination and task management\n\n**Key Tools:**\n- `swarm_init` - Initialize agent swarms\n- `agent_spawn` - Create specialized agents\n- `task_orchestrate` - Orchestrate complex tasks\n- `memory_search` - Search persistent memory\n- `neural_train` - Train neural networks with TensorFlow.js\n- `performance_report` - Generate performance reports\n\n**Features:**\n- Multi-agent coordination\n- Task orchestration\n- Neural network training (TensorFlow.js)\n- Memory management\n- Performance monitoring\n\n### Additional Servers:\n\n**ServiceNow CMDB/Event/HR/CSM/DevOps Server** - CI management, event correlation, HR processes, customer service, DevOps pipelines\n\n**ServiceNow Knowledge & Catalog Server** - Knowledge articles, service catalog items, catalog variables and policies\n\n**ServiceNow Change/Virtual Agent/PA Server** - Change management, virtual agent NLU, predictive analytics\n\n**ServiceNow Flow/Workspace/Mobile Server** - Flow Designer, workspace configuration, mobile app management\n\n**Features:**\n- Multi-agent coordination\n- Task orchestration\n- Neural network training (TensorFlow.js)\n- Memory management\n- Performance monitoring\n\n## Local Development with Artifact Sync\n\n### Dynamic Artifact Synchronization\n\nThe Local Development Server enables editing ServiceNow artifacts using Claude Code's native file tools. This creates a powerful development bridge between ServiceNow and local development environments.\n\n**Workflow:**\n\n1. **Pull Artifact to Local Files**\n ```javascript\n // Auto-detect artifact type\n snow_pull_artifact({ sys_id: 'any_sys_id' });\n \n // Or specify table for faster pull\n snow_pull_artifact({ \n sys_id: 'widget_sys_id',\n table: 'sp_widget' \n });\n ```\n\n2. **Edit with Claude Code Native Tools**\n - Full search capabilities across files\n - Multi-file editing and refactoring\n - Syntax highlighting and validation\n - Git-like diff viewing\n - Go-to-definition and references\n\n3. **Validate Coherence**\n ```javascript\n // Check artifact relationships\n snow_validate_artifact_coherence({ \n sys_id: 'artifact_sys_id' \n });\n ```\n\n4. **Push Changes Back**\n ```javascript\n // Push with automatic validation\n snow_push_artifact({ sys_id: 'artifact_sys_id' });\n \n // Force push despite warnings\n snow_push_artifact({ \n sys_id: 'artifact_sys_id',\n force: true \n });\n ```\n\n5. **Clean Up**\n ```javascript\n // Remove local files after sync\n snow_sync_cleanup({ sys_id: 'artifact_sys_id' });\n ```\n\n**Artifact Registry:**\n\nEach artifact type is configured with:\n- Field mappings to local files\n- Context-aware wrappers for better editing\n- ES5 validation flags for server scripts\n- Coherence rules for interconnected fields\n- Preprocessors/postprocessors for data transformation\n\n**File Structure Example:**\n```\n/tmp/snow-flow-artifacts/\n\u251C\u2500\u2500 widgets/\n\u2502 \u2514\u2500\u2500 my_widget/\n\u2502 \u251C\u2500\u2500 my_widget.html # Template\n\u2502 \u251C\u2500\u2500 my_widget.server.js # Server script (ES5)\n\u2502 \u251C\u2500\u2500 my_widget.client.js # Client script\n\u2502 \u251C\u2500\u2500 my_widget.css # Styles\n\u2502 \u251C\u2500\u2500 my_widget.config.json # Configuration\n\u2502 \u2514\u2500\u2500 README.md # Context & instructions\n\u251C\u2500\u2500 script_includes/\n\u2502 \u2514\u2500\u2500 MyScriptInclude/\n\u2502 \u251C\u2500\u2500 MyScriptInclude.js # Script\n\u2502 \u2514\u2500\u2500 MyScriptInclude.docs.md # Documentation\n\u2514\u2500\u2500 business_rules/\n \u2514\u2500\u2500 my_rule/\n \u251C\u2500\u2500 my_rule.js # Rule script\n \u2514\u2500\u2500 my_rule.condition.js # Condition\n```\n\n**Benefits:**\n- Use your favorite editor features\n- Full search and replace capabilities\n- Version control integration\n- Bulk operations across artifacts\n- Offline development capability\n- Advanced refactoring tools\n\n## Debugging Best Practices\n\n### Systematic Debugging Protocol\n\n1. **Reproduce the Issue**\n ```javascript\n // Always use ES5 and test exact code\n const result = await snow_execute_script_with_output({\n script: `/* Exact failing code in ES5 */`\n });\n ```\n\n2. **Verify Dependencies**\n - Check all referenced tables exist\n - Verify all properties are set\n - Confirm all fields are present\n - Test all integrations work\n\n3. **Test in Context**\n - Use same scope and variables\n - Include same imports\n - Test with same data\n\n4. **Apply Evidence-Based Fixes**\n - Fix only confirmed issues\n - Document why changes were made\n - Test fixes thoroughly\n\n### Common Verification Patterns\n\n**Table Verification:**\n```javascript\nvar table = new GlideRecord('table_name');\ngs.info('Table exists: ' + table.isValid());\n```\n\n**Property Verification:**\n```javascript\nvar prop = gs.getProperty('property.name');\ngs.info('Property value: ' + (prop || 'NOT SET'));\n```\n\n**Field Verification:**\n```javascript\nvar gr = new GlideRecord('table');\nvar element = gr.getElement('field_name');\ngs.info('Field exists: ' + (element ? 'Yes' : 'No'));\n```\n\n## Command Reference\n\n### Core Commands\n- `./snow-flow start` - Start orchestration system\n- `./snow-flow status` - System status\n- `./snow-flow monitor` - Real-time monitoring\n\n### Agent Management\n- `./snow-flow agent spawn <type>` - Create agents\n- `./snow-flow agent list` - List active agents\n\n### Task Management\n- `./snow-flow task create` - Create tasks\n- `./snow-flow task list` - View task queue\n\n### Memory Operations\n- `./snow-flow memory store <key> <data>` - Store data\n- `./snow-flow memory get <key>` - Retrieve data\n- `./snow-flow memory list` - List all keys\n\n### SPARC Modes\n- `./snow-flow sparc \"<task>\"` - Orchestrator mode\n- `./snow-flow sparc run <mode> \"<task>\"` - Specific mode\n- `./snow-flow sparc tdd \"<feature>\"` - Test-driven development\n\n### Swarm Coordination\n- `./snow-flow swarm \"<objective>\"` - Multi-agent coordination\n- Options: `--strategy`, `--mode`, `--parallel`, `--monitor`\n\n## Workflow Guidelines\n\n### Development Workflow\n1. **Plan** - Use TodoWrite for task management\n2. **Verify** - Check existing resources\n3. **Develop** - Follow ES5 standards\n4. **Test** - Use background scripts\n5. **Deploy** - Use update sets\n6. **Validate** - Verify deployment\n\n### Testing Workflow\n1. Run unit tests with background scripts\n2. Test integrations with REST tools\n3. Validate UI with widget coherence\n4. Check performance with tracing\n5. Review logs for errors\n\n### Debugging Workflow\n1. Reproduce issue exactly\n2. Gather evidence with scripts\n3. Verify all assumptions\n4. Apply minimal fixes\n5. Test thoroughly\n6. Document changes\n\n## Important Reminders\n\n### Always Remember\n- Every ServiceNow instance is unique\n- Custom implementations exist that you don't know about\n- Preview/beta features may be available\n- Organization-specific configurations are common\n- Test everything before making assumptions\n\n### Never Assume\n- That something doesn't exist without verification\n- That configurations are wrong without testing\n- That APIs aren't available without checking\n- That code won't work without running it\n- That you know better than existing implementations\n\n### Golden Rules\n1. **Verify First** - Test before declaring broken\n2. **ES5 Only** - No modern JavaScript in ServiceNow\n3. **Evidence-Based** - Make decisions on facts, not assumptions\n4. **Minimal Changes** - Fix only what's broken\n5. **Respect Context** - Understand why things exist as they do\n\n## Conclusion\n\nSnow-Flow is a powerful framework for ServiceNow development that demands **COMPLETE, PRODUCTION-READY IMPLEMENTATIONS** with absolutely **NO MOCK DATA, NO PLACEHOLDERS, and NO SHORTCUTS**.\n\n**The Snow-Flow Standard:**\n- **EVERY** line of code must be complete and functional\n- **EVERY** feature must be fully implemented\n- **EVERY** integration must be real and working\n- **EVERY** solution must be production-ready\n- **NO EXCEPTIONS, NO EXCUSES**\n\nBy following these guidelines and the **NO MOCK DATA** principle, you ensure:\n- Reliable, maintainable ServiceNow solutions\n- Complete implementations that work in production\n- Professional-grade code that users can depend on\n- Real solutions to real problems\n\nRemember: \n1. **NO MOCK DATA** - Everything must be real\n2. **TAKE THE TIME** - Do it right, no shortcuts\n3. **COMPLETE IMPLEMENTATIONS** - Every feature, every time\n4. **PRODUCTION READY** - Users depend on this being real\n5. **VERIFY AND TEST** - With real data, real systems\n\nYour job is to deliver **COMPLETE, WORKING SOLUTIONS**. Every implementation matters. Every line of code counts. Every feature must work.\n\n**TAKE THE TIME. DO IT RIGHT. NO MOCK DATA. NO EXCEPTIONS.**";
2
- export declare const CLAUDE_MD_TEMPLATE_VERSION = "3.6.1-NO-MOCK-DATA";
3
- //# sourceMappingURL=claude-md-template-old.d.ts.map