snow-flow 3.4.11 → 3.4.14

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.
@@ -11,9 +11,8 @@ const index_js_1 = require("@modelcontextprotocol/sdk/server/index.js");
11
11
  const stdio_js_1 = require("@modelcontextprotocol/sdk/server/stdio.js");
12
12
  const types_js_1 = require("@modelcontextprotocol/sdk/types.js");
13
13
  const servicenow_client_js_1 = require("../utils/servicenow-client.js");
14
- const logger_js_1 = require("../utils/logger.js");
14
+ const mcp_logger_js_1 = require("./shared/mcp-logger.js");
15
15
  const snow_oauth_js_1 = require("../utils/snow-oauth.js");
16
- const logger = new logger_js_1.Logger('ServiceNowSystemProperties');
17
16
  /**
18
17
  * ServiceNow System Properties MCP Server
19
18
  * Manages system properties through official ServiceNow REST APIs
@@ -31,6 +30,7 @@ class ServiceNowSystemPropertiesMCP {
31
30
  });
32
31
  this.client = new servicenow_client_js_1.ServiceNowClient();
33
32
  this.oauth = new snow_oauth_js_1.SnowOAuth();
33
+ this.logger = new mcp_logger_js_1.MCPLogger('ServiceNowSystemProperties');
34
34
  this.setupHandlers();
35
35
  this.setupTools();
36
36
  }
@@ -319,42 +319,60 @@ class ServiceNowSystemPropertiesMCP {
319
319
  this.server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request) => {
320
320
  const { name, arguments: args } = request.params;
321
321
  try {
322
+ // Start operation with token tracking
323
+ this.logger.operationStart(name, args);
322
324
  // Ensure authentication
323
325
  const isAuthenticated = await this.oauth.isAuthenticated();
324
326
  if (!isAuthenticated) {
325
327
  throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidRequest, 'Not authenticated. Please run "snow-flow auth login" first.');
326
328
  }
329
+ let result;
327
330
  switch (name) {
328
331
  case 'snow_property_get':
329
- return await this.getProperty(args);
332
+ result = await this.getProperty(args);
333
+ break;
330
334
  case 'snow_property_set':
331
- return await this.setProperty(args);
335
+ result = await this.setProperty(args);
336
+ break;
332
337
  case 'snow_property_list':
333
- return await this.listProperties(args);
338
+ result = await this.listProperties(args);
339
+ break;
334
340
  case 'snow_property_delete':
335
- return await this.deleteProperty(args);
341
+ result = await this.deleteProperty(args);
342
+ break;
336
343
  case 'snow_property_search':
337
- return await this.searchProperties(args);
344
+ result = await this.searchProperties(args);
345
+ break;
338
346
  case 'snow_property_bulk_get':
339
- return await this.bulkGetProperties(args);
347
+ result = await this.bulkGetProperties(args);
348
+ break;
340
349
  case 'snow_property_bulk_set':
341
- return await this.bulkSetProperties(args);
350
+ result = await this.bulkSetProperties(args);
351
+ break;
342
352
  case 'snow_property_export':
343
- return await this.exportProperties(args);
353
+ result = await this.exportProperties(args);
354
+ break;
344
355
  case 'snow_property_import':
345
- return await this.importProperties(args);
356
+ result = await this.importProperties(args);
357
+ break;
346
358
  case 'snow_property_validate':
347
- return await this.validateProperty(args);
359
+ result = await this.validateProperty(args);
360
+ break;
348
361
  case 'snow_property_categories':
349
- return await this.getCategories(args);
362
+ result = await this.getCategories(args);
363
+ break;
350
364
  case 'snow_property_history':
351
- return await this.getPropertyHistory(args);
365
+ result = await this.getPropertyHistory(args);
366
+ break;
352
367
  default:
353
368
  throw new types_js_1.McpError(types_js_1.ErrorCode.MethodNotFound, `Unknown tool: ${name}`);
354
369
  }
370
+ // Complete operation with token tracking
371
+ this.logger.operationComplete(name, result);
372
+ return result;
355
373
  }
356
374
  catch (error) {
357
- logger.error(`Tool execution failed: ${name}`, error);
375
+ this.logger.error(`Tool execution failed: ${name}`, error);
358
376
  throw new types_js_1.McpError(types_js_1.ErrorCode.InternalError, error instanceof Error ? error.message : String(error));
359
377
  }
360
378
  });
@@ -364,8 +382,9 @@ class ServiceNowSystemPropertiesMCP {
364
382
  */
