@claude-flow/cli 3.0.0-alpha.15 → 3.0.0-alpha.17

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 (65) hide show
  1. package/dist/src/commands/analyze.d.ts +19 -0
  2. package/dist/src/commands/analyze.d.ts.map +1 -0
  3. package/dist/src/commands/analyze.js +1819 -0
  4. package/dist/src/commands/analyze.js.map +1 -0
  5. package/dist/src/commands/hooks.d.ts.map +1 -1
  6. package/dist/src/commands/hooks.js +325 -1
  7. package/dist/src/commands/hooks.js.map +1 -1
  8. package/dist/src/commands/index.d.ts +2 -0
  9. package/dist/src/commands/index.d.ts.map +1 -1
  10. package/dist/src/commands/index.js +12 -0
  11. package/dist/src/commands/index.js.map +1 -1
  12. package/dist/src/commands/mcp.js +3 -3
  13. package/dist/src/commands/mcp.js.map +1 -1
  14. package/dist/src/commands/route.d.ts +16 -0
  15. package/dist/src/commands/route.d.ts.map +1 -0
  16. package/dist/src/commands/route.js +597 -0
  17. package/dist/src/commands/route.js.map +1 -0
  18. package/dist/src/init/claudemd-generator.d.ts.map +1 -1
  19. package/dist/src/init/claudemd-generator.js +218 -362
  20. package/dist/src/init/claudemd-generator.js.map +1 -1
  21. package/dist/src/mcp-client.d.ts.map +1 -1
  22. package/dist/src/mcp-client.js +2 -0
  23. package/dist/src/mcp-client.js.map +1 -1
  24. package/dist/src/mcp-tools/analyze-tools.d.ts +38 -0
  25. package/dist/src/mcp-tools/analyze-tools.d.ts.map +1 -0
  26. package/dist/src/mcp-tools/analyze-tools.js +317 -0
  27. package/dist/src/mcp-tools/analyze-tools.js.map +1 -0
  28. package/dist/src/mcp-tools/index.d.ts +2 -0
  29. package/dist/src/mcp-tools/index.d.ts.map +1 -1
  30. package/dist/src/mcp-tools/index.js +2 -0
  31. package/dist/src/mcp-tools/index.js.map +1 -1
  32. package/dist/src/ruvector/ast-analyzer.d.ts +67 -0
  33. package/dist/src/ruvector/ast-analyzer.d.ts.map +1 -0
  34. package/dist/src/ruvector/ast-analyzer.js +277 -0
  35. package/dist/src/ruvector/ast-analyzer.js.map +1 -0
  36. package/dist/src/ruvector/coverage-router.d.ts +145 -0
  37. package/dist/src/ruvector/coverage-router.d.ts.map +1 -0
  38. package/dist/src/ruvector/coverage-router.js +451 -0
  39. package/dist/src/ruvector/coverage-router.js.map +1 -0
  40. package/dist/src/ruvector/coverage-tools.d.ts +33 -0
  41. package/dist/src/ruvector/coverage-tools.d.ts.map +1 -0
  42. package/dist/src/ruvector/coverage-tools.js +157 -0
  43. package/dist/src/ruvector/coverage-tools.js.map +1 -0
  44. package/dist/src/ruvector/diff-classifier.d.ts +154 -0
  45. package/dist/src/ruvector/diff-classifier.d.ts.map +1 -0
  46. package/dist/src/ruvector/diff-classifier.js +508 -0
  47. package/dist/src/ruvector/diff-classifier.js.map +1 -0
  48. package/dist/src/ruvector/graph-analyzer.d.ts +174 -0
  49. package/dist/src/ruvector/graph-analyzer.d.ts.map +1 -0
  50. package/dist/src/ruvector/graph-analyzer.js +878 -0
  51. package/dist/src/ruvector/graph-analyzer.js.map +1 -0
  52. package/dist/src/ruvector/index.d.ts +27 -0
  53. package/dist/src/ruvector/index.d.ts.map +1 -0
  54. package/dist/src/ruvector/index.js +47 -0
  55. package/dist/src/ruvector/index.js.map +1 -0
  56. package/dist/src/ruvector/q-learning-router.d.ts +211 -0
  57. package/dist/src/ruvector/q-learning-router.d.ts.map +1 -0
  58. package/dist/src/ruvector/q-learning-router.js +681 -0
  59. package/dist/src/ruvector/q-learning-router.js.map +1 -0
  60. package/dist/src/ruvector/vector-db.d.ts +69 -0
  61. package/dist/src/ruvector/vector-db.d.ts.map +1 -0
  62. package/dist/src/ruvector/vector-db.js +243 -0
  63. package/dist/src/ruvector/vector-db.js.map +1 -0
  64. package/dist/tsconfig.tsbuildinfo +1 -1
  65. package/package.json +13 -1
