snow-flow 2.0.2 → 2.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. package/{.claude/mcp-config.json → .mcp.json} +13 -12
  2. package/.releaserc.json +47 -0
  3. package/README.md +6 -0
  4. package/package.json +1 -1
  5. package/.claude/claude-settings.json +0 -15
  6. package/.claude/commands/analysis/README.md +0 -9
  7. package/.claude/commands/automation/README.md +0 -9
  8. package/.claude/commands/github/README.md +0 -11
  9. package/.claude/commands/helpers/standard-checkpoint-hooks.sh +0 -179
  10. package/.claude/commands/hooks/README.md +0 -11
  11. package/.claude/commands/monitoring/README.md +0 -9
  12. package/.claude/commands/optimization/README.md +0 -9
  13. package/.claude/commands/training/README.md +0 -9
  14. package/.claude/commands/workflows/README.md +0 -9
  15. package/.claude/config.json +0 -36
  16. package/.claude/helpers/github-setup.sh +0 -28
  17. package/.claude/helpers/quick-start.sh +0 -19
  18. package/.claude/helpers/setup-mcp.sh +0 -18
  19. package/.claude/settings.json +0 -114
  20. package/.claude/settings.local.json +0 -33
  21. package/.claude-flow/metrics/agent-metrics.json +0 -1
  22. package/.claude-flow/metrics/performance.json +0 -9
  23. package/.claude-flow/metrics/system-metrics.json +0 -15986
  24. package/.claude-flow/metrics/task-metrics.json +0 -10
  25. package/.roo/README.md +0 -402
  26. package/.roo/mcp-list.txt +0 -257
  27. package/.roo/mcp.json +0 -32
  28. package/.roo/workflows/basic-tdd.json +0 -32
  29. package/.roomodes +0 -201
  30. package/CLAUDE.md +0 -393
  31. package/bin/snow-flow.js +0 -3
  32. package/dist/cli.js.bak +0 -2052
  33. package/dist/config/snow-flow-config.d.ts +0 -1492
  34. package/dist/config/snow-flow-config.js +0 -938
  35. package/scripts/create-env.js +0 -91
  36. package/scripts/postinstall.js +0 -30
  37. package/scripts/register-mcp-servers.js +0 -210
  38. package/scripts/reset-mcp-servers.js +0 -246
  39. package/scripts/setup-mcp.js +0 -106
  40. package/scripts/update-version.js +0 -31
  41. package/src/agents/README.md +0 -192
  42. package/src/agents/base-agent.ts +0 -251
  43. package/src/agents/coordinator.ts +0 -971
  44. package/src/agents/index.ts +0 -18
  45. package/src/agents/queen-403-handler.ts +0 -230
  46. package/src/agents/queen-agent.ts +0 -1399
  47. package/src/agents/script-writer-agent.ts +0 -769
  48. package/src/agents/security-agent.ts +0 -726
  49. package/src/agents/widget-creator-agent.ts +0 -568
  50. package/src/api/error-handling.ts +0 -1758
  51. package/src/api/natural-language-mapper.ts +0 -630
  52. package/src/api/performance-optimizer.ts +0 -891
  53. package/src/api/transaction-manager.ts +0 -754
  54. package/src/cli/deploy-artifact.ts +0 -304
  55. package/src/cli/snow-flow-cli-integration.ts +0 -434
  56. package/src/cli.ts +0 -4455
  57. package/src/cli.ts.bak +0 -5616
  58. package/src/compliance/advanced-compliance-system.ts +0 -1268
  59. package/src/compliance/index.ts +0 -19
  60. package/src/config/snow-flow-config.ts +0 -1019
  61. package/src/documentation/index.ts +0 -16
  62. package/src/documentation/self-documenting-system.ts +0 -1421
  63. package/src/dynamic-version.ts +0 -44
  64. package/src/healing/index.ts +0 -20
  65. package/src/healing/self-healing-system.ts +0 -1435
  66. package/src/health/README.md +0 -161
  67. package/src/health/system-health.ts +0 -995
  68. package/src/index.ts +0 -60
  69. package/src/intelligence/acl-analyzer.ts +0 -377
  70. package/src/intelligence/auto-resolution-engine.ts +0 -643
  71. package/src/intelligence/gap-analysis-engine.ts +0 -488
  72. package/src/intelligence/manual-instructions-generator.ts +0 -744
  73. package/src/intelligence/mcp-coverage-analyzer.ts +0 -708
  74. package/src/intelligence/multi-pass-requirements-analyzer.ts +0 -603
  75. package/src/intelligence/performance-recommendations-engine.ts +0 -1223
  76. package/src/intelligence/requirements-analyzer.ts +0 -1148
  77. package/src/intelligence/task-analyzer.ts +0 -628
  78. package/src/managers/scope-manager.ts +0 -555
  79. package/src/mcp/advanced/servicenow-advanced-features-mcp.ts +0 -16110
  80. package/src/mcp/base-mcp-server.ts +0 -660
  81. package/src/mcp/http-transport-wrapper.ts +0 -426
  82. package/src/mcp/service-discovery-client.ts +0 -312
  83. package/src/mcp/servicenow-automation-mcp-refactored.ts +0 -678
  84. package/src/mcp/servicenow-automation-mcp.ts +0 -838
  85. package/src/mcp/servicenow-deployment-mcp-refactored.ts +0 -1292
  86. package/src/mcp/servicenow-deployment-mcp.ts +0 -7244
  87. package/src/mcp/servicenow-graph-memory-mcp-refactored.ts +0 -721
  88. package/src/mcp/servicenow-graph-memory-mcp.ts +0 -832
  89. package/src/mcp/servicenow-integration-mcp-refactored.ts +0 -655
  90. package/src/mcp/servicenow-integration-mcp.ts +0 -819
  91. package/src/mcp/servicenow-intelligent-mcp-refactored.ts +0 -977
  92. package/src/mcp/servicenow-intelligent-mcp.ts +0 -4638
  93. package/src/mcp/servicenow-mcp-server.ts +0 -728
  94. package/src/mcp/servicenow-memory-mcp.ts +0 -474
  95. package/src/mcp/servicenow-operations-mcp-refactored.ts +0 -1995
  96. package/src/mcp/servicenow-operations-mcp.ts +0 -3384
  97. package/src/mcp/servicenow-platform-development-mcp-refactored.ts +0 -611
  98. package/src/mcp/servicenow-platform-development-mcp.ts +0 -970
  99. package/src/mcp/servicenow-progressive-indexer.ts +0 -370
  100. package/src/mcp/servicenow-reporting-analytics-mcp-refactored.ts +0 -695
  101. package/src/mcp/servicenow-reporting-analytics-mcp.ts +0 -1123
  102. package/src/mcp/servicenow-security-compliance-mcp-refactored.ts +0 -642
  103. package/src/mcp/servicenow-security-compliance-mcp.ts +0 -1157
  104. package/src/mcp/servicenow-update-set-mcp-refactored.ts +0 -751
  105. package/src/mcp/servicenow-update-set-mcp.ts +0 -811
  106. package/src/mcp/shared/agent-context-provider.ts +0 -365
  107. package/src/mcp/shared/base-mcp-server.ts +0 -2463
  108. package/src/mcp/shared/mcp-memory-manager.ts +0 -540
  109. package/src/mcp/shared/mcp-resource-manager.ts +0 -367
  110. package/src/mcp/snow-flow-mcp.ts +0 -911
  111. package/src/mcp/start-all-mcp-servers.ts +0 -102
  112. package/src/mcp/start-servicenow-mcp.ts +0 -67
  113. package/src/monitoring/enhanced-monitoring-system.ts +0 -1345
  114. package/src/monitoring/performance-tracker.ts +0 -777
  115. package/src/optimization/cost-optimization-engine.ts +0 -1125
  116. package/src/optimization/index.ts +0 -10
  117. package/src/queen/README.md +0 -403
  118. package/src/queen/agent-factory.ts +0 -574
  119. package/src/queen/index.ts +0 -94
  120. package/src/queen/mcp-execution-bridge.ts +0 -681
  121. package/src/queen/neural-learning.ts +0 -319
  122. package/src/queen/parallel-agent-engine.ts +0 -848
  123. package/src/queen/queen-memory-system.ts +0 -490
  124. package/src/queen/queen-memory.ts +0 -456
  125. package/src/queen/servicenow-queen.ts +0 -1029
  126. package/src/queen/types.ts +0 -87
  127. package/src/rollback/smart-rollback-system.ts +0 -866
  128. package/src/schemas/deployment.schema.json +0 -58
  129. package/src/schemas/flow.schema.json +0 -79
  130. package/src/schemas/widget.schema.json +0 -72
  131. package/src/snow-flow-system.ts +0 -541
  132. package/src/sparc/sparc-help.ts +0 -49
  133. package/src/sparc/team-sparc.ts +0 -88
  134. package/src/strategies/global-scope-strategy.ts +0 -736
  135. package/src/templates/base/application.template.json +0 -45
  136. package/src/templates/base/business_rule.template.json +0 -33
  137. package/src/templates/base/script_include.template.json +0 -18
  138. package/src/templates/base/table.template.json +0 -64
  139. package/src/templates/base/widget.template.json +0 -25
  140. package/src/templates/patterns/composite.incident-management.template.json +0 -140
  141. package/src/templates/patterns/widget.dashboard.template.json +0 -238
  142. package/src/templates/patterns/widget.datatable.template.json +0 -292
  143. package/src/testing/integration-test-suite.ts +0 -1276
  144. package/src/types/index.ts +0 -183
  145. package/src/types/neo4j-driver.d.ts +0 -23
  146. package/src/types/servicenow.types.ts +0 -307
  147. package/src/types/snow-flow.types.ts +0 -186
  148. package/src/types/todo.types.ts +0 -70
  149. package/src/utils/action-type-cache.ts +0 -286
  150. package/src/utils/agent-detector.ts +0 -573
  151. package/src/utils/artifact-tracker.ts +0 -379
  152. package/src/utils/dependency-detector.ts +0 -233
  153. package/src/utils/deployment-metadata-handler.ts +0 -518
  154. package/src/utils/error-recovery.ts +0 -680
  155. package/src/utils/logger.ts +0 -60
  156. package/src/utils/mcp-auth-middleware.ts +0 -262
  157. package/src/utils/mcp-config-manager.ts +0 -270
  158. package/src/utils/mcp-server-manager.ts +0 -446
  159. package/src/utils/mcp-tool-registry.ts +0 -298
  160. package/src/utils/migrate-snow-flow.ts +0 -98
  161. package/src/utils/oauth-html-templates.ts +0 -188
  162. package/src/utils/scope-utils.ts +0 -443
  163. package/src/utils/servicenow-client.ts +0 -3321
  164. package/src/utils/servicenow-id-generator.ts +0 -181
  165. package/src/utils/snow-memory-manager.ts +0 -605
  166. package/src/utils/snow-oauth.ts +0 -797
  167. package/src/utils/template-engine.ts +0 -463
  168. package/src/utils/theme-manager.ts +0 -295
  169. package/src/utils/unified-auth-store.ts +0 -222
  170. package/src/utils/update-set-importer.ts +0 -422
  171. package/src/utils/update-set-xml-packager.ts +0 -371
  172. package/src/utils/widget-template-generator.ts +0 -1744
  173. package/src/version.ts +0 -1950