365
383
  async getProperty(args) {
366
384
  const { name, include_metadata = false } = args;
367
- logger.info(`Getting property: ${name}`);
385
+ this.logger.info(`Getting property: ${name}`);
368
386
  try {
387
+ this.logger.trackAPICall('SEARCH', 'sys_properties', 1);
369
388
  const response = await this.client.searchRecords('sys_properties', `name=${name}`, 1);
370
389
  if (!response.success || !response.data?.result?.length) {
371
390
  return {
@@ -406,7 +425,7 @@ class ServiceNowSystemPropertiesMCP {
406
425
  }
407
426
  }
408
427
  catch (error) {
409
- logger.error('Failed to get property:', error);
428
+ this.logger.error('Failed to get property:', error);
410
429
  throw error;
411
430
  }
412
431
  }
@@ -415,14 +434,16 @@ class ServiceNowSystemPropertiesMCP {
415
434
  */
416
435
  async setProperty(args) {
417
436
  const { name, value, description, type = 'string', choices, is_private = false, suffix } = args;
418
- logger.info(`Setting property: ${name} = ${value}`);
437
+ this.logger.info(`Setting property: ${name} = ${value}`);
419
438
  try {
420
439
  // Check if property exists
440
+ this.logger.trackAPICall('SEARCH', 'sys_properties', 1);
421
441
  const existing = await this.client.searchRecords('sys_properties', `name=${name}`, 1);
422
442
  let result;
423
443
  if (existing.success && existing.data?.result?.length > 0) {
424
444
  // Update existing property
425
445
  const sys_id = existing.data.result[0].sys_id;
446
+ this.logger.trackAPICall('UPDATE', 'sys_properties', 1);
426
447
  result = await this.client.updateRecord('sys_properties', sys_id, {
427
448
  value,
428
449
  ...(description && { description }),
@@ -431,10 +452,11 @@ class ServiceNowSystemPropertiesMCP {
431
452
  ...(suffix && { suffix }),
432
453
  is_private: is_private ? 'true' : 'false'
433
454
  });
434
- logger.info(`Updated property: ${name}`);
455
+ this.logger.info(`Updated property: ${name}`);
435
456
  }
436
457
  else {
437
458
  // Create new property
459
+ this.logger.trackAPICall('CREATE', 'sys_properties', 1);
438
460
  result = await this.client.createRecord('sys_properties', {
439
461
  name,
440
462
  value,
@@ -444,7 +466,7 @@ class ServiceNowSystemPropertiesMCP {
444
466
  is_private: is_private ? 'true' : 'false',
445
467
  suffix: suffix || 'global'
446
468
  });
447
- logger.info(`Created new property: ${name}`);
469
+ this.logger.info(`Created new property: ${name}`);
448
470
  }
449
471
  if (!result.success) {
450
472
  throw new Error(`Failed to set property: ${result.error}`);
@@ -468,7 +490,7 @@ ${choices ? `**Choices:** ${choices}` : ''}
468
490
  };
469
491
  }
470
492
  catch (error) {
471
- logger.error('Failed to set property:', error);
493
+ this.logger.error('Failed to set property:', error);
472
494
  throw error;
473
495
  }
474
496
  }
@@ -477,7 +499,7 @@ ${choices ? `**Choices:** ${choices}` : ''}
477
499
  */
478
500
  async listProperties(args) {
479
501
  const { pattern, category, is_private, limit = 100, include_values = true } = args;
480
- logger.info('Listing properties', { pattern, category, limit });
502
+ this.logger.info('Listing properties', { pattern, category, limit });
481
503
  try {
482
504
  let query = '';
483
505
  const conditions = [];
@@ -535,7 +557,7 @@ ${choices ? `**Choices:** ${choices}` : ''}
535
557
  };
536
558
  }
537
559
  catch (error) {
538
- logger.error('Failed to list properties:', error);
560
+ this.logger.error('Failed to list properties:', error);
539
561
  throw error;
540
562
  }
541
563
  }
@@ -556,7 +578,7 @@ ${choices ? `**Choices:** ${choices}` : ''}
556
578
  }]
557
579
  };
558
580
  }
559
- logger.info(`Deleting property: ${name}`);
581
+ this.logger.info(`Deleting property: ${name}`);
560
582
  try {
561
583
  // Find the property
562
584
  const response = await this.client.searchRecords('sys_properties', `name=${name}`, 1);
@@ -585,7 +607,7 @@ ${choices ? `**Choices:** ${choices}` : ''}
585
607
  };
