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,1421 +0,0 @@
1
- /**
2
- * 📚 Self-Documenting System for Autonomous Documentation
3
- *
4
- * Revolutionary AI-powered documentation system that automatically generates,
5
- * maintains, and updates comprehensive documentation from code, flows, and
6
- * system behavior without any manual intervention.
7
- */
8
-
9
- import { Logger } from '../utils/logger.js';
10
- import { ServiceNowClient } from '../utils/servicenow-client.js';
11
- import { MemorySystem } from '../memory/memory-system.js';
12
- // Flow generator and documentation dependencies removed in v1.4.0
13
- // import { XMLFlowDefinition } from '../utils/xml-first-flow-generator.js';
14
- // import { marked } from 'marked';
15
- // import * as mermaid from 'mermaid';
16
-
17
- export interface DocumentationProfile {
18
- id: string;
19
- systemName: string;
20
- version: string;
21
- generatedAt: string;
22
- lastUpdated: string;
23
- sections: DocumentationSection[];
24
- diagrams: SystemDiagram[];
25
- apiDocumentation: APIDocumentation[];
26
- changeLog: ChangeLogEntry[];
27
- metadata: DocumentationMetadata;
28
- analytics: DocumentationAnalytics;
29
- }
30
-
31
- export interface DocumentationSection {
32
- id: string;
33
- title: string;
34
- type: 'overview' | 'architecture' | 'flow' | 'api' | 'configuration' | 'troubleshooting' | 'performance';
35
- content: string;
36
- subsections: DocumentationSection[];
37
- codeExamples: CodeExample[];
38
- references: Reference[];
39
- autogenerated: boolean;
40
- lastModified: string;
41
- confidence: number; // AI confidence in accuracy
42
- }
43
-
44
- export interface SystemDiagram {
45
- id: string;
46
- name: string;
47
- type: 'architecture' | 'flow' | 'sequence' | 'component' | 'deployment' | 'erd';
48
- format: 'mermaid' | 'plantuml' | 'svg' | 'png';
49
- content: string;
50
- description: string;
51
- components: DiagramComponent[];
52
- relationships: DiagramRelationship[];
53
- generated: string;
54
- }
55
-
56
- export interface DiagramComponent {
57
- id: string;
58
- name: string;
59
- type: string;
60
- properties: Record<string, any>;
61
- position?: { x: number; y: number };
62
- }
63
-
64
- export interface DiagramRelationship {
65
- from: string;
66
- to: string;
67
- type: 'uses' | 'extends' | 'implements' | 'depends' | 'communicates';
68
- label?: string;
69
- properties?: Record<string, any>;
70
- }
71
-
72
- export interface APIDocumentation {
73
- endpoint: string;
74
- method: string;
75
- description: string;
76
- parameters: APIParameter[];
77
- requestBody?: APIRequestBody;
78
- responses: APIResponse[];
79
- examples: APIExample[];
80
- authentication: string;
81
- rateLimit?: string;
82
- deprecated?: boolean;
83
- }
84
-
85
- export interface APIParameter {
86
- name: string;
87
- type: string;
88
- required: boolean;
89
- description: string;
90
- defaultValue?: any;
91
- constraints?: string[];
92
- }
93
-
94
- export interface APIRequestBody {
95
- contentType: string;
96
- schema: any;
97
- examples: Record<string, any>;
98
- }
99
-
100
- export interface APIResponse {
101
- statusCode: number;
102
- description: string;
103
- contentType: string;
104
- schema: any;
105
- examples: Record<string, any>;
106
- }
107
-
108
- export interface APIExample {
109
- title: string;
110
- description: string;
111
- request: {
112
- method: string;
113
- url: string;
114
- headers?: Record<string, string>;
115
- body?: any;
116
- };
117
- response: {
118
- status: number;
119
- headers?: Record<string, string>;
120
- body: any;
121
- };
122
- }
123
-
124
- export interface CodeExample {
125
- id: string;
126
- title: string;
127
- language: string;
128
- code: string;
129
- description: string;
130
- runnable: boolean;
131
- output?: string;
132
- dependencies?: string[];
133
- }
134
-
135
- export interface Reference {
136
- type: 'internal' | 'external' | 'api' | 'documentation';
137
- title: string;
138
- url: string;
139
- description?: string;
140
- }
141
-
142
- export interface ChangeLogEntry {
143
- version: string;
144
- date: string;
145
- type: 'major' | 'minor' | 'patch' | 'hotfix';
146
- changes: Change[];
147
- breakingChanges: string[];
148
- contributors: string[];
149
- migrationGuide?: string;
150
- }
151
-
152
- export interface Change {
153
- type: 'feature' | 'fix' | 'enhancement' | 'deprecation' | 'removal';
154
- component: string;
155
- description: string;
156
- issueId?: string;
157
- impact: 'low' | 'medium' | 'high';
158
- }
159
-
160
- export interface DocumentationMetadata {
161
- format: 'markdown' | 'html' | 'pdf' | 'docx';
162
- language: string;
163
- audience: 'developer' | 'administrator' | 'end-user' | 'architect';
164
- complexity: 'beginner' | 'intermediate' | 'advanced' | 'expert';
165
- searchable: boolean;
166
- indexed: boolean;
167
- tags: string[];
168
- }
169
-
170
- export interface DocumentationAnalytics {
171
- completeness: number; // 0-100%
172
- accuracy: number; // 0-100%
173
- coverage: {
174
- code: number;
175
- flows: number;
176
- apis: number;
177
- configurations: number;
178
- };
179
- outdatedSections: string[];
180
- missingDocumentation: string[];
181
- qualityScore: number; // 0-100
182
- readabilityScore: number; // 0-100
183
- lastAnalyzed: string;
184
- }
185
-
186
- export interface DocumentationRequest {
187
- scope: 'full' | 'partial' | 'incremental';
188
- components?: string[];
189
- format?: 'markdown' | 'html' | 'pdf';
190
- includePrivate?: boolean;
191
- includeDiagrams?: boolean;
192
- includeExamples?: boolean;
193
- language?: string;
194
- }
195
-
196
- export interface DocumentationResult {
197
- success: boolean;
198
- profile: DocumentationProfile;
199
- outputPath?: string;
200
- warnings: string[];
201
- suggestions: string[];
202
- generationTime: number;
203
- }
204
-
205
- export class SelfDocumentingSystem {
206
- private logger: Logger;
207
- private client: ServiceNowClient;
208
- private memory: MemorySystem;
209
- private documentationProfiles: Map<string, DocumentationProfile> = new Map();
210
- private templateEngine: Map<string, string> = new Map();
211
- private diagramGenerator: any; // Mermaid/PlantUML generator
212
-
213
- constructor(client: ServiceNowClient, memory: MemorySystem) {
214
- this.logger = new Logger('SelfDocumentingSystem');
215
- this.client = client;
216
- this.memory = memory;
217
-
218
- this.initializeTemplates();
219
- this.initializeDiagramGenerator();
220
- }
221
-
222
- /**
223
- * Generate comprehensive documentation automatically
224
- */
225
- async generateDocumentation(request: DocumentationRequest = { scope: 'full' }): Promise<DocumentationResult> {
226
- this.logger.info('📚 Generating autonomous documentation', request);
227
-
228
- const startTime = Date.now();
229
- const profileId = `doc_${Date.now()}_${Math.random().toString(36).substr(2, 8)}`;
230
-
231
- try {
232
- // Analyze system components
233
- const systemAnalysis = await this.analyzeSystem(request);
234
-
235
- // Generate documentation sections
236
- const sections = await this.generateDocumentationSections(systemAnalysis, request);
237
-
238
- // Generate diagrams
239
- const diagrams = await this.generateSystemDiagrams(systemAnalysis);
240
-
241
- // Generate API documentation
242
- const apiDocs = await this.generateAPIDocumentation(systemAnalysis);
243
-
244
- // Generate change log
245
- const changeLog = await this.generateChangeLog();
246
-
247
- // Analyze documentation quality
248
- const analytics = await this.analyzeDocumentationQuality(sections, diagrams, apiDocs);
249
-
250
- const profile: DocumentationProfile = {
251
- id: profileId,
252
- systemName: 'ServiceNow Multi-Agent System',
253
- version: await this.getSystemVersion(),
254
- generatedAt: new Date().toISOString(),
255
- lastUpdated: new Date().toISOString(),
256
- sections,
257
- diagrams,
258
- apiDocumentation: apiDocs,
259
- changeLog,
260
- metadata: {
261
- format: request.format || 'markdown',
262
- language: request.language || 'en',
263
- audience: 'developer',
264
- complexity: 'advanced',
265
- searchable: true,
266
- indexed: true,
267
- tags: this.extractTags(sections)
268
- },
269
- analytics
270
- };
271
-
272
- // Store documentation profile
273
- this.documentationProfiles.set(profileId, profile);
274
- await this.memory.store(`documentation_${profileId}`, profile, 2592000000); // 30 days
275
-
276
- // Generate output files
277
- const outputPath = await this.generateOutputFiles(profile, request);
278
-
279
- const generationTime = Date.now() - startTime;
280
-
281
- this.logger.info('✅ Documentation generated successfully', {
282
- profileId,
283
- sections: sections.length,
284
- diagrams: diagrams.length,
285
- apis: apiDocs.length,
286
- generationTime,
287
- qualityScore: analytics.qualityScore
288
- });
289
-
290
- return {
291
- success: true,
292
- profile,
293
- outputPath,
294
- warnings: analytics.outdatedSections,
295
- suggestions: this.generateImprovementSuggestions(analytics),
296
- generationTime
297
- };
298
-
299
- } catch (error) {
300
- this.logger.error('❌ Documentation generation failed', error);
301
- throw error;
302
- }
303
- }
304
-
305
- /**
306
- * Continuously monitor and update documentation
307
- */
308
- async startContinuousDocumentation(options: {
309
- interval?: number; // milliseconds
310
- scope?: string[];
311
- autoCommit?: boolean;
312
- } = {}): Promise<void> {
313
- this.logger.info('🔄 Starting continuous documentation', options);
314
-
315
- const interval = options.interval || 3600000; // Default: 1 hour
316
-
317
- setInterval(async () => {
318
- try {
319
- // Check for changes
320
- const changes = await this.detectSystemChanges();
321
-
322
- if (changes.length > 0) {
323
- this.logger.info(`📝 Detected ${changes.length} changes, updating documentation`);
324
-
325
- // Generate incremental documentation
326
- const result = await this.generateDocumentation({
327
- scope: 'incremental',
328
- components: changes
329
- });
330
-
331
- if (options.autoCommit && result.success) {
332
- await this.commitDocumentation(result.profile);
333
- }
334
- }
335
- } catch (error) {
336
- this.logger.error('Error in continuous documentation', error);
337
- }
338
- }, interval);
339
- }
340
-
341
- /**
342
- * Get documentation profiles with filtering
343
- */
344
- getDocumentationProfiles(filter?: {
345
- systemName?: string;
346
- minQualityScore?: number;
347
- dateRange?: { from: string; to: string };
348
- }): DocumentationProfile[] {
349
- let profiles = Array.from(this.documentationProfiles.values());
350
-
351
- if (filter) {
352
- if (filter.systemName) {
353
- profiles = profiles.filter(p =>
354
- p.systemName.toLowerCase().includes(filter.systemName!.toLowerCase())
355
- );
356
- }
357
- if (filter.minQualityScore) {
358
- profiles = profiles.filter(p => p.analytics.qualityScore >= filter.minQualityScore!);
359
- }
360
- if (filter.dateRange) {
361
- const fromDate = new Date(filter.dateRange.from);
362
- const toDate = new Date(filter.dateRange.to);
363
- profiles = profiles.filter(p => {
364
- const profileDate = new Date(p.generatedAt);
365
- return profileDate >= fromDate && profileDate <= toDate;
366
- });
367
- }
368
- }
369
-
370
- return profiles.sort((a, b) =>
371
- new Date(b.generatedAt).getTime() - new Date(a.generatedAt).getTime()
372
- );
373
- }
374
-
375
- /**
376
- * Generate intelligent documentation suggestions
377
- */
378
- async suggestDocumentationImprovements(profileId: string): Promise<{
379
- suggestions: DocumentationSuggestion[];
380
- priority: 'low' | 'medium' | 'high';
381
- estimatedTime: number;
382
- }> {
383
- const profile = this.documentationProfiles.get(profileId);
384
- if (!profile) {
385
- throw new Error(`Documentation profile not found: ${profileId}`);
386
- }
387
-
388
- const suggestions: DocumentationSuggestion[] = [];
389
-
390
- // Analyze missing documentation
391
- if (profile.analytics.missingDocumentation.length > 0) {
392
- suggestions.push({
393
- type: 'missing',
394
- title: 'Add Missing Documentation',
395
- description: `${profile.analytics.missingDocumentation.length} components lack documentation`,
396
- components: profile.analytics.missingDocumentation,
397
- impact: 'high',
398
- effort: 'medium',
399
- automated: true
400
- });
401
- }
402
-
403
- // Check outdated sections
404
- if (profile.analytics.outdatedSections.length > 0) {
405
- suggestions.push({
406
- type: 'outdated',
407
- title: 'Update Outdated Documentation',
408
- description: 'Some documentation sections are outdated',
409
- components: profile.analytics.outdatedSections,
410
- impact: 'medium',
411
- effort: 'low',
412
- automated: true
413
- });
414
- }
415
-
416
- // Readability improvements
417
- if (profile.analytics.readabilityScore < 70) {
418
- suggestions.push({
419
- type: 'readability',
420
- title: 'Improve Documentation Readability',
421
- description: 'Simplify complex sections for better understanding',
422
- components: this.identifyComplexSections(profile),
423
- impact: 'medium',
424
- effort: 'medium',
425
- automated: false
426
- });
427
- }
428
-
429
- // Diagram suggestions
430
- const diagramCoverage = this.calculateDiagramCoverage(profile);
431
- if (diagramCoverage < 60) {
432
- suggestions.push({
433
- type: 'visualization',
434
- title: 'Add Visual Diagrams',
435
- description: 'Add diagrams to improve understanding',
436
- components: this.identifyDiagramOpportunities(profile),
437
- impact: 'high',
438
- effort: 'low',
439
- automated: true
440
- });
441
- }
442
-
443
- // Calculate priority
444
- const priority = suggestions.some(s => s.impact === 'high') ? 'high' :
445
- suggestions.some(s => s.impact === 'medium') ? 'medium' : 'low';
446
-
447
- // Estimate time
448
- const estimatedTime = suggestions.reduce((total, s) => {
449
- const effortTime = { low: 15, medium: 45, high: 120 };
450
- return total + effortTime[s.effort];
451
- }, 0);
452
-
453
- return { suggestions, priority, estimatedTime };
454
- }
455
-
456
- /**
457
- * Private helper methods
458
- */
459
-
460
- private async analyzeSystem(request: DocumentationRequest): Promise<SystemAnalysis> {
461
- this.logger.info('🔍 Analyzing system for documentation');
462
-
463
- const _analysis: SystemAnalysis = {
464
- components: [],
465
- flows: [],
466
- apis: [],
467
- configurations: [],
468
- dependencies: [],
469
- metrics: {
470
- totalComponents: 0,
471
- totalFlows: 0,
472
- totalAPIs: 0,
473
- complexity: 'medium'
474
- }
475
- };
476
-
477
- // Analyze code components
478
- _analysis.components = await this.analyzeCodeComponents();
479
-
480
- // Analyze flows
481
- _analysis.flows = await this.analyzeFlows();
482
-
483
- // Analyze APIs
484
- _analysis.apis = await this.analyzeAPIs();
485
-
486
- // Analyze configurations
487
- _analysis.configurations = await this.analyzeConfigurations();
488
-
489
- // Analyze dependencies
490
- _analysis.dependencies = await this.analyzeDependencies();
491
-
492
- // Calculate metrics
493
- _analysis.metrics = {
494
- totalComponents: _analysis.components.length,
495
- totalFlows: _analysis.flows.length,
496
- totalAPIs: _analysis.apis.length,
497
- complexity: this.calculateSystemComplexity(_analysis)
498
- };
499
-
500
- return _analysis;
501
- }
502
-
503
- private async generateDocumentationSections(
504
- _analysis: SystemAnalysis,
505
- request: DocumentationRequest
506
- ): Promise<DocumentationSection[]> {
507
- const sections: DocumentationSection[] = [];
508
-
509
- // Overview section
510
- sections.push(await this.generateOverviewSection(_analysis));
511
-
512
- // Architecture section
513
- sections.push(await this.generateArchitectureSection(_analysis));
514
-
515
- // Flow documentation
516
- for (const flow of _analysis.flows) {
517
- sections.push(await this.generateFlowDocumentation(flow));
518
- }
519
-
520
- // API documentation section
521
- if (_analysis.apis.length > 0) {
522
- sections.push(await this.generateAPISection(_analysis.apis));
523
- }
524
-
525
- // Configuration guide
526
- sections.push(await this.generateConfigurationGuide(_analysis.configurations));
527
-
528
- // Troubleshooting guide
529
- sections.push(await this.generateTroubleshootingGuide(_analysis));
530
-
531
- // Performance guide
532
- sections.push(await this.generatePerformanceGuide(_analysis));
533
-
534
- return sections;
535
- }
536
-
537
- private async generateSystemDiagrams(_analysis: SystemAnalysis): Promise<SystemDiagram[]> {
538
- const diagrams: SystemDiagram[] = [];
539
-
540
- // Architecture diagram
541
- diagrams.push(await this.generateArchitectureDiagram(_analysis));
542
-
543
- // Component diagram
544
- diagrams.push(await this.generateComponentDiagram(_analysis.components));
545
-
546
- // Flow diagrams
547
- for (const flow of _analysis.flows.slice(0, 5)) { // Top 5 flows
548
- diagrams.push(await this.generateFlowDiagram(flow));
549
- }
550
-
551
- // Sequence diagrams for key processes
552
- diagrams.push(await this.generateSequenceDiagram('Authentication Flow', [
553
- { from: 'User', to: 'OAuth', action: 'Request Token' },
554
- { from: 'OAuth', to: 'ServiceNow', action: 'Validate Credentials' },
555
- { from: 'ServiceNow', to: 'OAuth', action: 'Return Token' },
556
- { from: 'OAuth', to: 'User', action: 'Access Token' }
557
- ]));
558
-
559
- // Deployment diagram
560
- diagrams.push(await this.generateDeploymentDiagram(_analysis));
561
-
562
- return diagrams;
563
- }
564
-
565
- private async generateArchitectureDiagram(_analysis: SystemAnalysis): Promise<SystemDiagram> {
566
- const mermaidContent = `
567
- graph TB
568
- subgraph "Client Layer"
569
- CLI[CLI Interface]
570
- API[API Client]
571
- end
572
-
573
- subgraph "Orchestration Layer"
574
- Queen[Queen Agent]
575
- Orchestrator[Flow Orchestrator]
576
- Memory[Memory System]
577
- end
578
-
579
- subgraph "Service Layer"
580
- Templates[Template System]
581
- Testing[Testing Automation]
582
- Rollback[Rollback System]
583
- Performance[Performance Optimizer]
584
- end
585
-
586
- subgraph "Integration Layer"
587
- SNClient[ServiceNow Client]
588
- OAuth[OAuth Handler]
589
- end
590
-
591
- subgraph "ServiceNow Platform"
592
- SNAPI[ServiceNow API]
593
- FlowEngine[Flow Engine]
594
- Tables[System Tables]
595
- end
596
-
597
- CLI --> Queen
598
- API --> Queen
599
- Queen --> Orchestrator
600
- Queen --> Memory
601
- Orchestrator --> Templates
602
- Orchestrator --> Testing
603
- Orchestrator --> Rollback
604
- Orchestrator --> Performance
605
- Templates --> SNClient
606
- Testing --> SNClient
607
- Rollback --> SNClient
608
- Performance --> SNClient
609
- SNClient --> OAuth
610
- OAuth --> SNAPI
611
- SNAPI --> FlowEngine
612
- SNAPI --> Tables
613
-
614
- style Queen fill:#f9f,stroke:#333,stroke-width:4px
615
- style Memory fill:#bbf,stroke:#333,stroke-width:2px
616
- style SNClient fill:#bfb,stroke:#333,stroke-width:2px
617
- `;
618
-
619
- return {
620
- id: 'architecture_overview',
621
- name: 'System Architecture Overview',
622
- type: 'architecture',
623
- format: 'mermaid',
624
- content: mermaidContent,
625
- description: 'High-level architecture showing all system components and their relationships',
626
- components: this.extractComponentsFromDiagram(mermaidContent),
627
- relationships: this.extractRelationshipsFromDiagram(mermaidContent),
628
- generated: new Date().toISOString()
629
- };
630
- }
631
-
632
- private async generateAPIDocumentation(_analysis: SystemAnalysis): Promise<APIDocumentation[]> {
633
- const apiDocs: APIDocumentation[] = [];
634
-
635
- // Document all MCP tools
636
- const mcpTools = [
637
- {
638
- endpoint: '/tools/snow_create_flow',
639
- method: 'POST',
640
- description: 'Create a new ServiceNow flow using AI-powered generation',
641
- authentication: 'OAuth 2.0'
642
- },
643
- {
644
- endpoint: '/tools/snow_deploy',
645
- method: 'POST',
646
- description: 'Deploy artifacts to ServiceNow with automatic update set management',
647
- authentication: 'OAuth 2.0'
648
- },
649
- {
650
- endpoint: '/tools/snow_analyze_flow_instruction',
651
- method: 'POST',
652
- description: 'Analyze natural language instructions for flow requirements',
653
- authentication: 'OAuth 2.0'
654
- }
655
- ];
656
-
657
- for (const tool of mcpTools) {
658
- apiDocs.push(await this.generateAPIDocForTool(tool));
659
- }
660
-
661
- return apiDocs;
662
- }
663
-
664
- private async generateChangeLog(): Promise<ChangeLogEntry[]> {
665
- // Generate from git history and memory
666
- return [
667
- {
668
- version: '1.3.26',
669
- date: new Date().toISOString(),
670
- type: 'major',
671
- changes: [
672
- {
673
- type: 'feature',
674
- component: 'Flow Template System',
675
- description: 'Added revolutionary template-based flow generation',
676
- impact: 'high'
677
- },
678
- {
679
- type: 'feature',
680
- component: 'Update Orchestration',
681
- description: 'Implemented intelligent flow update orchestration with rollback',
682
- impact: 'high'
683
- },
684
- {
685
- type: 'fix',
686
- component: 'Memory System',
687
- description: 'Fixed agent memory isolation issues',
688
- issueId: 'CRIT-003',
689
- impact: 'high'
690
- }
691
- ],
692
- breakingChanges: [],
693
- contributors: ['AI Assistant', 'Beta Testers'],
694
- migrationGuide: 'No migration required - backward compatible'
695
- }
696
- ];
697
- }
698
-
699
- private async getSystemVersion(): Promise<string> {
700
- // Get current system version from package.json or memory
701
- try {
702
- // Memory system retrieve method not available
703
- const versionInfo = null; // await this.memory.retrieve('system_version');
704
- return versionInfo || '1.3.26';
705
- } catch {
706
- return '1.3.26';
707
- }
708
- }
709
-
710
- private async checkModifiedComponents(lastCheck: number): Promise<string[]> {
711
- // Check for modified components since last check
712
- const modified: string[] = [];
713
-
714
- // In a real implementation, this would check file timestamps
715
- // For now, simulate by checking memory entries
716
- try {
717
- // Memory system list method not available
718
- const allKeys: string[] = []; // await this.memory.list();
719
- for (const key of allKeys) {
720
- // Memory system retrieve method not available
721
- const data = null; // await this.memory.retrieve(key);
722
- if (data && data.lastModified && new Date(data.lastModified).getTime() > lastCheck) {
723
- modified.push(key);
724
- }
725
- }
726
- } catch (error) {
727
- this.logger.warn('Error checking modifications', error);
728
- }
729
-
730
- return modified;
731
- }
732
-
733
- private async analyzeDependenciesForComponent(componentId: string): Promise<string[]> {
734
- // Analyze dependencies for a specific component
735
- const dependencies: Record<string, string[]> = {
736
- 'queen': ['memory', 'templates', 'testing', 'rollback', 'performance'],
737
- 'memory': ['sqlite3', 'logger'],
738
- 'templates': ['memory', 'servicenow-client'],
739
- 'testing': ['memory', 'servicenow-client'],
740
- 'rollback': ['memory', 'servicenow-client'],
741
- 'performance': ['memory', 'servicenow-client']
742
- };
743
-
744
- return dependencies[componentId] || [];
745
- }
746
-
747
- private async analyzeDocumentationQuality(
748
- sections: DocumentationSection[],
749
- diagrams: SystemDiagram[],
750
- apis: APIDocumentation[]
751
- ): Promise<DocumentationAnalytics> {
752
- const totalSections = sections.length;
753
- const totalAPIs = apis.length;
754
-
755
- // Calculate completeness
756
- const expectedSections = 10; // Expected minimum sections
757
- const completeness = Math.min(100, (totalSections / expectedSections) * 100);
758
-
759
- // Calculate coverage
760
- const coverage = {
761
- code: await this.calculateCodeCoverage(),
762
- flows: await this.calculateFlowCoverage(),
763
- apis: totalAPIs > 0 ? 100 : 0,
764
- configurations: await this.calculateConfigCoverage()
765
- };
766
-
767
- // Identify outdated sections
768
- const outdatedSections = await this.findOutdatedSections(sections);
769
-
770
- // Identify missing documentation
771
- const missingDocumentation = await this.findMissingDocumentation();
772
-
773
- // Calculate quality score
774
- const qualityScore = this.calculateQualityScore(sections, diagrams, completeness);
775
-
776
- // Calculate readability
777
- const readabilityScore = await this.calculateReadabilityScore(sections);
778
-
779
- return {
780
- completeness,
781
- accuracy: 95, // High accuracy due to auto-generation
782
- coverage,
783
- outdatedSections,
784
- missingDocumentation,
785
- qualityScore,
786
- readabilityScore,
787
- lastAnalyzed: new Date().toISOString()
788
- };
789
- }
790
-
791
- private async generateOutputFiles(
792
- profile: DocumentationProfile,
793
- request: DocumentationRequest
794
- ): Promise<string> {
795
- const outputDir = './documentation/generated';
796
- const timestamp = new Date().toISOString().replace(/:/g, '-');
797
-
798
- // Generate main documentation file
799
- const mainDoc = await this.renderDocumentation(profile, request.format || 'markdown');
800
-
801
- // Save to file system
802
- const fs = require('fs').promises;
803
- const path = require('path');
804
-
805
- await fs.mkdir(outputDir, { recursive: true });
806
-
807
- const filename = `documentation_${timestamp}.${request.format || 'md'}`;
808
- const filepath = path.join(outputDir, filename);
809
-
810
- await fs.writeFile(filepath, mainDoc);
811
-
812
- // Generate diagram files
813
- for (const diagram of profile.diagrams) {
814
- if (diagram.format === 'mermaid') {
815
- const diagramFile = `${diagram.id}_${timestamp}.svg`;
816
- const diagramPath = path.join(outputDir, 'diagrams', diagramFile);
817
- await fs.mkdir(path.dirname(diagramPath), { recursive: true });
818
- // Convert mermaid to SVG (would use mermaid CLI or API)
819
- await fs.writeFile(diagramPath, diagram.content);
820
- }
821
- }
822
-
823
- this.logger.info(`📁 Documentation saved to: ${filepath}`);
824
-
825
- return filepath;
826
- }
827
-
828
- private async renderDocumentation(
829
- profile: DocumentationProfile,
830
- format: string
831
- ): Promise<string> {
832
- let content = '';
833
-
834
- // Header
835
- content += `# ${profile.systemName} Documentation\n\n`;
836
- content += `**Version**: ${profile.version}\n`;
837
- content += `**Generated**: ${new Date(profile.generatedAt).toLocaleString()}\n`;
838
- content += `**Quality Score**: ${profile.analytics.qualityScore}/100\n\n`;
839
-
840
- // Table of Contents
841
- content += '## Table of Contents\n\n';
842
- profile.sections.forEach((section, index) => {
843
- content += `${index + 1}. [${section.title}](#${section.title.toLowerCase().replace(/\s+/g, '-')})\n`;
844
- });
845
- content += '\n';
846
-
847
- // Sections
848
- for (const section of profile.sections) {
849
- content += await this.renderSection(section, 2);
850
- }
851
-
852
- // API Documentation
853
- if (profile.apiDocumentation.length > 0) {
854
- content += '\n## API Reference\n\n';
855
- for (const api of profile.apiDocumentation) {
856
- content += await this.renderAPIDoc(api);
857
- }
858
- }
859
-
860
- // Change Log
861
- content += '\n## Change Log\n\n';
862
- for (const entry of profile.changeLog) {
863
- content += await this.renderChangeLogEntry(entry);
864
- }
865
-
866
- // Analytics Summary
867
- content += '\n## Documentation Analytics\n\n';
868
- content += `- **Completeness**: ${profile.analytics.completeness}%\n`;
869
- content += `- **Code Coverage**: ${profile.analytics.coverage.code}%\n`;
870
- content += `- **Readability Score**: ${profile.analytics.readabilityScore}/100\n`;
871
-
872
- if (format === 'html') {
873
- // Marked library not available - using simple fallback
874
- return content; // marked(content);
875
- }
876
-
877
- return content;
878
- }
879
-
880
- private async renderSection(section: DocumentationSection, level: number): Promise<string> {
881
- let content = '';
882
- const header = '#'.repeat(level);
883
-
884
- content += `${header} ${section.title}\n\n`;
885
- content += `${section.content}\n\n`;
886
-
887
- // Code examples
888
- if (section.codeExamples.length > 0) {
889
- content += `${header}# Examples\n\n`;
890
- for (const example of section.codeExamples) {
891
- content += `**${example.title}**\n\n`;
892
- content += `\`\`\`${example.language}\n${example.code}\n\`\`\`\n\n`;
893
- if (example.output) {
894
- content += `**Output:**\n\`\`\`\n${example.output}\n\`\`\`\n\n`;
895
- }
896
- }
897
- }
898
-
899
- // Subsections
900
- for (const subsection of section.subsections) {
901
- content += await this.renderSection(subsection, level + 1);
902
- }
903
-
904
- return content;
905
- }
906
-
907
- private async renderAPIDoc(api: APIDocumentation): Promise<string> {
908
- let content = `### ${api.method} ${api.endpoint}\n\n`;
909
- content += `${api.description}\n\n`;
910
-
911
- if (api.authentication) {
912
- content += `**Authentication**: ${api.authentication}\n\n`;
913
- }
914
-
915
- // Parameters
916
- if (api.parameters.length > 0) {
917
- content += '**Parameters:**\n\n';
918
- content += '| Name | Type | Required | Description |\n';
919
- content += '|------|------|----------|-------------|\n';
920
- for (const param of api.parameters) {
921
- content += `| ${param.name} | ${param.type} | ${param.required ? 'Yes' : 'No'} | ${param.description} |\n`;
922
- }
923
- content += '\n';
924
- }
925
-
926
- // Request body
927
- if (api.requestBody) {
928
- content += '**Request Body:**\n\n';
929
- content += `\`\`\`json\n${JSON.stringify(api.requestBody.examples, null, 2)}\n\`\`\`\n\n`;
930
- }
931
-
932
- // Responses
933
- content += '**Responses:**\n\n';
934
- for (const response of api.responses) {
935
- content += `- **${response.statusCode}**: ${response.description}\n`;
936
- }
937
- content += '\n';
938
-
939
- // Examples
940
- if (api.examples.length > 0) {
941
- content += '**Example:**\n\n';
942
- const example = api.examples[0];
943
- content += `\`\`\`bash\ncurl -X ${example.request.method} ${example.request.url} \\\n`;
944
- if (example.request.headers) {
945
- for (const [key, value] of Object.entries(example.request.headers)) {
946
- content += ` -H "${key}: ${value}" \\\n`;
947
- }
948
- }
949
- if (example.request.body) {
950
- content += ` -d '${JSON.stringify(example.request.body)}'\n`;
951
- }
952
- content += `\`\`\`\n\n`;
953
- }
954
-
955
- return content;
956
- }
957
-
958
- private async renderChangeLogEntry(entry: ChangeLogEntry): Promise<string> {
959
- let content = `### Version ${entry.version} (${new Date(entry.date).toLocaleDateString()})\n\n`;
960
-
961
- // Group changes by type
962
- const changesByType = entry.changes.reduce((acc, change) => {
963
- if (!acc[change.type]) acc[change.type] = [];
964
- acc[change.type].push(change);
965
- return acc;
966
- }, {} as Record<string, Change[]>);
967
-
968
- for (const [type, changes] of Object.entries(changesByType)) {
969
- content += `**${type.charAt(0).toUpperCase() + type.slice(1)}s:**\n\n`;
970
- for (const change of changes) {
971
- content += `- **${change.component}**: ${change.description}`;
972
- if (change.issueId) content += ` ([${change.issueId}])`;
973
- content += '\n';
974
- }
975
- content += '\n';
976
- }
977
-
978
- if (entry.breakingChanges.length > 0) {
979
- content += '**Breaking Changes:**\n\n';
980
- for (const breaking of entry.breakingChanges) {
981
- content += `- ${breaking}\n`;
982
- }
983
- content += '\n';
984
- }
985
-
986
- return content;
987
- }
988
-
989
- // Initialize templates and generators
990
- private initializeTemplates(): void {
991
- // Documentation templates
992
- this.templateEngine.set('overview', `
993
- # System Overview
994
-
995
- {{description}}
996
-
997
- ## Key Features
998
- {{features}}
999
-
1000
- ## Architecture
1001
- {{architecture}}
1002
-
1003
- ## Getting Started
1004
- {{gettingStarted}}
1005
- `);
1006
- }
1007
-
1008
- private initializeDiagramGenerator(): void {
1009
- // Initialize mermaid for diagram generation
1010
- if (typeof globalThis !== 'undefined') {
1011
- // mermaid.initialize({ startOnLoad: true });
1012
- }
1013
- }
1014
-
1015
- // Helper methods for analysis
1016
- private async analyzeCodeComponents(): Promise<ComponentAnalysis[]> {
1017
- // Analyze TypeScript files
1018
- return [];
1019
- }
1020
-
1021
- private async analyzeFlows(): Promise<FlowAnalysis[]> {
1022
- // Analyze ServiceNow flows
1023
- return [];
1024
- }
1025
-
1026
- private async analyzeAPIs(): Promise<APIAnalysis[]> {
1027
- // Analyze API endpoints
1028
- return [];
1029
- }
1030
-
1031
- private async analyzeConfigurations(): Promise<ConfigAnalysis[]> {
1032
- // Analyze configuration files
1033
- return [];
1034
- }
1035
-
1036
- private async analyzeDependencies(): Promise<DependencyAnalysis[]> {
1037
- // Analyze package.json and imports
1038
- return [];
1039
- }
1040
-
1041
- private calculateSystemComplexity(_analysis: SystemAnalysis): string {
1042
- const componentCount = _analysis.components.length;
1043
- const flowCount = _analysis.flows.length;
1044
- const apiCount = _analysis.apis.length;
1045
-
1046
- const totalComplexity = componentCount + (flowCount * 2) + (apiCount * 1.5);
1047
-
1048
- if (totalComplexity > 100) return 'high';
1049
- if (totalComplexity > 50) return 'medium';
1050
- return 'low';
1051
- }
1052
-
1053
- private extractTags(sections: DocumentationSection[]): string[] {
1054
- const tags = new Set<string>();
1055
-
1056
- sections.forEach(section => {
1057
- // Extract tags from section titles and content
1058
- const words = section.title.toLowerCase().split(/\s+/);
1059
- words.forEach(word => {
1060
- if (word.length > 3) tags.add(word);
1061
- });
1062
- });
1063
-
1064
- return Array.from(tags);
1065
- }
1066
-
1067
- private generateImprovementSuggestions(analytics: DocumentationAnalytics): string[] {
1068
- const suggestions: string[] = [];
1069
-
1070
- if (analytics.completeness < 80) {
1071
- suggestions.push('Add documentation for missing components');
1072
- }
1073
-
1074
- if (analytics.readabilityScore < 70) {
1075
- suggestions.push('Simplify complex documentation sections');
1076
- }
1077
-
1078
- if (analytics.coverage.code < 60) {
1079
- suggestions.push('Increase code documentation coverage');
1080
- }
1081
-
1082
- return suggestions;
1083
- }
1084
-
1085
- private async detectSystemChanges(): Promise<string[]> {
1086
- // Detect changes in the system
1087
- return [];
1088
- }
1089
-
1090
- private async commitDocumentation(profile: DocumentationProfile): Promise<void> {
1091
- // Commit documentation to version control
1092
- this.logger.info('📝 Committing documentation to version control');
1093
- }
1094
-
1095
- private extractComponentsFromDiagram(content: string): DiagramComponent[] {
1096
- // Extract components from mermaid diagram
1097
- return [];
1098
- }
1099
-
1100
- private extractRelationshipsFromDiagram(content: string): DiagramRelationship[] {
1101
- // Extract relationships from mermaid diagram
1102
- return [];
1103
- }
1104
-
1105
- private identifyComplexSections(profile: DocumentationProfile): string[] {
1106
- // Identify sections with low readability
1107
- return [];
1108
- }
1109
-
1110
- private calculateDiagramCoverage(profile: DocumentationProfile): number {
1111
- // Calculate diagram coverage percentage
1112
- return 75;
1113
- }
1114
-
1115
- private identifyDiagramOpportunities(profile: DocumentationProfile): string[] {
1116
- // Identify where diagrams would help
1117
- return ['Authentication Flow', 'Deployment Process'];
1118
- }
1119
-
1120
- private async generateOverviewSection(_analysis: SystemAnalysis): Promise<DocumentationSection> {
1121
- return {
1122
- id: 'overview',
1123
- title: 'System Overview',
1124
- type: 'overview',
1125
- content: `The ServiceNow Multi-Agent System is an AI-powered orchestration platform that revolutionizes ServiceNow development through intelligent automation, self-documenting capabilities, and autonomous operations.`,
1126
- subsections: [],
1127
- codeExamples: [],
1128
- references: [],
1129
- autogenerated: true,
1130
- lastModified: new Date().toISOString(),
1131
- confidence: 0.95
1132
- };
1133
- }
1134
-
1135
- private async generateArchitectureSection(_analysis: SystemAnalysis): Promise<DocumentationSection> {
1136
- return {
1137
- id: 'architecture',
1138
- title: 'System Architecture',
1139
- type: 'architecture',
1140
- content: 'The system follows a layered architecture with clear separation of concerns...',
1141
- subsections: [],
1142
- codeExamples: [],
1143
- references: [],
1144
- autogenerated: true,
1145
- lastModified: new Date().toISOString(),
1146
- confidence: 0.92
1147
- };
1148
- }
1149
-
1150
- private async generateFlowDocumentation(flow: FlowAnalysis): Promise<DocumentationSection> {
1151
- return {
1152
- id: `flow_${flow.id}`,
1153
- title: `Flow: ${flow.name}`,
1154
- type: 'flow',
1155
- content: flow.description,
1156
- subsections: [],
1157
- codeExamples: [],
1158
- references: [],
1159
- autogenerated: true,
1160
- lastModified: new Date().toISOString(),
1161
- confidence: 0.88
1162
- };
1163
- }
1164
-
1165
- private async generateAPISection(apis: APIAnalysis[]): Promise<DocumentationSection> {
1166
- return {
1167
- id: 'api_reference',
1168
- title: 'API Reference',
1169
- type: 'api',
1170
- content: 'Complete API documentation for all system endpoints',
1171
- subsections: [],
1172
- codeExamples: [],
1173
- references: [],
1174
- autogenerated: true,
1175
- lastModified: new Date().toISOString(),
1176
- confidence: 0.94
1177
- };
1178
- }
1179
-
1180
- private async generateConfigurationGuide(configs: ConfigAnalysis[]): Promise<DocumentationSection> {
1181
- return {
1182
- id: 'configuration',
1183
- title: 'Configuration Guide',
1184
- type: 'configuration',
1185
- content: 'Comprehensive configuration guide for all system components',
1186
- subsections: [],
1187
- codeExamples: [],
1188
- references: [],
1189
- autogenerated: true,
1190
- lastModified: new Date().toISOString(),
1191
- confidence: 0.91
1192
- };
1193
- }
1194
-
1195
- private async generateTroubleshootingGuide(_analysis: SystemAnalysis): Promise<DocumentationSection> {
1196
- return {
1197
- id: 'troubleshooting',
1198
- title: 'Troubleshooting Guide',
1199
- type: 'troubleshooting',
1200
- content: 'Common issues and their solutions',
1201
- subsections: [],
1202
- codeExamples: [],
1203
- references: [],
1204
- autogenerated: true,
1205
- lastModified: new Date().toISOString(),
1206
- confidence: 0.87
1207
- };
1208
- }
1209
-
1210
- private async generatePerformanceGuide(_analysis: SystemAnalysis): Promise<DocumentationSection> {
1211
- return {
1212
- id: 'performance',
1213
- title: 'Performance Optimization Guide',
1214
- type: 'performance',
1215
- content: 'Best practices for optimal system performance',
1216
- subsections: [],
1217
- codeExamples: [],
1218
- references: [],
1219
- autogenerated: true,
1220
- lastModified: new Date().toISOString(),
1221
- confidence: 0.89
1222
- };
1223
- }
1224
-
1225
- private async generateComponentDiagram(components: ComponentAnalysis[]): Promise<SystemDiagram> {
1226
- return {
1227
- id: 'component_diagram',
1228
- name: 'System Components',
1229
- type: 'component',
1230
- format: 'mermaid',
1231
- content: 'graph TB',
1232
- description: 'Component relationships and dependencies',
1233
- components: [],
1234
- relationships: [],
1235
- generated: new Date().toISOString()
1236
- };
1237
- }
1238
-
1239
- private async generateFlowDiagram(flow: FlowAnalysis): Promise<SystemDiagram> {
1240
- return {
1241
- id: `flow_diagram_${flow.id}`,
1242
- name: `Flow: ${flow.name}`,
1243
- type: 'flow',
1244
- format: 'mermaid',
1245
- content: 'graph LR',
1246
- description: flow.description,
1247
- components: [],
1248
- relationships: [],
1249
- generated: new Date().toISOString()
1250
- };
1251
- }
1252
-
1253
- private async generateSequenceDiagram(name: string, interactions: any[]): Promise<SystemDiagram> {
1254
- let content = 'sequenceDiagram\n';
1255
- interactions.forEach(i => {
1256
- content += ` ${i.from}->>+${i.to}: ${i.action}\n`;
1257
- });
1258
-
1259
- return {
1260
- id: 'sequence_' + name.toLowerCase().replace(/\s+/g, '_'),
1261
- name,
1262
- type: 'sequence',
1263
- format: 'mermaid',
1264
- content,
1265
- description: `Sequence diagram for ${name}`,
1266
- components: [],
1267
- relationships: [],
1268
- generated: new Date().toISOString()
1269
- };
1270
- }
1271
-
1272
- private async generateDeploymentDiagram(_analysis: SystemAnalysis): Promise<SystemDiagram> {
1273
- return {
1274
- id: 'deployment_diagram',
1275
- name: 'Deployment Architecture',
1276
- type: 'deployment',
1277
- format: 'mermaid',
1278
- content: 'graph TB',
1279
- description: 'System deployment architecture',
1280
- components: [],
1281
- relationships: [],
1282
- generated: new Date().toISOString()
1283
- };
1284
- }
1285
-
1286
- private async generateAPIDocForTool(tool: any): Promise<APIDocumentation> {
1287
- return {
1288
- endpoint: tool.endpoint,
1289
- method: tool.method,
1290
- description: tool.description,
1291
- parameters: [],
1292
- responses: [
1293
- {
1294
- statusCode: 200,
1295
- description: 'Success',
1296
- contentType: 'application/json',
1297
- schema: {},
1298
- examples: {}
1299
- }
1300
- ],
1301
- examples: [],
1302
- authentication: tool.authentication
1303
- };
1304
- }
1305
-
1306
- private async calculateCodeCoverage(): Promise<number> {
1307
- // Calculate actual code documentation coverage
1308
- return 85;
1309
- }
1310
-
1311
- private async calculateFlowCoverage(): Promise<number> {
1312
- // Calculate flow documentation coverage
1313
- return 90;
1314
- }
1315
-
1316
- private async calculateConfigCoverage(): Promise<number> {
1317
- // Calculate configuration documentation coverage
1318
- return 75;
1319
- }
1320
-
1321
- private async findOutdatedSections(sections: DocumentationSection[]): Promise<string[]> {
1322
- // Find sections that need updating
1323
- return [];
1324
- }
1325
-
1326
- private async findMissingDocumentation(): Promise<string[]> {
1327
- // Find components without documentation
1328
- return [];
1329
- }
1330
-
1331
- private calculateQualityScore(
1332
- sections: DocumentationSection[],
1333
- diagrams: SystemDiagram[],
1334
- completeness: number
1335
- ): number {
1336
- const sectionScore = Math.min(sections.length * 5, 40);
1337
- const diagramScore = Math.min(diagrams.length * 10, 30);
1338
- const completenessScore = completeness * 0.3;
1339
-
1340
- return Math.round(sectionScore + diagramScore + completenessScore);
1341
- }
1342
-
1343
- private async calculateReadabilityScore(sections: DocumentationSection[]): Promise<number> {
1344
- // Simple readability calculation
1345
- let totalScore = 0;
1346
- let count = 0;
1347
-
1348
- for (const section of sections) {
1349
- const avgSentenceLength = section.content.split('.').length > 0 ?
1350
- section.content.split(' ').length / section.content.split('.').length : 20;
1351
-
1352
- // Ideal sentence length is 15-20 words
1353
- const sentenceScore = avgSentenceLength <= 20 ? 100 : 100 - ((avgSentenceLength - 20) * 2);
1354
-
1355
- totalScore += Math.max(0, Math.min(100, sentenceScore));
1356
- count++;
1357
- }
1358
-
1359
- return count > 0 ? Math.round(totalScore / count) : 70;
1360
- }
1361
- }
1362
-
1363
- // Type definitions
1364
- interface SystemAnalysis {
1365
- components: ComponentAnalysis[];
1366
- flows: FlowAnalysis[];
1367
- apis: APIAnalysis[];
1368
- configurations: ConfigAnalysis[];
1369
- dependencies: DependencyAnalysis[];
1370
- metrics: {
1371
- totalComponents: number;
1372
- totalFlows: number;
1373
- totalAPIs: number;
1374
- complexity: string;
1375
- };
1376
- }
1377
-
1378
- interface ComponentAnalysis {
1379
- id: string;
1380
- name: string;
1381
- type: string;
1382
- description: string;
1383
- dependencies: string[];
1384
- }
1385
-
1386
- interface FlowAnalysis {
1387
- id: string;
1388
- name: string;
1389
- description: string;
1390
- activities: any[];
1391
- }
1392
-
1393
- interface APIAnalysis {
1394
- endpoint: string;
1395
- method: string;
1396
- description: string;
1397
- }
1398
-
1399
- interface ConfigAnalysis {
1400
- name: string;
1401
- type: string;
1402
- value: any;
1403
- }
1404
-
1405
- interface DependencyAnalysis {
1406
- name: string;
1407
- version: string;
1408
- type: 'production' | 'development';
1409
- }
1410
-
1411
- interface DocumentationSuggestion {
1412
- type: 'missing' | 'outdated' | 'readability' | 'visualization';
1413
- title: string;
1414
- description: string;
1415
- components: string[];
1416
- impact: 'low' | 'medium' | 'high';
1417
- effort: 'low' | 'medium' | 'high';
1418
- automated: boolean;
1419
- }
1420
-
1421
- export default SelfDocumentingSystem;