@@ -0,0 +1,1819 @@
1
+ /**
2
+ * V3 CLI Analyze Command
3
+ * Code analysis, diff classification, AST analysis, and change risk assessment
4
+ *
5
+ * Features:
6
+ * - AST analysis using ruvector (tree-sitter) with graceful fallback
7
+ * - Symbol extraction (functions, classes, variables, types)
8
+ * - Cyclomatic complexity scoring
9
+ * - Diff classification and risk assessment
10
+ * - Graph boundaries using MinCut algorithm
11
+ * - Module communities using Louvain algorithm
12
+ * - Circular dependency detection
13
+ *
14
+ * Created with ruv.io
15
+ */
16
+ import { output } from '../output.js';
17
+ import { callMCPTool, MCPClientError } from '../mcp-client.js';
18
+ import * as path from 'path';
19
+ import * as fs from 'fs/promises';
20
+ import { writeFile } from 'fs/promises';
21
+ import { resolve } from 'path';
22
+ // Dynamic import for AST analyzer
23
+ async function getASTAnalyzer() {
24
+ try {
25
+ return await import('../ruvector/ast-analyzer.js');
26
+ }
27
+ catch {
28
+ return null;
29
+ }
30
+ }
31
+ // Dynamic import for graph analyzer
32
+ async function getGraphAnalyzer() {
33
+ try {
34
+ return await import('../ruvector/graph-analyzer.js');
35
+ }
36
+ catch {
37
+ return null;
38
+ }
39
+ }
40
+ // Diff subcommand
41
+ const diffCommand = {
42
+ name: 'diff',
43
+ description: 'Analyze git diff for change risk assessment and classification',
44
+ options: [
45
+ {
46
+ name: 'risk',
47
+ short: 'r',
48
+ description: 'Show risk assessment',
49
+ type: 'boolean',
50
+ default: false,
51
+ },
52
+ {
53
+ name: 'classify',
54
+ short: 'c',
55
+ description: 'Classify change type',
56
+ type: 'boolean',
57
+ default: false,
58
+ },
59
+ {
60
+ name: 'reviewers',
61
+ description: 'Show recommended reviewers',
62
+ type: 'boolean',
63
+ default: false,
64
+ },
65
+ {
66
+ name: 'format',
67
+ short: 'f',
68
+ description: 'Output format: text, json, table',
69
+ type: 'string',
70
+ default: 'text',
71
+ choices: ['text', 'json', 'table'],
72
+ },
73
+ {
74
+ name: 'verbose',
75
+ short: 'v',
76
+ description: 'Show detailed file-level analysis',
77
+ type: 'boolean',
78
+ default: false,
79
+ },
80
+ ],
81
+ examples: [
82
+ { command: 'claude-flow analyze diff --risk', description: 'Analyze current diff with risk assessment' },
83
+ { command: 'claude-flow analyze diff HEAD~1 --classify', description: 'Classify changes from last commit' },
84
+ { command: 'claude-flow analyze diff main..feature --format json', description: 'Compare branches with JSON output' },
85
+ { command: 'claude-flow analyze diff --reviewers', description: 'Get recommended reviewers for changes' },
86
+ ],
87
+ action: async (ctx) => {
88
+ const ref = ctx.args[0] || 'HEAD';
89
+ const showRisk = ctx.flags.risk;
90
+ const showClassify = ctx.flags.classify;
91
+ const showReviewers = ctx.flags.reviewers;
92
+ const formatType = ctx.flags.format || 'text';
93
+ const verbose = ctx.flags.verbose;
94
+ // If no specific flag, show all
95
+ const showAll = !showRisk && !showClassify && !showReviewers;
96
+ output.printInfo(`Analyzing diff: ${output.highlight(ref)}`);
97
+ try {
98
+ // Call MCP tool for diff analysis
99
+ const result = await callMCPTool('analyze/diff', {
100
+ ref,
101
+ includeFileRisks: verbose,
102
+ includeReviewers: showReviewers || showAll,
103
+ });
104
+ // JSON output
105
+ if (formatType === 'json') {
106
+ output.printJson(result);
107
+ return { success: true, data: result };
108
+ }
109
+ output.writeln();
110
+ // Summary box
111
+ output.printBox([
112
+ `Ref: ${result.ref}`,
113
+ `Files: ${result.files.length}`,
114
+ `Risk: ${getRiskDisplay(result.risk.overall)} (${result.risk.score}/100)`,
115
+ `Type: ${result.classification.category}${result.classification.subcategory ? ` (${result.classification.subcategory})` : ''}`,
116
+ ``,
117
+ result.summary,
118
+ ].join('\n'), 'Diff Analysis');
119
+ // Risk assessment
120
+ if (showRisk || showAll) {
121
+ output.writeln();
122
+ output.writeln(output.bold('Risk Assessment'));
123
+ output.writeln(output.dim('-'.repeat(50)));
124
+ output.printTable({
125
+ columns: [
126
+ { key: 'metric', header: 'Metric', width: 25 },
127
+ { key: 'value', header: 'Value', width: 30 },
128
+ ],
129
+ data: [
130
+ { metric: 'Overall Risk', value: getRiskDisplay(result.risk.overall) },
131
+ { metric: 'Risk Score', value: `${result.risk.score}/100` },
132
+ { metric: 'Files Changed', value: result.risk.breakdown.fileCount },
133
+ { metric: 'Total Lines Changed', value: result.risk.breakdown.totalChanges },
134
+ { metric: 'Test Coverage', value: result.risk.breakdown.testCoverage },
135
+ ],
136
+ });
137
+ // Security concerns
138
+ if (result.risk.breakdown.securityConcerns.length > 0) {
139
+ output.writeln();
140
+ output.writeln(output.bold(output.warning('Security Concerns')));
141
+ output.printList(result.risk.breakdown.securityConcerns.map(c => output.warning(c)));
142
+ }
143
+ // Breaking changes
144
+ if (result.risk.breakdown.breakingChanges.length > 0) {
145
+ output.writeln();
146
+ output.writeln(output.bold(output.error('Potential Breaking Changes')));
147
+ output.printList(result.risk.breakdown.breakingChanges.map(c => output.error(c)));
148
+ }
149
+ // High risk files
150
+ if (result.risk.breakdown.highRiskFiles.length > 0) {
151
+ output.writeln();
152
+ output.writeln(output.bold('High Risk Files'));
153
+ output.printList(result.risk.breakdown.highRiskFiles.map(f => output.warning(f)));
154
+ }
155
+ }
156
+ // Classification
157
+ if (showClassify || showAll) {
158
+ output.writeln();
159
+ output.writeln(output.bold('Classification'));
160
+ output.writeln(output.dim('-'.repeat(50)));
161
+ output.printTable({
162
+ columns: [
163
+ { key: 'field', header: 'Field', width: 15 },
164
+ { key: 'value', header: 'Value', width: 40 },
165
+ ],
166
+ data: [
167
+ { field: 'Category', value: result.classification.category },
168
+ { field: 'Subcategory', value: result.classification.subcategory || '-' },
169
+ { field: 'Confidence', value: `${(result.classification.confidence * 100).toFixed(0)}%` },
170
+ ],
171
+ });
172
+ output.writeln();
173
+ output.writeln(output.dim(`Reasoning: ${result.classification.reasoning}`));
174
+ }
175
+ // Reviewers
176
+ if (showReviewers || showAll) {
177
+ output.writeln();
178
+ output.writeln(output.bold('Recommended Reviewers'));
179
+ output.writeln(output.dim('-'.repeat(50)));
180
+ if (result.recommendedReviewers.length > 0) {
181
+ output.printNumberedList(result.recommendedReviewers.map(r => output.highlight(r)));
182
+ }
183
+ else {
184
+ output.writeln(output.dim('No specific reviewers recommended'));
185
+ }
186
+ }
187
+ // Verbose file-level details
188
+ if (verbose && result.fileRisks) {
189
+ output.writeln();
190
+ output.writeln(output.bold('File-Level Analysis'));
191
+ output.writeln(output.dim('-'.repeat(50)));
192
+ output.printTable({
193
+ columns: [
194
+ { key: 'path', header: 'File', width: 40 },
195
+ { key: 'risk', header: 'Risk', width: 12, format: (v) => getRiskDisplay(String(v)) },
196
+ { key: 'score', header: 'Score', width: 8, align: 'right' },
197
+ { key: 'reasons', header: 'Reasons', width: 30, format: (v) => {
198
+ const reasons = v;
199
+ return reasons.slice(0, 2).join('; ');
200
+ } },
201
+ ],
202
+ data: result.fileRisks,
203
+ });
204
+ }
205
+ // Files changed table
206
+ if (formatType === 'table' || showAll) {
207
+ output.writeln();
208
+ output.writeln(output.bold('Files Changed'));
209
+ output.writeln(output.dim('-'.repeat(50)));
210
+ output.printTable({
211
+ columns: [
212
+ { key: 'status', header: 'Status', width: 10, format: (v) => getStatusDisplay(String(v)) },
213
+ { key: 'path', header: 'File', width: 45 },
214
+ { key: 'additions', header: '+', width: 8, align: 'right', format: (v) => output.success(`+${v}`) },
215
+ { key: 'deletions', header: '-', width: 8, align: 'right', format: (v) => output.error(`-${v}`) },
216
+ ],
217
+ data: result.files.slice(0, 20),
218
+ });
219
+ if (result.files.length > 20) {
220
+ output.writeln(output.dim(` ... and ${result.files.length - 20} more files`));
221
+ }
222
+ }
223
+ return { success: true, data: result };
224
+ }
225
+ catch (error) {
226
+ if (error instanceof MCPClientError) {
227
+ output.printError(`Diff analysis failed: ${error.message}`);
228
+ }
229
+ else {
230
+ output.printError(`Unexpected error: ${String(error)}`);
231
+ }
232
+ return { success: false, exitCode: 1 };
233
+ }
234
+ },
235
+ };
236
+ // Code subcommand (placeholder for future code analysis)
237
+ const codeCommand = {
238
+ name: 'code',
239
+ description: 'Static code analysis and quality assessment',
240
+ options: [
241
+ { name: 'path', short: 'p', type: 'string', description: 'Path to analyze', default: '.' },
242
+ { name: 'type', short: 't', type: 'string', description: 'Analysis type: quality, complexity, security', default: 'quality' },
243
+ { name: 'format', short: 'f', type: 'string', description: 'Output format: text, json', default: 'text' },
244
+ ],
245
+ examples: [
246
+ { command: 'claude-flow analyze code -p ./src', description: 'Analyze source directory' },
247
+ { command: 'claude-flow analyze code --type complexity', description: 'Run complexity analysis' },
248
+ ],
249
+ action: async (ctx) => {
250
+ const path = ctx.flags.path || '.';
251
+ const analysisType = ctx.flags.type || 'quality';
252
+ output.writeln();
253
+ output.writeln(output.bold('Code Analysis'));
254
+ output.writeln(output.dim('-'.repeat(50)));
255
+ output.printInfo(`Analyzing ${path} for ${analysisType}...`);
256
+ output.writeln();
257
+ // Placeholder - would integrate with actual code analysis tools
258
+ output.printBox([
259
+ `Path: ${path}`,
260
+ `Type: ${analysisType}`,
261
+ `Status: Feature in development`,
262
+ ``,
263
+ `Code analysis capabilities coming soon.`,
264
+ `Use 'analyze diff' for change analysis.`,
265
+ ].join('\n'), 'Code Analysis');
266
+ return { success: true };
267
+ },
268
+ };
269
+ // ============================================================================
270
+ // AST Analysis Subcommands (using ruvector tree-sitter with fallback)
271
+ // ============================================================================
272
+ /**
273
+ * Helper: Truncate file path for display
274
+ */
275
+ function truncatePathAst(filePath, maxLen = 45) {
276
+ if (filePath.length <= maxLen)
277
+ return filePath;
278
+ return '...' + filePath.slice(-(maxLen - 3));
279
+ }
280
+ /**
281
+ * Helper: Format complexity value with color coding
282
+ */
283
+ function formatComplexityValueAst(value) {
284
+ if (value <= 5)
285
+ return output.success(String(value));
286
+ if (value <= 10)
287
+ return output.warning(String(value));
288
+ return output.error(String(value));
289
+ }
290
+ /**
291
+ * Helper: Get type marker for symbols
292
+ */
293
+ function getTypeMarkerAst(type) {
294
+ switch (type) {
295
+ case 'function': return output.success('fn');
296
+ case 'class': return output.info('class');
297
+ case 'variable': return output.dim('var');
298
+ case 'type': return output.highlight('type');
299
+ case 'interface': return output.highlight('iface');
300
+ default: return output.dim(type.slice(0, 5));
301
+ }
302
+ }
303
+ /**
304
+ * Helper: Get complexity rating text
305
+ */
306
+ function getComplexityRatingAst(value) {
307
+ if (value <= 5)
308
+ return output.success('Simple');
309
+ if (value <= 10)
310
+ return output.warning('Moderate');
311
+ if (value <= 20)
312
+ return output.error('Complex');
313
+ return output.error(output.bold('Very Complex'));
314
+ }
315
+ /**
316
+ * AST analysis subcommand
317
+ */
318
+ const astCommand = {
319
+ name: 'ast',
320
+ description: 'Analyze code using AST parsing (tree-sitter via ruvector)',
321
+ options: [
322
+ {
323
+ name: 'complexity',
324
+ short: 'c',
325
+ description: 'Include complexity metrics',
326
+ type: 'boolean',
327
+ default: false,
328
+ },
329
+ {
330
+ name: 'symbols',
331
+ short: 's',
332
+ description: 'Include symbol extraction',
333
+ type: 'boolean',
334
+ default: false,
335
+ },
336
+ {
337
+ name: 'format',
338
+ short: 'f',
339
+ description: 'Output format (text, json, table)',
340
+ type: 'string',
341
+ default: 'text',
342
+ choices: ['text', 'json', 'table'],
343
+ },
344
+ {
345
+ name: 'output',
346
+ short: 'o',
347
+ description: 'Output file path',
348
+ type: 'string',
349
+ },
350
+ {
351
+ name: 'verbose',
352
+ short: 'v',
353
+ description: 'Show detailed analysis',
354
+ type: 'boolean',
355
+ default: false,
356
+ },
357
+ ],
358
+ examples: [
359
+ { command: 'claude-flow analyze ast src/', description: 'Analyze all files in src/' },
360
+ { command: 'claude-flow analyze ast src/index.ts --complexity', description: 'Analyze with complexity' },
361
+ { command: 'claude-flow analyze ast . --format json', description: 'JSON output' },
362
+ { command: 'claude-flow analyze ast src/ --symbols', description: 'Extract symbols' },
363
+ ],
364
+ action: async (ctx) => {
365
+ const targetPath = ctx.args[0] || ctx.cwd;
366
+ const showComplexity = ctx.flags.complexity;
367
+ const showSymbols = ctx.flags.symbols;
368
+ const formatType = ctx.flags.format || 'text';
369
+ const outputFile = ctx.flags.output;
370
+ const verbose = ctx.flags.verbose;
371
+ // If no specific flags, show summary
372
+ const showAll = !showComplexity && !showSymbols;
373
+ output.printInfo(`Analyzing: ${output.highlight(targetPath)}`);
374
+ output.writeln();
375
+ const spinner = output.createSpinner({ text: 'Parsing AST...', spinner: 'dots' });
376
+ spinner.start();
377
+ try {
378
+ const astModule = await getASTAnalyzer();
379
+ if (!astModule) {
380
+ spinner.stop();
381
+ output.printWarning('AST analyzer not available, using regex fallback');
382
+ }
383
+ // Resolve path and check if file or directory
384
+ const resolvedPath = resolve(targetPath);
385
+ const stat = await fs.stat(resolvedPath);
386
+ const isDirectory = stat.isDirectory();
387
+ let results = [];
388
+ if (isDirectory) {
389
+ // Scan directory for source files
390
+ const files = await scanSourceFiles(resolvedPath);
391
+ spinner.stop();
392
+ output.printInfo(`Found ${files.length} source files`);
393
+ spinner.start();
394
+ for (const file of files.slice(0, 100)) {
395
+ try {
396
+ const content = await fs.readFile(file, 'utf-8');
397
+ if (astModule) {
398
+ const analyzer = astModule.createASTAnalyzer();
399
+ const analysis = analyzer.analyze(content, file);
400
+ results.push(analysis);
401
+ }
402
+ else {
403
+ // Fallback analysis
404
+ results.push(fallbackAnalyze(content, file));
405
+ }
406
+ }
407
+ catch {
408
+ // Skip files that can't be analyzed
409
+ }
410
+ }
411
+ }
412
+ else {
413
+ // Single file
414
+ const content = await fs.readFile(resolvedPath, 'utf-8');
415
+ if (astModule) {
416
+ const analyzer = astModule.createASTAnalyzer();
417
+ const analysis = analyzer.analyze(content, resolvedPath);
418
+ results.push(analysis);
419
+ }
420
+ else {
421
+ results.push(fallbackAnalyze(content, resolvedPath));
422
+ }
423
+ }
424
+ spinner.stop();
425
+ if (results.length === 0) {
426
+ output.printWarning('No files analyzed');
427
+ return { success: true };
428
+ }
429
+ // Calculate totals
430
+ const totals = {
431
+ files: results.length,
432
+ functions: results.reduce((sum, r) => sum + r.functions.length, 0),
433
+ classes: results.reduce((sum, r) => sum + r.classes.length, 0),
434
+ imports: results.reduce((sum, r) => sum + r.imports.length, 0),
435
+ avgComplexity: results.reduce((sum, r) => sum + r.complexity.cyclomatic, 0) / results.length,
436
+ totalLoc: results.reduce((sum, r) => sum + r.complexity.loc, 0),
437
+ };
438
+ // JSON output
439
+ if (formatType === 'json') {
440
+ const jsonOutput = { files: results, totals };
441
+ if (outputFile) {
442
+ await writeFile(outputFile, JSON.stringify(jsonOutput, null, 2));
443
+ output.printSuccess(`Results written to ${outputFile}`);
444
+ }
445
+ else {
446
+ output.printJson(jsonOutput);
447
+ }
448
+ return { success: true, data: jsonOutput };
449
+ }
450
+ // Summary box
451
+ output.printBox([
452
+ `Files analyzed: ${totals.files}`,
453
+ `Functions: ${totals.functions}`,
454
+ `Classes: ${totals.classes}`,
455
+ `Total LOC: ${totals.totalLoc}`,
456
+ `Avg Complexity: ${formatComplexityValueAst(Math.round(totals.avgComplexity))}`,
457
+ ].join('\n'), 'AST Analysis Summary');
458
+ // Complexity view
459
+ if (showComplexity || showAll) {
460
+ output.writeln();
461
+ output.writeln(output.bold('Complexity by File'));
462
+ output.writeln(output.dim('-'.repeat(60)));
463
+ const complexityData = results
464
+ .map(r => ({
465
+ file: truncatePathAst(r.filePath),
466
+ cyclomatic: r.complexity.cyclomatic,
467
+ cognitive: r.complexity.cognitive,
468
+ loc: r.complexity.loc,
469
+ rating: getComplexityRatingAst(r.complexity.cyclomatic),
470
+ }))
471
+ .sort((a, b) => b.cyclomatic - a.cyclomatic)
472
+ .slice(0, 15);
473
+ output.printTable({
474
+ columns: [
475
+ { key: 'file', header: 'File', width: 40 },
476
+ { key: 'cyclomatic', header: 'Cyclo', width: 8, align: 'right', format: (v) => formatComplexityValueAst(v) },
477
+ { key: 'cognitive', header: 'Cogni', width: 8, align: 'right' },
478
+ { key: 'loc', header: 'LOC', width: 8, align: 'right' },
479
+ { key: 'rating', header: 'Rating', width: 15 },
480
+ ],
481
+ data: complexityData,
482
+ });
483
+ if (results.length > 15) {
484
+ output.writeln(output.dim(` ... and ${results.length - 15} more files`));
485
+ }
486
+ }
487
+ // Symbols view
488
+ if (showSymbols || showAll) {
489
+ output.writeln();
490
+ output.writeln(output.bold('Extracted Symbols'));
491
+ output.writeln(output.dim('-'.repeat(60)));
492
+ const allSymbols = [];
493
+ for (const r of results) {
494
+ for (const fn of r.functions) {
495
+ allSymbols.push({ name: fn.name, type: 'function', file: truncatePathAst(r.filePath, 30), line: fn.startLine });
496
+ }
497
+ for (const cls of r.classes) {
498
+ allSymbols.push({ name: cls.name, type: 'class', file: truncatePathAst(r.filePath, 30), line: cls.startLine });
499
+ }
500
+ }
501
+ const displaySymbols = allSymbols.slice(0, 20);
502
+ output.printTable({
503
+ columns: [
504
+ { key: 'type', header: 'Type', width: 8, format: (v) => getTypeMarkerAst(v) },
505
+ { key: 'name', header: 'Symbol', width: 30 },
506
+ { key: 'file', header: 'File', width: 35 },
507
+ { key: 'line', header: 'Line', width: 8, align: 'right' },
508
+ ],
509
+ data: displaySymbols,
510
+ });
511
+ if (allSymbols.length > 20) {
512
+ output.writeln(output.dim(` ... and ${allSymbols.length - 20} more symbols`));
513
+ }
514
+ }
515
+ // Verbose output
516
+ if (verbose) {
517
+ output.writeln();
518
+ output.writeln(output.bold('Import Analysis'));
519
+ output.writeln(output.dim('-'.repeat(60)));
520
+ const importCounts = new Map();
521
+ for (const r of results) {
522
+ for (const imp of r.imports) {
523
+ importCounts.set(imp, (importCounts.get(imp) || 0) + 1);
524
+ }
525
+ }
526
+ const topImports = Array.from(importCounts.entries())
527
+ .sort((a, b) => b[1] - a[1])
528
+ .slice(0, 10);
529
+ for (const [imp, count] of topImports) {
530
+ output.writeln(` ${output.highlight(count.toString().padStart(3))} ${imp}`);
531
+ }
532
+ }
533
+ if (outputFile) {
534
+ await writeFile(outputFile, JSON.stringify({ files: results, totals }, null, 2));
535
+ output.printSuccess(`Results written to ${outputFile}`);
536
+ }
537
+ return { success: true, data: { files: results, totals } };
538
+ }
539
+ catch (error) {
540
+ spinner.stop();
541
+ const message = error instanceof Error ? error.message : String(error);
542
+ output.printError(`AST analysis failed: ${message}`);
543
+ return { success: false, exitCode: 1 };
544
+ }
545
+ },
546
+ };
547
+ /**
548
+ * Complexity analysis subcommand
549
+ */
550
+ const complexityAstCommand = {
551
+ name: 'complexity',
552
+ aliases: ['cx'],
553
+ description: 'Analyze code complexity metrics',
554
+ options: [
555
+ {
556
+ name: 'threshold',
557
+ short: 't',
558
+ description: 'Complexity threshold to flag (default: 10)',
559
+ type: 'number',
560
+ default: 10,
561
+ },
562
+ {
563
+ name: 'format',
564
+ short: 'f',
565
+ description: 'Output format (text, json)',
566
+ type: 'string',
567
+ default: 'text',
568
+ choices: ['text', 'json'],
569
+ },
570
+ {
571
+ name: 'output',
572
+ short: 'o',
573
+ description: 'Output file path',
574
+ type: 'string',
575
+ },
576
+ ],
577
+ examples: [
578
+ { command: 'claude-flow analyze complexity src/', description: 'Analyze complexity' },
579
+ { command: 'claude-flow analyze complexity src/ --threshold 15', description: 'Flag high complexity' },
580
+ ],
581
+ action: async (ctx) => {
582
+ const targetPath = ctx.args[0] || ctx.cwd;
583
+ const threshold = ctx.flags.threshold || 10;
584
+ const formatType = ctx.flags.format || 'text';
585
+ const outputFile = ctx.flags.output;
586
+ output.printInfo(`Analyzing complexity: ${output.highlight(targetPath)}`);
587
+ output.writeln();
588
+ const spinner = output.createSpinner({ text: 'Calculating complexity...', spinner: 'dots' });
589
+ spinner.start();
590
+ try {
591
+ const astModule = await getASTAnalyzer();
592
+ const resolvedPath = resolve(targetPath);
593
+ const stat = await fs.stat(resolvedPath);
594
+ const files = stat.isDirectory() ? await scanSourceFiles(resolvedPath) : [resolvedPath];
595
+ const results = [];
596
+ for (const file of files.slice(0, 100)) {
597
+ try {
598
+ const content = await fs.readFile(file, 'utf-8');
599
+ let analysis;
600
+ if (astModule) {
601
+ const analyzer = astModule.createASTAnalyzer();
602
+ analysis = analyzer.analyze(content, file);
603
+ }
604
+ else {
605
+ analysis = fallbackAnalyze(content, file);
606
+ }
607
+ const flagged = analysis.complexity.cyclomatic > threshold;
608
+ const rating = analysis.complexity.cyclomatic <= 5 ? 'Simple' :
609
+ analysis.complexity.cyclomatic <= 10 ? 'Moderate' :
610
+ analysis.complexity.cyclomatic <= 20 ? 'Complex' : 'Very Complex';
611
+ results.push({
612
+ file: file,
613
+ cyclomatic: analysis.complexity.cyclomatic,
614
+ cognitive: analysis.complexity.cognitive,
615
+ loc: analysis.complexity.loc,
616
+ commentDensity: analysis.complexity.commentDensity,
617
+ rating,
618
+ flagged,
619
+ });
620
+ }
621
+ catch {
622
+ // Skip files that can't be analyzed
623
+ }
624
+ }
625
+ spinner.stop();
626
+ // Sort by complexity descending
627
+ results.sort((a, b) => b.cyclomatic - a.cyclomatic);
628
+ const flaggedCount = results.filter(r => r.flagged).length;
629
+ const avgComplexity = results.length > 0
630
+ ? results.reduce((sum, r) => sum + r.cyclomatic, 0) / results.length
631
+ : 0;
632
+ if (formatType === 'json') {
633
+ const jsonOutput = { files: results, summary: { total: results.length, flagged: flaggedCount, avgComplexity, threshold } };
634
+ if (outputFile) {
635
+ await writeFile(outputFile, JSON.stringify(jsonOutput, null, 2));
636
+ output.printSuccess(`Results written to ${outputFile}`);
637
+ }
638
+ else {
639
+ output.printJson(jsonOutput);
640
+ }
641
+ return { success: true, data: jsonOutput };
642
+ }
643
+ // Summary
644
+ output.printBox([
645
+ `Files analyzed: ${results.length}`,
646
+ `Threshold: ${threshold}`,
647
+ `Flagged files: ${flaggedCount > 0 ? output.error(String(flaggedCount)) : output.success('0')}`,
648
+ `Average complexity: ${formatComplexityValueAst(Math.round(avgComplexity))}`,
649
+ ].join('\n'), 'Complexity Analysis');
650
+ // Show flagged files first
651
+ if (flaggedCount > 0) {
652
+ output.writeln();
653
+ output.writeln(output.bold(output.warning(`High Complexity Files (>${threshold})`)));
654
+ output.writeln(output.dim('-'.repeat(60)));
655
+ const flaggedFiles = results.filter(r => r.flagged).slice(0, 10);
656
+ output.printTable({
657
+ columns: [
658
+ { key: 'file', header: 'File', width: 40, format: (v) => truncatePathAst(v) },
659
+ { key: 'cyclomatic', header: 'Cyclo', width: 8, align: 'right', format: (v) => output.error(String(v)) },
660
+ { key: 'cognitive', header: 'Cogni', width: 8, align: 'right' },
661
+ { key: 'loc', header: 'LOC', width: 8, align: 'right' },
662
+ { key: 'rating', header: 'Rating', width: 15 },
663
+ ],
664
+ data: flaggedFiles,
665
+ });
666
+ }
667
+ // Show all files in table format
668
+ output.writeln();
669
+ output.writeln(output.bold('All Files'));
670
+ output.writeln(output.dim('-'.repeat(60)));
671
+ const displayFiles = results.slice(0, 15);
672
+ output.printTable({
673
+ columns: [
674
+ { key: 'file', header: 'File', width: 40, format: (v) => truncatePathAst(v) },
675
+ { key: 'cyclomatic', header: 'Cyclo', width: 8, align: 'right', format: (v) => formatComplexityValueAst(v) },
676
+ { key: 'cognitive', header: 'Cogni', width: 8, align: 'right' },
677
+ { key: 'loc', header: 'LOC', width: 8, align: 'right' },
678
+ ],
679
+ data: displayFiles,
680
+ });
681
+ if (results.length > 15) {
682
+ output.writeln(output.dim(` ... and ${results.length - 15} more files`));
683
+ }
684
+ if (outputFile) {
685
+ await writeFile(outputFile, JSON.stringify({ files: results, summary: { total: results.length, flagged: flaggedCount, avgComplexity, threshold } }, null, 2));
686
+ output.printSuccess(`Results written to ${outputFile}`);
687
+ }
688
+ return { success: true, data: { files: results, flaggedCount } };
689
+ }
690
+ catch (error) {
691
+ spinner.stop();
692
+ const message = error instanceof Error ? error.message : String(error);
693
+ output.printError(`Complexity analysis failed: ${message}`);
694
+ return { success: false, exitCode: 1 };
695
+ }
696
+ },
697
+ };
698
+ /**
699
+ * Symbol extraction subcommand
700
+ */
701
+ const symbolsCommand = {
702
+ name: 'symbols',
703
+ aliases: ['sym'],
704
+ description: 'Extract and list code symbols (functions, classes, types)',
705
+ options: [
706
+ {
707
+ name: 'type',
708
+ short: 't',
709
+ description: 'Filter by symbol type (function, class, all)',
710
+ type: 'string',
711
+ default: 'all',
712
+ choices: ['function', 'class', 'all'],
713
+ },
714
+ {
715
+ name: 'format',
716
+ short: 'f',
717
+ description: 'Output format (text, json)',
718
+ type: 'string',
719
+ default: 'text',
720
+ choices: ['text', 'json'],
721
+ },
722
+ {
723
+ name: 'output',
724
+ short: 'o',
725
+ description: 'Output file path',
726
+ type: 'string',
727
+ },
728
+ ],
729
+ examples: [
730
+ { command: 'claude-flow analyze symbols src/', description: 'Extract all symbols' },
731
+ { command: 'claude-flow analyze symbols src/ --type function', description: 'Only functions' },
732
+ { command: 'claude-flow analyze symbols src/ --format json', description: 'JSON output' },
733
+ ],
734
+ action: async (ctx) => {
735
+ const targetPath = ctx.args[0] || ctx.cwd;
736
+ const symbolType = ctx.flags.type || 'all';
737
+ const formatType = ctx.flags.format || 'text';
738
+ const outputFile = ctx.flags.output;
739
+ output.printInfo(`Extracting symbols: ${output.highlight(targetPath)}`);
740
+ output.writeln();
741
+ const spinner = output.createSpinner({ text: 'Parsing code...', spinner: 'dots' });
742
+ spinner.start();
743
+ try {
744
+ const astModule = await getASTAnalyzer();
745
+ const resolvedPath = resolve(targetPath);
746
+ const stat = await fs.stat(resolvedPath);
747
+ const files = stat.isDirectory() ? await scanSourceFiles(resolvedPath) : [resolvedPath];
748
+ const symbols = [];
749
+ for (const file of files.slice(0, 100)) {
750
+ try {
751
+ const content = await fs.readFile(file, 'utf-8');
752
+ let analysis;
753
+ if (astModule) {
754
+ const analyzer = astModule.createASTAnalyzer();
755
+ analysis = analyzer.analyze(content, file);
756
+ }
757
+ else {
758
+ analysis = fallbackAnalyze(content, file);
759
+ }
760
+ if (symbolType === 'all' || symbolType === 'function') {
761
+ for (const fn of analysis.functions) {
762
+ symbols.push({
763
+ name: fn.name,
764
+ type: 'function',
765
+ file,
766
+ startLine: fn.startLine,
767
+ endLine: fn.endLine,
768
+ });
769
+ }
770
+ }
771
+ if (symbolType === 'all' || symbolType === 'class') {
772
+ for (const cls of analysis.classes) {
773
+ symbols.push({
774
+ name: cls.name,
775
+ type: 'class',
776
+ file,
777
+ startLine: cls.startLine,
778
+ endLine: cls.endLine,
779
+ });
780
+ }
781
+ }
782
+ }
783
+ catch {
784
+ // Skip files that can't be parsed
785
+ }
786
+ }
787
+ spinner.stop();
788
+ // Sort by file then name
789
+ symbols.sort((a, b) => a.file.localeCompare(b.file) || a.name.localeCompare(b.name));
790
+ if (formatType === 'json') {
791
+ if (outputFile) {
792
+ await writeFile(outputFile, JSON.stringify(symbols, null, 2));
793
+ output.printSuccess(`Results written to ${outputFile}`);
794
+ }
795
+ else {
796
+ output.printJson(symbols);
797
+ }
798
+ return { success: true, data: symbols };
799
+ }
800
+ // Summary
801
+ const functionCount = symbols.filter(s => s.type === 'function').length;
802
+ const classCount = symbols.filter(s => s.type === 'class').length;
803
+ output.printBox([
804
+ `Total symbols: ${symbols.length}`,
805
+ `Functions: ${functionCount}`,
806
+ `Classes: ${classCount}`,
807
+ `Files: ${files.length}`,
808
+ ].join('\n'), 'Symbol Extraction');
809
+ output.writeln();
810
+ output.writeln(output.bold('Symbols'));
811
+ output.writeln(output.dim('-'.repeat(60)));
812
+ const displaySymbols = symbols.slice(0, 30);
813
+ output.printTable({
814
+ columns: [
815
+ { key: 'type', header: 'Type', width: 10, format: (v) => getTypeMarkerAst(v) },
816
+ { key: 'name', header: 'Name', width: 30 },
817
+ { key: 'file', header: 'File', width: 35, format: (v) => truncatePathAst(v, 33) },
818
+ { key: 'startLine', header: 'Line', width: 8, align: 'right' },
819
+ ],
820
+ data: displaySymbols,
821
+ });
822
+ if (symbols.length > 30) {
823
+ output.writeln(output.dim(` ... and ${symbols.length - 30} more symbols`));
824
+ }
825
+ if (outputFile) {
826
+ await writeFile(outputFile, JSON.stringify(symbols, null, 2));
827
+ output.printSuccess(`Results written to ${outputFile}`);
828
+ }
829
+ return { success: true, data: symbols };
830
+ }
831
+ catch (error) {
832
+ spinner.stop();
833
+ const message = error instanceof Error ? error.message : String(error);
834
+ output.printError(`Symbol extraction failed: ${message}`);
835
+ return { success: false, exitCode: 1 };
836
+ }
837
+ },
838
+ };
839
+ /**
840
+ * Imports analysis subcommand
841
+ */
842
+ const importsCommand = {
843
+ name: 'imports',
844
+ aliases: ['imp'],
845
+ description: 'Analyze import dependencies across files',
846
+ options: [
847
+ {
848
+ name: 'format',
849
+ short: 'f',
850
+ description: 'Output format (text, json)',
851
+ type: 'string',
852
+ default: 'text',
853
+ choices: ['text', 'json'],
854
+ },
855
+ {
856
+ name: 'output',
857
+ short: 'o',
858
+ description: 'Output file path',
859
+ type: 'string',
860
+ },
861
+ {
862
+ name: 'external',
863
+ short: 'e',
864
+ description: 'Show only external (npm) imports',
865
+ type: 'boolean',
866
+ default: false,
867
+ },
868
+ ],
869
+ examples: [
870
+ { command: 'claude-flow analyze imports src/', description: 'Analyze all imports' },
871
+ { command: 'claude-flow analyze imports src/ --external', description: 'Only npm packages' },
872
+ ],
873
+ action: async (ctx) => {
874
+ const targetPath = ctx.args[0] || ctx.cwd;
875
+ const formatType = ctx.flags.format || 'text';
876
+ const outputFile = ctx.flags.output;
877
+ const externalOnly = ctx.flags.external;
878
+ output.printInfo(`Analyzing imports: ${output.highlight(targetPath)}`);
879
+ output.writeln();
880
+ const spinner = output.createSpinner({ text: 'Scanning imports...', spinner: 'dots' });
881
+ spinner.start();
882
+ try {
883
+ const astModule = await getASTAnalyzer();
884
+ const resolvedPath = resolve(targetPath);
885
+ const stat = await fs.stat(resolvedPath);
886
+ const files = stat.isDirectory() ? await scanSourceFiles(resolvedPath) : [resolvedPath];
887
+ const importCounts = new Map();
888
+ const fileImports = new Map();
889
+ for (const file of files.slice(0, 100)) {
890
+ try {
891
+ const content = await fs.readFile(file, 'utf-8');
892
+ let analysis;
893
+ if (astModule) {
894
+ const analyzer = astModule.createASTAnalyzer();
895
+ analysis = analyzer.analyze(content, file);
896
+ }
897
+ else {
898
+ analysis = fallbackAnalyze(content, file);
899
+ }
900
+ const imports = analysis.imports.filter(imp => {
901
+ if (externalOnly) {
902
+ return !imp.startsWith('.') && !imp.startsWith('/');
903
+ }
904
+ return true;
905
+ });
906
+ fileImports.set(file, imports);
907
+ for (const imp of imports) {
908
+ const existing = importCounts.get(imp) || { count: 0, files: [] };
909
+ existing.count++;
910
+ existing.files.push(file);
911
+ importCounts.set(imp, existing);
912
+ }
913
+ }
914
+ catch {
915
+ // Skip files that can't be parsed
916
+ }
917
+ }
918
+ spinner.stop();
919
+ // Sort by count
920
+ const sortedImports = Array.from(importCounts.entries())
921
+ .sort((a, b) => b[1].count - a[1].count);
922
+ if (formatType === 'json') {
923
+ const jsonOutput = {
924
+ imports: Object.fromEntries(sortedImports),
925
+ fileImports: Object.fromEntries(fileImports),
926
+ };
927
+ if (outputFile) {
928
+ await writeFile(outputFile, JSON.stringify(jsonOutput, null, 2));
929
+ output.printSuccess(`Results written to ${outputFile}`);
930
+ }
931
+ else {
932
+ output.printJson(jsonOutput);
933
+ }
934
+ return { success: true, data: jsonOutput };
935
+ }
936
+ // Summary
937
+ const externalImports = sortedImports.filter(([imp]) => !imp.startsWith('.') && !imp.startsWith('/'));
938
+ const localImports = sortedImports.filter(([imp]) => imp.startsWith('.') || imp.startsWith('/'));
939
+ output.printBox([
940
+ `Total unique imports: ${sortedImports.length}`,
941
+ `External (npm): ${externalImports.length}`,
942
+ `Local (relative): ${localImports.length}`,
943
+ `Files scanned: ${files.length}`,
944
+ ].join('\n'), 'Import Analysis');
945
+ // Most used imports
946
+ output.writeln();
947
+ output.writeln(output.bold('Most Used Imports'));
948
+ output.writeln(output.dim('-'.repeat(60)));
949
+ const topImports = sortedImports.slice(0, 20);
950
+ output.printTable({
951
+ columns: [
952
+ { key: 'count', header: 'Uses', width: 8, align: 'right' },
953
+ { key: 'import', header: 'Import', width: 50 },
954
+ { key: 'type', header: 'Type', width: 10 },
955
+ ],
956
+ data: topImports.map(([imp, data]) => ({
957
+ count: data.count,
958
+ import: imp,
959
+ type: imp.startsWith('.') || imp.startsWith('/') ? output.dim('local') : output.highlight('npm'),
960
+ })),
961
+ });
962
+ if (sortedImports.length > 20) {
963
+ output.writeln(output.dim(` ... and ${sortedImports.length - 20} more imports`));
964
+ }
965
+ if (outputFile) {
966
+ await writeFile(outputFile, JSON.stringify({
967
+ imports: Object.fromEntries(sortedImports),
968
+ fileImports: Object.fromEntries(fileImports),
969
+ }, null, 2));
970
+ output.printSuccess(`Results written to ${outputFile}`);
971
+ }
972
+ return { success: true, data: { imports: sortedImports } };
973
+ }
974
+ catch (error) {
975
+ spinner.stop();
976
+ const message = error instanceof Error ? error.message : String(error);
977
+ output.printError(`Import analysis failed: ${message}`);
978
+ return { success: false, exitCode: 1 };
979
+ }
980
+ },
981
+ };
982
+ /**
983
+ * Helper: Scan directory for source files
984
+ */
985
+ async function scanSourceFiles(dir, maxDepth = 10) {
986
+ const files = [];
987
+ const extensions = ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs'];
988
+ const excludeDirs = ['node_modules', 'dist', 'build', '.git', 'coverage', '__pycache__'];
989
+ async function scan(currentDir, depth) {
990
+ if (depth > maxDepth)
991
+ return;
992
+ try {
993
+ const entries = await fs.readdir(currentDir, { withFileTypes: true });
994
+ for (const entry of entries) {
995
+ const fullPath = path.join(currentDir, entry.name);
996
+ if (entry.isDirectory()) {
997
+ if (!excludeDirs.includes(entry.name)) {
998
+ await scan(fullPath, depth + 1);
999
+ }
1000
+ }
1001
+ else if (entry.isFile()) {
1002
+ const ext = path.extname(entry.name);
1003
+ if (extensions.includes(ext)) {
1004
+ files.push(fullPath);
1005
+ }
1006
+ }
1007
+ }
1008
+ }
1009
+ catch {
1010
+ // Skip directories we can't read
1011
+ }
1012
+ }
1013
+ await scan(dir, 0);
1014
+ return files;
1015
+ }
1016
+ /**
1017
+ * Fallback analysis when ruvector is not available
1018
+ */
1019
+ function fallbackAnalyze(code, filePath) {
1020
+ const lines = code.split('\n');
1021
+ const functions = [];
1022
+ const classes = [];
1023
+ const imports = [];
1024
+ const exports = [];
1025
+ // Extract functions
1026
+ const funcPattern = /(?:export\s+)?(?:async\s+)?function\s+(\w+)|(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?\([^)]*\)\s*=>|^\s*(?:async\s+)?(\w+)\s*\([^)]*\)\s*(?::\s*\w+)?\s*\{/gm;
1027
+ let match;
1028
+ while ((match = funcPattern.exec(code)) !== null) {
1029
+ const name = match[1] || match[2] || match[3];
1030
+ if (name && !['if', 'while', 'for', 'switch'].includes(name)) {
1031
+ const lineNum = code.substring(0, match.index).split('\n').length;
1032
+ functions.push({ name, startLine: lineNum, endLine: lineNum + 10 });
1033
+ }
1034
+ }
1035
+ // Extract classes
1036
+ const classPattern = /(?:export\s+)?class\s+(\w+)/gm;
1037
+ while ((match = classPattern.exec(code)) !== null) {
1038
+ const lineNum = code.substring(0, match.index).split('\n').length;
1039
+ classes.push({ name: match[1], startLine: lineNum, endLine: lineNum + 20 });
1040
+ }
1041
+ // Extract imports
1042
+ const importPattern = /import\s+(?:.*\s+from\s+)?['"]([^'"]+)['"]/gm;
1043
+ while ((match = importPattern.exec(code)) !== null) {
1044
+ imports.push(match[1]);
1045
+ }
1046
+ const requirePattern = /require\s*\(\s*['"]([^'"]+)['"]\s*\)/gm;
1047
+ while ((match = requirePattern.exec(code)) !== null) {
1048
+ imports.push(match[1]);
1049
+ }
1050
+ // Extract exports
1051
+ const exportPattern = /export\s+(?:default\s+)?(?:const|let|var|function|class|interface|type|enum)\s+(\w+)/gm;
1052
+ while ((match = exportPattern.exec(code)) !== null) {
1053
+ exports.push(match[1]);
1054
+ }
1055
+ // Calculate complexity
1056
+ const nonEmptyLines = lines.filter(l => l.trim().length > 0).length;
1057
+ const commentLines = lines.filter(l => /^\s*(\/\/|\/\*|\*|#)/.test(l)).length;
1058
+ const decisionPoints = (code.match(/\b(if|else|for|while|switch|case|catch|&&|\|\||\?)\b/g) || []).length;
1059
+ let cognitive = 0;
1060
+ let nestingLevel = 0;
1061
+ for (const line of lines) {
1062
+ const opens = (line.match(/\{/g) || []).length;
1063
+ const closes = (line.match(/\}/g) || []).length;
1064
+ if (/\b(if|for|while|switch)\b/.test(line)) {
1065
+ cognitive += 1 + nestingLevel;
1066
+ }
1067
+ nestingLevel = Math.max(0, nestingLevel + opens - closes);
1068
+ }
1069
+ // Detect language
1070
+ const ext = path.extname(filePath).toLowerCase();
1071
+ const language = ext === '.ts' || ext === '.tsx' ? 'typescript' :
1072
+ ext === '.js' || ext === '.jsx' || ext === '.mjs' || ext === '.cjs' ? 'javascript' :
1073
+ ext === '.py' ? 'python' : 'unknown';
1074
+ return {
1075
+ filePath,
1076
+ language,
1077
+ functions,
1078
+ classes,
1079
+ imports,
1080
+ exports,
1081
+ complexity: {
1082
+ cyclomatic: decisionPoints + 1,
1083
+ cognitive,
1084
+ loc: nonEmptyLines,
1085
+ commentDensity: lines.length > 0 ? commentLines / lines.length : 0,
1086
+ },
1087
+ };
1088
+ }
1089
+ // Dependencies subcommand
1090
+ const depsCommand = {
1091
+ name: 'deps',
1092
+ description: 'Analyze project dependencies',
1093
+ options: [
1094
+ { name: 'outdated', short: 'o', type: 'boolean', description: 'Show only outdated dependencies' },
1095
+ { name: 'security', short: 's', type: 'boolean', description: 'Check for security vulnerabilities' },
1096
+ { name: 'format', short: 'f', type: 'string', description: 'Output format: text, json', default: 'text' },
1097
+ ],
1098
+ examples: [
1099
+ { command: 'claude-flow analyze deps --outdated', description: 'Show outdated dependencies' },
1100
+ { command: 'claude-flow analyze deps --security', description: 'Check for vulnerabilities' },
1101
+ ],
1102
+ action: async (ctx) => {
1103
+ const showOutdated = ctx.flags.outdated;
1104
+ const checkSecurity = ctx.flags.security;
1105
+ output.writeln();
1106
+ output.writeln(output.bold('Dependency Analysis'));
1107
+ output.writeln(output.dim('-'.repeat(50)));
1108
+ output.printInfo('Analyzing dependencies...');
1109
+ output.writeln();
1110
+ // Placeholder - would integrate with npm/yarn audit
1111
+ output.printBox([
1112
+ `Outdated Check: ${showOutdated ? 'Enabled' : 'Disabled'}`,
1113
+ `Security Check: ${checkSecurity ? 'Enabled' : 'Disabled'}`,
1114
+ `Status: Feature in development`,
1115
+ ``,
1116
+ `Dependency analysis capabilities coming soon.`,
1117
+ `Use 'security scan --type deps' for security scanning.`,
1118
+ ].join('\n'), 'Dependency Analysis');
1119
+ return { success: true };
1120
+ },
1121
+ };
1122
+ // ============================================================================
1123
+ // Graph Analysis Subcommands (MinCut, Louvain, Circular Dependencies)
1124
+ // ============================================================================
1125
+ /**
1126
+ * Analyze code boundaries using MinCut algorithm
1127
+ */
1128
+ const boundariesCommand = {
1129
+ name: 'boundaries',
1130
+ aliases: ['boundary', 'mincut'],
1131
+ description: 'Find natural code boundaries using MinCut algorithm',
1132
+ options: [
1133
+ {
1134
+ name: 'partitions',
1135
+ short: 'p',
1136
+ description: 'Number of partitions to find',
1137
+ type: 'number',
1138
+ default: 2,
1139
+ },
1140
+ {
1141
+ name: 'output',
1142
+ short: 'o',
1143
+ description: 'Output file path',
1144
+ type: 'string',
1145
+ },
1146
+ {
1147
+ name: 'format',
1148
+ short: 'f',
1149
+ description: 'Output format (text, json, dot)',
1150
+ type: 'string',
1151
+ default: 'text',
1152
+ choices: ['text', 'json', 'dot'],
1153
+ },
1154
+ ],
1155
+ examples: [
1156
+ { command: 'claude-flow analyze boundaries src/', description: 'Find code boundaries in src/' },
1157
+ { command: 'claude-flow analyze boundaries -p 3 src/', description: 'Find 3 partitions' },
1158
+ { command: 'claude-flow analyze boundaries -f dot -o graph.dot src/', description: 'Export to DOT format' },
1159
+ ],
1160
+ action: async (ctx) => {
1161
+ const targetDir = ctx.args[0] || ctx.cwd;
1162
+ const numPartitions = ctx.flags.partitions || 2;
1163
+ const outputFile = ctx.flags.output;
1164
+ const format = ctx.flags.format || 'text';
1165
+ output.printInfo(`Analyzing code boundaries in: ${output.highlight(targetDir)}`);
1166
+ output.writeln();
1167
+ const spinner = output.createSpinner({ text: 'Building dependency graph...', spinner: 'dots' });
1168
+ spinner.start();
1169
+ try {
1170
+ const analyzer = await getGraphAnalyzer();
1171
+ if (!analyzer) {
1172
+ spinner.stop();
1173
+ output.printError('Graph analyzer module not available');
1174
+ return { success: false, exitCode: 1 };
1175
+ }
1176
+ const result = await analyzer.analyzeGraph(resolve(targetDir), {
1177
+ includeBoundaries: true,
1178
+ includeModules: false,
1179
+ numPartitions,
1180
+ });
1181
+ spinner.stop();
1182
+ // Handle different output formats
1183
+ if (format === 'json') {
1184
+ const jsonOutput = {
1185
+ boundaries: result.boundaries,
1186
+ statistics: result.statistics,
1187
+ circularDependencies: result.circularDependencies,
1188
+ };
1189
+ if (outputFile) {
1190
+ await writeFile(outputFile, JSON.stringify(jsonOutput, null, 2));
1191
+ output.printSuccess(`Results written to ${outputFile}`);
1192
+ }
1193
+ else {
1194
+ output.printJson(jsonOutput);
1195
+ }
1196
+ return { success: true, data: jsonOutput };
1197
+ }
1198
+ if (format === 'dot') {
1199
+ const dotOutput = analyzer.exportToDot(result, {
1200
+ includeLabels: true,
1201
+ highlightCycles: true,
1202
+ });
1203
+ if (outputFile) {
1204
+ await writeFile(outputFile, dotOutput);
1205
+ output.printSuccess(`DOT graph written to ${outputFile}`);
1206
+ output.writeln(output.dim('Visualize with: dot -Tpng -o graph.png ' + outputFile));
1207
+ }
1208
+ else {
1209
+ output.writeln(dotOutput);
1210
+ }
1211
+ return { success: true };
1212
+ }
1213
+ // Text format (default)
1214
+ output.printBox([
1215
+ `Files analyzed: ${result.statistics.nodeCount}`,
1216
+ `Dependencies: ${result.statistics.edgeCount}`,
1217
+ `Avg degree: ${result.statistics.avgDegree.toFixed(2)}`,
1218
+ `Density: ${(result.statistics.density * 100).toFixed(2)}%`,
1219
+ `Components: ${result.statistics.componentCount}`,
1220
+ ].join('\n'), 'Graph Statistics');
1221
+ if (result.boundaries && result.boundaries.length > 0) {
1222
+ output.writeln();
1223
+ output.writeln(output.bold('MinCut Boundaries'));
1224
+ output.writeln();
1225
+ for (let i = 0; i < result.boundaries.length; i++) {
1226
+ const boundary = result.boundaries[i];
1227
+ output.writeln(output.bold(`Boundary ${i + 1} (cut value: ${boundary.cutValue})`));
1228
+ output.writeln();
1229
+ output.writeln(output.dim('Partition 1:'));
1230
+ const p1Display = boundary.partition1.slice(0, 10);
1231
+ output.printList(p1Display);
1232
+ if (boundary.partition1.length > 10) {
1233
+ output.writeln(output.dim(` ... and ${boundary.partition1.length - 10} more files`));
1234
+ }
1235
+ output.writeln();
1236
+ output.writeln(output.dim('Partition 2:'));
1237
+ const p2Display = boundary.partition2.slice(0, 10);
1238
+ output.printList(p2Display);
1239
+ if (boundary.partition2.length > 10) {
1240
+ output.writeln(output.dim(` ... and ${boundary.partition2.length - 10} more files`));
1241
+ }
1242
+ output.writeln();
1243
+ output.writeln(output.success('Suggestion:'));
1244
+ output.writeln(` ${boundary.suggestion}`);
1245
+ output.writeln();
1246
+ }
1247
+ }
1248
+ // Show circular dependencies
1249
+ if (result.circularDependencies.length > 0) {
1250
+ output.writeln();
1251
+ output.writeln(output.bold(output.warning('Circular Dependencies Detected')));
1252
+ output.writeln();
1253
+ for (const cycle of result.circularDependencies.slice(0, 5)) {
1254
+ const severityColor = cycle.severity === 'high' ? output.error : cycle.severity === 'medium' ? output.warning : output.dim;
1255
+ output.writeln(`${severityColor(`[${cycle.severity.toUpperCase()}]`)} ${cycle.cycle.join(' -> ')}`);
1256
+ output.writeln(output.dim(` ${cycle.suggestion}`));
1257
+ output.writeln();
1258
+ }
1259
+ if (result.circularDependencies.length > 5) {
1260
+ output.writeln(output.dim(`... and ${result.circularDependencies.length - 5} more cycles`));
1261
+ }
1262
+ }
1263
+ if (outputFile) {
1264
+ await writeFile(outputFile, JSON.stringify(result, null, 2));
1265
+ output.printSuccess(`Full results written to ${outputFile}`);
1266
+ }
1267
+ return { success: true, data: result };
1268
+ }
1269
+ catch (error) {
1270
+ spinner.stop();
1271
+ const message = error instanceof Error ? error.message : String(error);
1272
+ output.printError(`Analysis failed: ${message}`);
1273
+ return { success: false, exitCode: 1 };
1274
+ }
1275
+ },
1276
+ };
1277
+ /**
1278
+ * Analyze modules/communities using Louvain algorithm
1279
+ */
1280
+ const modulesCommand = {
1281
+ name: 'modules',
1282
+ aliases: ['communities', 'louvain'],
1283
+ description: 'Detect module communities using Louvain algorithm',
1284
+ options: [
1285
+ {
1286
+ name: 'output',
1287
+ short: 'o',
1288
+ description: 'Output file path',
1289
+ type: 'string',
1290
+ },
1291
+ {
1292
+ name: 'format',
1293
+ short: 'f',
1294
+ description: 'Output format (text, json, dot)',
1295
+ type: 'string',
1296
+ default: 'text',
1297
+ choices: ['text', 'json', 'dot'],
1298
+ },
1299
+ {
1300
+ name: 'min-size',
1301
+ short: 'm',
1302
+ description: 'Minimum community size to display',
1303
+ type: 'number',
1304
+ default: 2,
1305
+ },
1306
+ ],
1307
+ examples: [
1308
+ { command: 'claude-flow analyze modules src/', description: 'Detect module communities' },
1309
+ { command: 'claude-flow analyze modules -f dot -o modules.dot src/', description: 'Export colored DOT graph' },
1310
+ { command: 'claude-flow analyze modules -m 3 src/', description: 'Only show communities with 3+ files' },
1311
+ ],
1312
+ action: async (ctx) => {
1313
+ const targetDir = ctx.args[0] || ctx.cwd;
1314
+ const outputFile = ctx.flags.output;
1315
+ const format = ctx.flags.format || 'text';
1316
+ const minSize = ctx.flags['min-size'] || 2;
1317
+ output.printInfo(`Detecting module communities in: ${output.highlight(targetDir)}`);
1318
+ output.writeln();
1319
+ const spinner = output.createSpinner({ text: 'Building dependency graph...', spinner: 'dots' });
1320
+ spinner.start();
1321
+ try {
1322
+ const analyzer = await getGraphAnalyzer();
1323
+ if (!analyzer) {
1324
+ spinner.stop();
1325
+ output.printError('Graph analyzer module not available');
1326
+ return { success: false, exitCode: 1 };
1327
+ }
1328
+ const result = await analyzer.analyzeGraph(resolve(targetDir), {
1329
+ includeBoundaries: false,
1330
+ includeModules: true,
1331
+ });
1332
+ spinner.stop();
1333
+ // Filter communities by size
1334
+ const communities = result.communities?.filter(c => c.members.length >= minSize) || [];
1335
+ // Handle different output formats
1336
+ if (format === 'json') {
1337
+ const jsonOutput = {
1338
+ communities,
1339
+ statistics: result.statistics,
1340
+ };
1341
+ if (outputFile) {
1342
+ await writeFile(outputFile, JSON.stringify(jsonOutput, null, 2));
1343
+ output.printSuccess(`Results written to ${outputFile}`);
1344
+ }
1345
+ else {
1346
+ output.printJson(jsonOutput);
1347
+ }
1348
+ return { success: true, data: jsonOutput };
1349
+ }
1350
+ if (format === 'dot') {
1351
+ const dotOutput = analyzer.exportToDot(result, {
1352
+ includeLabels: true,
1353
+ colorByCommunity: true,
1354
+ highlightCycles: true,
1355
+ });
1356
+ if (outputFile) {
1357
+ await writeFile(outputFile, dotOutput);
1358
+ output.printSuccess(`DOT graph written to ${outputFile}`);
1359
+ output.writeln(output.dim('Visualize with: dot -Tpng -o modules.png ' + outputFile));
1360
+ }
1361
+ else {
1362
+ output.writeln(dotOutput);
1363
+ }
1364
+ return { success: true };
1365
+ }
1366
+ // Text format (default)
1367
+ output.printBox([
1368
+ `Files analyzed: ${result.statistics.nodeCount}`,
1369
+ `Dependencies: ${result.statistics.edgeCount}`,
1370
+ `Communities found: ${result.communities?.length || 0}`,
1371
+ `Showing: ${communities.length} (min size: ${minSize})`,
1372
+ ].join('\n'), 'Module Detection Results');
1373
+ if (communities.length > 0) {
1374
+ output.writeln();
1375
+ output.writeln(output.bold('Detected Communities'));
1376
+ output.writeln();
1377
+ for (const community of communities.slice(0, 10)) {
1378
+ const cohesionIndicator = community.cohesion > 0.5 ? output.success('High') :
1379
+ community.cohesion > 0.2 ? output.warning('Medium') : output.dim('Low');
1380
+ output.writeln(output.bold(`Community ${community.id}: ${community.suggestedName || 'unnamed'}`));
1381
+ output.writeln(` ${output.dim('Cohesion:')} ${cohesionIndicator} (${(community.cohesion * 100).toFixed(1)}%)`);
1382
+ output.writeln(` ${output.dim('Central node:')} ${community.centralNode || 'none'}`);
1383
+ output.writeln(` ${output.dim('Members:')} ${community.members.length} files`);
1384
+ const displayMembers = community.members.slice(0, 5);
1385
+ for (const member of displayMembers) {
1386
+ output.writeln(` - ${member}`);
1387
+ }
1388
+ if (community.members.length > 5) {
1389
+ output.writeln(output.dim(` ... and ${community.members.length - 5} more`));
1390
+ }
1391
+ output.writeln();
1392
+ }
1393
+ if (communities.length > 10) {
1394
+ output.writeln(output.dim(`... and ${communities.length - 10} more communities`));
1395
+ }
1396
+ }
1397
+ if (outputFile) {
1398
+ await writeFile(outputFile, JSON.stringify(result, null, 2));
1399
+ output.printSuccess(`Full results written to ${outputFile}`);
1400
+ }
1401
+ return { success: true, data: result };
1402
+ }
1403
+ catch (error) {
1404
+ spinner.stop();
1405
+ const message = error instanceof Error ? error.message : String(error);
1406
+ output.printError(`Analysis failed: ${message}`);
1407
+ return { success: false, exitCode: 1 };
1408
+ }
1409
+ },
1410
+ };
1411
+ /**
1412
+ * Build and export dependency graph
1413
+ */
1414
+ const dependenciesCommand = {
1415
+ name: 'dependencies',
1416
+ aliases: ['graph'],
1417
+ description: 'Build and export full dependency graph',
1418
+ options: [
1419
+ {
1420
+ name: 'output',
1421
+ short: 'o',
1422
+ description: 'Output file path',
1423
+ type: 'string',
1424
+ },
1425
+ {
1426
+ name: 'format',
1427
+ short: 'f',
1428
+ description: 'Output format (text, json, dot)',
1429
+ type: 'string',
1430
+ default: 'text',
1431
+ choices: ['text', 'json', 'dot'],
1432
+ },
1433
+ {
1434
+ name: 'include',
1435
+ short: 'i',
1436
+ description: 'File extensions to include (comma-separated)',
1437
+ type: 'string',
1438
+ default: '.ts,.tsx,.js,.jsx,.mjs,.cjs',
1439
+ },
1440
+ {
1441
+ name: 'exclude',
1442
+ short: 'e',
1443
+ description: 'Patterns to exclude (comma-separated)',
1444
+ type: 'string',
1445
+ default: 'node_modules,dist,build,.git',
1446
+ },
1447
+ {
1448
+ name: 'depth',
1449
+ short: 'd',
1450
+ description: 'Maximum directory depth',
1451
+ type: 'number',
1452
+ default: 10,
1453
+ },
1454
+ ],
1455
+ examples: [
1456
+ { command: 'claude-flow analyze dependencies src/', description: 'Build dependency graph' },
1457
+ { command: 'claude-flow analyze dependencies -f dot -o deps.dot src/', description: 'Export to DOT' },
1458
+ { command: 'claude-flow analyze dependencies -i .ts,.tsx src/', description: 'Only TypeScript files' },
1459
+ ],
1460
+ action: async (ctx) => {
1461
+ const targetDir = ctx.args[0] || ctx.cwd;
1462
+ const outputFile = ctx.flags.output;
1463
+ const format = ctx.flags.format || 'text';
1464
+ const include = (ctx.flags.include || '.ts,.tsx,.js,.jsx,.mjs,.cjs').split(',');
1465
+ const exclude = (ctx.flags.exclude || 'node_modules,dist,build,.git').split(',');
1466
+ const maxDepth = ctx.flags.depth || 10;
1467
+ output.printInfo(`Building dependency graph for: ${output.highlight(targetDir)}`);
1468
+ output.writeln();
1469
+ const spinner = output.createSpinner({ text: 'Scanning files...', spinner: 'dots' });
1470
+ spinner.start();
1471
+ try {
1472
+ const analyzer = await getGraphAnalyzer();
1473
+ if (!analyzer) {
1474
+ spinner.stop();
1475
+ output.printError('Graph analyzer module not available');
1476
+ return { success: false, exitCode: 1 };
1477
+ }
1478
+ const graph = await analyzer.buildDependencyGraph(resolve(targetDir), {
1479
+ include,
1480
+ exclude,
1481
+ maxDepth,
1482
+ });
1483
+ spinner.stop();
1484
+ // Detect circular dependencies
1485
+ const circularDeps = analyzer.detectCircularDependencies(graph);
1486
+ // Handle different output formats
1487
+ if (format === 'json') {
1488
+ const jsonOutput = {
1489
+ nodes: Array.from(graph.nodes.values()),
1490
+ edges: graph.edges,
1491
+ metadata: graph.metadata,
1492
+ circularDependencies: circularDeps,
1493
+ };
1494
+ if (outputFile) {
1495
+ await writeFile(outputFile, JSON.stringify(jsonOutput, null, 2));
1496
+ output.printSuccess(`Graph written to ${outputFile}`);
1497
+ }
1498
+ else {
1499
+ output.printJson(jsonOutput);
1500
+ }
1501
+ return { success: true, data: jsonOutput };
1502
+ }
1503
+ if (format === 'dot') {
1504
+ const result = { graph, circularDependencies: circularDeps, statistics: {
1505
+ nodeCount: graph.nodes.size,
1506
+ edgeCount: graph.edges.length,
1507
+ avgDegree: 0,
1508
+ maxDegree: 0,
1509
+ density: 0,
1510
+ componentCount: 0,
1511
+ } };
1512
+ const dotOutput = analyzer.exportToDot(result, {
1513
+ includeLabels: true,
1514
+ highlightCycles: true,
1515
+ });
1516
+ if (outputFile) {
1517
+ await writeFile(outputFile, dotOutput);
1518
+ output.printSuccess(`DOT graph written to ${outputFile}`);
1519
+ output.writeln(output.dim('Visualize with: dot -Tpng -o deps.png ' + outputFile));
1520
+ }
1521
+ else {
1522
+ output.writeln(dotOutput);
1523
+ }
1524
+ return { success: true };
1525
+ }
1526
+ // Text format (default)
1527
+ output.printBox([
1528
+ `Files: ${graph.metadata.totalFiles}`,
1529
+ `Dependencies: ${graph.metadata.totalEdges}`,
1530
+ `Build time: ${graph.metadata.buildTime}ms`,
1531
+ `Root: ${graph.metadata.rootDir}`,
1532
+ ].join('\n'), 'Dependency Graph');
1533
+ // Show top files by imports
1534
+ output.writeln();
1535
+ output.writeln(output.bold('Most Connected Files'));
1536
+ output.writeln();
1537
+ const nodesByDegree = Array.from(graph.nodes.values())
1538
+ .map(n => ({
1539
+ ...n,
1540
+ degree: graph.edges.filter(e => e.source === n.id || e.target === n.id).length,
1541
+ }))
1542
+ .sort((a, b) => b.degree - a.degree)
1543
+ .slice(0, 10);
1544
+ output.printTable({
1545
+ columns: [
1546
+ { key: 'path', header: 'File', width: 50 },
1547
+ { key: 'degree', header: 'Connections', width: 12, align: 'right' },
1548
+ { key: 'complexity', header: 'Complexity', width: 12, align: 'right' },
1549
+ ],
1550
+ data: nodesByDegree.map(n => ({
1551
+ path: n.path.length > 48 ? '...' + n.path.slice(-45) : n.path,
1552
+ degree: n.degree,
1553
+ complexity: n.complexity || 0,
1554
+ })),
1555
+ });
1556
+ // Show circular dependencies
1557
+ if (circularDeps.length > 0) {
1558
+ output.writeln();
1559
+ output.writeln(output.bold(output.warning(`Circular Dependencies: ${circularDeps.length}`)));
1560
+ output.writeln();
1561
+ for (const cycle of circularDeps.slice(0, 3)) {
1562
+ output.writeln(` ${cycle.cycle.join(' -> ')}`);
1563
+ }
1564
+ if (circularDeps.length > 3) {
1565
+ output.writeln(output.dim(` ... and ${circularDeps.length - 3} more`));
1566
+ }
1567
+ }
1568
+ if (outputFile) {
1569
+ const fullOutput = {
1570
+ nodes: Array.from(graph.nodes.values()),
1571
+ edges: graph.edges,
1572
+ metadata: graph.metadata,
1573
+ circularDependencies: circularDeps,
1574
+ };
1575
+ await writeFile(outputFile, JSON.stringify(fullOutput, null, 2));
1576
+ output.printSuccess(`Full results written to ${outputFile}`);
1577
+ }
1578
+ return { success: true };
1579
+ }
1580
+ catch (error) {
1581
+ spinner.stop();
1582
+ const message = error instanceof Error ? error.message : String(error);
1583
+ output.printError(`Analysis failed: ${message}`);
1584
+ return { success: false, exitCode: 1 };
1585
+ }
1586
+ },
1587
+ };
1588
+ /**
1589
+ * Detect circular dependencies
1590
+ */
1591
+ const circularCommand = {
1592
+ name: 'circular',
1593
+ aliases: ['cycles'],
1594
+ description: 'Detect circular dependencies in codebase',
1595
+ options: [
1596
+ {
1597
+ name: 'output',
1598
+ short: 'o',
1599
+ description: 'Output file path',
1600
+ type: 'string',
1601
+ },
1602
+ {
1603
+ name: 'format',
1604
+ short: 'f',
1605
+ description: 'Output format (text, json)',
1606
+ type: 'string',
1607
+ default: 'text',
1608
+ choices: ['text', 'json'],
1609
+ },
1610
+ {
1611
+ name: 'severity',
1612
+ short: 's',
1613
+ description: 'Minimum severity to show (low, medium, high)',
1614
+ type: 'string',
1615
+ default: 'low',
1616
+ choices: ['low', 'medium', 'high'],
1617
+ },
1618
+ ],
1619
+ examples: [
1620
+ { command: 'claude-flow analyze circular src/', description: 'Find circular dependencies' },
1621
+ { command: 'claude-flow analyze circular -s high src/', description: 'Only high severity cycles' },
1622
+ ],
1623
+ action: async (ctx) => {
1624
+ const targetDir = ctx.args[0] || ctx.cwd;
1625
+ const outputFile = ctx.flags.output;
1626
+ const format = ctx.flags.format || 'text';
1627
+ const minSeverity = ctx.flags.severity || 'low';
1628
+ output.printInfo(`Detecting circular dependencies in: ${output.highlight(targetDir)}`);
1629
+ output.writeln();
1630
+ const spinner = output.createSpinner({ text: 'Analyzing dependencies...', spinner: 'dots' });
1631
+ spinner.start();
1632
+ try {
1633
+ const analyzer = await getGraphAnalyzer();
1634
+ if (!analyzer) {
1635
+ spinner.stop();
1636
+ output.printError('Graph analyzer module not available');
1637
+ return { success: false, exitCode: 1 };
1638
+ }
1639
+ const graph = await analyzer.buildDependencyGraph(resolve(targetDir));
1640
+ const cycles = analyzer.detectCircularDependencies(graph);
1641
+ spinner.stop();
1642
+ // Filter by severity
1643
+ const severityOrder = { low: 0, medium: 1, high: 2 };
1644
+ const minLevel = severityOrder[minSeverity] || 0;
1645
+ const filtered = cycles.filter(c => severityOrder[c.severity] >= minLevel);
1646
+ if (format === 'json') {
1647
+ const jsonOutput = { cycles: filtered, total: cycles.length, filtered: filtered.length };
1648
+ if (outputFile) {
1649
+ await writeFile(outputFile, JSON.stringify(jsonOutput, null, 2));
1650
+ output.printSuccess(`Results written to ${outputFile}`);
1651
+ }
1652
+ else {
1653
+ output.printJson(jsonOutput);
1654
+ }
1655
+ return { success: true, data: jsonOutput };
1656
+ }
1657
+ // Text format
1658
+ if (filtered.length === 0) {
1659
+ output.printSuccess('No circular dependencies found!');
1660
+ return { success: true };
1661
+ }
1662
+ output.printBox([
1663
+ `Total cycles: ${cycles.length}`,
1664
+ `Shown (${minSeverity}+): ${filtered.length}`,
1665
+ `High severity: ${cycles.filter(c => c.severity === 'high').length}`,
1666
+ `Medium severity: ${cycles.filter(c => c.severity === 'medium').length}`,
1667
+ `Low severity: ${cycles.filter(c => c.severity === 'low').length}`,
1668
+ ].join('\n'), 'Circular Dependencies');
1669
+ output.writeln();
1670
+ // Group by severity
1671
+ const grouped = {
1672
+ high: filtered.filter(c => c.severity === 'high'),
1673
+ medium: filtered.filter(c => c.severity === 'medium'),
1674
+ low: filtered.filter(c => c.severity === 'low'),
1675
+ };
1676
+ for (const [severity, items] of Object.entries(grouped)) {
1677
+ if (items.length === 0)
1678
+ continue;
1679
+ const color = severity === 'high' ? output.error : severity === 'medium' ? output.warning : output.dim;
1680
+ output.writeln(color(output.bold(`${severity.toUpperCase()} SEVERITY (${items.length})`)));
1681
+ output.writeln();
1682
+ for (const cycle of items.slice(0, 5)) {
1683
+ output.writeln(` ${cycle.cycle.join(' -> ')}`);
1684
+ output.writeln(output.dim(` Fix: ${cycle.suggestion}`));
1685
+ output.writeln();
1686
+ }
1687
+ if (items.length > 5) {
1688
+ output.writeln(output.dim(` ... and ${items.length - 5} more ${severity} cycles`));
1689
+ output.writeln();
1690
+ }
1691
+ }
1692
+ if (outputFile) {
1693
+ await writeFile(outputFile, JSON.stringify({ cycles: filtered }, null, 2));
1694
+ output.printSuccess(`Results written to ${outputFile}`);
1695
+ }
1696
+ return { success: true, data: { cycles: filtered } };
1697
+ }
1698
+ catch (error) {
1699
+ spinner.stop();
1700
+ const message = error instanceof Error ? error.message : String(error);
1701
+ output.printError(`Analysis failed: ${message}`);
1702
+ return { success: false, exitCode: 1 };
1703
+ }
1704
+ },
1705
+ };
1706
+ // Helper functions
1707
+ function getRiskDisplay(risk) {
1708
+ switch (risk) {
1709
+ case 'critical':
1710
+ return output.color(output.bold('CRITICAL'), 'bgRed', 'white');
1711
+ case 'high-risk':
1712
+ return output.error('HIGH');
1713
+ case 'medium-risk':
1714
+ return output.warning('MEDIUM');
1715
+ case 'low-risk':
1716
+ return output.success('LOW');
1717
+ default:
1718
+ return risk;
1719
+ }
1720
+ }
1721
+ function getStatusDisplay(status) {
1722
+ switch (status) {
1723
+ case 'added':
1724
+ return output.success('A');
1725
+ case 'modified':
1726
+ return output.warning('M');
1727
+ case 'deleted':
1728
+ return output.error('D');
1729
+ case 'renamed':
1730
+ return output.info('R');
1731
+ default:
1732
+ return status;
1733
+ }
1734
+ }
1735
+ // Main analyze command
1736
+ export const analyzeCommand = {
1737
+ name: 'analyze',
1738
+ description: 'Code analysis, diff classification, graph boundaries, and change risk assessment',
1739
+ aliases: ['an'],
1740
+ subcommands: [
1741
+ diffCommand,
1742
+ codeCommand,
1743
+ depsCommand,
1744
+ astCommand,
1745
+ complexityAstCommand,
1746
+ symbolsCommand,
1747
+ importsCommand,
1748
+ boundariesCommand,
1749
+ modulesCommand,
1750
+ dependenciesCommand,
1751
+ circularCommand,
1752
+ ],
1753
+ options: [
1754
+ {
1755
+ name: 'format',
1756
+ short: 'f',
1757
+ description: 'Output format: text, json, table',
1758
+ type: 'string',
1759
+ default: 'text',
1760
+ },
1761
+ ],
1762
+ examples: [
1763
+ { command: 'claude-flow analyze ast src/', description: 'Analyze code with AST parsing' },
1764
+ { command: 'claude-flow analyze complexity src/ --threshold 15', description: 'Find high-complexity files' },
1765
+ { command: 'claude-flow analyze symbols src/ --type function', description: 'Extract all functions' },
1766
+ { command: 'claude-flow analyze imports src/ --external', description: 'List npm dependencies' },
1767
+ { command: 'claude-flow analyze diff --risk', description: 'Analyze diff with risk assessment' },
1768
+ { command: 'claude-flow analyze boundaries src/', description: 'Find code boundaries using MinCut' },
1769
+ { command: 'claude-flow analyze modules src/', description: 'Detect module communities with Louvain' },
1770
+ { command: 'claude-flow analyze dependencies src/ --format dot', description: 'Export dependency graph as DOT' },
1771
+ { command: 'claude-flow analyze circular src/', description: 'Find circular dependencies' },
1772
+ { command: 'claude-flow analyze deps --security', description: 'Check dependency vulnerabilities' },
1773
+ ],
1774
+ action: async (ctx) => {
1775
+ // If no subcommand, show help
1776
+ output.writeln();
1777
+ output.writeln(output.bold('Analyze Commands'));
1778
+ output.writeln(output.dim('-'.repeat(50)));
1779
+ output.writeln();
1780
+ output.writeln(output.bold('Available subcommands:'));
1781
+ output.writeln();
1782
+ output.writeln(` ${output.highlight('diff')} Analyze git diff for change risk and classification`);
1783
+ output.writeln(` ${output.highlight('code')} Static code analysis and quality assessment`);
1784
+ output.writeln(` ${output.highlight('deps')} Analyze project dependencies`);
1785
+ output.writeln(` ${output.highlight('ast')} AST analysis with symbol extraction and complexity`);
1786
+ output.writeln(` ${output.highlight('complexity')} Analyze cyclomatic and cognitive complexity`);
1787
+ output.writeln(` ${output.highlight('symbols')} Extract functions, classes, and types`);
1788
+ output.writeln(` ${output.highlight('imports')} Analyze import dependencies`);
1789
+ output.writeln(` ${output.highlight('boundaries')} Find code boundaries using MinCut algorithm`);
1790
+ output.writeln(` ${output.highlight('modules')} Detect module communities using Louvain algorithm`);
1791
+ output.writeln(` ${output.highlight('dependencies')} Build and export full dependency graph`);
1792
+ output.writeln(` ${output.highlight('circular')} Detect circular dependencies in codebase`);
1793
+ output.writeln();
1794
+ output.writeln(output.bold('AST Analysis Examples:'));
1795
+ output.writeln();
1796
+ output.writeln(` ${output.dim('claude-flow analyze ast src/')} # Full AST analysis`);
1797
+ output.writeln(` ${output.dim('claude-flow analyze ast src/index.ts -c')} # Include complexity`);
1798
+ output.writeln(` ${output.dim('claude-flow analyze complexity src/ -t 15')} # Flag high complexity`);
1799
+ output.writeln(` ${output.dim('claude-flow analyze symbols src/ --type fn')} # Extract functions`);
1800
+ output.writeln(` ${output.dim('claude-flow analyze imports src/ --external')} # Only npm imports`);
1801
+ output.writeln();
1802
+ output.writeln(output.bold('Graph Analysis Examples:'));
1803
+ output.writeln();
1804
+ output.writeln(` ${output.dim('claude-flow analyze boundaries src/')} # Find natural code boundaries`);
1805
+ output.writeln(` ${output.dim('claude-flow analyze modules src/')} # Detect module communities`);
1806
+ output.writeln(` ${output.dim('claude-flow analyze dependencies -f dot src/')} # Export to DOT format`);
1807
+ output.writeln(` ${output.dim('claude-flow analyze circular src/')} # Find circular deps`);
1808
+ output.writeln();
1809
+ output.writeln(output.bold('Diff Analysis Examples:'));
1810
+ output.writeln();
1811
+ output.writeln(` ${output.dim('claude-flow analyze diff --risk')} # Risk assessment`);
1812
+ output.writeln(` ${output.dim('claude-flow analyze diff HEAD~1 --classify')} # Classify changes`);
1813
+ output.writeln(` ${output.dim('claude-flow analyze diff main..feature')} # Compare branches`);
1814
+ output.writeln();
1815
+ return { success: true };
1816
+ },
1817
+ };
1818
+ export default analyzeCommand;
1819
+ //# sourceMappingURL=analyze.js.map