586
608
  }
587
609
  catch (error) {
588
- logger.error('Failed to delete property:', error);
610
+ this.logger.error('Failed to delete property:', error);
589
611
  throw error;
590
612
  }
591
613
  }
@@ -594,7 +616,7 @@ ${choices ? `**Choices:** ${choices}` : ''}
594
616
  */
595
617
  async searchProperties(args) {
596
618
  const { search_term, search_in = 'all', limit = 50 } = args;
597
- logger.info(`Searching properties for: ${search_term}`);
619
+ this.logger.info(`Searching properties for: ${search_term}`);
598
620
  try {
599
621
  let query = '';
600
622
  switch (search_in) {
@@ -642,7 +664,7 @@ ${choices ? `**Choices:** ${choices}` : ''}
642
664
  };
643
665
  }
644
666
  catch (error) {
645
- logger.error('Search failed:', error);
667
+ this.logger.error('Search failed:', error);
646
668
  throw error;
647
669
  }
648
670
  }
@@ -651,7 +673,7 @@ ${choices ? `**Choices:** ${choices}` : ''}
651
673
  */
652
674
  async bulkGetProperties(args) {
653
675
  const { names, include_metadata = false } = args;
654
- logger.info(`Bulk getting ${names.length} properties`);
676
+ this.logger.info(`Bulk getting ${names.length} properties`);
655
677
  const results = {};
656
678
  const errors = [];
657
679
  for (const name of names) {
@@ -673,7 +695,7 @@ ${choices ? `**Choices:** ${choices}` : ''}
673
695
  }
674
696
  }
675
697
  catch (error) {
676
- logger.error(`Failed to get property ${name}:`, error);
698
+ this.logger.error(`Failed to get property ${name}:`, error);
677
699
  results[name] = null;
678
700
  errors.push(name);
679
701
  }
@@ -702,7 +724,7 @@ ${choices ? `**Choices:** ${choices}` : ''}
702
724
  */
