@kodus/kodus-graph 0.2.8 → 0.2.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (171) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +252 -0
  3. package/dist/analysis/blast-radius.d.ts +2 -0
  4. package/dist/analysis/blast-radius.js +55 -0
  5. package/dist/analysis/communities.d.ts +28 -0
  6. package/dist/analysis/communities.js +100 -0
  7. package/dist/analysis/context-builder.d.ts +34 -0
  8. package/dist/analysis/context-builder.js +92 -0
  9. package/dist/analysis/diff.d.ts +41 -0
  10. package/dist/analysis/diff.js +155 -0
  11. package/dist/analysis/enrich.d.ts +5 -0
  12. package/dist/analysis/enrich.js +126 -0
  13. package/dist/analysis/flows.d.ts +27 -0
  14. package/dist/analysis/flows.js +86 -0
  15. package/dist/analysis/inheritance.d.ts +3 -0
  16. package/dist/analysis/inheritance.js +31 -0
  17. package/dist/analysis/prompt-formatter.d.ts +2 -0
  18. package/dist/analysis/prompt-formatter.js +173 -0
  19. package/dist/analysis/risk-score.d.ts +4 -0
  20. package/dist/analysis/risk-score.js +51 -0
  21. package/dist/analysis/search.d.ts +11 -0
  22. package/dist/analysis/search.js +64 -0
  23. package/dist/analysis/test-gaps.d.ts +2 -0
  24. package/dist/analysis/test-gaps.js +14 -0
  25. package/dist/cli.d.ts +2 -0
  26. package/dist/cli.js +210 -0
  27. package/dist/commands/analyze.d.ts +9 -0
  28. package/dist/commands/analyze.js +116 -0
  29. package/dist/commands/communities.d.ts +8 -0
  30. package/dist/commands/communities.js +9 -0
  31. package/dist/commands/context.d.ts +12 -0
  32. package/dist/commands/context.js +130 -0
  33. package/dist/commands/diff.d.ts +9 -0
  34. package/dist/commands/diff.js +89 -0
  35. package/dist/commands/flows.d.ts +8 -0
  36. package/dist/commands/flows.js +9 -0
  37. package/dist/commands/parse.d.ts +11 -0
  38. package/dist/commands/parse.js +101 -0
  39. package/dist/commands/search.d.ts +12 -0
  40. package/dist/commands/search.js +27 -0
  41. package/dist/commands/update.d.ts +7 -0
  42. package/dist/commands/update.js +154 -0
  43. package/dist/graph/builder.d.ts +6 -0
  44. package/dist/graph/builder.js +248 -0
  45. package/dist/graph/edges.d.ts +23 -0
  46. package/dist/graph/edges.js +159 -0
  47. package/dist/graph/json-writer.d.ts +9 -0
  48. package/dist/graph/json-writer.js +38 -0
  49. package/dist/graph/loader.d.ts +13 -0
  50. package/dist/graph/loader.js +101 -0
  51. package/dist/graph/merger.d.ts +7 -0
  52. package/dist/graph/merger.js +18 -0
  53. package/dist/graph/types.d.ts +252 -0
  54. package/dist/graph/types.js +1 -0
  55. package/dist/parser/batch.d.ts +5 -0
  56. package/dist/parser/batch.js +93 -0
  57. package/dist/parser/discovery.d.ts +7 -0
  58. package/dist/parser/discovery.js +61 -0
  59. package/dist/parser/extractor.d.ts +4 -0
  60. package/dist/parser/extractor.js +33 -0
  61. package/dist/parser/extractors/generic.d.ts +8 -0
  62. package/dist/parser/extractors/generic.js +471 -0
  63. package/dist/parser/extractors/python.d.ts +8 -0
  64. package/dist/parser/extractors/python.js +133 -0
  65. package/dist/parser/extractors/ruby.d.ts +8 -0
  66. package/dist/parser/extractors/ruby.js +153 -0
  67. package/dist/parser/extractors/typescript.d.ts +10 -0
  68. package/dist/parser/extractors/typescript.js +365 -0
  69. package/dist/parser/languages.d.ts +32 -0
  70. package/dist/parser/languages.js +304 -0
  71. package/dist/resolver/call-resolver.d.ts +36 -0
  72. package/dist/resolver/call-resolver.js +178 -0
  73. package/dist/resolver/external-detector.d.ts +11 -0
  74. package/dist/resolver/external-detector.js +820 -0
  75. package/dist/resolver/fs-cache.d.ts +8 -0
  76. package/dist/resolver/fs-cache.js +36 -0
  77. package/dist/resolver/import-map.d.ts +12 -0
  78. package/dist/resolver/import-map.js +21 -0
  79. package/dist/resolver/import-resolver.d.ts +19 -0
  80. package/dist/resolver/import-resolver.js +310 -0
  81. package/dist/resolver/languages/csharp.d.ts +3 -0
  82. package/dist/resolver/languages/csharp.js +94 -0
  83. package/dist/resolver/languages/go.d.ts +3 -0
  84. package/dist/resolver/languages/go.js +197 -0
  85. package/dist/resolver/languages/java.d.ts +1 -0
  86. package/dist/resolver/languages/java.js +193 -0
  87. package/dist/resolver/languages/php.d.ts +3 -0
  88. package/dist/resolver/languages/php.js +75 -0
  89. package/dist/resolver/languages/python.d.ts +11 -0
  90. package/dist/resolver/languages/python.js +127 -0
  91. package/dist/resolver/languages/ruby.d.ts +24 -0
  92. package/dist/resolver/languages/ruby.js +110 -0
  93. package/dist/resolver/languages/rust.d.ts +1 -0
  94. package/dist/resolver/languages/rust.js +197 -0
  95. package/dist/resolver/languages/typescript.d.ts +35 -0
  96. package/dist/resolver/languages/typescript.js +416 -0
  97. package/dist/resolver/re-export-resolver.d.ts +24 -0
  98. package/dist/resolver/re-export-resolver.js +57 -0
  99. package/dist/resolver/symbol-table.d.ts +17 -0
  100. package/dist/resolver/symbol-table.js +60 -0
  101. package/dist/shared/extract-calls.d.ts +26 -0
  102. package/dist/shared/extract-calls.js +57 -0
  103. package/dist/shared/file-hash.d.ts +3 -0
  104. package/dist/shared/file-hash.js +10 -0
  105. package/dist/shared/filters.d.ts +3 -0
  106. package/dist/shared/filters.js +240 -0
  107. package/dist/shared/logger.d.ts +6 -0
  108. package/dist/shared/logger.js +17 -0
  109. package/dist/shared/qualified-name.d.ts +1 -0
  110. package/dist/shared/qualified-name.js +9 -0
  111. package/dist/shared/safe-path.d.ts +6 -0
  112. package/dist/shared/safe-path.js +29 -0
  113. package/dist/shared/schemas.d.ts +43 -0
  114. package/dist/shared/schemas.js +30 -0
  115. package/dist/shared/temp.d.ts +11 -0
  116. package/{src/shared/temp.ts → dist/shared/temp.js} +4 -5
  117. package/package.json +20 -6
  118. package/src/analysis/blast-radius.ts +0 -54
  119. package/src/analysis/communities.ts +0 -135
  120. package/src/analysis/context-builder.ts +0 -130
  121. package/src/analysis/diff.ts +0 -169
  122. package/src/analysis/enrich.ts +0 -110
  123. package/src/analysis/flows.ts +0 -112
  124. package/src/analysis/inheritance.ts +0 -34
  125. package/src/analysis/prompt-formatter.ts +0 -175
  126. package/src/analysis/risk-score.ts +0 -62
  127. package/src/analysis/search.ts +0 -76
  128. package/src/analysis/test-gaps.ts +0 -21
  129. package/src/cli.ts +0 -210
  130. package/src/commands/analyze.ts +0 -128
  131. package/src/commands/communities.ts +0 -19
  132. package/src/commands/context.ts +0 -182
  133. package/src/commands/diff.ts +0 -96
  134. package/src/commands/flows.ts +0 -19
  135. package/src/commands/parse.ts +0 -124
  136. package/src/commands/search.ts +0 -41
  137. package/src/commands/update.ts +0 -166
  138. package/src/graph/builder.ts +0 -209
  139. package/src/graph/edges.ts +0 -101
  140. package/src/graph/json-writer.ts +0 -43
  141. package/src/graph/loader.ts +0 -113
  142. package/src/graph/merger.ts +0 -25
  143. package/src/graph/types.ts +0 -283
  144. package/src/parser/batch.ts +0 -82
  145. package/src/parser/discovery.ts +0 -75
  146. package/src/parser/extractor.ts +0 -37
  147. package/src/parser/extractors/generic.ts +0 -132
  148. package/src/parser/extractors/python.ts +0 -133
  149. package/src/parser/extractors/ruby.ts +0 -147
  150. package/src/parser/extractors/typescript.ts +0 -350
  151. package/src/parser/languages.ts +0 -122
  152. package/src/resolver/call-resolver.ts +0 -244
  153. package/src/resolver/import-map.ts +0 -27
  154. package/src/resolver/import-resolver.ts +0 -72
  155. package/src/resolver/languages/csharp.ts +0 -7
  156. package/src/resolver/languages/go.ts +0 -7
  157. package/src/resolver/languages/java.ts +0 -7
  158. package/src/resolver/languages/php.ts +0 -7
  159. package/src/resolver/languages/python.ts +0 -35
  160. package/src/resolver/languages/ruby.ts +0 -21
  161. package/src/resolver/languages/rust.ts +0 -7
  162. package/src/resolver/languages/typescript.ts +0 -168
  163. package/src/resolver/re-export-resolver.ts +0 -66
  164. package/src/resolver/symbol-table.ts +0 -67
  165. package/src/shared/extract-calls.ts +0 -75
  166. package/src/shared/file-hash.ts +0 -12
  167. package/src/shared/filters.ts +0 -243
  168. package/src/shared/logger.ts +0 -17
  169. package/src/shared/qualified-name.ts +0 -5
  170. package/src/shared/safe-path.ts +0 -31
  171. package/src/shared/schemas.ts +0 -32