@@ -1,736 +0,0 @@
1
- /**
2
- * Global Scope Strategy for ServiceNow Flow Creation
3
- *
4
- * This strategy implements a global scope approach for ServiceNow artifacts,
5
- * replacing the current application-scoped approach with a more flexible
6
- * global scope deployment model.
7
- */
8
-
9
- import { ServiceNowClient } from '../utils/servicenow-client.js';
10
- import { ServiceNowOAuth } from '../utils/snow-oauth.js';
11
- import { Logger } from '../utils/logger.js';
12
-
13
- export enum ScopeType {
14
- GLOBAL = 'global',
15
- APPLICATION = 'application',
16
- AUTO = 'auto'
17
- }
18
-
19
- export interface ScopeConfiguration {
20
- type: ScopeType;
21
- applicationId?: string;
22
- applicationName?: string;
23
- globalDomain?: string;
24
- fallbackToGlobal?: boolean;
25
- permissions?: string[];
26
- }
27
-
28
- export interface GlobalScopeDeploymentResult {
29
- success: boolean;
30
- scope: ScopeType;
31
- domain: string;
32
- artifactId: string;
33
- permissions: string[];
34
- message: string;
35
- warnings?: string[];
36
- fallbackApplied?: boolean;
37
- }
38
-
39
- export interface ScopeValidationResult {
40
- isValid: boolean;
41
- hasPermissions: boolean;
42
- canCreateGlobal: boolean;
43
- canCreateScoped: boolean;
44
- recommendedScope: ScopeType;
45
- issues: string[];
46
- warnings: string[];
47
- }
48
-
49
- export class GlobalScopeStrategy {
50
- private client: ServiceNowClient;
51
- private oauth: ServiceNowOAuth;
52
- private logger: Logger;
53
- private defaultConfiguration: ScopeConfiguration;
54
-
55
- constructor() {
56
- this.client = new ServiceNowClient();
57
- this.oauth = new ServiceNowOAuth();
58
- this.logger = new Logger('GlobalScopeStrategy');
59
-
60
- // Default configuration prioritizes global scope
61
- this.defaultConfiguration = {
62
- type: ScopeType.GLOBAL,
63
- globalDomain: 'global',
64
- fallbackToGlobal: true,
65
- permissions: ['sys_scope.write', 'sys_metadata.write']
66
- };
67
- }
68
-
69
- /**
70
- * Analyze and determine the optimal scope for deployment
71
- */
72
- async analyzeScopeRequirements(artifactType: string, artifactData: any): Promise<ScopeConfiguration> {
73
- this.logger.info('Analyzing scope requirements', { artifactType, artifactData: artifactData.name });
74
-
75
- const scopeConfig: ScopeConfiguration = { ...this.defaultConfiguration };
76
-
77
- // Analyze artifact complexity and dependencies
78
- const complexity = this.assessArtifactComplexity(artifactType, artifactData);
79
- const dependencies = await this.analyzeDependencies(artifactType, artifactData);
80
- const permissions = await this.checkRequiredPermissions(artifactType);
81
-
82
- // Global scope is preferred for:
83
- // 1. System-wide flows and utilities
84
- // 2. Cross-application integrations
85
- // 3. Infrastructure components
86
- // 4. Shared libraries and common functions
87
-
88
- const globalScopeIndicators = [
89
- artifactData.name?.toLowerCase().includes('global'),
90
- artifactData.name?.toLowerCase().includes('system'),
91
- artifactData.name?.toLowerCase().includes('util'),
92
- artifactData.description?.toLowerCase().includes('cross-application'),
93
- artifactData.description?.toLowerCase().includes('shared'),
94
- complexity.isInfrastructure,
95
- dependencies.crossApplication,
96
- artifactType === 'script_include' && artifactData.api_name?.includes('Global'),
97
- artifactType === 'business_rule' && artifactData.table === 'global'
98
- ];
99
-
100
- const globalIndicatorCount = globalScopeIndicators.filter(Boolean).length;
101
-
102
- // Application scope is preferred for:
103
- // 1. Application-specific business logic
104
- // 2. Isolated functionality
105
- // 3. Customer-specific customizations
106
- const applicationScopeIndicators = [
107
- artifactData.scope && artifactData.scope !== 'global',
108
- artifactData.application_specific === true,
109
- complexity.isApplicationSpecific,
110
- !dependencies.crossApplication,
111
- artifactData.name?.toLowerCase().includes('custom'),
112
- artifactData.description?.toLowerCase().includes('application-specific')
113
- ];
114
-
115
- const applicationIndicatorCount = applicationScopeIndicators.filter(Boolean).length;
116
-
117
- // Decision logic
118
- if (globalIndicatorCount > applicationIndicatorCount) {
119
- scopeConfig.type = ScopeType.GLOBAL;
120
- scopeConfig.globalDomain = 'global';
121
- this.logger.info('Global scope recommended', {
122
- globalIndicators: globalIndicatorCount,
123
- applicationIndicators: applicationIndicatorCount
124
- });
125
- } else if (applicationIndicatorCount > globalIndicatorCount && artifactData.scope) {
126
- scopeConfig.type = ScopeType.APPLICATION;
127
- scopeConfig.applicationId = artifactData.scope;
128
- scopeConfig.applicationName = artifactData.application_name;
129
- this.logger.info('Application scope recommended', {
130
- scope: artifactData.scope,
131
- applicationIndicators: applicationIndicatorCount
132
- });
133
- } else {
134
- // Auto mode - let the system decide based on permissions and context
135
- scopeConfig.type = ScopeType.AUTO;
136
- this.logger.info('Auto scope mode selected - will determine at deployment time');
137
- }
138
-
139
- scopeConfig.permissions = permissions;
140
- return scopeConfig;
141
- }
142
-
143
- /**
144
- * Validate scope permissions and capabilities
145
- */
146
- async validateScopePermissions(scopeConfig: ScopeConfiguration): Promise<ScopeValidationResult> {
147
- this.logger.info('Validating scope permissions', { scopeType: scopeConfig.type });
148
-
149
- const result: ScopeValidationResult = {
150
- isValid: false,
151
- hasPermissions: false,
152
- canCreateGlobal: false,
153
- canCreateScoped: false,
154
- recommendedScope: ScopeType.GLOBAL,
155
- issues: [],
156
- warnings: []
157
- };
158
-
159
- try {
160
- // Check if user has global scope permissions
161
- const globalPermissions = await this.checkGlobalScopePermissions();
162
- result.canCreateGlobal = globalPermissions.hasPermission;
163
-
164
- if (!globalPermissions.hasPermission) {
165
- result.issues.push(...globalPermissions.issues);
166
- result.warnings.push('Global scope permissions not available - consider using application scope');
167
- }
168
-
169
- // Check if user has application scope permissions
170
- const applicationPermissions = await this.checkApplicationScopePermissions(scopeConfig.applicationId);
171
- result.canCreateScoped = applicationPermissions.hasPermission;
172
-
173
- if (!applicationPermissions.hasPermission) {
174
- result.issues.push(...applicationPermissions.issues);
175
- }
176
-
177
- // Determine validity and recommendation
178
- if (scopeConfig.type === ScopeType.GLOBAL) {
179
- result.isValid = result.canCreateGlobal;
180
- result.hasPermissions = result.canCreateGlobal;
181
- result.recommendedScope = result.canCreateGlobal ? ScopeType.GLOBAL : ScopeType.APPLICATION;
182
- } else if (scopeConfig.type === ScopeType.APPLICATION) {
183
- result.isValid = result.canCreateScoped;
184
- result.hasPermissions = result.canCreateScoped;
185
- result.recommendedScope = result.canCreateScoped ? ScopeType.APPLICATION : ScopeType.GLOBAL;
186
- } else {
187
- // Auto mode - prefer global if available, fallback to application
188
- result.isValid = result.canCreateGlobal || result.canCreateScoped;
189
- result.hasPermissions = result.canCreateGlobal || result.canCreateScoped;
190
- result.recommendedScope = result.canCreateGlobal ? ScopeType.GLOBAL : ScopeType.APPLICATION;
191
- }
192
-
193
- if (!result.isValid) {
194
- result.issues.push('Insufficient permissions for any scope type');
195
- }
196
-
197
- this.logger.info('Scope validation completed', {
198
- isValid: result.isValid,
199
- canCreateGlobal: result.canCreateGlobal,
200
- canCreateScoped: result.canCreateScoped,
201
- recommendedScope: result.recommendedScope
202
- });
203
-
204
- } catch (error) {
205
- this.logger.error('Scope validation failed', error);
206
- result.issues.push(`Validation error: ${error instanceof Error ? error.message : String(error)}`);
207
- }
208
-
209
- return result;
210
- }
211
-
212
- /**
213
- * Deploy artifact using global scope strategy
214
- */
215
- async deployWithGlobalScope(
216
- artifactType: string,
217
- artifactData: any,
218
- scopeConfig?: ScopeConfiguration
219
- ): Promise<GlobalScopeDeploymentResult> {
220
- this.logger.info('Starting global scope deployment', {
221
- artifactType,
222
- artifactName: artifactData.name,
223
- scopeType: scopeConfig?.type || 'default'
224
- });
225
-
226
- const config = scopeConfig || await this.analyzeScopeRequirements(artifactType, artifactData);
227
- const validation = await this.validateScopePermissions(config);
228
-
229
- if (!validation.isValid) {
230
- return {
231
- success: false,
232
- scope: config.type,
233
- domain: config.globalDomain || 'unknown',
234
- artifactId: '',
235
- permissions: config.permissions || [],
236
- message: `Deployment failed: ${validation.issues.join(', ')}`,
237
- warnings: validation.warnings
238
- };
239
- }
240
-
241
- try {
242
- // Apply the appropriate scope strategy
243
- let deploymentResult: any;
244
- let actualScope: ScopeType;
245
-
246
- if (config.type === ScopeType.GLOBAL || validation.recommendedScope === ScopeType.GLOBAL) {
247
- deploymentResult = await this.deployToGlobalScope(artifactType, artifactData, config);
248
- actualScope = ScopeType.GLOBAL;
249
- } else if (config.type === ScopeType.APPLICATION || validation.recommendedScope === ScopeType.APPLICATION) {
250
- deploymentResult = await this.deployToApplicationScope(artifactType, artifactData, config);
251
- actualScope = ScopeType.APPLICATION;
252
- } else {
253
- // Auto mode - try global first, fallback to application
254
- try {
255
- deploymentResult = await this.deployToGlobalScope(artifactType, artifactData, config);
256
- actualScope = ScopeType.GLOBAL;
257
- } catch (error) {
258
- if (config.fallbackToGlobal) {
259
- this.logger.warn('Global scope deployment failed, falling back to application scope', error);
260
- deploymentResult = await this.deployToApplicationScope(artifactType, artifactData, config);
261
- actualScope = ScopeType.APPLICATION;
262
- } else {
263
- throw error;
264
- }
265
- }
266
- }
267
-
268
- return {
269
- success: deploymentResult.success,
270
- scope: actualScope,
271
- domain: actualScope === ScopeType.GLOBAL ? 'global' : (config.applicationName || 'application'),
272
- artifactId: deploymentResult.sys_id || deploymentResult.id,
273
- permissions: config.permissions || [],
274
- message: `Successfully deployed to ${actualScope} scope`,
275
- warnings: validation.warnings,
276
- fallbackApplied: config.type !== actualScope
277
- };
278
-
279
- } catch (error) {
280
- this.logger.error('Global scope deployment failed', error);
281
- return {
282
- success: false,
283
- scope: config.type,
284
- domain: config.globalDomain || 'global',
285
- artifactId: '',
286
- permissions: config.permissions || [],
287
- message: `Deployment failed: ${error instanceof Error ? error.message : String(error)}`
288
- };
289
- }
290
- }
291
-
292
- /**
293
- * Deploy artifact to global scope
294
- */
295
- private async deployToGlobalScope(
296
- artifactType: string,
297
- artifactData: any,
298
- config: ScopeConfiguration
299
- ): Promise<any> {
300
- this.logger.info('Deploying to global scope', { artifactType, name: artifactData.name });
301
-
302
- // Set global scope context
303
- const globalArtifactData = {
304
- ...artifactData,
305
- sys_scope: 'global',
306
- sys_domain: 'global',
307
- sys_domain_path: '/',
308
- application: null, // Remove application association
309
- scope: 'global'
310
- };
311
-
312
- // Remove application-specific fields
313
- delete globalArtifactData.application_id;
314
- delete globalArtifactData.application_name;
315
- delete globalArtifactData.vendor;
316
- delete globalArtifactData.vendor_prefix;
317
-
318
- // Add global scope metadata
319
- globalArtifactData.sys_created_on = new Date().toISOString();
320
- globalArtifactData.sys_updated_on = new Date().toISOString();
321
- globalArtifactData.sys_class_name = this.getSystemClassName(artifactType);
322
-
323
- // Deploy based on artifact type
324
- switch (artifactType) {
325
- case 'flow':
326
- return await this.deployFlowToGlobalScope(globalArtifactData);
327
- case 'widget':
328
- return await this.deployWidgetToGlobalScope(globalArtifactData);
329
- case 'script_include':
330
- return await this.deployScriptIncludeToGlobalScope(globalArtifactData);
331
- case 'business_rule':
332
- return await this.deployBusinessRuleToGlobalScope(globalArtifactData);
333
- case 'table':
334
- return await this.deployTableToGlobalScope(globalArtifactData);
335
- default:
336
- throw new Error(`Unsupported artifact type for global scope: ${artifactType}`);
337
- }
338
- }
339
-
340
- /**
341
- * Deploy artifact to application scope (fallback)
342
- */
343
- private async deployToApplicationScope(
344
- artifactType: string,
345
- artifactData: any,
346
- config: ScopeConfiguration
347
- ): Promise<any> {
348
- this.logger.info('Deploying to application scope', {
349
- artifactType,
350
- name: artifactData.name,
351
- applicationId: config.applicationId
352
- });
353
-
354
- // If no application is specified, create one
355
- if (!config.applicationId) {
356
- const application = await this.createTemporaryApplication(artifactData.name);
357
- config.applicationId = application.sys_id;
358
- config.applicationName = application.name;
359
- }
360
-
361
- // Set application scope context
362
- const scopedArtifactData = {
363
- ...artifactData,
364
- sys_scope: config.applicationId,
365
- application: config.applicationId,
366
- scope: config.applicationId
367
- };
368
-
369
- // Use existing application deployment logic
370
- return await this.client.createRecord(this.getTableName(artifactType), scopedArtifactData);
371
- }
372
-
373
- /**
374
- * Deploy flow to global scope
375
- */
376
- private async deployFlowToGlobalScope(flowData: any): Promise<any> {
377
- this.logger.info('Deploying flow to global scope', { name: flowData.name });
378
-
379
- // Enhanced flow data for global scope
380
- const globalFlowData = {
381
- ...flowData,
382
- // Global scope specific fields
383
- sys_scope: 'global',
384
- run_as: 'user_who_triggers', // Global flows typically run as triggering user
385
- access: 'public', // Global access
386
- source_ui: 'flow_designer',
387
-
388
- // Remove application-specific constraints
389
- application: null,
390
- category: flowData.category || 'global_automation',
391
-
392
- // Enhanced metadata
393
- sys_class_name: 'sys_hub_flow',
394
- type: 'flow',
395
- status: 'published'
396
- };
397
-
398
- // Ensure we're creating a flow, not a subflow
399
- globalFlowData.flow_type = 'flow';
400
- globalFlowData.sys_class_name = 'sys_hub_flow';
401
-
402
- this.logger.info('Creating flow with explicit type', {
403
- name: globalFlowData.name,
404
- type: globalFlowData.type,
405
- flow_type: globalFlowData.flow_type,
406
- sys_class_name: globalFlowData.sys_class_name
407
- });
408
-
409
- return await this.client.createFlow(globalFlowData);
410
- }
411
-
412
- /**
413
- * Deploy widget to global scope
414
- */
415
- private async deployWidgetToGlobalScope(widgetData: any): Promise<any> {
416
- this.logger.info('Deploying widget to global scope', { name: widgetData.name });
417
-
418
- const globalWidgetData = {
419
- ...widgetData,
420
- sys_scope: 'global',
421
- category: widgetData.category || 'global_widgets',
422
- has_preview: true,
423
- public: true // Global widgets are public
424
- };
425
-
426
- return await this.client.createWidget(globalWidgetData);
427
- }
428
-
429
- /**
430
- * Deploy script include to global scope
431
- */
432
- private async deployScriptIncludeToGlobalScope(scriptData: any): Promise<any> {
433
- this.logger.info('Deploying script include to global scope', { name: scriptData.name });
434
-
435
- const globalScriptData = {
436
- ...scriptData,
437
- sys_scope: 'global',
438
- access: 'public', // Global script includes are typically public
439
- active: true,
440
- api_name: scriptData.api_name || scriptData.name
441
- };
442
-
443
- return await this.client.createScriptInclude(globalScriptData);
444
- }
445
-
446
- /**
447
- * Deploy business rule to global scope
448
- */
449
- private async deployBusinessRuleToGlobalScope(ruleData: any): Promise<any> {
450
- this.logger.info('Deploying business rule to global scope', { name: ruleData.name });
451
-
452
- const globalRuleData = {
453
- ...ruleData,
454
- sys_scope: 'global',
455
- active: true,
456
- order: ruleData.order || 100
457
- };
458
-
459
- return await this.client.createBusinessRule(globalRuleData);
460
- }
461
-
462
- /**
463
- * Deploy table to global scope
464
- */
465
- private async deployTableToGlobalScope(tableData: any): Promise<any> {
466
- this.logger.info('Deploying table to global scope', { name: tableData.name });
467
-
468
- const globalTableData = {
469
- ...tableData,
470
- sys_scope: 'global',
471
- access: 'public',
472
- is_extendable: true,
473
- create_access_controls: true
474
- };
475
-
476
- return await this.client.createTable(globalTableData);
477
- }
478
-
479
- /**
480
- * Check global scope permissions
481
- */
482
- private async checkGlobalScopePermissions(): Promise<{ hasPermission: boolean; issues: string[] }> {
483
- try {
484
- // Check if user can create global scope artifacts
485
- const userRoles = await this.client.getRecords('sys_user_has_role', {
486
- sysparm_query: `user=javascript:gs.getUserID()`,
487
- sysparm_fields: 'role.name'
488
- });
489
-
490
- if (!userRoles.success) {
491
- return { hasPermission: false, issues: ['Cannot check user roles'] };
492
- }
493
-
494
- const roles = userRoles.data.map((r: any) => r.role?.name).filter(Boolean);
495
- const globalPermissionRoles = ['admin', 'system_administrator', 'global_admin'];
496
-
497
- const hasGlobalPermission = globalPermissionRoles.some(role => roles.includes(role));
498
-
499
- return {
500
- hasPermission: hasGlobalPermission,
501
- issues: hasGlobalPermission ? [] : [
502
- '🔐 Permission Error: Global scope access required',
503
- `Missing roles: ${globalPermissionRoles.filter(r => !roles.includes(r)).join(', ')}`,
504
- 'To fix:',
505
- '1. Run: snow_escalate_permissions tool for detailed instructions',
506
- '2. Or contact your ServiceNow administrator',
507
- '3. Or use a personal developer instance from developer.servicenow.com'
508
- ]
509
- };
510
-
511
- } catch (error) {
512
- return {
513
- hasPermission: false,
514
- issues: [`Permission check failed: ${error instanceof Error ? error.message : String(error)}`]
515
- };
516
- }
517
- }
518
-
519
- /**
520
- * Check application scope permissions
521
- */
522
- private async checkApplicationScopePermissions(applicationId?: string): Promise<{ hasPermission: boolean; issues: string[] }> {
523
- try {
524
- if (!applicationId) {
525
- // User can create applications if they have app_creator or admin role
526
- const userRoles = await this.client.getRecords('sys_user_has_role', {
527
- sysparm_query: `user=javascript:gs.getUserID()`,
528
- sysparm_fields: 'role.name'
529
- });
530
-
531
- if (!userRoles.success) {
532
- return { hasPermission: false, issues: ['Cannot check user roles'] };
533
- }
534
-
535
- const roles = userRoles.data.map((r: any) => r.role?.name).filter(Boolean);
536
- const appCreatorRoles = ['admin', 'system_administrator', 'app_creator'];
537
-
538
- const hasAppPermission = appCreatorRoles.some(role => roles.includes(role));
539
-
540
- return {
541
- hasPermission: hasAppPermission,
542
- issues: hasAppPermission ? [] : ['User lacks application creation permissions (admin, system_administrator, or app_creator role required)']
543
- };
544
- }
545
-
546
- // Check if application exists and user has access
547
- const app = await this.client.getRecord('sys_app', applicationId);
548
- return {
549
- hasPermission: !!app,
550
- issues: app ? [] : [`Application ${applicationId} not found or not accessible`]
551
- };
552
-
553
- } catch (error) {
554
- return {
555
- hasPermission: false,
556
- issues: [`Permission check failed: ${error instanceof Error ? error.message : String(error)}`]
557
- };
558
- }
559
- }
560
-
561
- /**
562
- * Assess artifact complexity for scope decision
563
- */
564
- private assessArtifactComplexity(artifactType: string, artifactData: any): any {
565
- const complexity = {
566
- isInfrastructure: false,
567
- isApplicationSpecific: false,
568
- crossApplication: false,
569
- sharedUtility: false
570
- };
571
-
572
- // Infrastructure indicators
573
- const infraKeywords = ['system', 'global', 'util', 'lib', 'common', 'shared', 'infrastructure'];
574
- const artifactText = `${artifactData.name} ${artifactData.description || ''}`.toLowerCase();
575
-
576
- complexity.isInfrastructure = infraKeywords.some(keyword => artifactText.includes(keyword));
577
-
578
- // Application-specific indicators
579
- const appKeywords = ['custom', 'specific', 'application', 'business', 'process'];
580
- complexity.isApplicationSpecific = appKeywords.some(keyword => artifactText.includes(keyword));
581
-
582
- // Cross-application indicators
583
- const crossAppKeywords = ['integration', 'cross', 'bridge', 'connector', 'api'];
584
- complexity.crossApplication = crossAppKeywords.some(keyword => artifactText.includes(keyword));
585
-
586
- // Shared utility indicators
587
- const utilityKeywords = ['utility', 'helper', 'tool', 'function', 'method'];
588
- complexity.sharedUtility = utilityKeywords.some(keyword => artifactText.includes(keyword));
589
-
590
- return complexity;
591
- }
592
-
593
- /**
594
- * Analyze artifact dependencies
595
- */
596
- private async analyzeDependencies(artifactType: string, artifactData: any): Promise<any> {
597
- const dependencies = {
598
- crossApplication: false,
599
- globalDependencies: [],
600
- applicationDependencies: []
601
- };
602
-
603
- // Simple dependency _analysis based on artifact content
604
- const content = JSON.stringify(artifactData);
605
-
606
- // Check for global API calls
607
- const globalApiPatterns = [
608
- /gs\./g, // GlideSystem calls
609
- /GlideRecord\(/g, // Database access
610
- /gs\.getProperty\(/g, // System properties
611
- /gs\.log\(/g // System logging
612
- ];
613
-
614
- const hasGlobalApis = globalApiPatterns.some(pattern => pattern.test(content));
615
- if (hasGlobalApis) {
616
- dependencies.crossApplication = true;
617
- dependencies.globalDependencies.push('system_apis');
618
- }
619
-
620
- return dependencies;
621
- }
622
-
623
- /**
624
- * Check required permissions for artifact type
625
- */
626
- private async checkRequiredPermissions(artifactType: string): Promise<string[]> {
627
- const permissionMap: Record<string, string[]> = {
628
- 'flow': ['sys_hub_flow.write', 'sys_metadata.write'],
629
- 'widget': ['sp_widget.write', 'sys_metadata.write'],
630
- 'script_include': ['sys_script_include.write', 'sys_metadata.write'],
631
- 'business_rule': ['sys_script.write', 'sys_metadata.write'],
632
- 'table': ['sys_db_object.write', 'sys_metadata.write']
633
- };
634
-
635
- return permissionMap[artifactType] || ['sys_metadata.write'];
636
- }
637
-
638
- /**
639
- * Create temporary application for scoped deployment
640
- */
641
- private async createTemporaryApplication(baseName: string): Promise<any> {
642
- const applicationData = {
643
- name: `Temp App for ${baseName}`,
644
- scope: `x_temp_${Date.now()}`,
645
- version: '1.0.0',
646
- short_description: `Temporary application for ${baseName}`,
647
- description: `Temporary application for scoped deployment of ${baseName}`,
648
- vendor: 'System',
649
- vendor_prefix: 'x',
650
- active: true
651
- };
652
-
653
- const result = await this.client.createApplication(applicationData);
654
- if (!result.success) {
655
- throw new Error(`Failed to create temporary application: ${result.error}`);
656
- }
657
-
658
- return result.data;
659
- }
660
-
661
- /**
662
- * Get system class name for artifact type
663
- */
664
- private getSystemClassName(artifactType: string): string {
665
- const classMap: Record<string, string> = {
666
- 'flow': 'sys_hub_flow',
667
- 'widget': 'sp_widget',
668
- 'script_include': 'sys_script_include',
669
- 'business_rule': 'sys_script',
670
- 'table': 'sys_db_object'
671
- };
672
-
673
- return classMap[artifactType] || 'sys_metadata';
674
- }
675
-
676
- /**
677
- * Get table name for artifact type
678
- */
679
- private getTableName(artifactType: string): string {
680
- const tableMap: Record<string, string> = {
681
- 'flow': 'sys_hub_flow',
682
- 'widget': 'sp_widget',
683
- 'script_include': 'sys_script_include',
684
- 'business_rule': 'sys_script',
685
- 'table': 'sys_db_object'
686
- };
687
-
688
- return tableMap[artifactType] || 'sys_metadata';
689
- }
690
-
691
- /**
692
- * Get migration strategy for existing scoped artifacts
693
- */
694
- async getMigrationStrategy(existingArtifacts: any[]): Promise<any> {
695
- this.logger.info('Generating migration strategy', { count: existingArtifacts.length });
696
-
697
- const migrationPlan = {
698
- totalArtifacts: existingArtifacts.length,
699
- globalCandidates: [],
700
- keepScoped: [],
701
- requiresReview: [],
702
- estimatedTime: 0,
703
- risks: [],
704
- recommendations: []
705
- };
706
-
707
- for (const artifact of existingArtifacts) {
708
- const _analysis = await this.analyzeScopeRequirements(artifact.type, artifact);
709
-
710
- if (_analysis.type === ScopeType.GLOBAL) {
711
- migrationPlan.globalCandidates.push({
712
- ...artifact,
713
- migrationComplexity: 'low',
714
- dependencies: await this.analyzeDependencies(artifact.type, artifact)
715
- });
716
- } else {
717
- migrationPlan.keepScoped.push(artifact);
718
- }
719
- }
720
-
721
- // Calculate migration complexity and time
722
- migrationPlan.estimatedTime = migrationPlan.globalCandidates.length * 5; // 5 minutes per artifact
723
-
724
- if (migrationPlan.globalCandidates.length > 10) {
725
- migrationPlan.risks.push('Large number of artifacts to migrate - consider phased approach');
726
- }
727
-
728
- migrationPlan.recommendations.push(
729
- 'Test migration in development environment first',
730
- 'Backup existing artifacts before migration',
731
- 'Monitor for breaking changes after migration'
732
- );
733
-
734
- return migrationPlan;
735
- }
736
- }