703
725
  async bulkSetProperties(args) {
704
726
  const { properties } = args;
705
- logger.info(`Bulk setting ${properties.length} properties`);
727
+ this.logger.info(`Bulk setting ${properties.length} properties`);
706
728
  const results = {
707
729
  created: [],
708
730
  updated: [],
@@ -730,6 +752,7 @@ ${choices ? `**Choices:** ${choices}` : ''}
730
752
  }
731
753
  else {
732
754
  // Create
755
+ this.logger.trackAPICall('CREATE', 'sys_properties', 1);
733
756
  result = await this.client.createRecord('sys_properties', {
734
757
  name: prop.name,
735
758
  value: prop.value,
@@ -747,7 +770,7 @@ ${choices ? `**Choices:** ${choices}` : ''}
747
770
  this.propertyCache.delete(prop.name);
748
771
  }
749
772
  catch (error) {
750
- logger.error(`Failed to set property ${prop.name}:`, error);
773
+ this.logger.error(`Failed to set property ${prop.name}:`, error);
751
774
  results.failed.push(`${prop.name}: ${error}`);
752
775
  }
753
776
  }
@@ -773,7 +796,7 @@ Total processed: ${properties.length}`
773
796
  */
774
797
  async exportProperties(args) {
775
798
  const { pattern, include_system = false, include_private = false } = args;
776
- logger.info('Exporting properties', { pattern, include_system, include_private });
799
+ this.logger.info('Exporting properties', { pattern, include_system, include_private });
777
800
  try {
778
801
  let query = '';
779
802
  const conditions = [];
@@ -823,7 +846,7 @@ ${JSON.stringify(exportData, null, 2)}
823
846
  };
824
847
  }
825
848
  catch (error) {
826
- logger.error('Export failed:', error);
849
+ this.logger.error('Export failed:', error);
827
850
  throw error;
828
851
  }
829
852
  }
@@ -832,7 +855,7 @@ ${JSON.stringify(exportData, null, 2)}
832
855
  */
833
856
  async importProperties(args) {
834
857
  const { properties, overwrite = false, dry_run = false } = args;
835
- logger.info('Importing properties', { count: Object.keys(properties).length, overwrite, dry_run });
858
+ this.logger.info('Importing properties', { count: Object.keys(properties).length, overwrite, dry_run });
836
859
  const results = {
837
860
  would_create: [],
838
861
  would_update: [],
@@ -884,6 +907,7 @@ ${JSON.stringify(exportData, null, 2)}
884
907
  }
885
908
  else {
886
909
  // Create
910
+ this.logger.trackAPICall('CREATE', 'sys_properties', 1);
887
911
  const result = await this.client.createRecord('sys_properties', {
888
912
  name,
889
913
  value: propertyData.value,
@@ -904,7 +928,7 @@ ${JSON.stringify(exportData, null, 2)}
904
928
  this.propertyCache.delete(name);
905
929
  }
906
930
  catch (error) {
907
- logger.error(`Failed to import property ${name}:`, error);
931
+ this.logger.error(`Failed to import property ${name}:`, error);
908
932
  results.failed.push(`${name}: ${error}`);
909
933
  }
910
934
  }
@@ -946,7 +970,7 @@ Total processed: ${Object.keys(properties).length}`
946
970
  */
947
971
  async validateProperty(args) {
948
972
  const { name, value } = args;
949
- logger.info(`Validating property: ${name} = ${value}`);
973
+ this.logger.info(`Validating property: ${name} = ${value}`);
950
974
  try {
951
975
  // Get property metadata
952
976
  const response = await this.client.searchRecords('sys_properties', `name=${name}`, 1);
@@ -1026,7 +1050,7 @@ ${validationResults.join('\n')}
1026
1050
  };
1027
1051
  }
1028
1052
  catch (error) {
1029
- logger.error('Validation failed:', error);
1053
+ this.logger.error('Validation failed:', error);
1030
1054
  throw error;
1031
1055
  }
1032
1056
  }
@@ -1035,7 +1059,7 @@ ${validationResults.join('\n')}
1035
1059
  */
1036
1060
  async getCategories(args) {
1037
1061
  const { include_counts = true } = args;
1038
- logger.info('Getting property categories');
1062
+ this.logger.info('Getting property categories');
1039
1063
  try {
1040
1064
  // Get distinct suffixes (categories)
1041
1065
  const response = await this.client.searchRecords('sys_properties', '', 1000);
@@ -1067,7 +1091,7 @@ ${validationResults.join('\n')}
1067
1091
  };
1068
1092
  }
1069
1093
  catch (error) {
1070
- logger.error('Failed to get categories:', error);
1094
+ this.logger.error('Failed to get categories:', error);
1071
1095
  throw error;
1072
1096
  }
1073
1097
  }
@@ -1076,7 +1100,7 @@ ${validationResults.join('\n')}
1076
1100
  */
1077
1101
  async getPropertyHistory(args) {
1078
1102
  const { name, limit = 10 } = args;
1079
- logger.info(`Getting history for property: ${name}`);
1103
+ this.logger.info(`Getting history for property: ${name}`);
1080
1104
  try {
1081
1105
  // First, get the property to get its sys_id
1082
1106
  const propResponse = await this.client.searchRecords('sys_properties', `name=${name}`, 1);
@@ -1116,7 +1140,7 @@ ${validationResults.join('\n')}
1116
1140
  };
1117
1141
  }
