snow-flow 3.0.8 → 3.0.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (295) hide show
  1. package/claude-flow.bat +0 -0
  2. package/claude-flow.ps1 +0 -0
  3. package/dist/mcp/servicenow-automation-mcp.js +0 -0
  4. package/dist/mcp/servicenow-deployment-mcp.js +0 -0
  5. package/dist/mcp/servicenow-integration-mcp.js +0 -0
  6. package/dist/mcp/servicenow-mcp-server.js +0 -0
  7. package/dist/mcp/servicenow-operations-mcp.js +0 -0
  8. package/dist/mcp/servicenow-platform-development-mcp.js +0 -0
  9. package/dist/mcp/servicenow-progressive-indexer.js +0 -0
  10. package/dist/mcp/servicenow-reporting-analytics-mcp.js +133 -19
  11. package/dist/mcp/servicenow-security-compliance-mcp.js +0 -0
  12. package/dist/mcp/servicenow-update-set-mcp.js +0 -0
  13. package/dist/mcp/start-all-mcp-servers.js +0 -0
  14. package/dist/mcp/start-servicenow-mcp.js +0 -0
  15. package/dist/utils/snow-oauth.js +53 -16
  16. package/memory/agents/README.md +1 -1
  17. package/memory/claude-flow-data.json +1 -1
  18. package/memory/sessions/README.md +1 -1
  19. package/package.json +2 -2
  20. package/.mcp.json +0 -22
  21. package/claude-flow.config.json +0 -20
  22. package/dist/agents/app-creator.agent.d.ts +0 -55
  23. package/dist/agents/app-creator.agent.js +0 -1292
  24. package/dist/agents/base/base-snow-agent.d.ts +0 -75
  25. package/dist/agents/base/base-snow-agent.js +0 -169
  26. package/dist/agents/base-snow-agent.d.ts +0 -63
  27. package/dist/agents/base-snow-agent.js +0 -296
  28. package/dist/agents/coordinator.d.ts +0 -200
  29. package/dist/agents/coordinator.js +0 -777
  30. package/dist/agents/flow-builder-agent.d.ts +0 -18
  31. package/dist/agents/flow-builder-agent.js +0 -197
  32. package/dist/agents/queen-403-handler.d.ts +0 -47
  33. package/dist/agents/queen-403-handler.js +0 -175
  34. package/dist/agents/queen-agent-example.d.ts +0 -23
  35. package/dist/agents/queen-agent-example.js +0 -240
  36. package/dist/agents/queen-agent.test.d.ts +0 -6
  37. package/dist/agents/script-generator.agent.d.ts +0 -32
  38. package/dist/agents/script-generator.agent.js +0 -772
  39. package/dist/agents/script-writer-agent.d.ts +0 -22
  40. package/dist/agents/script-writer-agent.js +0 -695
  41. package/dist/agents/security-agent.d.ts +0 -23
  42. package/dist/agents/security-agent.js +0 -619
  43. package/dist/agents/specialists/automation-specialist.agent.d.ts +0 -44
  44. package/dist/agents/specialists/automation-specialist.agent.js +0 -204
  45. package/dist/agents/specialists/data-specialist.agent.d.ts +0 -165
  46. package/dist/agents/specialists/data-specialist.agent.js +0 -484
  47. package/dist/agents/specialists/integration-specialist.agent.d.ts +0 -227
  48. package/dist/agents/specialists/integration-specialist.agent.js +0 -725
  49. package/dist/agents/specialists/reporting-specialist.agent.d.ts +0 -54
  50. package/dist/agents/specialists/reporting-specialist.agent.js +0 -193
  51. package/dist/agents/specialists/security-specialist.agent.d.ts +0 -85
  52. package/dist/agents/specialists/security-specialist.agent.js +0 -309
  53. package/dist/agents/teams/adaptive/adaptive-coordinator.agent.d.ts +0 -111
  54. package/dist/agents/teams/adaptive/adaptive-coordinator.agent.js +0 -383
  55. package/dist/agents/teams/base-team.d.ts +0 -72
  56. package/dist/agents/teams/base-team.js +0 -253
  57. package/dist/agents/teams/team-types.d.ts +0 -265
  58. package/dist/agents/teams/team-types.js +0 -3
  59. package/dist/agents/teams/widget/widget-architect.agent.d.ts +0 -61
  60. package/dist/agents/teams/widget/widget-architect.agent.js +0 -436
  61. package/dist/agents/teams/widget/widget-backend.agent.d.ts +0 -74
  62. package/dist/agents/teams/widget/widget-backend.agent.js +0 -1531
  63. package/dist/agents/teams/widget/widget-frontend.agent.d.ts +0 -67
  64. package/dist/agents/teams/widget/widget-frontend.agent.js +0 -1014
  65. package/dist/agents/teams/widget/widget-platform.agent.d.ts +0 -90
  66. package/dist/agents/teams/widget/widget-platform.agent.js +0 -1190
  67. package/dist/agents/teams/widget/widget-uiux.agent.d.ts +0 -107
  68. package/dist/agents/teams/widget/widget-uiux.agent.js +0 -1033
  69. package/dist/agents/test-agent.d.ts +0 -26
  70. package/dist/agents/test-agent.js +0 -734
  71. package/dist/agents/test-agents.d.ts +0 -7
  72. package/dist/agents/test-agents.js +0 -64
  73. package/dist/agents/ui-builder.agent.d.ts +0 -50
  74. package/dist/agents/ui-builder.agent.js +0 -1539
  75. package/dist/agents/widget-builder.agent.d.ts +0 -32
  76. package/dist/agents/widget-builder.agent.js +0 -439
  77. package/dist/agents/widget-creator-agent.d.ts +0 -18
  78. package/dist/agents/widget-creator-agent.js +0 -498
  79. package/dist/agents/workflow-designer.agent.d.ts +0 -31
  80. package/dist/agents/workflow-designer.agent.js +0 -583
  81. package/dist/api/error-handling.d.ts +0 -325
  82. package/dist/api/error-handling.js +0 -1488
  83. package/dist/api/flow-designer-api.d.ts +0 -167
  84. package/dist/api/flow-designer-api.js +0 -554
  85. package/dist/api/natural-language-mapper.d.ts +0 -124
  86. package/dist/api/natural-language-mapper.js +0 -501
  87. package/dist/api/performance-optimizer.d.ts +0 -240
  88. package/dist/api/performance-optimizer.js +0 -706
  89. package/dist/api/transaction-manager.d.ts +0 -189
  90. package/dist/api/transaction-manager.js +0 -576
  91. package/dist/assembly/team-assembler.d.ts +0 -140
  92. package/dist/assembly/team-assembler.js +0 -502
  93. package/dist/benchmark-performance.d.ts +0 -41
  94. package/dist/benchmark-performance.js +0 -230
  95. package/dist/cli/snow-flow-cli-integration.d.ts +0 -30
  96. package/dist/cli/snow-flow-cli-integration.js +0 -396
  97. package/dist/coordination/coordination-engine.d.ts +0 -41
  98. package/dist/coordination/coordination-engine.js +0 -324
  99. package/dist/coordination/coordination.test.d.ts +0 -6
  100. package/dist/coordination/example.d.ts +0 -31
  101. package/dist/coordination/example.js +0 -394
  102. package/dist/coordination/execution-patterns.d.ts +0 -43
  103. package/dist/coordination/execution-patterns.js +0 -507
  104. package/dist/coordination/factory.d.ts +0 -94
  105. package/dist/coordination/factory.js +0 -433
  106. package/dist/coordination/index.d.ts +0 -71
  107. package/dist/coordination/index.js +0 -135
  108. package/dist/coordination/progress-monitor.d.ts +0 -71
  109. package/dist/coordination/progress-monitor.js +0 -505
  110. package/dist/coordination/quality-gates.d.ts +0 -124
  111. package/dist/coordination/quality-gates.js +0 -577
  112. package/dist/coordination/shared-memory.d.ts +0 -39
  113. package/dist/coordination/shared-memory.js +0 -289
  114. package/dist/coordination/task-dependencies.d.ts +0 -50
  115. package/dist/coordination/task-dependencies.js +0 -407
  116. package/dist/coordination/team-coordinator.d.ts +0 -59
  117. package/dist/coordination/team-coordinator.js +0 -550
  118. package/dist/coordination/types.d.ts +0 -152
  119. package/dist/coordination/types.js +0 -3
  120. package/dist/mcp/mcp-wrapper.d.ts +0 -8
  121. package/dist/mcp/mcp-wrapper.js +0 -77
  122. package/dist/mcp/servicenow-flow-composer-enhanced.js +0 -396
  123. package/dist/mcp/servicenow-flow-composer-mcp.d.ts +0 -7
  124. package/dist/mcp/servicenow-flow-composer-mcp.js +0 -3103
  125. package/dist/mcp/servicenow-graph-memory-mcp.d.ts +0 -7
  126. package/dist/mcp/servicenow-intelligent-mcp.d.ts +0 -143
  127. package/dist/mcp/servicenow-intelligent-mcp.js +0 -4156
  128. package/dist/mcp/servicenow-xml-flow-mcp.d.ts +0 -53
  129. package/dist/mcp/servicenow-xml-flow-mcp.js +0 -1704
  130. package/dist/mcp/singleton-check.js +0 -31
  131. package/dist/mcp/test-simple-mcp.d.ts +0 -6
  132. package/dist/mcp/test-simple-mcp.js +0 -63
  133. package/dist/memory/hierarchical-memory-system.d.ts +0 -90
  134. package/dist/memory/hierarchical-memory-system.js +0 -400
  135. package/dist/memory/index.d.ts +0 -9
  136. package/dist/memory/index.js +0 -20
  137. package/dist/memory/mcp-integration-example.d.ts +0 -6
  138. package/dist/memory/mcp-integration-example.js +0 -281
  139. package/dist/memory/memory-client.d.ts +0 -199
  140. package/dist/memory/memory-client.js +0 -364
  141. package/dist/memory/memory-manager.d.ts +0 -29
  142. package/dist/memory/memory-manager.js +0 -280
  143. package/dist/memory/memory-operations.d.ts +0 -179
  144. package/dist/memory/memory-operations.js +0 -691
  145. package/dist/memory/memory-system.d.ts +0 -153
  146. package/dist/memory/memory-system.js +0 -651
  147. package/dist/memory/memory-test.d.ts +0 -6
  148. package/dist/memory/memory-test.js +0 -161
  149. package/dist/memory/snow-flow-memory-patterns.d.ts +0 -213
  150. package/dist/memory/snow-flow-memory-patterns.js +0 -200
  151. package/dist/memory/snow-memory.d.ts +0 -54
  152. package/dist/memory/snow-memory.js +0 -301
  153. package/dist/memory/swarm-memory.d.ts +0 -135
  154. package/dist/memory/swarm-memory.js +0 -378
  155. package/dist/optimization/flow-performance-optimizer.js +0 -723
  156. package/dist/orchestration/discovery/service-discovery.d.ts +0 -81
  157. package/dist/orchestration/discovery/service-discovery.js +0 -808
  158. package/dist/orchestration/distributed-orchestrator.d.ts +0 -131
  159. package/dist/orchestration/distributed-orchestrator.js +0 -712
  160. package/dist/orchestration/distribution/task-distribution-engine.d.ts +0 -53
  161. package/dist/orchestration/distribution/task-distribution-engine.js +0 -586
  162. package/dist/orchestration/flow-update-orchestrator.js +0 -648
  163. package/dist/orchestration/interfaces/distributed-orchestration.interface.d.ts +0 -606
  164. package/dist/orchestration/interfaces/distributed-orchestration.interface.js +0 -65
  165. package/dist/orchestration/protocols/mcpx-protocol.d.ts +0 -71
  166. package/dist/orchestration/protocols/mcpx-protocol.js +0 -668
  167. package/dist/orchestration/state/distributed-state-manager.d.ts +0 -89
  168. package/dist/orchestration/state/distributed-state-manager.js +0 -716
  169. package/dist/orchestrator/flow-composer.d.ts +0 -105
  170. package/dist/orchestrator/flow-composer.js +0 -404
  171. package/dist/orchestrator/flow-pattern-templates.d.ts +0 -260
  172. package/dist/orchestrator/flow-pattern-templates.js +0 -908
  173. package/dist/orchestrator/flow-subflow-decision-engine.d.ts +0 -202
  174. package/dist/orchestrator/flow-subflow-decision-engine.js +0 -769
  175. package/dist/orchestrator/flow-validation-engine.d.ts +0 -169
  176. package/dist/orchestrator/flow-validation-engine.js +0 -913
  177. package/dist/orchestrator/snow-orchestrator.d.ts +0 -49
  178. package/dist/orchestrator/snow-orchestrator.js +0 -235
  179. package/dist/orchestrator/subflow-creation-handler.d.ts +0 -230
  180. package/dist/orchestrator/subflow-creation-handler.js +0 -791
  181. package/dist/patterns/adaptive-patterns.d.ts +0 -140
  182. package/dist/patterns/adaptive-patterns.js +0 -549
  183. package/dist/queen/advanced-integration-test.d.ts +0 -48
  184. package/dist/queen/advanced-integration-test.js +0 -473
  185. package/dist/queen/integration-example.d.ts +0 -82
  186. package/dist/queen/integration-example.js +0 -219
  187. package/dist/queen/integration-test.d.ts +0 -72
  188. package/dist/queen/integration-test.js +0 -563
  189. package/dist/queen/mock-mcp-client.d.ts +0 -71
  190. package/dist/queen/mock-mcp-client.js +0 -317
  191. package/dist/queen/run-integration-tests.d.ts +0 -9
  192. package/dist/queen/run-integration-tests.js +0 -27
  193. package/dist/sparc/coordinators/adaptive-coordinator.d.ts +0 -54
  194. package/dist/sparc/coordinators/adaptive-coordinator.js +0 -367
  195. package/dist/sparc/coordinators/team-coordinator.d.ts +0 -66
  196. package/dist/sparc/coordinators/team-coordinator.js +0 -402
  197. package/dist/sparc/modes/team-modes.d.ts +0 -33
  198. package/dist/sparc/modes/team-modes.js +0 -399
  199. package/dist/sparc/teams/application-team.d.ts +0 -73
  200. package/dist/sparc/teams/application-team.js +0 -463
  201. package/dist/sparc/teams/flow-team.d.ts +0 -67
  202. package/dist/sparc/teams/flow-team.js +0 -373
  203. package/dist/sparc/teams/widget-team.d.ts +0 -61
  204. package/dist/sparc/teams/widget-team.js +0 -280
  205. package/dist/specialists/app-specialists.d.ts +0 -93
  206. package/dist/specialists/app-specialists.js +0 -1639
  207. package/dist/specialists/base-specialist.d.ts +0 -19
  208. package/dist/specialists/base-specialist.js +0 -54
  209. package/dist/specialists/flow-specialists.d.ts +0 -113
  210. package/dist/specialists/flow-specialists.js +0 -1787
  211. package/dist/specialists/individual-specialists.d.ts +0 -67
  212. package/dist/specialists/individual-specialists.js +0 -632
  213. package/dist/specialists/widget-specialists.d.ts +0 -70
  214. package/dist/specialists/widget-specialists.js +0 -1264
  215. package/dist/src/utils/agent-detector.js +0 -655
  216. package/dist/teams/adaptive-team.d.ts +0 -81
  217. package/dist/teams/adaptive-team.js +0 -1153
  218. package/dist/teams/application-team.d.ts +0 -30
  219. package/dist/teams/application-team.js +0 -547
  220. package/dist/teams/base-team.d.ts +0 -55
  221. package/dist/teams/base-team.js +0 -243
  222. package/dist/teams/flow-team.d.ts +0 -28
  223. package/dist/teams/flow-team.js +0 -525
  224. package/dist/teams/widget-team.d.ts +0 -26
  225. package/dist/teams/widget-team.js +0 -459
  226. package/dist/templates/flow-template-system.js +0 -625
  227. package/dist/test-fetch-incidents.d.ts +0 -2
  228. package/dist/test-fetch-incidents.js +0 -84
  229. package/dist/test-incident-access.d.ts +0 -2
  230. package/dist/test-incident-access.js +0 -72
  231. package/dist/test-iphone-flow.js +0 -189
  232. package/dist/test-limit-problem.d.ts +0 -2
  233. package/dist/test-limit-problem.js +0 -60
  234. package/dist/test-ml-batch-fix.d.ts +0 -2
  235. package/dist/test-ml-batch-fix.js +0 -104
  236. package/dist/test-ml-batch.d.ts +0 -2
  237. package/dist/test-ml-batch.js +0 -87
  238. package/dist/test-ml-query.d.ts +0 -2
  239. package/dist/test-ml-query.js +0 -100
  240. package/dist/test-ml-training-fix.d.ts +0 -12
  241. package/dist/test-ml-training-fix.js +0 -113
  242. package/dist/test-ml-training.d.ts +0 -2
  243. package/dist/test-ml-training.js +0 -32
  244. package/dist/test-operations-query.d.ts +0 -2
  245. package/dist/test-operations-query.js +0 -84
  246. package/dist/test-performance-query.d.ts +0 -2
  247. package/dist/test-performance-query.js +0 -52
  248. package/dist/test-singleton-protection.d.ts +0 -8
  249. package/dist/test-singleton-protection.js +0 -110
  250. package/dist/test-smart-limits.d.ts +0 -13
  251. package/dist/test-smart-limits.js +0 -100
  252. package/dist/test-snow-query-incidents.d.ts +0 -2
  253. package/dist/test-snow-query-incidents.js +0 -66
  254. package/dist/test-universal-query.d.ts +0 -2
  255. package/dist/test-universal-query.js +0 -106
  256. package/dist/testing/flow-testing-automation.js +0 -641
  257. package/dist/utils/complete-flow-xml-generator.js +0 -1285
  258. package/dist/utils/file-storage-fallback.d.ts +0 -62
  259. package/dist/utils/file-storage-fallback.js +0 -289
  260. package/dist/utils/flow-api-discovery.d.ts +0 -151
  261. package/dist/utils/flow-api-discovery.js +0 -439
  262. package/dist/utils/flow-examples.js +0 -720
  263. package/dist/utils/flow-structure-builder.js +0 -677
  264. package/dist/utils/flow-xml-generator.d.ts +0 -41
  265. package/dist/utils/flow-xml-generator.js +0 -258
  266. package/dist/utils/improved-flow-xml-generator.js +0 -820
  267. package/dist/utils/mcp-process-manager.backup.d.ts +0 -58
  268. package/dist/utils/mcp-process-manager.backup.js +0 -220
  269. package/dist/utils/mcp-singleton-enforcer.d.ts +0 -36
  270. package/dist/utils/mcp-singleton-enforcer.js +0 -201
  271. package/dist/utils/mcp-timeout-fix.d.ts +0 -53
  272. package/dist/utils/mcp-timeout-fix.js +0 -221
  273. package/dist/utils/migrate-claude-flow.d.ts +0 -22
  274. package/dist/utils/migrate-claude-flow.js +0 -120
  275. package/dist/utils/scope-utils.d.ts +0 -72
  276. package/dist/utils/scope-utils.js +0 -386
  277. package/dist/utils/snow-oauth-old.d.ts +0 -65
  278. package/dist/utils/snow-oauth-old.js +0 -345
  279. package/dist/utils/xml-first-flow-generator.js +0 -513
  280. package/memory/servicenow_artifacts/000d9224c895221055906c7518aa2d3d.json +0 -30
  281. package/memory/servicenow_artifacts/0196b66173303010e46b4a2214f6a7a2.json +0 -36
  282. package/memory/servicenow_artifacts/125e5d1d837e2a102a7ea130ceaad397.json +0 -30
  283. package/memory/servicenow_artifacts/7637c1f2b7112210a5e5911cde11a972.json +0 -30
  284. package/memory/servicenow_artifacts/default_documentation_tables_1754056582292.json +0 -55
  285. package/memory/servicenow_artifacts/default_documentation_tables_1754057477189.json +0 -55
  286. package/memory/update-set-sessions/01f82af583faea102a7ea130ceaad3d4.json +0 -9
  287. package/memory/update-set-sessions/27718fb983faea102a7ea130ceaad34b.json +0 -9
  288. package/memory/update-set-sessions/412e9bf6833e22502a7ea130ceaad30a.json +0 -8
  289. package/memory/update-set-sessions/66fc5a79837aea102a7ea130ceaad3ab.json +0 -9
  290. package/memory/update-set-sessions/71a30ff5837eea102a7ea130ceaad37f.json +0 -9
  291. package/memory/update-set-sessions/74fba27983faea102a7ea130ceaad3bd.json +0 -9
  292. package/memory/update-set-sessions/a0b147b5837eea102a7ea130ceaad344.json +0 -58
  293. package/memory/update-set-sessions/b13f5eb983baea102a7ea130ceaad33e.json +0 -9
  294. package/reports/swarm-auto-centralized-1752649029776.json +0 -13
  295. package/src/memory/README.md +0 -240
