@kodus/kodus-graph 0.2.7 → 0.2.9

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 (167) 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 +57 -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 +83 -0
  9. package/dist/analysis/diff.d.ts +35 -0
  10. package/dist/analysis/diff.js +140 -0
  11. package/dist/analysis/enrich.d.ts +5 -0
  12. package/dist/analysis/enrich.js +98 -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 +166 -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 +208 -0
  27. package/dist/commands/analyze.d.ts +9 -0
  28. package/dist/commands/analyze.js +114 -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 +10 -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 +2 -0
  44. package/dist/graph/builder.js +216 -0
  45. package/dist/graph/edges.d.ts +19 -0
  46. package/dist/graph/edges.js +105 -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 +249 -0
  54. package/dist/graph/types.js +1 -0
  55. package/dist/parser/batch.d.ts +4 -0
  56. package/dist/parser/batch.js +78 -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 +303 -0
  71. package/dist/resolver/call-resolver.d.ts +36 -0
  72. package/dist/resolver/call-resolver.js +178 -0
  73. package/dist/resolver/import-map.d.ts +12 -0
  74. package/dist/resolver/import-map.js +21 -0
  75. package/dist/resolver/import-resolver.d.ts +19 -0
  76. package/dist/resolver/import-resolver.js +212 -0
  77. package/dist/resolver/languages/csharp.d.ts +1 -0
  78. package/dist/resolver/languages/csharp.js +31 -0
  79. package/dist/resolver/languages/go.d.ts +3 -0
  80. package/dist/resolver/languages/go.js +196 -0
  81. package/dist/resolver/languages/java.d.ts +1 -0
  82. package/dist/resolver/languages/java.js +108 -0
  83. package/dist/resolver/languages/php.d.ts +3 -0
  84. package/dist/resolver/languages/php.js +54 -0
  85. package/dist/resolver/languages/python.d.ts +11 -0
  86. package/dist/resolver/languages/python.js +51 -0
  87. package/dist/resolver/languages/ruby.d.ts +9 -0
  88. package/dist/resolver/languages/ruby.js +59 -0
  89. package/dist/resolver/languages/rust.d.ts +1 -0
  90. package/dist/resolver/languages/rust.js +196 -0
  91. package/dist/resolver/languages/typescript.d.ts +27 -0
  92. package/dist/resolver/languages/typescript.js +240 -0
  93. package/dist/resolver/re-export-resolver.d.ts +24 -0
  94. package/dist/resolver/re-export-resolver.js +57 -0
  95. package/dist/resolver/symbol-table.d.ts +17 -0
  96. package/dist/resolver/symbol-table.js +60 -0
  97. package/dist/shared/extract-calls.d.ts +26 -0
  98. package/dist/shared/extract-calls.js +57 -0
  99. package/dist/shared/file-hash.d.ts +3 -0
  100. package/dist/shared/file-hash.js +10 -0
  101. package/dist/shared/filters.d.ts +3 -0
  102. package/dist/shared/filters.js +240 -0
  103. package/dist/shared/logger.d.ts +6 -0
  104. package/dist/shared/logger.js +17 -0
  105. package/dist/shared/qualified-name.d.ts +1 -0
  106. package/dist/shared/qualified-name.js +9 -0
  107. package/dist/shared/safe-path.d.ts +6 -0
  108. package/dist/shared/safe-path.js +29 -0
  109. package/dist/shared/schemas.d.ts +43 -0
  110. package/dist/shared/schemas.js +30 -0
  111. package/dist/shared/temp.d.ts +11 -0
  112. package/{src/shared/temp.ts → dist/shared/temp.js} +4 -5
  113. package/package.json +20 -6
  114. package/src/analysis/blast-radius.ts +0 -54
  115. package/src/analysis/communities.ts +0 -135
  116. package/src/analysis/context-builder.ts +0 -130
  117. package/src/analysis/diff.ts +0 -131
  118. package/src/analysis/enrich.ts +0 -110
  119. package/src/analysis/flows.ts +0 -112
  120. package/src/analysis/inheritance.ts +0 -34
  121. package/src/analysis/prompt-formatter.ts +0 -175
  122. package/src/analysis/risk-score.ts +0 -62
  123. package/src/analysis/search.ts +0 -76
  124. package/src/analysis/test-gaps.ts +0 -21
  125. package/src/cli.ts +0 -207
  126. package/src/commands/analyze.ts +0 -128
  127. package/src/commands/communities.ts +0 -19
  128. package/src/commands/context.ts +0 -139
  129. package/src/commands/diff.ts +0 -96
  130. package/src/commands/flows.ts +0 -19
  131. package/src/commands/parse.ts +0 -124
  132. package/src/commands/search.ts +0 -41
  133. package/src/commands/update.ts +0 -166
  134. package/src/graph/builder.ts +0 -209
  135. package/src/graph/edges.ts +0 -101
  136. package/src/graph/json-writer.ts +0 -43
  137. package/src/graph/loader.ts +0 -113
  138. package/src/graph/merger.ts +0 -25
  139. package/src/graph/types.ts +0 -283
  140. package/src/parser/batch.ts +0 -82
  141. package/src/parser/discovery.ts +0 -75
  142. package/src/parser/extractor.ts +0 -37
  143. package/src/parser/extractors/generic.ts +0 -132
  144. package/src/parser/extractors/python.ts +0 -133
  145. package/src/parser/extractors/ruby.ts +0 -147
  146. package/src/parser/extractors/typescript.ts +0 -350
  147. package/src/parser/languages.ts +0 -122
  148. package/src/resolver/call-resolver.ts +0 -244
  149. package/src/resolver/import-map.ts +0 -27
  150. package/src/resolver/import-resolver.ts +0 -72
  151. package/src/resolver/languages/csharp.ts +0 -7
  152. package/src/resolver/languages/go.ts +0 -7
  153. package/src/resolver/languages/java.ts +0 -7
  154. package/src/resolver/languages/php.ts +0 -7
  155. package/src/resolver/languages/python.ts +0 -35
  156. package/src/resolver/languages/ruby.ts +0 -21
  157. package/src/resolver/languages/rust.ts +0 -7
  158. package/src/resolver/languages/typescript.ts +0 -168
  159. package/src/resolver/re-export-resolver.ts +0 -66
  160. package/src/resolver/symbol-table.ts +0 -67
  161. package/src/shared/extract-calls.ts +0 -75
  162. package/src/shared/file-hash.ts +0 -12
  163. package/src/shared/filters.ts +0 -243
  164. package/src/shared/logger.ts +0 -14
  165. package/src/shared/qualified-name.ts +0 -5
  166. package/src/shared/safe-path.ts +0 -31
  167. package/src/shared/schemas.ts +0 -32