1118
1142
  catch (error) {
1119
- logger.error('Failed to get history:', error);
1143
+ this.logger.error('Failed to get history:', error);
1120
1144
  // Audit might not be available
1121
1145
  return {
1122
1146
  content: [{
@@ -1131,7 +1155,7 @@ Note: Audit history requires sys_audit to be enabled for sys_properties table.`
1131
1155
  async start() {
1132
1156
  const transport = new stdio_js_1.StdioServerTransport();
1133
1157
  await this.server.connect(transport);
1134
- logger.info('ServiceNow System Properties MCP Server started');
1158
+ this.logger.info('ServiceNow System Properties MCP Server started');
1135
1159
  }
1136
1160
  }
1137
1161
  exports.ServiceNowSystemPropertiesMCP = ServiceNowSystemPropertiesMCP;
@@ -10,7 +10,7 @@ const stdio_js_1 = require("@modelcontextprotocol/sdk/server/stdio.js");
10
10
  const types_js_1 = require("@modelcontextprotocol/sdk/types.js");
11
11
  const servicenow_client_js_1 = require("../utils/servicenow-client.js");
12
12
  const snow_oauth_js_1 = require("../utils/snow-oauth.js");
13
- const logger_js_1 = require("../utils/logger.js");
13
+ const mcp_logger_js_1 = require("../shared/mcp-logger.js");
14
14
  const fs_1 = require("fs");
15
15
  const path_1 = require("path");
16
16
  class ServiceNowUpdateSetMCP {
@@ -26,7 +26,7 @@ class ServiceNowUpdateSetMCP {
26
26
  });
27
27
  this.client = new servicenow_client_js_1.ServiceNowClient();
28
28
  this.oauth = new snow_oauth_js_1.ServiceNowOAuth();
29
- this.logger = new logger_js_1.Logger('ServiceNowUpdateSetMCP');
29
+ this.logger = new mcp_logger_js_1.MCPLogger('ServiceNowUpdateSetMCP');
30
30
  this.sessionsPath = (0, path_1.join)(process.cwd(), 'memory', 'update-set-sessions');
31
31
  // Debug: Test credentials on startup
32
32
  this.testCredentials();
@@ -227,33 +227,48 @@ class ServiceNowUpdateSetMCP {
227
227
  this.server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request) => {
228
228
  const { name, arguments: args } = request.params;
229
229
  try {
230
+ // Start operation with token tracking
231
+ this.logger.operationStart(name, args);
230
232
  // Check authentication for all operations
231
233
  const isAuthenticated = await this.oauth.isAuthenticated();
232
234
  if (!isAuthenticated) {
233
235
  throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidRequest, 'Not authenticated. Run "snow-flow auth login" first.');
234
236
  }
237
+ let result;
235
238
  switch (name) {
236
239
  case 'snow_update_set_create':
237
- return await this.createUpdateSet(args);
240
+ result = await this.createUpdateSet(args);
241
+ break;
238
242
  case 'snow_update_set_switch':
239
- return await this.switchUpdateSet(args);
243
+ result = await this.switchUpdateSet(args);
244
+ break;
240
245
  case 'snow_update_set_current':
241
- return await this.getCurrentUpdateSet();
246
+ result = await this.getCurrentUpdateSet();
247
+ break;
242
248
  case 'snow_update_set_list':
243
- return await this.listUpdateSets(args);
249
+ result = await this.listUpdateSets(args);
250
+ break;
244
251
  case 'snow_update_set_complete':
245
- return await this.completeUpdateSet(args);
252
+ result = await this.completeUpdateSet(args);
253
+ break;
246
254
  case 'snow_update_set_add_artifact':
247
- return await this.addArtifactToSession(args);
255
+ result = await this.addArtifactToSession(args);
256
+ break;
248
257
  case 'snow_update_set_preview':
249
- return await this.previewUpdateSet(args);
258
+ result = await this.previewUpdateSet(args);
259
+ break;
250
260
  case 'snow_update_set_export':
251
- return await this.exportUpdateSet(args);
261
+ result = await this.exportUpdateSet(args);
262
+ break;
252
263
  case 'snow_ensure_active_update_set':
253
- return await this.ensureActiveUpdateSet(args);
264
+ result = await this.ensureActiveUpdateSet(args);
265
+ break;
254
266
  default:
255
267
  throw new types_js_1.McpError(types_js_1.ErrorCode.MethodNotFound, `Unknown tool: ${name}`);
256
268
  }
269
+ // Complete operation with token tracking
270
+ this.logger.operationComplete(name, result);
271
+ return result;
257
272
  }
258
273
  catch (error) {
259
274
  if (error instanceof types_js_1.McpError)
@@ -267,6 +282,7 @@ class ServiceNowUpdateSetMCP {
267
282
  try {
268
283
  this.logger.info('Creating new Update Set', args);
269
284
  // Create Update Set in ServiceNow
285
+ this.logger.trackAPICall('CREATE', 'sys_update_set', 1);
270
286
  const response = await this.client.createUpdateSet({
271
287
  name: args.name,
272
288
  description: args.description,
@@ -284,6 +300,7 @@ class ServiceNowUpdateSetMCP {
284
300
  const autoSwitch = args.auto_switch !== false;
285
301
  let switchedToUpdateSet = false;
286
302
  if (autoSwitch) {
303
+ this.logger.trackAPICall('UPDATE', 'sys_update_set', 1);
287
304
  await this.client.setCurrentUpdateSet(response.data.sys_id);
288
305
  switchedToUpdateSet = true;
289
306
  // Create local session
@@ -339,6 +356,7 @@ Use \`snow_update_set_switch\` to activate this Update Set before making changes
339
356
  try {
340
357
  this.logger.info('Switching to Update Set', { update_set_id: args.update_set_id });
341
358
  // Set as current in ServiceNow
359
+ this.logger.trackAPICall('UPDATE', 'sys_update_set', 1);
342
360
  await this.client.setCurrentUpdateSet(args.update_set_id);
343
361
  // Load or create session
344
362
  const sessionFile = (0, path_1.join)(this.sessionsPath, `${args.update_set_id}.json`);
@@ -348,6 +366,7 @@ Use \`snow_update_set_switch\` to activate this Update Set before making changes
348
366
  }
349
367
  catch {
350
368
  // Create new session for existing Update Set
369
+ this.logger.trackAPICall('GET', 'sys_update_set', 1);
351
370
  const updateSet = await this.client.getUpdateSet(args.update_set_id);
352
371
  this.currentSession = {
353
372
  update_set_id: args.update_set_id,
@@ -382,6 +401,7 @@ All subsequent changes will be tracked in this Update Set.`
382
401
  async getCurrentUpdateSet() {
383
402
  if (!this.currentSession) {
384
403
  // Try to get from ServiceNow
404
+ this.logger.trackAPICall('GET', 'sys_update_set', 1);
385
405
  const current = await this.client.getCurrentUpdateSet();
386
406
  if (current.success && current.data) {
387
407
  return {
@@ -423,6 +443,7 @@ ${this.currentSession.artifacts.length > 0
423
443
  }
424
444
  async listUpdateSets(args) {
425
445
  try {
446
+ this.logger.trackAPICall('SEARCH', 'sys_update_set', args.limit || 10);
426
447
  const response = await this.client.listUpdateSets({
427
448
  state: args.state,
428
449
  limit: args.limit || 10
@@ -462,6 +483,7 @@ ${updateSets.map((us) => `
462
483
  throw new Error('No Update Set specified and no active session');
463
484
  }
464
485
  // Mark as complete in ServiceNow
486
+ this.logger.trackAPICall('UPDATE', 'sys_update_set', 1);
465
487
  const response = await this.client.completeUpdateSet(updateSetId, args.notes);
466
488
  if (!response.success) {
467
489
  throw new Error(response.error || 'Failed to complete Update Set');
@@ -559,6 +581,7 @@ ${autoCreatedNotice}
559
581
  throw new Error('No Update Set specified and no active session');
560
582
  }
561
583
  // Get Update Set details and changes
584
+ this.logger.trackAPICall('GET', 'sys_update_set_preview', 1);
562
585
  const response = await this.client.previewUpdateSet(updateSetId);
563
586
  if (!response.success) {
564
587
  throw new Error(response.error || 'Failed to preview Update Set');
@@ -601,6 +624,7 @@ ${changes.length > 20 ? `\n... and ${changes.length - 20} more changes` : ''}
601
624
  throw new Error('Update Set ID is required for export');
602
625
  }
603
626
  // Export Update Set as XML
627
+ this.logger.trackAPICall('GET', 'sys_update_set_export', 1);
604
628
  const response = await this.client.exportUpdateSet(updateSetId);
605
629
  if (!response.success) {
606
630
  throw new Error(response.error || 'Failed to export Update Set');
@@ -1,2 +1,2 @@
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## 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## 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\nconst verify = await snow_execute_script_with_output({\n script: `/* Test the exact code or resource */`\n});\n\n// Step 2: Check if resources exist\nconst tableCheck = await snow_discover_table_fields({\n table_name: 'potentially_custom_table'\n});\n\n// Step 3: Validate configurations\nconst propertyCheck = await snow_property_manager({\n action: 'get',\n name: 'system.property'\n});\n\n// Step 4: Only then make informed decisions\n```\n\n## Fundamental Rules\n\n### Rule 1: ES5 JavaScript Only in ServiceNow\n\nServiceNow uses the Rhino JavaScript engine which supports only ES5. Modern JavaScript syntax will fail.\n\n**Never Use:**\n- `const` or `let` - use `var`\n- Arrow functions `() => {}` - use `function() {}`\n- Template literals `` `${var}` `` - use string concatenation\n- Destructuring `{a, b} = obj` - use explicit property access\n- `for...of` loops - use traditional `for` loops\n- Default parameters - use `typeof` checks\n- `async/await` - use callbacks or GlideAjax\n\n**Always Use:**\n```javascript\n// ES5 compatible code\nvar name = 'value';\nfunction processData() {\n return 'result';\n}\nvar message = 'Hello ' + userName;\nfor (var i = 0; i < array.length; i++) {\n var item = array[i];\n}\n```\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\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\nsnow_execute_background_script({\n script: \"var gr = new GlideRecord('incident'); gr.query();\",\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();\",\n description: \"Query incidents\",\n allowDataModification: false,\n autoConfirm: true // \u26A0\uFE0F Bypasses user confirmation!\n});\n```\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```javascript\n// Universal verification pattern\nconst verify = await snow_execute_script_with_output({\n script: `\n gs.info('=== VERIFICATION TEST ===');\n \n // Test table existence\n var table = new GlideRecord('table_name');\n gs.info('Table valid: ' + table.isValid());\n \n // Test property existence\n var prop = gs.getProperty('property.name');\n gs.info('Property: ' + (prop || 'NOT SET'));\n \n // Test actual code\n try {\n // User's code here\n gs.info('SUCCESS');\n } catch(e) {\n gs.error('ERROR: ' + e.message);\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: 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**CRITICAL: Direct Widget Updates (Not Background Scripts!)**\n- Use `snow_update({ type: 'widget', identifier: 'widget_name', config: { /* fields to update */ }})` \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\n**Creating New Widgets:**\n```javascript\nsnow_deploy({\n type: 'widget',\n config: {\n name: 'my_widget',\n title: 'My Widget', // Required for display\n template: '<div>{{data.message}}</div>', // Required HTML\n server_script: 'data.message = \"Hello\";',\n client_script: 'function($scope) { var c = this; }'\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 server_script: 'data.updated = true;'\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**Key Tools:**\n- `snow_execute_background_script` - Execute background scripts (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\n- `snow_get_script_output` - Retrieve script execution history\n- `snow_execute_script_sync` - Synchronous script execution\n- `snow_get_logs` - Access system logs\n- `snow_test_rest_connection` - Test REST integrations\n- `snow_trace_execution` - Trace script execution\n- `snow_schedule_job` - Create scheduled jobs\n- `snow_create_event` - Trigger system events\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. 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### 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## 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 emphasizes verification, testing, and evidence-based decision making. By following these guidelines and best practices, you ensure reliable, maintainable, and effective ServiceNow solutions.\n\nRemember: Your job is to solve problems, not to judge implementations. Every environment has its reasons for existing configurations. Verify, test, and respect what you find.";
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## 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## 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\nconst verify = await snow_execute_script_with_output({\n script: `/* Test the exact code or resource */`\n});\n\n// Step 2: Check if resources exist\nconst tableCheck = await snow_discover_table_fields({\n table_name: 'potentially_custom_table'\n});\n\n// Step 3: Validate configurations\nconst propertyCheck = await snow_property_manager({\n action: 'get',\n name: 'system.property'\n});\n\n// Step 4: Only then make informed decisions\n```\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\nconst verify = await snow_execute_script_with_output({\n script: `\n gs.info('=== VERIFICATION TEST ===');\n \n // Test table existence\n var table = new GlideRecord('table_name');\n gs.info('Table valid: ' + table.isValid());\n \n // Test property existence\n var prop = gs.getProperty('property.name');\n gs.info('Property: ' + (prop || 'NOT SET'));\n \n // Test actual code\n try {\n // User's code here\n gs.info('SUCCESS');\n } catch(e) {\n gs.error('ERROR: ' + e.message);\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: 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**CRITICAL: Direct Widget Updates (Not Background Scripts!)**\n- Use `snow_update({ type: 'widget', identifier: 'widget_name', config: { /* fields to update */ }})` \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\n**Creating New Widgets:**\n```javascript\nsnow_deploy({\n type: 'widget',\n config: {\n name: 'my_widget',\n title: 'My Widget', // Required for display\n template: '<div>{{data.message}}</div>', // Required HTML\n server_script: 'data.message = \"Hello\";',\n client_script: 'function($scope) { var c = this; }'\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 server_script: 'data.updated = true;'\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. 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### 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## 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 emphasizes verification, testing, and evidence-based decision making. By following these guidelines and best practices, you ensure reliable, maintainable, and effective ServiceNow solutions.\n\nRemember: Your job is to solve problems, not to judge implementations. Every environment has its reasons for existing configurations. Verify, test, and respect what you find.";
2
2
  //# sourceMappingURL=claude-md-template.d.ts.map