@@ -1,913 +0,0 @@
1
- "use strict";
2
- /**
3
- * ServiceNow Flow Validation Engine
4
- *
5
- * This module implements comprehensive validation logic for flow vs subflow decisions,
6
- * ensuring that the recommendations are sound and the created flows/subflows are valid.
7
- */
8
- Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.FlowValidationEngine = exports.ValidationRuleType = exports.ValidationSeverity = void 0;
10
- const logger_js_1 = require("../utils/logger.js");
11
- const flow_subflow_decision_engine_js_1 = require("./flow-subflow-decision-engine.js");
12
- /**
13
- * Validation severity levels
14
- */
15
- var ValidationSeverity;
16
- (function (ValidationSeverity) {
17
- ValidationSeverity["INFO"] = "info";
18
- ValidationSeverity["WARNING"] = "warning";
19
- ValidationSeverity["ERROR"] = "error";
20
- ValidationSeverity["CRITICAL"] = "critical";
21
- })(ValidationSeverity || (exports.ValidationSeverity = ValidationSeverity = {}));
22
- /**
23
- * Validation rule types
24
- */
25
- var ValidationRuleType;
26
- (function (ValidationRuleType) {
27
- ValidationRuleType["DECISION_LOGIC"] = "decision_logic";
28
- ValidationRuleType["COMPLEXITY_ANALYSIS"] = "complexity_analysis";
29
- ValidationRuleType["REUSABILITY_ANALYSIS"] = "reusability_analysis";
30
- ValidationRuleType["TECHNICAL_FEASIBILITY"] = "technical_feasibility";
31
- ValidationRuleType["BEST_PRACTICES"] = "best_practices";
32
- ValidationRuleType["PERFORMANCE"] = "performance";
33
- ValidationRuleType["MAINTAINABILITY"] = "maintainability";
34
- ValidationRuleType["SECURITY"] = "security";
35
- })(ValidationRuleType || (exports.ValidationRuleType = ValidationRuleType = {}));
36
- /**
37
- * Flow Validation Engine
38
- */
39
- class FlowValidationEngine {
40
- constructor() {
41
- this.rules = new Map();
42
- this.logger = new logger_js_1.Logger('FlowValidationEngine');
43
- this.initializeValidationRules();
44
- }
45
- /**
46
- * Validate flow vs subflow decision
47
- */
48
- validateDecision(analysisResult, instruction) {
49
- this.logger.info('Validating flow vs subflow decision', {
50
- recommendedType: analysisResult.recommendedType,
51
- confidence: analysisResult.confidence
52
- });
53
- const context = {
54
- instruction,
55
- analysisResult,
56
- criteria: analysisResult.criteria,
57
- targetType: analysisResult.recommendedType
58
- };
59
- return this.executeValidation(context);
60
- }
61
- /**
62
- * Validate subflow definition
63
- */
64
- validateSubflowDefinition(definition, instruction) {
65
- this.logger.info('Validating subflow definition', {
66
- name: definition.name,
67
- activityCount: definition.activities.length
68
- });
69
- const context = {
70
- instruction,
71
- subflowDefinition: definition,
72
- targetType: flow_subflow_decision_engine_js_1.FlowType.SUBFLOW
73
- };
74
- return this.executeValidation(context);
75
- }
76
- /**
77
- * Validate flow template application
78
- */
79
- validateTemplateApplication(template, instruction) {
80
- this.logger.info('Validating template application', {
81
- templateId: template.id,
82
- templateName: template.name
83
- });
84
- const context = {
85
- instruction,
86
- flowTemplate: template,
87
- targetType: template.recommendedType
88
- };
89
- return this.executeValidation(context);
90
- }
91
- /**
92
- * Validate subflow candidate
93
- */
94
- validateSubflowCandidate(candidate, instruction) {
95
- this.logger.info('Validating subflow candidate', {
96
- name: candidate.name,
97
- complexity: candidate.complexity
98
- });
99
- const context = {
100
- instruction,
101
- targetType: flow_subflow_decision_engine_js_1.FlowType.SUBFLOW,
102
- metadata: {
103
- candidate
104
- }
105
- };
106
- return this.executeValidation(context);
107
- }
108
- /**
109
- * Execute validation with applicable rules
110
- */
111
- executeValidation(context) {
112
- const issues = [];
113
- const recommendations = [];
114
- let totalScore = 0;
115
- let maxScore = 0;
116
- // Get applicable rules
117
- const applicableRules = this.getApplicableRules(context);
118
- // Execute each rule
119
- for (const rule of applicableRules) {
120
- try {
121
- const result = rule.validator(context);
122
- // Calculate score
123
- totalScore += result.score;
124
- maxScore += rule.weight;
125
- // Add issues with rule ID
126
- for (const issue of result.issues) {
127
- issues.push({
128
- ...issue,
129
- id: `${rule.id}_${issues.length + 1}`,
130
- ruleId: rule.id
131
- });
132
- }
133
- // Add recommendations with ID
134
- for (const recommendation of result.recommendations) {
135
- recommendations.push({
136
- ...recommendation,
137
- id: `${rule.id}_rec_${recommendations.length + 1}`
138
- });
139
- }
140
- }
141
- catch (error) {
142
- this.logger.error(`Validation rule ${rule.id} failed`, error);
143
- issues.push({
144
- id: `${rule.id}_error`,
145
- type: rule.type,
146
- severity: ValidationSeverity.ERROR,
147
- message: `Validation rule failed: ${rule.name}`,
148
- description: `Internal error in validation rule: ${error}`,
149
- impact: 'Validation incomplete',
150
- ruleId: rule.id
151
- });
152
- }
153
- }
154
- // Determine overall validation result
155
- const criticalIssues = issues.filter(i => i.severity === ValidationSeverity.CRITICAL);
156
- const errorIssues = issues.filter(i => i.severity === ValidationSeverity.ERROR);
157
- const isValid = criticalIssues.length === 0 && errorIssues.length === 0;
158
- const overallSeverity = this.determineOverallSeverity(issues);
159
- return {
160
- isValid,
161
- severity: overallSeverity,
162
- issues,
163
- recommendations,
164
- score: totalScore,
165
- maxScore
166
- };
167
- }
168
- /**
169
- * Get applicable validation rules for context
170
- */
171
- getApplicableRules(context) {
172
- const applicableRules = [];
173
- for (const rule of this.rules.values()) {
174
- // Check if rule applies to target type
175
- if (context.targetType && !rule.applicableTypes.includes(context.targetType)) {
176
- continue;
177
- }
178
- // Check if rule applies to context
179
- if (context.analysisResult?.criteria.context) {
180
- if (rule.applicableContexts.length > 0 &&
181
- !rule.applicableContexts.includes(context.analysisResult.criteria.context)) {
182
- continue;
183
- }
184
- }
185
- applicableRules.push(rule);
186
- }
187
- return applicableRules;
188
- }
189
- /**
190
- * Determine overall validation severity
191
- */
192
- determineOverallSeverity(issues) {
193
- if (issues.some(i => i.severity === ValidationSeverity.CRITICAL)) {
194
- return ValidationSeverity.CRITICAL;
195
- }
196
- if (issues.some(i => i.severity === ValidationSeverity.ERROR)) {
197
- return ValidationSeverity.ERROR;
198
- }
199
- if (issues.some(i => i.severity === ValidationSeverity.WARNING)) {
200
- return ValidationSeverity.WARNING;
201
- }
202
- return ValidationSeverity.INFO;
203
- }
204
- /**
205
- * Initialize validation rules
206
- */
207
- initializeValidationRules() {
208
- // Decision Logic Validation Rules
209
- this.rules.set('decision_confidence', {
210
- id: 'decision_confidence',
211
- name: 'Decision Confidence',
212
- description: 'Validate that the decision confidence is reasonable',
213
- type: ValidationRuleType.DECISION_LOGIC,
214
- severity: ValidationSeverity.WARNING,
215
- weight: 10,
216
- applicableContexts: [],
217
- applicableTypes: [flow_subflow_decision_engine_js_1.FlowType.MAIN_FLOW, flow_subflow_decision_engine_js_1.FlowType.SUBFLOW],
218
- validator: (context) => {
219
- const confidence = context.analysisResult?.confidence || 0;
220
- const issues = [];
221
- const recommendations = [];
222
- let score = 10;
223
- if (confidence < 0.5) {
224
- score = 3;
225
- issues.push({
226
- type: ValidationRuleType.DECISION_LOGIC,
227
- severity: ValidationSeverity.WARNING,
228
- message: 'Low decision confidence',
229
- description: `Decision confidence is ${confidence.toFixed(2)}, which is below the recommended threshold of 0.5`,
230
- impact: 'Decision may not be optimal',
231
- suggestedFix: 'Review the requirements and consider providing more specific details'
232
- });
233
- recommendations.push({
234
- type: ValidationRuleType.DECISION_LOGIC,
235
- priority: 'high',
236
- message: 'Provide more specific requirements',
237
- description: 'Add more specific details about the workflow to improve decision confidence',
238
- benefits: ['More accurate recommendations', 'Better fit for requirements'],
239
- implementation: 'Include specific actions, data flows, and business rules in the instruction',
240
- effort: 'low'
241
- });
242
- }
243
- else if (confidence < 0.7) {
244
- score = 7;
245
- issues.push({
246
- type: ValidationRuleType.DECISION_LOGIC,
247
- severity: ValidationSeverity.INFO,
248
- message: 'Moderate decision confidence',
249
- description: `Decision confidence is ${confidence.toFixed(2)}, which is acceptable but could be improved`,
250
- impact: 'Decision is likely correct but may benefit from refinement',
251
- suggestedFix: 'Consider adding more context or specific requirements'
252
- });
253
- }
254
- return {
255
- passed: confidence >= 0.5,
256
- score,
257
- issues,
258
- recommendations
259
- };
260
- }
261
- });
262
- this.rules.set('complexity_appropriateness', {
263
- id: 'complexity_appropriateness',
264
- name: 'Complexity Appropriateness',
265
- description: 'Validate that the complexity level matches the recommended flow type',
266
- type: ValidationRuleType.COMPLEXITY_ANALYSIS,
267
- severity: ValidationSeverity.WARNING,
268
- weight: 15,
269
- applicableContexts: [],
270
- applicableTypes: [flow_subflow_decision_engine_js_1.FlowType.MAIN_FLOW, flow_subflow_decision_engine_js_1.FlowType.SUBFLOW],
271
- validator: (context) => {
272
- const complexity = context.analysisResult?.criteria.complexity || context.metadata?.candidate?.complexity;
273
- const recommendedType = context.analysisResult?.recommendedType || context.targetType;
274
- const issues = [];
275
- const recommendations = [];
276
- let score = 15;
277
- // High complexity should generally favor subflows if reusable
278
- if (complexity === flow_subflow_decision_engine_js_1.ComplexityLevel.HIGH || complexity === flow_subflow_decision_engine_js_1.ComplexityLevel.VERY_HIGH) {
279
- const reusability = context.analysisResult?.criteria.reusability || context.metadata?.candidate?.reusability;
280
- if (recommendedType === flow_subflow_decision_engine_js_1.FlowType.MAIN_FLOW && reusability === flow_subflow_decision_engine_js_1.ReusabilityLevel.HIGH) {
281
- score = 5;
282
- issues.push({
283
- type: ValidationRuleType.COMPLEXITY_ANALYSIS,
284
- severity: ValidationSeverity.WARNING,
285
- message: 'High complexity with high reusability in main flow',
286
- description: 'Complex workflows with high reusability potential should consider subflow implementation',
287
- impact: 'Missed opportunity for reusability and maintainability',
288
- suggestedFix: 'Consider breaking complex logic into reusable subflows'
289
- });
290
- recommendations.push({
291
- type: ValidationRuleType.COMPLEXITY_ANALYSIS,
292
- priority: 'medium',
293
- message: 'Consider subflow implementation',
294
- description: 'Break complex logic into reusable subflows for better maintainability',
295
- benefits: ['Improved reusability', 'Better maintainability', 'Easier testing'],
296
- implementation: 'Identify reusable components and extract them into subflows',
297
- effort: 'medium'
298
- });
299
- }
300
- }
301
- // Low complexity should generally favor main flows unless highly reusable
302
- if (complexity === flow_subflow_decision_engine_js_1.ComplexityLevel.LOW) {
303
- if (recommendedType === flow_subflow_decision_engine_js_1.FlowType.SUBFLOW) {
304
- const reusability = context.analysisResult?.criteria.reusability || context.metadata?.candidate?.reusability;
305
- if (reusability === flow_subflow_decision_engine_js_1.ReusabilityLevel.LOW || reusability === flow_subflow_decision_engine_js_1.ReusabilityLevel.NONE) {
306
- score = 8;
307
- issues.push({
308
- type: ValidationRuleType.COMPLEXITY_ANALYSIS,
309
- severity: ValidationSeverity.INFO,
310
- message: 'Low complexity with low reusability as subflow',
311
- description: 'Simple workflows with low reusability might be better as main flows',
312
- impact: 'Over-engineering for current needs',
313
- suggestedFix: 'Consider implementing as main flow unless reusability is important'
314
- });
315
- }
316
- }
317
- }
318
- return {
319
- passed: score >= 10,
320
- score,
321
- issues,
322
- recommendations
323
- };
324
- }
325
- });
326
- this.rules.set('reusability_validation', {
327
- id: 'reusability_validation',
328
- name: 'Reusability Validation',
329
- description: 'Validate that reusability assessment is appropriate for the recommended flow type',
330
- type: ValidationRuleType.REUSABILITY_ANALYSIS,
331
- severity: ValidationSeverity.WARNING,
332
- weight: 15,
333
- applicableContexts: [],
334
- applicableTypes: [flow_subflow_decision_engine_js_1.FlowType.MAIN_FLOW, flow_subflow_decision_engine_js_1.FlowType.SUBFLOW],
335
- validator: (context) => {
336
- const reusability = context.analysisResult?.criteria.reusability || context.metadata?.candidate?.reusability;
337
- const recommendedType = context.analysisResult?.recommendedType || context.targetType;
338
- const issues = [];
339
- const recommendations = [];
340
- let score = 15;
341
- // High reusability should favor subflows
342
- if (reusability === flow_subflow_decision_engine_js_1.ReusabilityLevel.HIGH && recommendedType === flow_subflow_decision_engine_js_1.FlowType.MAIN_FLOW) {
343
- score = 5;
344
- issues.push({
345
- type: ValidationRuleType.REUSABILITY_ANALYSIS,
346
- severity: ValidationSeverity.WARNING,
347
- message: 'High reusability potential in main flow',
348
- description: 'Workflows with high reusability should be implemented as subflows',
349
- impact: 'Lost opportunity for reuse across multiple flows',
350
- suggestedFix: 'Implement as subflow to maximize reusability'
351
- });
352
- recommendations.push({
353
- type: ValidationRuleType.REUSABILITY_ANALYSIS,
354
- priority: 'high',
355
- message: 'Implement as subflow',
356
- description: 'Create subflow to enable reuse across multiple workflows',
357
- benefits: ['Code reuse', 'Consistency', 'Easier maintenance'],
358
- implementation: 'Design subflow with clear inputs and outputs',
359
- effort: 'medium'
360
- });
361
- }
362
- // Low reusability in subflow might be over-engineering
363
- if (reusability === flow_subflow_decision_engine_js_1.ReusabilityLevel.NONE && recommendedType === flow_subflow_decision_engine_js_1.FlowType.SUBFLOW) {
364
- score = 8;
365
- issues.push({
366
- type: ValidationRuleType.REUSABILITY_ANALYSIS,
367
- severity: ValidationSeverity.INFO,
368
- message: 'No reusability in subflow',
369
- description: 'Creating subflow with no reusability potential might be over-engineering',
370
- impact: 'Unnecessary complexity',
371
- suggestedFix: 'Consider main flow implementation unless other factors apply'
372
- });
373
- }
374
- return {
375
- passed: score >= 10,
376
- score,
377
- issues,
378
- recommendations
379
- };
380
- }
381
- });
382
- this.rules.set('technical_feasibility', {
383
- id: 'technical_feasibility',
384
- name: 'Technical Feasibility',
385
- description: 'Validate technical feasibility of the recommended approach',
386
- type: ValidationRuleType.TECHNICAL_FEASIBILITY,
387
- severity: ValidationSeverity.ERROR,
388
- weight: 20,
389
- applicableContexts: [],
390
- applicableTypes: [flow_subflow_decision_engine_js_1.FlowType.MAIN_FLOW, flow_subflow_decision_engine_js_1.FlowType.SUBFLOW],
391
- validator: (context) => {
392
- const issues = [];
393
- const recommendations = [];
394
- let score = 20;
395
- // Check for subflow input/output requirements
396
- if (context.targetType === flow_subflow_decision_engine_js_1.FlowType.SUBFLOW) {
397
- const candidate = context.metadata?.candidate;
398
- const definition = context.subflowDefinition;
399
- if (candidate && candidate.inputs.length === 0) {
400
- score = 0;
401
- issues.push({
402
- type: ValidationRuleType.TECHNICAL_FEASIBILITY,
403
- severity: ValidationSeverity.ERROR,
404
- message: 'Subflow has no input parameters',
405
- description: 'Subflows must have at least one input parameter to be reusable',
406
- impact: 'Subflow cannot be properly invoked',
407
- suggestedFix: 'Add appropriate input parameters'
408
- });
409
- }
410
- if (candidate && candidate.outputs.length === 0) {
411
- score = Math.min(score, 5);
412
- issues.push({
413
- type: ValidationRuleType.TECHNICAL_FEASIBILITY,
414
- severity: ValidationSeverity.ERROR,
415
- message: 'Subflow has no output parameters',
416
- description: 'Subflows should have at least one output parameter',
417
- impact: 'Subflow results cannot be used by calling flows',
418
- suggestedFix: 'Add appropriate output parameters'
419
- });
420
- }
421
- if (definition && definition.activities.length < 3) {
422
- score = Math.min(score, 10);
423
- issues.push({
424
- type: ValidationRuleType.TECHNICAL_FEASIBILITY,
425
- severity: ValidationSeverity.WARNING,
426
- message: 'Subflow has very few activities',
427
- description: 'Subflow should have meaningful processing activities',
428
- impact: 'Subflow may not provide sufficient value',
429
- suggestedFix: 'Ensure subflow has adequate processing logic'
430
- });
431
- }
432
- }
433
- return {
434
- passed: score >= 15,
435
- score,
436
- issues,
437
- recommendations
438
- };
439
- }
440
- });
441
- this.rules.set('best_practices', {
442
- id: 'best_practices',
443
- name: 'Best Practices',
444
- description: 'Validate adherence to ServiceNow flow best practices',
445
- type: ValidationRuleType.BEST_PRACTICES,
446
- severity: ValidationSeverity.INFO,
447
- weight: 10,
448
- applicableContexts: [],
449
- applicableTypes: [flow_subflow_decision_engine_js_1.FlowType.MAIN_FLOW, flow_subflow_decision_engine_js_1.FlowType.SUBFLOW],
450
- validator: (context) => {
451
- const issues = [];
452
- const recommendations = [];
453
- let score = 10;
454
- // Check for error handling
455
- const definition = context.subflowDefinition;
456
- if (definition && definition.errorHandling.length === 0) {
457
- score = 7;
458
- issues.push({
459
- type: ValidationRuleType.BEST_PRACTICES,
460
- severity: ValidationSeverity.INFO,
461
- message: 'No error handling defined',
462
- description: 'Flow should include error handling for robustness',
463
- impact: 'Flow may fail ungracefully',
464
- suggestedFix: 'Add error handling activities'
465
- });
466
- recommendations.push({
467
- type: ValidationRuleType.BEST_PRACTICES,
468
- priority: 'medium',
469
- message: 'Add error handling',
470
- description: 'Include error handling to improve flow robustness',
471
- benefits: ['Better error recovery', 'Improved user experience'],
472
- implementation: 'Add try-catch patterns and error notifications',
473
- effort: 'low'
474
- });
475
- }
476
- // Check for documentation
477
- if (definition && (!definition.metadata.documentation || definition.metadata.documentation.length < 50)) {
478
- score = Math.min(score, 8);
479
- recommendations.push({
480
- type: ValidationRuleType.BEST_PRACTICES,
481
- priority: 'low',
482
- message: 'Add comprehensive documentation',
483
- description: 'Document the flow purpose, inputs, outputs, and usage',
484
- benefits: ['Better maintainability', 'Easier onboarding'],
485
- implementation: 'Add detailed description and usage examples',
486
- effort: 'low'
487
- });
488
- }
489
- return {
490
- passed: score >= 7,
491
- score,
492
- issues,
493
- recommendations
494
- };
495
- }
496
- });
497
- this.rules.set('performance_considerations', {
498
- id: 'performance_considerations',
499
- name: 'Performance Considerations',
500
- description: 'Validate performance implications of the recommended approach',
501
- type: ValidationRuleType.PERFORMANCE,
502
- severity: ValidationSeverity.WARNING,
503
- weight: 10,
504
- applicableContexts: [],
505
- applicableTypes: [flow_subflow_decision_engine_js_1.FlowType.MAIN_FLOW, flow_subflow_decision_engine_js_1.FlowType.SUBFLOW],
506
- validator: (context) => {
507
- const issues = [];
508
- const recommendations = [];
509
- let score = 10;
510
- // Check for excessive complexity
511
- const complexity = context.analysisResult?.criteria.complexity;
512
- if (complexity === flow_subflow_decision_engine_js_1.ComplexityLevel.VERY_HIGH) {
513
- score = 6;
514
- issues.push({
515
- type: ValidationRuleType.PERFORMANCE,
516
- severity: ValidationSeverity.WARNING,
517
- message: 'Very high complexity may impact performance',
518
- description: 'Extremely complex flows can have performance implications',
519
- impact: 'Slow execution, resource consumption',
520
- suggestedFix: 'Consider breaking into smaller, more focused flows'
521
- });
522
- recommendations.push({
523
- type: ValidationRuleType.PERFORMANCE,
524
- priority: 'medium',
525
- message: 'Optimize for performance',
526
- description: 'Break complex flows into smaller, more efficient components',
527
- benefits: ['Better performance', 'Improved scalability'],
528
- implementation: 'Use subflows to modularize complex logic',
529
- effort: 'medium'
530
- });
531
- }
532
- // Check for deep nesting in subflows
533
- if (context.targetType === flow_subflow_decision_engine_js_1.FlowType.SUBFLOW) {
534
- const definition = context.subflowDefinition;
535
- if (definition && definition.activities.length > 20) {
536
- score = Math.min(score, 7);
537
- issues.push({
538
- type: ValidationRuleType.PERFORMANCE,
539
- severity: ValidationSeverity.INFO,
540
- message: 'Large subflow may impact performance',
541
- description: 'Subflows with many activities can impact performance',
542
- impact: 'Slower execution',
543
- suggestedFix: 'Consider breaking into smaller subflows'
544
- });
545
- }
546
- }
547
- return {
548
- passed: score >= 7,
549
- score,
550
- issues,
551
- recommendations
552
- };
553
- }
554
- });
555
- this.rules.set('maintainability_assessment', {
556
- id: 'maintainability_assessment',
557
- name: 'Maintainability Assessment',
558
- description: 'Validate maintainability aspects of the recommended approach',
559
- type: ValidationRuleType.MAINTAINABILITY,
560
- severity: ValidationSeverity.INFO,
561
- weight: 10,
562
- applicableContexts: [],
563
- applicableTypes: [flow_subflow_decision_engine_js_1.FlowType.MAIN_FLOW, flow_subflow_decision_engine_js_1.FlowType.SUBFLOW],
564
- validator: (context) => {
565
- const issues = [];
566
- const recommendations = [];
567
- let score = 10;
568
- // Check for maintainability score
569
- const maintainabilityScore = context.analysisResult?.criteria.maintainabilityScore || 5;
570
- if (maintainabilityScore < 5) {
571
- score = 6;
572
- issues.push({
573
- type: ValidationRuleType.MAINTAINABILITY,
574
- severity: ValidationSeverity.INFO,
575
- message: 'Low maintainability score',
576
- description: 'Flow may be difficult to maintain over time',
577
- impact: 'Higher maintenance cost',
578
- suggestedFix: 'Consider simplifying or modularizing the flow'
579
- });
580
- }
581
- // Check for appropriate naming
582
- const definition = context.subflowDefinition;
583
- if (definition && (definition.name.length < 3 || definition.name.includes('_'))) {
584
- score = Math.min(score, 8);
585
- recommendations.push({
586
- type: ValidationRuleType.MAINTAINABILITY,
587
- priority: 'low',
588
- message: 'Improve naming convention',
589
- description: 'Use clear, descriptive names for better maintainability',
590
- benefits: ['Better readability', 'Easier understanding'],
591
- implementation: 'Use descriptive names without underscores',
592
- effort: 'low'
593
- });
594
- }
595
- return {
596
- passed: score >= 6,
597
- score,
598
- issues,
599
- recommendations
600
- };
601
- }
602
- });
603
- this.rules.set('security_considerations', {
604
- id: 'security_considerations',
605
- name: 'Security Considerations',
606
- description: 'Validate security aspects of the recommended approach',
607
- type: ValidationRuleType.SECURITY,
608
- severity: ValidationSeverity.ERROR,
609
- weight: 15,
610
- applicableContexts: [],
611
- applicableTypes: [flow_subflow_decision_engine_js_1.FlowType.MAIN_FLOW, flow_subflow_decision_engine_js_1.FlowType.SUBFLOW],
612
- validator: (context) => {
613
- const issues = [];
614
- const recommendations = [];
615
- let score = 15;
616
- // Check for sensitive data handling
617
- const instruction = context.instruction.toLowerCase();
618
- if (instruction.includes('password') || instruction.includes('secret') || instruction.includes('token')) {
619
- score = 10;
620
- issues.push({
621
- type: ValidationRuleType.SECURITY,
622
- severity: ValidationSeverity.WARNING,
623
- message: 'Potential sensitive data handling',
624
- description: 'Flow may handle sensitive data that requires special security considerations',
625
- impact: 'Security risk if not properly handled',
626
- suggestedFix: 'Ensure proper encryption and access controls'
627
- });
628
- recommendations.push({
629
- type: ValidationRuleType.SECURITY,
630
- priority: 'high',
631
- message: 'Implement security controls',
632
- description: 'Add appropriate security measures for sensitive data',
633
- benefits: ['Data protection', 'Compliance'],
634
- implementation: 'Use encryption, access controls, and audit logging',
635
- effort: 'medium'
636
- });
637
- }
638
- // Check for external integrations
639
- if (instruction.includes('api') || instruction.includes('external') || instruction.includes('integration')) {
640
- score = Math.min(score, 12);
641
- recommendations.push({
642
- type: ValidationRuleType.SECURITY,
643
- priority: 'medium',
644
- message: 'Secure external integrations',
645
- description: 'Ensure external integrations follow security best practices',
646
- benefits: ['Secure data exchange', 'Reduced attack surface'],
647
- implementation: 'Use secure protocols, authentication, and input validation',
648
- effort: 'medium'
649
- });
650
- }
651
- return {
652
- passed: score >= 10,
653
- score,
654
- issues,
655
- recommendations
656
- };
657
- }
658
- });
659
- this.logger.info('Initialized validation rules', { ruleCount: this.rules.size });
660
- }
661
- /**
662
- * Validate and auto-correct JSON schema for Flow Designer
663
- */
664
- validateAndCorrectFlowSchema(flowDefinition) {
665
- const corrections = [];
666
- const errors = [];
667
- let corrected = JSON.parse(JSON.stringify(flowDefinition));
668
- try {
669
- // Ensure top-level structure
670
- if (!corrected.name) {
671
- corrected.name = 'Auto Generated Flow';
672
- corrections.push('Added missing flow name');
673
- }
674
- if (!corrected.description) {
675
- corrected.description = 'Auto-generated flow description';
676
- corrections.push('Added missing description');
677
- }
678
- // Ensure correct flow type
679
- if (!corrected.type || !['flow', 'subflow', 'action'].includes(corrected.type)) {
680
- corrected.type = 'flow';
681
- corrections.push('Set flow type to "flow"');
682
- }
683
- // Ensure activities array exists
684
- if (!corrected.activities || !Array.isArray(corrected.activities)) {
685
- corrected.activities = [];
686
- corrections.push('Created missing activities array');
687
- }
688
- // Validate and correct activities
689
- corrected.activities = corrected.activities.map((activity, index) => {
690
- const correctedActivity = { ...activity };
691
- // Ensure activity has required fields
692
- if (!correctedActivity.sys_id) {
693
- correctedActivity.sys_id = `activity_${index + 1}`;
694
- corrections.push(`Added sys_id to activity ${index + 1}`);
695
- }
696
- if (!correctedActivity.name) {
697
- correctedActivity.name = `Activity ${index + 1}`;
698
- corrections.push(`Added name to activity ${index + 1}`);
699
- }
700
- if (!correctedActivity.type) {
701
- correctedActivity.type = 'condition';
702
- corrections.push(`Added type to activity ${index + 1}`);
703
- }
704
- // Ensure inputs and outputs are objects/arrays
705
- if (!correctedActivity.inputs) {
706
- correctedActivity.inputs = {};
707
- corrections.push(`Added inputs object to activity ${index + 1}`);
708
- }
709
- if (!correctedActivity.outputs) {
710
- correctedActivity.outputs = {};
711
- corrections.push(`Added outputs object to activity ${index + 1}`);
712
- }
713
- return correctedActivity;
714
- });
715
- // Ensure trigger exists for main flows
716
- if (corrected.type === 'flow') {
717
- if (!corrected.trigger) {
718
- corrected.trigger = {
719
- type: 'manual',
720
- table: '',
721
- condition: ''
722
- };
723
- corrections.push('Added missing trigger for flow');
724
- }
725
- // Validate trigger structure
726
- if (!corrected.trigger.type) {
727
- corrected.trigger.type = 'manual';
728
- corrections.push('Set missing trigger type');
729
- }
730
- if (!corrected.trigger.table && corrected.trigger.type !== 'manual') {
731
- corrected.trigger.table = 'incident';
732
- corrections.push('Set default trigger table');
733
- }
734
- }
735
- // Ensure inputs/outputs for subflows
736
- if (corrected.type === 'subflow') {
737
- if (!corrected.inputs || !Array.isArray(corrected.inputs)) {
738
- corrected.inputs = [];
739
- corrections.push('Created missing inputs array for subflow');
740
- }
741
- if (!corrected.outputs || !Array.isArray(corrected.outputs)) {
742
- corrected.outputs = [];
743
- corrections.push('Created missing outputs array for subflow');
744
- }
745
- }
746
- // Validate connections
747
- if (!corrected.connections || !Array.isArray(corrected.connections)) {
748
- corrected.connections = [];
749
- corrections.push('Created missing connections array');
750
- }
751
- // Auto-generate basic connections if activities exist but no connections
752
- if (corrected.activities.length > 1 && corrected.connections.length === 0) {
753
- for (let i = 0; i < corrected.activities.length - 1; i++) {
754
- corrected.connections.push({
755
- from: corrected.activities[i].sys_id,
756
- to: corrected.activities[i + 1].sys_id,
757
- condition_type: 'always'
758
- });
759
- }
760
- corrections.push('Auto-generated sequential connections between activities');
761
- }
762
- // Validate variables
763
- if (!corrected.variables || !Array.isArray(corrected.variables)) {
764
- corrected.variables = [];
765
- corrections.push('Created missing variables array');
766
- }
767
- return {
768
- isValid: errors.length === 0,
769
- correctedDefinition: corrected,
770
- corrections,
771
- errors
772
- };
773
- }
774
- catch (error) {
775
- errors.push(`JSON schema correction failed: ${error instanceof Error ? error.message : String(error)}`);
776
- return {
777
- isValid: false,
778
- correctedDefinition: flowDefinition,
779
- corrections,
780
- errors
781
- };
782
- }
783
- }
784
- /**
785
- * Convert flow definition to Business Rule equivalent
786
- */
787
- convertFlowToBusinessRule(flowDefinition, args) {
788
- const activities = flowDefinition.activities || [];
789
- const trigger = flowDefinition.trigger || {};
790
- let script = `// Auto-converted from Flow: ${flowDefinition.name || args.name}
791
- // Original Flow Type: ${flowDefinition.type || 'flow'}
792
- // Conversion Strategy: Flow Designer → Business Rule
793
-
794
- (function executeRule(current, previous /*null when async*/) {
795
-
796
- try {
797
- gs.log('Snow-Flow converted Business Rule executing: ${flowDefinition.name || args.name}', 'INFO');
798
-
799
- // Variables from flow
800
- var flowVars = {};
801
- ${(flowDefinition.variables || []).map((v) => `flowVars.${v.name} = ${JSON.stringify(v.defaultValue || null)};`).join('\n ')}
802
-
803
- // Flow activities converted to sequential logic
804
- ${this.generateBusinessRuleActivities(activities)}
805
-
806
- gs.log('Snow-Flow converted Business Rule completed: ${flowDefinition.name || args.name}', 'INFO');
807
-
808
- } catch (error) {
809
- gs.error('Snow-Flow converted Business Rule error in ${flowDefinition.name || args.name}: ' + error.message);
810
- }
811
-
812
- })(current, previous);`;
813
- const metadata = {
814
- originalFlowDefinition: flowDefinition,
815
- conversionDate: new Date().toISOString(),
816
- triggerMapping: {
817
- original: trigger,
818
- businessRule: {
819
- table: args.table || trigger.table || 'sys_user',
820
- when: this.mapTriggerToBusinessRuleWhen(trigger.type),
821
- condition: args.condition || trigger.condition || ''
822
- }
823
- },
824
- activitiesConverted: activities.length,
825
- fallbackReason: 'Flow Designer deployment failed'
826
- };
827
- return {
828
- businessRuleScript: script,
829
- metadata
830
- };
831
- }
832
- /**
833
- * Generate Business Rule activities from flow activities
834
- */
835
- generateBusinessRuleActivities(activities) {
836
- if (!activities || activities.length === 0) {
837
- return ` // No activities to convert
838
- gs.log('Business Rule triggered for record: ' + current.getDisplayValue(), 'INFO');`;
839
- }
840
- return activities.map((activity, index) => {
841
- const activityComment = ` // Activity ${index + 1}: ${activity.name || activity.type}`;
842
- switch (activity.type) {
843
- case 'create_record':
844
- return `${activityComment}
845
- var record${index} = new GlideRecord('${activity.table || 'sc_request'}');
846
- record${index}.newRecord();
847
- ${Object.entries(activity.field_values || activity.inputs || {}).map(([field, value]) => `record${index}.${field} = '${value}';`).join('\n ')}
848
- var recordId${index} = record${index}.insert();
849
- gs.log('Created record: ' + recordId${index}, 'INFO');`;
850
- case 'update_record':
851
- return `${activityComment}
852
- var updateRecord${index} = new GlideRecord('${activity.table || 'current.getTableName()'}');
853
- if (updateRecord${index}.get(current.sys_id)) {
854
- ${Object.entries(activity.field_values || activity.inputs || {}).map(([field, value]) => `updateRecord${index}.${field} = '${value}';`).join('\n ')}
855
- updateRecord${index}.update();
856
- gs.log('Updated record: ' + current.sys_id, 'INFO');
857
- }`;
858
- case 'notification':
859
- case 'send_email':
860
- const emailInputs = activity.inputs || {};
861
- return `${activityComment}
862
- var notification${index} = new GlideEmailOutbound();
863
- notification${index}.setTo('${emailInputs.to || 'current.requested_for.email'}');
864
- notification${index}.setSubject('${emailInputs.subject || 'Notification'}');
865
- notification${index}.setBody('${emailInputs.body || 'Automated notification'}');
866
- notification${index}.send();
867
- gs.log('Notification sent', 'INFO');`;
868
- case 'approval':
869
- const approvalInputs = activity.inputs || {};
870
- return `${activityComment}
871
- var approval${index} = new GlideRecord('sysapproval_approver');
872
- approval${index}.newRecord();
873
- approval${index}.approver = '${approvalInputs.approver || 'admin'}';
874
- approval${index}.sysapproval = current.sys_id;
875
- approval${index}.state = 'requested';
876
- approval${index}.comments = 'Approval required';
877
- approval${index}.insert();
878
- gs.log('Approval request created', 'INFO');`;
879
- case 'condition':
880
- return `${activityComment}
881
- if (${activity.condition || 'true'}) {
882
- gs.log('Condition met: ${activity.condition || 'true'}', 'INFO');
883
- // Add condition-specific logic here
884
- }`;
885
- default:
886
- return `${activityComment}
887
- // TODO: Implement ${activity.type} logic
888
- gs.log('Activity ${activity.name || activity.type} executed', 'INFO');`;
889
- }
890
- }).join('\n\n');
891
- }
892
- /**
893
- * Map flow trigger type to business rule when
894
- */
895
- mapTriggerToBusinessRuleWhen(triggerType) {
896
- switch (triggerType) {
897
- case 'record_created':
898
- return 'after';
899
- case 'record_updated':
900
- return 'after';
901
- case 'record_deleted':
902
- return 'before';
903
- case 'manual':
904
- return 'async';
905
- case 'scheduled':
906
- return 'async';
907
- default:
908
- return 'after';
909
- }
910
- }
911
- }
912
- exports.FlowValidationEngine = FlowValidationEngine;
913
- //# sourceMappingURL=flow-validation-engine.js.map