@@ -1,175 +0,0 @@
1
- import type { ContextV2Output } from './context-builder';
2
-
3
- export function formatPrompt(output: ContextV2Output): string {
4
- const { analysis } = output;
5
- const lines: string[] = [];
6
-
7
- // Header
8
- const risk = analysis.risk;
9
- const br = analysis.blast_radius;
10
- const meta = analysis.metadata;
11
- lines.push('# Code Review Context');
12
- lines.push('');
13
- lines.push(
14
- `Risk: ${risk.level} (${risk.score}) | ${br.total_functions} functions impacted across ${br.total_files} files | ${meta.untested_count} untested`,
15
- );
16
- lines.push('');
17
-
18
- // Changed functions
19
- if (analysis.changed_functions.length > 0) {
20
- lines.push('## Changed Functions');
21
- lines.push('');
22
-
23
- for (const fn of analysis.changed_functions) {
24
- lines.push(`### ${fn.signature} [${fn.file_path}:${fn.line_start}-${fn.line_end}]`);
25
-
26
- // Status
27
- if (fn.is_new) {
28
- lines.push('Status: new');
29
- } else if (fn.diff_changes.length > 0) {
30
- lines.push(`Status: modified (${fn.diff_changes.join(', ')})`);
31
- } else {
32
- lines.push('Status: unchanged');
33
- }
34
-
35
- // Callers
36
- if (fn.callers.length > 0) {
37
- lines.push('Callers:');
38
- for (const c of fn.callers) {
39
- const conf = c.confidence < 0.85 ? ` confidence=${c.confidence.toFixed(2)}` : '';
40
- lines.push(` - ${c.name} [${c.file_path}:${c.line}]${conf}`);
41
- }
42
- } else {
43
- lines.push('Callers: none');
44
- }
45
-
46
- // Callees
47
- if (fn.callees.length > 0) {
48
- lines.push('Callees:');
49
- for (const c of fn.callees) {
50
- lines.push(` - ${c.signature} [${c.file_path}]`);
51
- }
52
- } else {
53
- lines.push('Callees: none');
54
- }
55
-
56
- // Test coverage
57
- lines.push(`Test coverage: ${fn.has_test_coverage ? 'yes' : 'no'}`);
58
-
59
- // Affected flows
60
- if (fn.in_flows.length > 0) {
61
- lines.push('Affected flows:');
62
- for (const ep of fn.in_flows) {
63
- const flow = analysis.affected_flows.find((f) => f.entry_point === ep);
64
- if (flow) {
65
- const prefix = flow.type === 'http' ? 'HTTP' : 'TEST';
66
- lines.push(` - ${prefix}: ${flow.path.map((q) => q.split('::').pop()).join(' → ')}`);
67
- } else {
68
- lines.push(` - ${ep.split('::').pop()}`);
69
- }
70
- }
71
- } else {
72
- lines.push('Affected flows: none');
73
- }
74
-
75
- lines.push('');
76
- }
77
- }
78
-
79
- // Inheritance
80
- if (analysis.inheritance.length > 0) {
81
- lines.push('## Inheritance');
82
- lines.push('');
83
- for (const entry of analysis.inheritance) {
84
- const name = entry.qualified_name.split('::').pop();
85
- const parts: string[] = [];
86
- if (entry.extends) parts.push(`extends ${entry.extends.split('::').pop()}`);
87
- if (entry.implements.length > 0)
88
- parts.push(`implements ${entry.implements.map((i) => i.split('::').pop()).join(', ')}`);
89
- lines.push(`- ${name} ${parts.join(', ')}`);
90
- if (entry.children.length > 0) {
91
- lines.push(` Children: ${entry.children.map((c) => c.split('::').pop()).join(', ')}`);
92
- }
93
- }
94
- lines.push('');
95
- }
96
-
97
- // Blast radius by depth
98
- const byDepth = analysis.blast_radius.by_depth;
99
- const depthKeys = Object.keys(byDepth).sort();
100
- if (depthKeys.length > 0) {
101
- lines.push('## Blast Radius');
102
- lines.push('');
103
- for (const depth of depthKeys) {
104
- const names = byDepth[depth].map((q) => q.split('::').pop());
105
- lines.push(`Depth ${depth}: ${names.join(', ')} (${names.length} functions)`);
106
- }
107
- lines.push('');
108
- }
109
-
110
- // Test gaps
111
- if (analysis.test_gaps.length > 0) {
112
- lines.push('## Test Gaps');
113
- lines.push('');
114
- for (const gap of analysis.test_gaps) {
115
- const name = gap.function.split('::').pop();
116
- lines.push(`- ${name} [${gap.file_path}:${gap.line_start}]`);
117
- }
118
- lines.push('');
119
- }
120
-
121
- // Structural diff
122
- const diff = analysis.structural_diff;
123
- const hasNodeChanges = diff.summary.added > 0 || diff.summary.removed > 0 || diff.summary.modified > 0;
124
- const hasEdgeChanges = diff.edges.added.length > 0 || diff.edges.removed.length > 0;
125
-
126
- if (hasNodeChanges || hasEdgeChanges) {
127
- lines.push('## Structural Changes');
128
- lines.push('');
129
-
130
- if (hasNodeChanges) {
131
- const parts: string[] = [];
132
- if (diff.summary.added > 0) parts.push(`${diff.summary.added} added`);
133
- if (diff.summary.removed > 0) parts.push(`${diff.summary.removed} removed`);
134
- if (diff.summary.modified > 0) parts.push(`${diff.summary.modified} modified`);
135
- lines.push(parts.join(', '));
136
- }
137
-
138
- if (diff.nodes.removed.length > 0) {
139
- lines.push('');
140
- lines.push('Removed:');
141
- for (const n of diff.nodes.removed) {
142
- const name = n.qualified_name.split('::').pop();
143
- lines.push(` - [${n.kind}] ${name} [${n.file_path}:${n.line_start}]`);
144
- }
145
- }
146
-
147
- if (diff.nodes.modified.length > 0) {
148
- lines.push('');
149
- lines.push('Modified:');
150
- for (const m of diff.nodes.modified) {
151
- const name = m.qualified_name.split('::').pop();
152
- lines.push(` - ${name} (${m.changes.join(', ')})`);
153
- }
154
- }
155
-
156
- if (hasEdgeChanges) {
157
- lines.push('');
158
- lines.push('Dependency changes:');
159
- for (const e of diff.edges.added) {
160
- const src = e.source_qualified.split('::').pop();
161
- const tgt = e.target_qualified.split('::').pop();
162
- lines.push(` + ${e.kind}: ${src} → ${tgt}`);
163
- }
164
- for (const e of diff.edges.removed) {
165
- const src = e.source_qualified.split('::').pop();
166
- const tgt = e.target_qualified.split('::').pop();
167
- lines.push(` - ${e.kind}: ${src} → ${tgt}`);
168
- }
169
- }
170
-
171
- lines.push('');
172
- }
173
-
174
- return lines.join('\n');
175
- }
@@ -1,62 +0,0 @@
1
- import type { BlastRadiusResult, GraphData, RiskScoreResult } from '../graph/types';
2
-
3
- export function computeRiskScore(
4
- graph: GraphData,
5
- changedFiles: string[],
6
- blastRadius: BlastRadiusResult,
7
- ): RiskScoreResult {
8
- const changedSet = new Set(changedFiles);
9
- const changedNodes = graph.nodes.filter((n) => changedSet.has(n.file_path) && !n.is_test);
10
-
11
- // Factor 1: Blast radius (0.35)
12
- const brValue = Math.min(blastRadius.total_functions / 20, 1); // cap at 20
13
-
14
- // Factor 2: Test gaps (0.30)
15
- const testedFiles = new Set(graph.edges.filter((e) => e.kind === 'TESTED_BY').map((e) => e.source_qualified));
16
- const changedFunctions = changedNodes.filter((n) => n.kind === 'Function' || n.kind === 'Method');
17
- const untestedCount = changedFunctions.filter((n) => !testedFiles.has(n.file_path)).length;
18
- const tgValue = changedFunctions.length > 0 ? untestedCount / changedFunctions.length : 0;
19
-
20
- // Factor 3: Complexity (0.20)
21
- const avgSize =
22
- changedNodes.length > 0
23
- ? changedNodes.reduce((s, n) => s + (n.line_end - n.line_start), 0) / changedNodes.length
24
- : 0;
25
- const cxValue = Math.min(avgSize / 50, 1); // cap at 50 lines
26
-
27
- // Factor 4: Inheritance (0.15)
28
- const hasInheritance = graph.edges.some(
29
- (e) => (e.kind === 'INHERITS' || e.kind === 'IMPLEMENTS') && changedSet.has(e.file_path),
30
- );
31
- const ihValue = hasInheritance ? 1 : 0;
32
-
33
- const score = brValue * 0.35 + tgValue * 0.3 + cxValue * 0.2 + ihValue * 0.15;
34
- const level = score >= 0.6 ? 'HIGH' : score >= 0.3 ? 'MEDIUM' : 'LOW';
35
-
36
- return {
37
- level,
38
- score: Math.round(score * 100) / 100,
39
- factors: {
40
- blast_radius: {
41
- weight: 0.35,
42
- value: Math.round(brValue * 100) / 100,
43
- detail: `${blastRadius.total_functions} functions, ${blastRadius.total_files} files`,
44
- },
45
- test_gaps: {
46
- weight: 0.3,
47
- value: Math.round(tgValue * 100) / 100,
48
- detail: `${untestedCount}/${changedFunctions.length} untested`,
49
- },
50
- complexity: {
51
- weight: 0.2,
52
- value: Math.round(cxValue * 100) / 100,
53
- detail: `avg ${Math.round(avgSize)} lines`,
54
- },
55
- inheritance: {
56
- weight: 0.15,
57
- value: ihValue,
58
- detail: hasInheritance ? 'has inheritance' : 'no inheritance',
59
- },
60
- },
61
- };
62
- }
@@ -1,76 +0,0 @@
1
- import type { IndexedGraph } from '../graph/loader';
2
- import type { GraphNode } from '../graph/types';
3
-
4
- export interface SearchOptions {
5
- query?: string;
6
- kind?: string;
7
- file?: string;
8
- limit?: number;
9
- }
10
-
11
- export function searchNodes(graph: IndexedGraph, opts: SearchOptions): GraphNode[] {
12
- const { query, kind, file, limit = 50 } = opts;
13
- let results = graph.nodes;
14
-
15
- if (query) {
16
- const matcher = buildMatcher(query);
17
- results = results.filter((n) => matcher(n.name) || matcher(n.qualified_name));
18
- }
19
-
20
- if (kind) {
21
- results = results.filter((n) => n.kind === kind);
22
- }
23
-
24
- if (file) {
25
- const fileMatcher = buildMatcher(file);
26
- results = results.filter((n) => fileMatcher(n.file_path));
27
- }
28
-
29
- results.sort((a, b) => a.file_path.localeCompare(b.file_path) || a.line_start - b.line_start);
30
-
31
- return results.slice(0, limit);
32
- }
33
-
34
- export function findCallers(graph: IndexedGraph, qualifiedName: string): GraphNode[] {
35
- const edges = graph.reverseAdjacency.get(qualifiedName) || [];
36
- const callers: GraphNode[] = [];
37
- for (const e of edges) {
38
- if (e.kind !== 'CALLS') continue;
39
- const node = graph.byQualified.get(e.source_qualified);
40
- if (node) callers.push(node);
41
- }
42
- return callers;
43
- }
44
-
45
- export function findCallees(graph: IndexedGraph, qualifiedName: string): GraphNode[] {
46
- const edges = graph.adjacency.get(qualifiedName) || [];
47
- const callees: GraphNode[] = [];
48
- for (const e of edges) {
49
- if (e.kind !== 'CALLS') continue;
50
- const node = graph.byQualified.get(e.target_qualified);
51
- if (node) callees.push(node);
52
- }
53
- return callees;
54
- }
55
-
56
- function buildMatcher(pattern: string): (text: string) => boolean {
57
- // Regex: /pattern/flags
58
- if (pattern.startsWith('/')) {
59
- const lastSlash = pattern.lastIndexOf('/');
60
- if (lastSlash > 0) {
61
- const regex = new RegExp(pattern.slice(1, lastSlash), pattern.slice(lastSlash + 1));
62
- return (text) => regex.test(text);
63
- }
64
- }
65
-
66
- // Glob: contains *
67
- if (pattern.includes('*')) {
68
- const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*');
69
- const regex = new RegExp(`^${escaped}$`, 'i');
70
- return (text) => regex.test(text);
71
- }
72
-
73
- // Substring (case-insensitive)
74
- const lower = pattern.toLowerCase();
75
- return (text) => text.toLowerCase().includes(lower);
76
- }
@@ -1,21 +0,0 @@
1
- import type { GraphData, TestGap } from '../graph/types';
2
-
3
- export function findTestGaps(graph: GraphData, changedFiles: string[]): TestGap[] {
4
- const changedSet = new Set(changedFiles);
5
-
6
- const testedFiles = new Set(graph.edges.filter((e) => e.kind === 'TESTED_BY').map((e) => e.source_qualified));
7
-
8
- return graph.nodes
9
- .filter(
10
- (n) =>
11
- changedSet.has(n.file_path) &&
12
- (n.kind === 'Function' || n.kind === 'Method') &&
13
- !n.is_test &&
14
- !testedFiles.has(n.file_path),
15
- )
16
- .map((n) => ({
17
- function: n.qualified_name,
18
- file_path: n.file_path,
19
- line_start: n.line_start,
20
- }));
21
- }
package/src/cli.ts DELETED
@@ -1,210 +0,0 @@
1
- #!/usr/bin/env bun
2
- import { Command } from 'commander';
3
- import { existsSync } from 'fs';
4
- import { resolve } from 'path';
5
- import { executeAnalyze } from './commands/analyze';
6
- import { executeCommunities } from './commands/communities';
7
- import { executeContext } from './commands/context';
8
- import { executeDiff } from './commands/diff';
9
- import { executeFlows } from './commands/flows';
10
- import { executeParse } from './commands/parse';
11
- import { executeSearch } from './commands/search';
12
- import { executeUpdate } from './commands/update';
13
-
14
- const program = new Command();
15
-
16
- import pkg from '../package.json';
17
- import { log } from './shared/logger';
18
-
19
- log.info(`kodus-graph v${pkg.version}`, { node: process.version, platform: process.platform });
20
- program.name('kodus-graph').description('Code graph builder for Kodus code review').version(pkg.version);
21
-
22
- program
23
- .command('parse')
24
- .description('Parse source files and generate nodes + edges')
25
- .option('--all', 'Parse all files in repo')
26
- .option('--files <paths...>', 'Parse specific files')
27
- .option('--repo-dir <path>', 'Repository root directory', '.')
28
- .option('--include <glob...>', 'Include only files matching glob (repeatable)')
29
- .option('--exclude <glob...>', 'Exclude files matching glob (repeatable)')
30
- .requiredOption('--out <path>', 'Output JSON file path')
31
- .action(async (opts) => {
32
- const repoDir = resolve(opts.repoDir);
33
- if (!existsSync(repoDir)) {
34
- process.stderr.write(`Error: --repo-dir does not exist: ${repoDir}\n`);
35
- process.exit(1);
36
- }
37
- await executeParse({
38
- repoDir: opts.repoDir,
39
- files: opts.files,
40
- all: opts.all ?? false,
41
- out: opts.out,
42
- include: opts.include,
43
- exclude: opts.exclude,
44
- });
45
- });
46
-
47
- program
48
- .command('analyze')
49
- .description('Compute blast radius, risk score, and test gaps')
50
- .requiredOption('--files <paths...>', 'Changed files to analyze')
51
- .option('--repo-dir <path>', 'Repository root directory', '.')
52
- .option('--graph <path>', 'Path to main graph JSON')
53
- .requiredOption('--out <path>', 'Output JSON file path')
54
- .action(async (opts) => {
55
- const repoDir = resolve(opts.repoDir);
56
- if (!existsSync(repoDir)) {
57
- process.stderr.write(`Error: --repo-dir does not exist: ${repoDir}\n`);
58
- process.exit(1);
59
- }
60
- await executeAnalyze({
61
- repoDir: opts.repoDir,
62
- files: opts.files,
63
- graph: opts.graph,
64
- out: opts.out,
65
- });
66
- });
67
-
68
- program
69
- .command('context')
70
- .description('Generate enriched review context for agents')
71
- .requiredOption('--files <paths...>', 'Changed files')
72
- .option('--repo-dir <path>', 'Repository root directory', '.')
73
- .option('--graph <path>', 'Path to main graph JSON')
74
- .requiredOption('--out <path>', 'Output JSON file path')
75
- .option('--min-confidence <n>', 'Minimum CALLS edge confidence', '0.5')
76
- .option('--max-depth <n>', 'Blast radius BFS depth', '3')
77
- .option('--format <type>', 'Output format: json or prompt', 'json')
78
- .action(async (opts) => {
79
- const repoDir = resolve(opts.repoDir);
80
- if (!existsSync(repoDir)) {
81
- process.stderr.write(`Error: --repo-dir does not exist: ${repoDir}\n`);
82
- process.exit(1);
83
- }
84
- if (opts.format !== 'json' && opts.format !== 'prompt') {
85
- process.stderr.write('Error: --format must be "json" or "prompt"\n');
86
- process.exit(1);
87
- }
88
- await executeContext({
89
- repoDir: opts.repoDir,
90
- files: opts.files,
91
- graph: opts.graph,
92
- out: opts.out,
93
- minConfidence: Number.parseFloat(opts.minConfidence),
94
- maxDepth: Number.parseInt(opts.maxDepth, 10),
95
- format: opts.format,
96
- });
97
- });
98
-
99
- program
100
- .command('diff')
101
- .description('Compare changed files against an existing graph')
102
- .option('--base <ref>', 'Git ref to diff against')
103
- .option('--files <paths...>', 'Explicit list of changed files')
104
- .option('--repo-dir <path>', 'Repository root directory', '.')
105
- .option('--graph <path>', 'Previous graph JSON', '.kodus-graph/graph.json')
106
- .requiredOption('--out <path>', 'Output JSON file path')
107
- .action(async (opts) => {
108
- if (!opts.base && !opts.files) {
109
- process.stderr.write('Error: one of --base or --files is required\n');
110
- process.exit(1);
111
- }
112
- const repoDir = resolve(opts.repoDir);
113
- if (!existsSync(repoDir)) {
114
- process.stderr.write(`Error: --repo-dir does not exist: ${repoDir}\n`);
115
- process.exit(1);
116
- }
117
- await executeDiff({
118
- repoDir: opts.repoDir,
119
- base: opts.base,
120
- files: opts.files,
121
- graph: opts.graph,
122
- out: opts.out,
123
- });
124
- });
125
-
126
- program
127
- .command('update')
128
- .description('Incrementally update graph (only re-parse changed files)')
129
- .option('--repo-dir <path>', 'Repository root directory', '.')
130
- .option('--graph <path>', 'Previous graph JSON (default: .kodus-graph/graph.json)')
131
- .option('--out <path>', 'Output path (default: same as --graph)')
132
- .action(async (opts) => {
133
- const repoDir = resolve(opts.repoDir);
134
- if (!existsSync(repoDir)) {
135
- process.stderr.write(`Error: --repo-dir does not exist: ${repoDir}\n`);
136
- process.exit(1);
137
- }
138
- await executeUpdate({
139
- repoDir: opts.repoDir,
140
- graph: opts.graph,
141
- out: opts.out,
142
- });
143
- });
144
-
145
- program
146
- .command('communities')
147
- .description('Detect module clusters and coupling between them')
148
- .requiredOption('--graph <path>', 'Path to graph JSON')
149
- .requiredOption('--out <path>', 'Output JSON file path')
150
- .option('--min-size <n>', 'Minimum nodes per community', '2')
151
- .option('--depth <n>', 'Directory grouping depth', '2')
152
- .action((opts) => {
153
- executeCommunities({
154
- graph: opts.graph,
155
- out: opts.out,
156
- minSize: parseInt(opts.minSize, 10),
157
- depth: parseInt(opts.depth, 10),
158
- });
159
- });
160
-
161
- program
162
- .command('flows')
163
- .description('Detect entry points and trace execution paths')
164
- .requiredOption('--graph <path>', 'Path to graph JSON')
165
- .requiredOption('--out <path>', 'Output JSON file path')
166
- .option('--max-depth <n>', 'Max BFS trace depth', '10')
167
- .option('--type <kind>', 'Filter: test, http, all', 'all')
168
- .action((opts) => {
169
- executeFlows({
170
- graph: opts.graph,
171
- out: opts.out,
172
- maxDepth: parseInt(opts.maxDepth, 10),
173
- type: opts.type as 'test' | 'http' | 'all',
174
- });
175
- });
176
-
177
- program
178
- .command('search')
179
- .description('Search the graph by name, kind, file, or relations')
180
- .requiredOption('--graph <path>', 'Path to graph JSON')
181
- .option('--query <pattern>', 'Search by name/qualified_name (glob or /regex/)')
182
- .option('--kind <type>', 'Filter by kind: Function, Method, Class, Interface, Enum, Test')
183
- .option('--file <pattern>', 'Filter by file path (glob)')
184
- .option('--callers-of <qualified>', 'Find callers of this node')
185
- .option('--callees-of <qualified>', 'Find callees of this node')
186
- .option('--limit <n>', 'Max results', '50')
187
- .option('--out <path>', 'Output file (default: stdout)')
188
- .action((opts) => {
189
- const modes = [opts.query, opts.callersOf, opts.calleesOf].filter(Boolean).length;
190
- if (modes === 0) {
191
- process.stderr.write('Error: one of --query, --callers-of, or --callees-of is required\n');
192
- process.exit(1);
193
- }
194
- if (modes > 1) {
195
- process.stderr.write('Error: --query, --callers-of, and --callees-of are mutually exclusive\n');
196
- process.exit(1);
197
- }
198
- executeSearch({
199
- graph: opts.graph,
200
- query: opts.query,
201
- kind: opts.kind,
202
- file: opts.file,
203
- callersOf: opts.callersOf,
204
- calleesOf: opts.calleesOf,
205
- limit: parseInt(opts.limit, 10),
206
- out: opts.out,
207
- });
208
- });
209
-
210
- program.parse();
@@ -1,128 +0,0 @@
1
- import { readFileSync, writeFileSync } from 'fs';
2
- import { resolve, relative } from 'path';
3
- import { computeBlastRadius } from '../analysis/blast-radius';
4
- import { computeRiskScore } from '../analysis/risk-score';
5
- import { findTestGaps } from '../analysis/test-gaps';
6
- import { buildGraphData } from '../graph/builder';
7
- import { mergeGraphs } from '../graph/merger';
8
- import type { AnalysisOutput, ImportEdge, MainGraphInput } from '../graph/types';
9
- import { parseBatch } from '../parser/batch';
10
- import { discoverFiles } from '../parser/discovery';
11
- import { resolveAllCalls } from '../resolver/call-resolver';
12
- import { createImportMap } from '../resolver/import-map';
13
- import { loadTsconfigAliases, resolveImport } from '../resolver/import-resolver';
14
- import { buildReExportMap } from '../resolver/re-export-resolver';
15
- import { createSymbolTable } from '../resolver/symbol-table';
16
- import { computeFileHash } from '../shared/file-hash';
17
- import { log } from '../shared/logger';
18
- import { GraphInputSchema } from '../shared/schemas';
19
-
20
- interface AnalyzeOptions {
21
- repoDir: string;
22
- files: string[];
23
- graph?: string;
24
- out: string;
25
- }
26
-
27
- export async function executeAnalyze(opts: AnalyzeOptions): Promise<void> {
28
- const repoDir = resolve(opts.repoDir);
29
-
30
- // Load main graph if provided
31
- let mainGraph: MainGraphInput | null = null;
32
- if (opts.graph) {
33
- let raw: unknown;
34
- try {
35
- raw = JSON.parse(readFileSync(opts.graph, 'utf-8'));
36
- } catch (_err) {
37
- process.stderr.write(`Error: Failed to read --graph file: ${opts.graph}\n`);
38
- process.exit(1);
39
- }
40
- const validated = GraphInputSchema.safeParse(raw);
41
- if (!validated.success) {
42
- process.stderr.write(`Error: Invalid graph JSON: ${validated.error.message}\n`);
43
- process.exit(1);
44
- }
45
- mainGraph = {
46
- repo_id: '',
47
- sha: '',
48
- nodes: validated.data.nodes,
49
- edges: validated.data.edges,
50
- };
51
- }
52
-
53
- // Parse changed files locally
54
- const localFiles = discoverFiles(repoDir, opts.files);
55
- const rawGraph = await parseBatch(localFiles, repoDir);
56
-
57
- // Resolve imports
58
- const tsconfigAliases = loadTsconfigAliases(repoDir);
59
- const symbolTable = createSymbolTable();
60
- const importMap = createImportMap();
61
- const importEdges: ImportEdge[] = [];
62
-
63
- for (const f of rawGraph.functions) symbolTable.add(f.file, f.name, f.qualified);
64
- for (const c of rawGraph.classes) symbolTable.add(c.file, c.name, c.qualified);
65
- for (const i of rawGraph.interfaces) symbolTable.add(i.file, i.name, i.qualified);
66
-
67
- // Pre-resolve re-exports so barrel imports follow through to actual definitions
68
- const barrelMap = buildReExportMap(rawGraph.reExports, repoDir, tsconfigAliases);
69
-
70
- for (const imp of rawGraph.imports) {
71
- const langKey = imp.lang === 'python' ? 'python' : imp.lang === 'ruby' ? 'ruby' : 'typescript';
72
- const resolved = resolveImport(resolve(repoDir, imp.file), imp.module, langKey, repoDir, tsconfigAliases);
73
- const resolvedRel = resolved ? relative(repoDir, resolved) : null;
74
- importEdges.push({
75
- source: imp.file,
76
- target: resolvedRel || imp.module,
77
- resolved: !!resolvedRel,
78
- line: imp.line,
79
- });
80
- const target = resolvedRel || imp.module;
81
- for (const name of imp.names) {
82
- let finalTarget = target;
83
- if (resolvedRel) {
84
- const reExportedFiles = barrelMap.get(resolvedRel);
85
- if (reExportedFiles) {
86
- for (const reFile of reExportedFiles) {
87
- if (symbolTable.lookupExact(reFile, name)) {
88
- finalTarget = reFile;
89
- break;
90
- }
91
- }
92
- }
93
- }
94
- importMap.add(imp.file, name, finalTarget);
95
- }
96
- }
97
-
98
- // Resolve calls
99
- const { callEdges } = resolveAllCalls(rawGraph.rawCalls, rawGraph.diMaps, symbolTable, importMap);
100
-
101
- // Build graph with file hashes
102
- const fileHashes = new Map<string, string>();
103
- for (const f of localFiles) {
104
- try {
105
- fileHashes.set(relative(repoDir, f), computeFileHash(f));
106
- } catch (err) {
107
- log.warn('Failed to compute file hash', { file: f, error: String(err) });
108
- }
109
- }
110
-
111
- const localGraphData = buildGraphData(rawGraph, callEdges, importEdges, repoDir, fileHashes);
112
-
113
- // Merge with main graph (or use local only)
114
- const mergedGraph = mainGraph ? mergeGraphs(mainGraph, localGraphData, opts.files) : localGraphData;
115
-
116
- // Analyze
117
- const blastRadius = computeBlastRadius(mergedGraph, opts.files);
118
- const riskScore = computeRiskScore(mergedGraph, opts.files, blastRadius);
119
- const testGaps = findTestGaps(mergedGraph, opts.files);
120
-
121
- const output: AnalysisOutput = {
122
- blast_radius: blastRadius,
123
- risk_score: riskScore,
124
- test_gaps: testGaps,
125
- };
126
-
127
- writeFileSync(opts.out, JSON.stringify(output, null, 2));
128
- }
@@ -1,19 +0,0 @@
1
- import { writeFileSync } from 'fs';
2
- import { detectCommunities } from '../analysis/communities';
3
- import { loadGraph } from '../graph/loader';
4
-
5
- interface CommunitiesCommandOptions {
6
- graph: string;
7
- out: string;
8
- minSize: number;
9
- depth: number;
10
- }
11
-
12
- export function executeCommunities(opts: CommunitiesCommandOptions): void {
13
- const graph = loadGraph(opts.graph);
14
- const result = detectCommunities(graph, { depth: opts.depth, minSize: opts.minSize });
15
- writeFileSync(opts.out, JSON.stringify(result, null, 2));
16
- process.stderr.write(
17
- `Communities: ${result.summary.total_communities} detected, avg cohesion ${result.summary.avg_cohesion}, ${result.summary.high_coupling_pairs} high-coupling pairs\n`,
18
- );
19
- }