@@ -0,0 +1,140 @@
1
+ import { log } from '../shared/logger';
2
+ export function computeStructuralDiff(oldGraph, newNodes, newEdges, changedFiles) {
3
+ const changedSet = new Set(changedFiles);
4
+ // Old nodes in changed files
5
+ const oldNodesInChanged = new Map();
6
+ for (const n of oldGraph.nodes) {
7
+ if (changedSet.has(n.file_path)) {
8
+ oldNodesInChanged.set(n.qualified_name, n);
9
+ }
10
+ }
11
+ // New nodes in changed files
12
+ const newNodesMap = new Map();
13
+ for (const n of newNodes) {
14
+ if (changedSet.has(n.file_path)) {
15
+ newNodesMap.set(n.qualified_name, n);
16
+ }
17
+ }
18
+ log.debug('diff: input', {
19
+ oldNodesInChanged: oldNodesInChanged.size,
20
+ newNodesInChanged: newNodesMap.size,
21
+ changedFiles,
22
+ });
23
+ // Classify nodes
24
+ const added = [];
25
+ const removed = [];
26
+ const modified = [];
27
+ for (const [qn, n] of newNodesMap) {
28
+ if (!oldNodesInChanged.has(qn)) {
29
+ added.push({
30
+ qualified_name: qn,
31
+ kind: n.kind,
32
+ file_path: n.file_path,
33
+ line_start: n.line_start,
34
+ line_end: n.line_end,
35
+ });
36
+ }
37
+ }
38
+ for (const [qn, n] of oldNodesInChanged) {
39
+ if (!newNodesMap.has(qn)) {
40
+ removed.push({
41
+ qualified_name: qn,
42
+ kind: n.kind,
43
+ file_path: n.file_path,
44
+ line_start: n.line_start,
45
+ line_end: n.line_end,
46
+ });
47
+ }
48
+ else {
49
+ const newN = newNodesMap.get(qn);
50
+ const changes = [];
51
+ // Detect real content changes vs. pure displacement.
52
+ // content_hash = SHA256 of the node's source text (position-independent).
53
+ if (n.content_hash && newN.content_hash) {
54
+ // Definitive: hash comparison catches ALL content changes,
55
+ // even same-line-count edits (e.g. `return 1` → `return 2`).
56
+ if (n.content_hash !== newN.content_hash) {
57
+ changes.push('body');
58
+ log.debug('diff: body change detected', {
59
+ node: qn,
60
+ oldHash: n.content_hash.substring(0, 8),
61
+ newHash: newN.content_hash.substring(0, 8),
62
+ });
63
+ }
64
+ else {
65
+ log.debug('diff: hash match (displacement only)', {
66
+ node: qn,
67
+ oldLines: `${n.line_start}-${n.line_end}`,
68
+ newLines: `${newN.line_start}-${newN.line_end}`,
69
+ });
70
+ }
71
+ }
72
+ else if (n.line_start !== newN.line_start || n.line_end !== newN.line_end) {
73
+ // Fallback (legacy data without content_hash): size heuristic.
74
+ const oldSize = n.line_end - n.line_start;
75
+ const newSize = newN.line_end - newN.line_start;
76
+ if (oldSize !== newSize) {
77
+ changes.push('line_range');
78
+ log.debug('diff: line_range fallback (no content_hash)', {
79
+ node: qn,
80
+ hasOldHash: !!n.content_hash,
81
+ hasNewHash: !!newN.content_hash,
82
+ oldSize,
83
+ newSize,
84
+ });
85
+ }
86
+ }
87
+ if ((n.params || '') !== (newN.params || '')) {
88
+ changes.push('params');
89
+ }
90
+ if ((n.return_type || '') !== (newN.return_type || '')) {
91
+ changes.push('return_type');
92
+ }
93
+ if (changes.length > 0) {
94
+ modified.push({ qualified_name: qn, changes });
95
+ }
96
+ }
97
+ }
98
+ // Classify edges
99
+ const oldEdgesInChanged = oldGraph.edges.filter((e) => changedSet.has(e.file_path));
100
+ const oldEdgeKeys = new Set(oldEdgesInChanged.map((e) => `${e.kind}|${e.source_qualified}|${e.target_qualified}`));
101
+ const newEdgesInChanged = newEdges.filter((e) => changedSet.has(e.file_path));
102
+ const newEdgeKeys = new Set(newEdgesInChanged.map((e) => `${e.kind}|${e.source_qualified}|${e.target_qualified}`));
103
+ const addedEdges = newEdgesInChanged
104
+ .filter((e) => !oldEdgeKeys.has(`${e.kind}|${e.source_qualified}|${e.target_qualified}`))
105
+ .map((e) => ({ kind: e.kind, source_qualified: e.source_qualified, target_qualified: e.target_qualified }));
106
+ const removedEdges = oldEdgesInChanged
107
+ .filter((e) => !newEdgeKeys.has(`${e.kind}|${e.source_qualified}|${e.target_qualified}`))
108
+ .map((e) => ({ kind: e.kind, source_qualified: e.source_qualified, target_qualified: e.target_qualified }));
109
+ // Risk by file: count unique dependents via reverse adjacency
110
+ const riskByFile = {};
111
+ for (const file of changedFiles) {
112
+ const nodesInFile = oldGraph.byFile.get(file) || [];
113
+ const dependents = new Set();
114
+ for (const n of nodesInFile) {
115
+ for (const edge of oldGraph.reverseAdjacency.get(n.qualified_name) || []) {
116
+ if (!changedSet.has(edge.file_path)) {
117
+ dependents.add(edge.source_qualified);
118
+ }
119
+ }
120
+ }
121
+ const count = dependents.size;
122
+ const risk = count >= 10 ? 'HIGH' : count >= 3 ? 'MEDIUM' : 'LOW';
123
+ riskByFile[file] = { dependents: count, risk };
124
+ }
125
+ log.info('diff: result', {
126
+ added: added.length,
127
+ removed: removed.length,
128
+ modified: modified.length,
129
+ edgesAdded: addedEdges.length,
130
+ edgesRemoved: removedEdges.length,
131
+ modifiedDetails: modified.map((m) => `${m.qualified_name} [${m.changes.join(',')}]`),
132
+ });
133
+ return {
134
+ changed_files: changedFiles,
135
+ summary: { added: added.length, removed: removed.length, modified: modified.length },
136
+ nodes: { added, removed, modified },
137
+ edges: { added: addedEdges, removed: removedEdges },
138
+ risk_by_file: riskByFile,
139
+ };
140
+ }
@@ -0,0 +1,5 @@
1
+ import type { IndexedGraph } from '../graph/loader';
2
+ import type { EnrichedFunction } from '../graph/types';
3
+ import type { DiffResult } from './diff';
4
+ import type { Flow } from './flows';
5
+ export declare function enrichChangedFunctions(graph: IndexedGraph, changedFiles: string[], diff: DiffResult, allFlows: Flow[], minConfidence: number): EnrichedFunction[];
@@ -0,0 +1,98 @@
1
+ export function enrichChangedFunctions(graph, changedFiles, diff, allFlows, minConfidence) {
2
+ const changedSet = new Set(changedFiles);
3
+ // Pre-index diff results
4
+ const addedSet = new Set(diff.nodes.added.map((n) => n.qualified_name));
5
+ const modifiedMap = new Map(diff.nodes.modified.map((m) => [m.qualified_name, m.changes]));
6
+ // Pre-index TESTED_BY
7
+ const testedFiles = new Set(graph.edges.filter((e) => e.kind === 'TESTED_BY').map((e) => e.source_qualified));
8
+ // Pre-index flows by function
9
+ const flowsByFunction = new Map();
10
+ for (const flow of allFlows) {
11
+ for (const qn of flow.path) {
12
+ const list = flowsByFunction.get(qn);
13
+ if (list) {
14
+ if (!list.includes(flow.entry_point)) {
15
+ list.push(flow.entry_point);
16
+ }
17
+ }
18
+ else {
19
+ flowsByFunction.set(qn, [flow.entry_point]);
20
+ }
21
+ }
22
+ }
23
+ // Filter functions in changed files
24
+ const changedFunctions = graph.nodes.filter((n) => changedSet.has(n.file_path) &&
25
+ !n.is_test &&
26
+ n.kind !== 'Constructor' &&
27
+ n.kind !== 'Class' &&
28
+ n.kind !== 'Interface' &&
29
+ n.kind !== 'Enum');
30
+ return changedFunctions
31
+ .sort((a, b) => a.file_path.localeCompare(b.file_path) || a.line_start - b.line_start)
32
+ .map((node) => {
33
+ // Callers
34
+ const callers = [];
35
+ for (const edge of graph.reverseAdjacency.get(node.qualified_name) || []) {
36
+ if (edge.kind !== 'CALLS') {
37
+ continue;
38
+ }
39
+ // null/undefined confidence = high confidence (edge came from DB or parser without scoring)
40
+ if ((edge.confidence ?? 1.0) < minConfidence) {
41
+ continue;
42
+ }
43
+ const sourceNode = graph.byQualified.get(edge.source_qualified);
44
+ callers.push({
45
+ qualified_name: edge.source_qualified,
46
+ name: sourceNode?.name || edge.source_qualified.split('::').pop() || 'unknown',
47
+ file_path: sourceNode?.file_path || edge.file_path,
48
+ line: edge.line,
49
+ confidence: edge.confidence ?? 1.0,
50
+ });
51
+ }
52
+ // Callees
53
+ const callees = [];
54
+ const seenCallees = new Set();
55
+ for (const edge of graph.adjacency.get(node.qualified_name) || []) {
56
+ if (edge.kind !== 'CALLS') {
57
+ continue;
58
+ }
59
+ if (seenCallees.has(edge.target_qualified)) {
60
+ continue;
61
+ }
62
+ seenCallees.add(edge.target_qualified);
63
+ const targetNode = graph.byQualified.get(edge.target_qualified);
64
+ const name = targetNode?.name || edge.target_qualified.split('::').pop() || 'unknown';
65
+ const params = targetNode?.params && targetNode.params !== '()' ? targetNode.params : '';
66
+ const ret = targetNode?.return_type ? ` -> ${targetNode.return_type}` : '';
67
+ callees.push({
68
+ qualified_name: edge.target_qualified,
69
+ name,
70
+ file_path: targetNode?.file_path || '',
71
+ signature: `${name}${params}${ret}`,
72
+ });
73
+ }
74
+ // Signature
75
+ const shortName = node.name.includes('.') ? node.name.split('.').pop() : node.name;
76
+ const params = node.params && node.params !== '()' ? node.params : '';
77
+ const ret = node.return_type ? ` -> ${node.return_type}` : '';
78
+ const signature = `${shortName}${params}${ret}`;
79
+ // Diff
80
+ const isNew = addedSet.has(node.qualified_name);
81
+ const diffChanges = isNew ? [] : modifiedMap.get(node.qualified_name) || [];
82
+ return {
83
+ qualified_name: node.qualified_name,
84
+ name: node.name,
85
+ kind: node.kind,
86
+ signature,
87
+ file_path: node.file_path,
88
+ line_start: node.line_start,
89
+ line_end: node.line_end,
90
+ callers,
91
+ callees,
92
+ has_test_coverage: testedFiles.has(node.file_path),
93
+ diff_changes: diffChanges,
94
+ is_new: isNew,
95
+ in_flows: flowsByFunction.get(node.qualified_name) || [],
96
+ };
97
+ });
98
+ }
@@ -0,0 +1,27 @@
1
+ import type { IndexedGraph } from '../graph/loader';
2
+ export interface FlowOptions {
3
+ maxDepth: number;
4
+ type: 'test' | 'http' | 'all';
5
+ }
6
+ export interface Flow {
7
+ entry_point: string;
8
+ type: 'test' | 'http';
9
+ depth: number;
10
+ node_count: number;
11
+ file_count: number;
12
+ criticality: number;
13
+ path: string[];
14
+ }
15
+ export interface FlowsResult {
16
+ flows: Flow[];
17
+ summary: {
18
+ total_flows: number;
19
+ by_type: {
20
+ test: number;
21
+ http: number;
22
+ };
23
+ avg_depth: number;
24
+ max_criticality: number;
25
+ };
26
+ }
27
+ export declare function detectFlows(graph: IndexedGraph, opts: FlowOptions): FlowsResult;
@@ -0,0 +1,86 @@
1
+ const HTTP_METHOD_NAMES = new Set(['get', 'post', 'put', 'delete', 'patch', 'handle', 'handler']);
2
+ function isHttpHandler(_qualifiedName, name, parentName) {
3
+ if (HTTP_METHOD_NAMES.has(name.toLowerCase())) {
4
+ return true;
5
+ }
6
+ if (parentName?.toLowerCase().endsWith('controller')) {
7
+ return true;
8
+ }
9
+ return false;
10
+ }
11
+ export function detectFlows(graph, opts) {
12
+ const { maxDepth, type } = opts;
13
+ // Find entry points
14
+ const entryPoints = [];
15
+ for (const node of graph.nodes) {
16
+ if (type !== 'http' && node.kind === 'Test') {
17
+ entryPoints.push({ qualified: node.qualified_name, type: 'test' });
18
+ }
19
+ if (type !== 'test' && (node.kind === 'Method' || node.kind === 'Function')) {
20
+ if (isHttpHandler(node.qualified_name, node.name, node.parent_name)) {
21
+ entryPoints.push({ qualified: node.qualified_name, type: 'http' });
22
+ }
23
+ }
24
+ }
25
+ // BFS for each entry point
26
+ const flows = [];
27
+ for (const ep of entryPoints) {
28
+ const path = [ep.qualified];
29
+ const visited = new Set([ep.qualified]);
30
+ const files = new Set();
31
+ const startNode = graph.byQualified.get(ep.qualified);
32
+ if (startNode) {
33
+ files.add(startNode.file_path);
34
+ }
35
+ let frontier = [ep.qualified];
36
+ let depth = 0;
37
+ while (frontier.length > 0 && depth < maxDepth) {
38
+ const next = [];
39
+ for (const q of frontier) {
40
+ for (const edge of graph.adjacency.get(q) || []) {
41
+ if (edge.kind !== 'CALLS') {
42
+ continue;
43
+ }
44
+ if (visited.has(edge.target_qualified)) {
45
+ continue;
46
+ }
47
+ visited.add(edge.target_qualified);
48
+ next.push(edge.target_qualified);
49
+ path.push(edge.target_qualified);
50
+ const targetNode = graph.byQualified.get(edge.target_qualified);
51
+ if (targetNode) {
52
+ files.add(targetNode.file_path);
53
+ }
54
+ }
55
+ }
56
+ if (next.length === 0) {
57
+ break;
58
+ }
59
+ frontier = next;
60
+ depth++;
61
+ }
62
+ flows.push({
63
+ entry_point: ep.qualified,
64
+ type: ep.type,
65
+ depth,
66
+ node_count: visited.size,
67
+ file_count: files.size,
68
+ criticality: visited.size * files.size,
69
+ path,
70
+ });
71
+ }
72
+ flows.sort((a, b) => b.criticality - a.criticality);
73
+ const testFlows = flows.filter((f) => f.type === 'test').length;
74
+ const httpFlows = flows.filter((f) => f.type === 'http').length;
75
+ const avgDepth = flows.length > 0 ? Math.round((flows.reduce((s, f) => s + f.depth, 0) / flows.length) * 10) / 10 : 0;
76
+ const maxCriticality = flows.length > 0 ? flows[0].criticality : 0;
77
+ return {
78
+ flows,
79
+ summary: {
80
+ total_flows: flows.length,
81
+ by_type: { test: testFlows, http: httpFlows },
82
+ avg_depth: avgDepth,
83
+ max_criticality: maxCriticality,
84
+ },
85
+ };
86
+ }
@@ -0,0 +1,3 @@
1
+ import type { IndexedGraph } from '../graph/loader';
2
+ import type { InheritanceEntry } from '../graph/types';
3
+ export declare function extractInheritance(graph: IndexedGraph, changedFiles: string[]): InheritanceEntry[];
@@ -0,0 +1,31 @@
1
+ export function extractInheritance(graph, changedFiles) {
2
+ const changedSet = new Set(changedFiles);
3
+ const entries = [];
4
+ const changedClasses = graph.nodes.filter((n) => changedSet.has(n.file_path) && n.kind === 'Class');
5
+ for (const cls of changedClasses) {
6
+ let extendsClass;
7
+ const implementsList = [];
8
+ const children = [];
9
+ for (const edge of graph.adjacency.get(cls.qualified_name) || []) {
10
+ if (edge.kind === 'INHERITS') {
11
+ extendsClass = edge.target_qualified;
12
+ }
13
+ if (edge.kind === 'IMPLEMENTS') {
14
+ implementsList.push(edge.target_qualified);
15
+ }
16
+ }
17
+ for (const edge of graph.reverseAdjacency.get(cls.qualified_name) || []) {
18
+ if (edge.kind === 'INHERITS') {
19
+ children.push(edge.source_qualified);
20
+ }
21
+ }
22
+ entries.push({
23
+ qualified_name: cls.qualified_name,
24
+ file_path: cls.file_path,
25
+ extends: extendsClass,
26
+ implements: implementsList,
27
+ children,
28
+ });
29
+ }
30
+ return entries;
31
+ }
@@ -0,0 +1,2 @@
1
+ import type { ContextV2Output } from './context-builder';
2
+ export declare function formatPrompt(output: ContextV2Output): string;
@@ -0,0 +1,166 @@
1
+ export function formatPrompt(output) {
2
+ const { analysis } = output;
3
+ const lines = [];
4
+ // Header
5
+ const risk = analysis.risk;
6
+ const br = analysis.blast_radius;
7
+ const meta = analysis.metadata;
8
+ lines.push('# Code Review Context');
9
+ lines.push('');
10
+ lines.push(`Risk: ${risk.level} (${risk.score}) | ${br.total_functions} functions impacted across ${br.total_files} files | ${meta.untested_count} untested`);
11
+ lines.push('');
12
+ // Changed functions
13
+ if (analysis.changed_functions.length > 0) {
14
+ lines.push('## Changed Functions');
15
+ lines.push('');
16
+ for (const fn of analysis.changed_functions) {
17
+ lines.push(`### ${fn.signature} [${fn.file_path}:${fn.line_start}-${fn.line_end}]`);
18
+ // Status
19
+ if (fn.is_new) {
20
+ lines.push('Status: new');
21
+ }
22
+ else if (fn.diff_changes.length > 0) {
23
+ lines.push(`Status: modified (${fn.diff_changes.join(', ')})`);
24
+ }
25
+ else {
26
+ lines.push('Status: unchanged');
27
+ }
28
+ // Callers
29
+ if (fn.callers.length > 0) {
30
+ lines.push('Callers:');
31
+ for (const c of fn.callers) {
32
+ const conf = c.confidence < 0.85 ? ` confidence=${c.confidence.toFixed(2)}` : '';
33
+ lines.push(` - ${c.name} [${c.file_path}:${c.line}]${conf}`);
34
+ }
35
+ }
36
+ else {
37
+ lines.push('Callers: none');
38
+ }
39
+ // Callees
40
+ if (fn.callees.length > 0) {
41
+ lines.push('Callees:');
42
+ for (const c of fn.callees) {
43
+ lines.push(` - ${c.signature} [${c.file_path}]`);
44
+ }
45
+ }
46
+ else {
47
+ lines.push('Callees: none');
48
+ }
49
+ // Test coverage
50
+ lines.push(`Test coverage: ${fn.has_test_coverage ? 'yes' : 'no'}`);
51
+ // Affected flows
52
+ if (fn.in_flows.length > 0) {
53
+ lines.push('Affected flows:');
54
+ for (const ep of fn.in_flows) {
55
+ const flow = analysis.affected_flows.find((f) => f.entry_point === ep);
56
+ if (flow) {
57
+ const prefix = flow.type === 'http' ? 'HTTP' : 'TEST';
58
+ lines.push(` - ${prefix}: ${flow.path.map((q) => q.split('::').pop()).join(' → ')}`);
59
+ }
60
+ else {
61
+ lines.push(` - ${ep.split('::').pop()}`);
62
+ }
63
+ }
64
+ }
65
+ else {
66
+ lines.push('Affected flows: none');
67
+ }
68
+ lines.push('');
69
+ }
70
+ }
71
+ // Inheritance
72
+ if (analysis.inheritance.length > 0) {
73
+ lines.push('## Inheritance');
74
+ lines.push('');
75
+ for (const entry of analysis.inheritance) {
76
+ const name = entry.qualified_name.split('::').pop();
77
+ const parts = [];
78
+ if (entry.extends) {
79
+ parts.push(`extends ${entry.extends.split('::').pop()}`);
80
+ }
81
+ if (entry.implements.length > 0) {
82
+ parts.push(`implements ${entry.implements.map((i) => i.split('::').pop()).join(', ')}`);
83
+ }
84
+ lines.push(`- ${name} ${parts.join(', ')}`);
85
+ if (entry.children.length > 0) {
86
+ lines.push(` Children: ${entry.children.map((c) => c.split('::').pop()).join(', ')}`);
87
+ }
88
+ }
89
+ lines.push('');
90
+ }
91
+ // Blast radius by depth
92
+ const byDepth = analysis.blast_radius.by_depth;
93
+ const depthKeys = Object.keys(byDepth).sort();
94
+ if (depthKeys.length > 0) {
95
+ lines.push('## Blast Radius');
96
+ lines.push('');
97
+ for (const depth of depthKeys) {
98
+ const names = byDepth[depth].map((q) => q.split('::').pop());
99
+ lines.push(`Depth ${depth}: ${names.join(', ')} (${names.length} functions)`);
100
+ }
101
+ lines.push('');
102
+ }
103
+ // Test gaps
104
+ if (analysis.test_gaps.length > 0) {
105
+ lines.push('## Test Gaps');
106
+ lines.push('');
107
+ for (const gap of analysis.test_gaps) {
108
+ const name = gap.function.split('::').pop();
109
+ lines.push(`- ${name} [${gap.file_path}:${gap.line_start}]`);
110
+ }
111
+ lines.push('');
112
+ }
113
+ // Structural diff
114
+ const diff = analysis.structural_diff;
115
+ const hasNodeChanges = diff.summary.added > 0 || diff.summary.removed > 0 || diff.summary.modified > 0;
116
+ const hasEdgeChanges = diff.edges.added.length > 0 || diff.edges.removed.length > 0;
117
+ if (hasNodeChanges || hasEdgeChanges) {
118
+ lines.push('## Structural Changes');
119
+ lines.push('');
120
+ if (hasNodeChanges) {
121
+ const parts = [];
122
+ if (diff.summary.added > 0) {
123
+ parts.push(`${diff.summary.added} added`);
124
+ }
125
+ if (diff.summary.removed > 0) {
126
+ parts.push(`${diff.summary.removed} removed`);
127
+ }
128
+ if (diff.summary.modified > 0) {
129
+ parts.push(`${diff.summary.modified} modified`);
130
+ }
131
+ lines.push(parts.join(', '));
132
+ }
133
+ if (diff.nodes.removed.length > 0) {
134
+ lines.push('');
135
+ lines.push('Removed:');
136
+ for (const n of diff.nodes.removed) {
137
+ const name = n.qualified_name.split('::').pop();
138
+ lines.push(` - [${n.kind}] ${name} [${n.file_path}:${n.line_start}]`);
139
+ }
140
+ }
141
+ if (diff.nodes.modified.length > 0) {
142
+ lines.push('');
143
+ lines.push('Modified:');
144
+ for (const m of diff.nodes.modified) {
145
+ const name = m.qualified_name.split('::').pop();
146
+ lines.push(` - ${name} (${m.changes.join(', ')})`);
147
+ }
148
+ }
149
+ if (hasEdgeChanges) {
150
+ lines.push('');
151
+ lines.push('Dependency changes:');
152
+ for (const e of diff.edges.added) {
153
+ const src = e.source_qualified.split('::').pop();
154
+ const tgt = e.target_qualified.split('::').pop();
155
+ lines.push(` + ${e.kind}: ${src} → ${tgt}`);
156
+ }
157
+ for (const e of diff.edges.removed) {
158
+ const src = e.source_qualified.split('::').pop();
159
+ const tgt = e.target_qualified.split('::').pop();
160
+ lines.push(` - ${e.kind}: ${src} → ${tgt}`);
161
+ }
162
+ }
163
+ lines.push('');
164
+ }
165
+ return lines.join('\n');
166
+ }
@@ -0,0 +1,4 @@
1
+ import type { BlastRadiusResult, GraphData, RiskScoreResult } from '../graph/types';
2
+ export declare function computeRiskScore(graph: GraphData, changedFiles: string[], blastRadius: BlastRadiusResult, options?: {
3
+ skipTests?: boolean;
4
+ }): RiskScoreResult;
@@ -0,0 +1,51 @@
1
+ export function computeRiskScore(graph, changedFiles, blastRadius, options) {
2
+ const changedSet = new Set(changedFiles);
3
+ const changedNodes = graph.nodes.filter((n) => changedSet.has(n.file_path) && !n.is_test);
4
+ // Factor 1: Blast radius (0.35)
5
+ const brValue = Math.min(blastRadius.total_functions / 20, 1); // cap at 20
6
+ // Factor 2: Test gaps (0.30) — skipped when test detection is disabled
7
+ let tgValue = 0;
8
+ let untestedCount = 0;
9
+ const changedFunctions = changedNodes.filter((n) => n.kind === 'Function' || n.kind === 'Method');
10
+ if (!options?.skipTests) {
11
+ const testedFiles = new Set(graph.edges.filter((e) => e.kind === 'TESTED_BY').map((e) => e.source_qualified));
12
+ untestedCount = changedFunctions.filter((n) => !testedFiles.has(n.file_path)).length;
13
+ tgValue = changedFunctions.length > 0 ? untestedCount / changedFunctions.length : 0;
14
+ }
15
+ // Factor 3: Complexity (0.20)
16
+ const avgSize = changedNodes.length > 0
17
+ ? changedNodes.reduce((s, n) => s + (n.line_end - n.line_start), 0) / changedNodes.length
18
+ : 0;
19
+ const cxValue = Math.min(avgSize / 50, 1); // cap at 50 lines
20
+ // Factor 4: Inheritance (0.15)
21
+ const hasInheritance = graph.edges.some((e) => (e.kind === 'INHERITS' || e.kind === 'IMPLEMENTS') && changedSet.has(e.file_path));
22
+ const ihValue = hasInheritance ? 1 : 0;
23
+ const score = brValue * 0.35 + tgValue * 0.3 + cxValue * 0.2 + ihValue * 0.15;
24
+ const level = score >= 0.6 ? 'HIGH' : score >= 0.3 ? 'MEDIUM' : 'LOW';
25
+ return {
26
+ level,
27
+ score: Math.round(score * 100) / 100,
28
+ factors: {
29
+ blast_radius: {
30
+ weight: 0.35,
31
+ value: Math.round(brValue * 100) / 100,
32
+ detail: `${blastRadius.total_functions} functions, ${blastRadius.total_files} files`,
33
+ },
34
+ test_gaps: {
35
+ weight: 0.3,
36
+ value: Math.round(tgValue * 100) / 100,
37
+ detail: `${untestedCount}/${changedFunctions.length} untested`,
38
+ },
39
+ complexity: {
40
+ weight: 0.2,
41
+ value: Math.round(cxValue * 100) / 100,
42
+ detail: `avg ${Math.round(avgSize)} lines`,
43
+ },
44
+ inheritance: {
45
+ weight: 0.15,
46
+ value: ihValue,
47
+ detail: hasInheritance ? 'has inheritance' : 'no inheritance',
48
+ },
49
+ },
50
+ };
51
+ }
@@ -0,0 +1,11 @@
1
+ import type { IndexedGraph } from '../graph/loader';
2
+ import type { GraphNode } from '../graph/types';
3
+ export interface SearchOptions {
4
+ query?: string;
5
+ kind?: string;
6
+ file?: string;
7
+ limit?: number;
8
+ }
9
+ export declare function searchNodes(graph: IndexedGraph, opts: SearchOptions): GraphNode[];
10
+ export declare function findCallers(graph: IndexedGraph, qualifiedName: string): GraphNode[];
11
+ export declare function findCallees(graph: IndexedGraph, qualifiedName: string): GraphNode[];