@optave/codegraph 3.1.4 → 3.2.0

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 (210) hide show
  1. package/README.md +29 -72
  2. package/package.json +10 -8
  3. package/src/ast-analysis/engine.js +260 -246
  4. package/src/ast-analysis/shared.js +2 -14
  5. package/src/ast-analysis/visitors/cfg-visitor.js +635 -649
  6. package/src/ast-analysis/visitors/complexity-visitor.js +135 -139
  7. package/src/ast-analysis/visitors/dataflow-visitor.js +230 -224
  8. package/src/cli/commands/ast.js +4 -7
  9. package/src/cli/commands/audit.js +11 -11
  10. package/src/cli/commands/batch.js +6 -5
  11. package/src/cli/commands/branch-compare.js +1 -1
  12. package/src/cli/commands/brief.js +12 -0
  13. package/src/cli/commands/build.js +1 -1
  14. package/src/cli/commands/cfg.js +5 -8
  15. package/src/cli/commands/check.js +28 -36
  16. package/src/cli/commands/children.js +9 -7
  17. package/src/cli/commands/co-change.js +5 -3
  18. package/src/cli/commands/communities.js +2 -6
  19. package/src/cli/commands/complexity.js +5 -3
  20. package/src/cli/commands/context.js +9 -8
  21. package/src/cli/commands/cycles.js +12 -8
  22. package/src/cli/commands/dataflow.js +5 -8
  23. package/src/cli/commands/deps.js +9 -8
  24. package/src/cli/commands/diff-impact.js +2 -6
  25. package/src/cli/commands/embed.js +1 -1
  26. package/src/cli/commands/export.js +34 -31
  27. package/src/cli/commands/exports.js +2 -6
  28. package/src/cli/commands/flow.js +5 -8
  29. package/src/cli/commands/fn-impact.js +9 -8
  30. package/src/cli/commands/impact.js +2 -6
  31. package/src/cli/commands/info.js +2 -2
  32. package/src/cli/commands/map.js +1 -1
  33. package/src/cli/commands/mcp.js +1 -1
  34. package/src/cli/commands/models.js +1 -1
  35. package/src/cli/commands/owners.js +5 -3
  36. package/src/cli/commands/path.js +2 -2
  37. package/src/cli/commands/plot.js +40 -31
  38. package/src/cli/commands/query.js +9 -8
  39. package/src/cli/commands/registry.js +2 -2
  40. package/src/cli/commands/roles.js +5 -8
  41. package/src/cli/commands/search.js +9 -3
  42. package/src/cli/commands/sequence.js +5 -8
  43. package/src/cli/commands/snapshot.js +6 -1
  44. package/src/cli/commands/stats.js +1 -1
  45. package/src/cli/commands/structure.js +5 -4
  46. package/src/cli/commands/triage.js +41 -30
  47. package/src/cli/commands/watch.js +1 -1
  48. package/src/cli/commands/where.js +2 -6
  49. package/src/cli/index.js +11 -5
  50. package/src/cli/shared/open-graph.js +13 -0
  51. package/src/cli/shared/options.js +22 -2
  52. package/src/cli.js +1 -1
  53. package/src/db/connection.js +140 -11
  54. package/src/{db.js → db/index.js} +12 -5
  55. package/src/db/migrations.js +42 -65
  56. package/src/db/query-builder.js +72 -9
  57. package/src/db/repository/base.js +1 -1
  58. package/src/db/repository/graph-read.js +3 -3
  59. package/src/db/repository/in-memory-repository.js +30 -28
  60. package/src/db/repository/nodes.js +10 -17
  61. package/src/domain/analysis/brief.js +155 -0
  62. package/src/domain/analysis/context.js +392 -0
  63. package/src/domain/analysis/dependencies.js +395 -0
  64. package/src/{analysis → domain/analysis}/exports.js +11 -6
  65. package/src/domain/analysis/impact.js +581 -0
  66. package/src/domain/analysis/module-map.js +348 -0
  67. package/src/{analysis → domain/analysis}/roles.js +12 -9
  68. package/src/{analysis → domain/analysis}/symbol-lookup.js +19 -11
  69. package/src/{builder → domain/graph/builder}/helpers.js +4 -4
  70. package/src/{builder → domain/graph/builder}/incremental.js +119 -93
  71. package/src/domain/graph/builder/pipeline.js +156 -0
  72. package/src/domain/graph/builder/stages/build-edges.js +376 -0
  73. package/src/{builder → domain/graph/builder}/stages/build-structure.js +4 -4
  74. package/src/{builder → domain/graph/builder}/stages/collect-files.js +2 -2
  75. package/src/{builder → domain/graph/builder}/stages/detect-changes.js +204 -183
  76. package/src/{builder → domain/graph/builder}/stages/finalize.js +4 -4
  77. package/src/domain/graph/builder/stages/insert-nodes.js +203 -0
  78. package/src/{builder → domain/graph/builder}/stages/parse-files.js +2 -2
  79. package/src/{builder → domain/graph/builder}/stages/resolve-imports.js +1 -1
  80. package/src/{builder → domain/graph/builder}/stages/run-analyses.js +2 -2
  81. package/src/{change-journal.js → domain/graph/change-journal.js} +1 -1
  82. package/src/{cycles.js → domain/graph/cycles.js} +4 -4
  83. package/src/{journal.js → domain/graph/journal.js} +1 -1
  84. package/src/{resolve.js → domain/graph/resolve.js} +2 -2
  85. package/src/{watcher.js → domain/graph/watcher.js} +7 -7
  86. package/src/{parser.js → domain/parser.js} +24 -15
  87. package/src/{queries.js → domain/queries.js} +17 -16
  88. package/src/{embeddings → domain/search}/generator.js +3 -3
  89. package/src/{embeddings → domain/search}/models.js +2 -2
  90. package/src/{embeddings → domain/search}/search/cli-formatter.js +1 -1
  91. package/src/{embeddings → domain/search}/search/filters.js +9 -5
  92. package/src/{embeddings → domain/search}/search/hybrid.js +1 -1
  93. package/src/{embeddings → domain/search}/search/keyword.js +13 -6
  94. package/src/{embeddings → domain/search}/search/prepare.js +15 -7
  95. package/src/{embeddings → domain/search}/search/semantic.js +1 -1
  96. package/src/{embeddings → domain/search}/strategies/structured.js +1 -1
  97. package/src/extractors/csharp.js +224 -207
  98. package/src/extractors/go.js +176 -172
  99. package/src/extractors/hcl.js +94 -78
  100. package/src/extractors/java.js +213 -207
  101. package/src/extractors/javascript.js +275 -305
  102. package/src/extractors/php.js +234 -221
  103. package/src/extractors/python.js +252 -250
  104. package/src/extractors/ruby.js +192 -185
  105. package/src/extractors/rust.js +182 -167
  106. package/src/{ast.js → features/ast.js} +13 -11
  107. package/src/{audit.js → features/audit.js} +20 -46
  108. package/src/{batch.js → features/batch.js} +5 -5
  109. package/src/{boundaries.js → features/boundaries.js} +100 -85
  110. package/src/{branch-compare.js → features/branch-compare.js} +3 -3
  111. package/src/{cfg.js → features/cfg.js} +141 -150
  112. package/src/{check.js → features/check.js} +13 -30
  113. package/src/{cochange.js → features/cochange.js} +5 -5
  114. package/src/{communities.js → features/communities.js} +72 -57
  115. package/src/{complexity.js → features/complexity.js} +154 -143
  116. package/src/{dataflow.js → features/dataflow.js} +155 -158
  117. package/src/{export.js → features/export.js} +6 -6
  118. package/src/{flow.js → features/flow.js} +4 -4
  119. package/src/{viewer.js → features/graph-enrichment.js} +8 -8
  120. package/src/{manifesto.js → features/manifesto.js} +15 -12
  121. package/src/{owners.js → features/owners.js} +6 -5
  122. package/src/features/sequence.js +300 -0
  123. package/src/features/shared/find-nodes.js +31 -0
  124. package/src/{snapshot.js → features/snapshot.js} +3 -3
  125. package/src/{structure.js → features/structure.js} +139 -108
  126. package/src/features/triage.js +141 -0
  127. package/src/graph/builders/dependency.js +33 -14
  128. package/src/graph/classifiers/risk.js +3 -2
  129. package/src/graph/classifiers/roles.js +6 -3
  130. package/src/index.cjs +16 -0
  131. package/src/index.js +40 -39
  132. package/src/{native.js → infrastructure/native.js} +1 -1
  133. package/src/mcp/middleware.js +1 -1
  134. package/src/mcp/server.js +68 -59
  135. package/src/mcp/tool-registry.js +15 -2
  136. package/src/mcp/tools/ast-query.js +1 -1
  137. package/src/mcp/tools/audit.js +1 -1
  138. package/src/mcp/tools/batch-query.js +1 -1
  139. package/src/mcp/tools/branch-compare.js +3 -1
  140. package/src/mcp/tools/brief.js +8 -0
  141. package/src/mcp/tools/cfg.js +1 -1
  142. package/src/mcp/tools/check.js +3 -3
  143. package/src/mcp/tools/co-changes.js +1 -1
  144. package/src/mcp/tools/code-owners.js +1 -1
  145. package/src/mcp/tools/communities.js +1 -1
  146. package/src/mcp/tools/complexity.js +1 -1
  147. package/src/mcp/tools/dataflow.js +2 -2
  148. package/src/mcp/tools/execution-flow.js +2 -2
  149. package/src/mcp/tools/export-graph.js +2 -2
  150. package/src/mcp/tools/find-cycles.js +2 -2
  151. package/src/mcp/tools/index.js +2 -0
  152. package/src/mcp/tools/list-repos.js +1 -1
  153. package/src/mcp/tools/sequence.js +1 -1
  154. package/src/mcp/tools/structure.js +1 -1
  155. package/src/mcp/tools/triage.js +2 -2
  156. package/src/{commands → presentation}/audit.js +2 -2
  157. package/src/{commands → presentation}/batch.js +1 -1
  158. package/src/{commands → presentation}/branch-compare.js +2 -2
  159. package/src/presentation/brief.js +51 -0
  160. package/src/{commands → presentation}/cfg.js +1 -1
  161. package/src/{commands → presentation}/check.js +2 -2
  162. package/src/{commands → presentation}/communities.js +1 -1
  163. package/src/{commands → presentation}/complexity.js +1 -1
  164. package/src/{commands → presentation}/dataflow.js +1 -1
  165. package/src/{commands → presentation}/flow.js +2 -2
  166. package/src/{commands → presentation}/manifesto.js +1 -1
  167. package/src/{commands → presentation}/owners.js +1 -1
  168. package/src/presentation/queries-cli/exports.js +53 -0
  169. package/src/presentation/queries-cli/impact.js +214 -0
  170. package/src/presentation/queries-cli/index.js +5 -0
  171. package/src/presentation/queries-cli/inspect.js +329 -0
  172. package/src/presentation/queries-cli/overview.js +196 -0
  173. package/src/presentation/queries-cli/path.js +65 -0
  174. package/src/presentation/queries-cli.js +27 -0
  175. package/src/{commands → presentation}/query.js +1 -1
  176. package/src/presentation/result-formatter.js +126 -3
  177. package/src/{commands → presentation}/sequence.js +2 -2
  178. package/src/{commands → presentation}/structure.js +1 -1
  179. package/src/presentation/table.js +0 -8
  180. package/src/{commands → presentation}/triage.js +1 -1
  181. package/src/{constants.js → shared/constants.js} +1 -1
  182. package/src/shared/file-utils.js +2 -2
  183. package/src/shared/generators.js +9 -5
  184. package/src/shared/hierarchy.js +1 -1
  185. package/src/{kinds.js → shared/kinds.js} +1 -1
  186. package/src/analysis/context.js +0 -408
  187. package/src/analysis/dependencies.js +0 -341
  188. package/src/analysis/impact.js +0 -463
  189. package/src/analysis/module-map.js +0 -322
  190. package/src/builder/pipeline.js +0 -130
  191. package/src/builder/stages/build-edges.js +0 -297
  192. package/src/builder/stages/insert-nodes.js +0 -195
  193. package/src/mcp.js +0 -2
  194. package/src/queries-cli.js +0 -866
  195. package/src/sequence.js +0 -289
  196. package/src/triage.js +0 -126
  197. /package/src/{builder → domain/graph/builder}/context.js +0 -0
  198. /package/src/{builder.js → domain/graph/builder.js} +0 -0
  199. /package/src/{embeddings → domain/search}/index.js +0 -0
  200. /package/src/{embeddings → domain/search}/stores/fts5.js +0 -0
  201. /package/src/{embeddings → domain/search}/stores/sqlite-blob.js +0 -0
  202. /package/src/{embeddings → domain/search}/strategies/source.js +0 -0
  203. /package/src/{embeddings → domain/search}/strategies/text-utils.js +0 -0
  204. /package/src/{config.js → infrastructure/config.js} +0 -0
  205. /package/src/{logger.js → infrastructure/logger.js} +0 -0
  206. /package/src/{registry.js → infrastructure/registry.js} +0 -0
  207. /package/src/{update-check.js → infrastructure/update-check.js} +0 -0
  208. /package/src/{commands → presentation}/cochange.js +0 -0
  209. /package/src/{errors.js → shared/errors.js} +0 -0
  210. /package/src/{paginate.js → shared/paginate.js} +0 -0
@@ -1,463 +0,0 @@
1
- import { execFileSync } from 'node:child_process';
2
- import fs from 'node:fs';
3
- import path from 'node:path';
4
- import { evaluateBoundaries } from '../boundaries.js';
5
- import { coChangeForFiles } from '../cochange.js';
6
- import { loadConfig } from '../config.js';
7
- import {
8
- findDbPath,
9
- findDistinctCallers,
10
- findFileNodes,
11
- findImportDependents,
12
- findNodeById,
13
- openReadonlyOrFail,
14
- } from '../db.js';
15
- import { isTestFile } from '../infrastructure/test-filter.js';
16
- import { ownersForFiles } from '../owners.js';
17
- import { paginateResult } from '../paginate.js';
18
- import { normalizeSymbol } from '../shared/normalize.js';
19
- import { findMatchingNodes } from './symbol-lookup.js';
20
-
21
- export function impactAnalysisData(file, customDbPath, opts = {}) {
22
- const db = openReadonlyOrFail(customDbPath);
23
- try {
24
- const noTests = opts.noTests || false;
25
- const fileNodes = findFileNodes(db, `%${file}%`);
26
- if (fileNodes.length === 0) {
27
- return { file, sources: [], levels: {}, totalDependents: 0 };
28
- }
29
-
30
- const visited = new Set();
31
- const queue = [];
32
- const levels = new Map();
33
-
34
- for (const fn of fileNodes) {
35
- visited.add(fn.id);
36
- queue.push(fn.id);
37
- levels.set(fn.id, 0);
38
- }
39
-
40
- while (queue.length > 0) {
41
- const current = queue.shift();
42
- const level = levels.get(current);
43
- const dependents = findImportDependents(db, current);
44
- for (const dep of dependents) {
45
- if (!visited.has(dep.id) && (!noTests || !isTestFile(dep.file))) {
46
- visited.add(dep.id);
47
- queue.push(dep.id);
48
- levels.set(dep.id, level + 1);
49
- }
50
- }
51
- }
52
-
53
- const byLevel = {};
54
- for (const [id, level] of levels) {
55
- if (level === 0) continue;
56
- if (!byLevel[level]) byLevel[level] = [];
57
- const node = findNodeById(db, id);
58
- if (node) byLevel[level].push({ file: node.file });
59
- }
60
-
61
- return {
62
- file,
63
- sources: fileNodes.map((f) => f.file),
64
- levels: byLevel,
65
- totalDependents: visited.size - fileNodes.length,
66
- };
67
- } finally {
68
- db.close();
69
- }
70
- }
71
-
72
- export function fnImpactData(name, customDbPath, opts = {}) {
73
- const db = openReadonlyOrFail(customDbPath);
74
- try {
75
- const maxDepth = opts.depth || 5;
76
- const noTests = opts.noTests || false;
77
- const hc = new Map();
78
-
79
- const nodes = findMatchingNodes(db, name, { noTests, file: opts.file, kind: opts.kind });
80
- if (nodes.length === 0) {
81
- return { name, results: [] };
82
- }
83
-
84
- const results = nodes.map((node) => {
85
- const visited = new Set([node.id]);
86
- const levels = {};
87
- let frontier = [node.id];
88
-
89
- for (let d = 1; d <= maxDepth; d++) {
90
- const nextFrontier = [];
91
- for (const fid of frontier) {
92
- const callers = findDistinctCallers(db, fid);
93
- for (const c of callers) {
94
- if (!visited.has(c.id) && (!noTests || !isTestFile(c.file))) {
95
- visited.add(c.id);
96
- nextFrontier.push(c.id);
97
- if (!levels[d]) levels[d] = [];
98
- levels[d].push({ name: c.name, kind: c.kind, file: c.file, line: c.line });
99
- }
100
- }
101
- }
102
- frontier = nextFrontier;
103
- if (frontier.length === 0) break;
104
- }
105
-
106
- return {
107
- ...normalizeSymbol(node, db, hc),
108
- levels,
109
- totalDependents: visited.size - 1,
110
- };
111
- });
112
-
113
- const base = { name, results };
114
- return paginateResult(base, 'results', { limit: opts.limit, offset: opts.offset });
115
- } finally {
116
- db.close();
117
- }
118
- }
119
-
120
- /**
121
- * Fix #2: Shell injection vulnerability.
122
- * Uses execFileSync instead of execSync to prevent shell interpretation of user input.
123
- */
124
- export function diffImpactData(customDbPath, opts = {}) {
125
- const db = openReadonlyOrFail(customDbPath);
126
- try {
127
- const noTests = opts.noTests || false;
128
- const maxDepth = opts.depth || 3;
129
-
130
- const dbPath = findDbPath(customDbPath);
131
- const repoRoot = path.resolve(path.dirname(dbPath), '..');
132
-
133
- // Verify we're in a git repository before running git diff
134
- let checkDir = repoRoot;
135
- let isGitRepo = false;
136
- while (checkDir) {
137
- if (fs.existsSync(path.join(checkDir, '.git'))) {
138
- isGitRepo = true;
139
- break;
140
- }
141
- const parent = path.dirname(checkDir);
142
- if (parent === checkDir) break;
143
- checkDir = parent;
144
- }
145
- if (!isGitRepo) {
146
- return { error: `Not a git repository: ${repoRoot}` };
147
- }
148
-
149
- let diffOutput;
150
- try {
151
- const args = opts.staged
152
- ? ['diff', '--cached', '--unified=0', '--no-color']
153
- : ['diff', opts.ref || 'HEAD', '--unified=0', '--no-color'];
154
- diffOutput = execFileSync('git', args, {
155
- cwd: repoRoot,
156
- encoding: 'utf-8',
157
- maxBuffer: 10 * 1024 * 1024,
158
- stdio: ['pipe', 'pipe', 'pipe'],
159
- });
160
- } catch (e) {
161
- return { error: `Failed to run git diff: ${e.message}` };
162
- }
163
-
164
- if (!diffOutput.trim()) {
165
- return {
166
- changedFiles: 0,
167
- newFiles: [],
168
- affectedFunctions: [],
169
- affectedFiles: [],
170
- summary: null,
171
- };
172
- }
173
-
174
- const changedRanges = new Map();
175
- const newFiles = new Set();
176
- let currentFile = null;
177
- let prevIsDevNull = false;
178
- for (const line of diffOutput.split('\n')) {
179
- if (line.startsWith('--- /dev/null')) {
180
- prevIsDevNull = true;
181
- continue;
182
- }
183
- if (line.startsWith('--- ')) {
184
- prevIsDevNull = false;
185
- continue;
186
- }
187
- const fileMatch = line.match(/^\+\+\+ b\/(.+)/);
188
- if (fileMatch) {
189
- currentFile = fileMatch[1];
190
- if (!changedRanges.has(currentFile)) changedRanges.set(currentFile, []);
191
- if (prevIsDevNull) newFiles.add(currentFile);
192
- prevIsDevNull = false;
193
- continue;
194
- }
195
- const hunkMatch = line.match(/^@@ .+ \+(\d+)(?:,(\d+))? @@/);
196
- if (hunkMatch && currentFile) {
197
- const start = parseInt(hunkMatch[1], 10);
198
- const count = parseInt(hunkMatch[2] || '1', 10);
199
- changedRanges.get(currentFile).push({ start, end: start + count - 1 });
200
- }
201
- }
202
-
203
- if (changedRanges.size === 0) {
204
- return {
205
- changedFiles: 0,
206
- newFiles: [],
207
- affectedFunctions: [],
208
- affectedFiles: [],
209
- summary: null,
210
- };
211
- }
212
-
213
- const affectedFunctions = [];
214
- for (const [file, ranges] of changedRanges) {
215
- if (noTests && isTestFile(file)) continue;
216
- const defs = db
217
- .prepare(
218
- `SELECT * FROM nodes WHERE file = ? AND kind IN ('function', 'method', 'class') ORDER BY line`,
219
- )
220
- .all(file);
221
- for (let i = 0; i < defs.length; i++) {
222
- const def = defs[i];
223
- const endLine = def.end_line || (defs[i + 1] ? defs[i + 1].line - 1 : 999999);
224
- for (const range of ranges) {
225
- if (range.start <= endLine && range.end >= def.line) {
226
- affectedFunctions.push(def);
227
- break;
228
- }
229
- }
230
- }
231
- }
232
-
233
- const allAffected = new Set();
234
- const functionResults = affectedFunctions.map((fn) => {
235
- const visited = new Set([fn.id]);
236
- let frontier = [fn.id];
237
- let totalCallers = 0;
238
- const levels = {};
239
- const edges = [];
240
- const idToKey = new Map();
241
- idToKey.set(fn.id, `${fn.file}::${fn.name}:${fn.line}`);
242
- for (let d = 1; d <= maxDepth; d++) {
243
- const nextFrontier = [];
244
- for (const fid of frontier) {
245
- const callers = findDistinctCallers(db, fid);
246
- for (const c of callers) {
247
- if (!visited.has(c.id) && (!noTests || !isTestFile(c.file))) {
248
- visited.add(c.id);
249
- nextFrontier.push(c.id);
250
- allAffected.add(`${c.file}:${c.name}`);
251
- const callerKey = `${c.file}::${c.name}:${c.line}`;
252
- idToKey.set(c.id, callerKey);
253
- if (!levels[d]) levels[d] = [];
254
- levels[d].push({ name: c.name, kind: c.kind, file: c.file, line: c.line });
255
- edges.push({ from: idToKey.get(fid), to: callerKey });
256
- totalCallers++;
257
- }
258
- }
259
- }
260
- frontier = nextFrontier;
261
- if (frontier.length === 0) break;
262
- }
263
- return {
264
- name: fn.name,
265
- kind: fn.kind,
266
- file: fn.file,
267
- line: fn.line,
268
- transitiveCallers: totalCallers,
269
- levels,
270
- edges,
271
- };
272
- });
273
-
274
- const affectedFiles = new Set();
275
- for (const key of allAffected) affectedFiles.add(key.split(':')[0]);
276
-
277
- // Look up historically coupled files from co-change data
278
- let historicallyCoupled = [];
279
- try {
280
- db.prepare('SELECT 1 FROM co_changes LIMIT 1').get();
281
- const changedFilesList = [...changedRanges.keys()];
282
- const coResults = coChangeForFiles(changedFilesList, db, {
283
- minJaccard: 0.3,
284
- limit: 20,
285
- noTests,
286
- });
287
- // Exclude files already found via static analysis
288
- historicallyCoupled = coResults.filter((r) => !affectedFiles.has(r.file));
289
- } catch {
290
- /* co_changes table doesn't exist — skip silently */
291
- }
292
-
293
- // Look up CODEOWNERS for changed + affected files
294
- let ownership = null;
295
- try {
296
- const allFilePaths = [...new Set([...changedRanges.keys(), ...affectedFiles])];
297
- const ownerResult = ownersForFiles(allFilePaths, repoRoot);
298
- if (ownerResult.affectedOwners.length > 0) {
299
- ownership = {
300
- owners: Object.fromEntries(ownerResult.owners),
301
- affectedOwners: ownerResult.affectedOwners,
302
- suggestedReviewers: ownerResult.suggestedReviewers,
303
- };
304
- }
305
- } catch {
306
- /* CODEOWNERS missing or unreadable — skip silently */
307
- }
308
-
309
- // Check boundary violations scoped to changed files
310
- let boundaryViolations = [];
311
- let boundaryViolationCount = 0;
312
- try {
313
- const config = loadConfig(repoRoot);
314
- const boundaryConfig = config.manifesto?.boundaries;
315
- if (boundaryConfig) {
316
- const result = evaluateBoundaries(db, boundaryConfig, {
317
- scopeFiles: [...changedRanges.keys()],
318
- noTests,
319
- });
320
- boundaryViolations = result.violations;
321
- boundaryViolationCount = result.violationCount;
322
- }
323
- } catch {
324
- /* boundary check failed — skip silently */
325
- }
326
-
327
- const base = {
328
- changedFiles: changedRanges.size,
329
- newFiles: [...newFiles],
330
- affectedFunctions: functionResults,
331
- affectedFiles: [...affectedFiles],
332
- historicallyCoupled,
333
- ownership,
334
- boundaryViolations,
335
- boundaryViolationCount,
336
- summary: {
337
- functionsChanged: affectedFunctions.length,
338
- callersAffected: allAffected.size,
339
- filesAffected: affectedFiles.size,
340
- historicallyCoupledCount: historicallyCoupled.length,
341
- ownersAffected: ownership ? ownership.affectedOwners.length : 0,
342
- boundaryViolationCount,
343
- },
344
- };
345
- return paginateResult(base, 'affectedFunctions', { limit: opts.limit, offset: opts.offset });
346
- } finally {
347
- db.close();
348
- }
349
- }
350
-
351
- export function diffImpactMermaid(customDbPath, opts = {}) {
352
- const data = diffImpactData(customDbPath, opts);
353
- if (data.error) return data.error;
354
- if (data.changedFiles === 0 || data.affectedFunctions.length === 0) {
355
- return 'flowchart TB\n none["No impacted functions detected"]';
356
- }
357
-
358
- const newFileSet = new Set(data.newFiles || []);
359
- const lines = ['flowchart TB'];
360
-
361
- // Assign stable Mermaid node IDs
362
- let nodeCounter = 0;
363
- const nodeIdMap = new Map();
364
- const nodeLabels = new Map();
365
- function nodeId(key, label) {
366
- if (!nodeIdMap.has(key)) {
367
- nodeIdMap.set(key, `n${nodeCounter++}`);
368
- if (label) nodeLabels.set(key, label);
369
- }
370
- return nodeIdMap.get(key);
371
- }
372
-
373
- // Register all nodes (changed functions + their callers)
374
- for (const fn of data.affectedFunctions) {
375
- nodeId(`${fn.file}::${fn.name}:${fn.line}`, fn.name);
376
- for (const callers of Object.values(fn.levels || {})) {
377
- for (const c of callers) {
378
- nodeId(`${c.file}::${c.name}:${c.line}`, c.name);
379
- }
380
- }
381
- }
382
-
383
- // Collect all edges and determine blast radius
384
- const allEdges = new Set();
385
- const edgeFromNodes = new Set();
386
- const edgeToNodes = new Set();
387
- const changedKeys = new Set();
388
-
389
- for (const fn of data.affectedFunctions) {
390
- changedKeys.add(`${fn.file}::${fn.name}:${fn.line}`);
391
- for (const edge of fn.edges || []) {
392
- const edgeKey = `${edge.from}|${edge.to}`;
393
- if (!allEdges.has(edgeKey)) {
394
- allEdges.add(edgeKey);
395
- edgeFromNodes.add(edge.from);
396
- edgeToNodes.add(edge.to);
397
- }
398
- }
399
- }
400
-
401
- // Blast radius: caller nodes that are never a source (leaf nodes of the impact tree)
402
- const blastRadiusKeys = new Set();
403
- for (const key of edgeToNodes) {
404
- if (!edgeFromNodes.has(key) && !changedKeys.has(key)) {
405
- blastRadiusKeys.add(key);
406
- }
407
- }
408
-
409
- // Intermediate callers: not changed, not blast radius
410
- const intermediateKeys = new Set();
411
- for (const key of edgeToNodes) {
412
- if (!changedKeys.has(key) && !blastRadiusKeys.has(key)) {
413
- intermediateKeys.add(key);
414
- }
415
- }
416
-
417
- // Group changed functions by file
418
- const fileGroups = new Map();
419
- for (const fn of data.affectedFunctions) {
420
- if (!fileGroups.has(fn.file)) fileGroups.set(fn.file, []);
421
- fileGroups.get(fn.file).push(fn);
422
- }
423
-
424
- // Emit changed-file subgraphs
425
- let sgCounter = 0;
426
- for (const [file, fns] of fileGroups) {
427
- const isNew = newFileSet.has(file);
428
- const tag = isNew ? 'new' : 'modified';
429
- const sgId = `sg${sgCounter++}`;
430
- lines.push(` subgraph ${sgId}["${file} **(${tag})**"]`);
431
- for (const fn of fns) {
432
- const key = `${fn.file}::${fn.name}:${fn.line}`;
433
- lines.push(` ${nodeIdMap.get(key)}["${fn.name}"]`);
434
- }
435
- lines.push(' end');
436
- const style = isNew ? 'fill:#e8f5e9,stroke:#4caf50' : 'fill:#fff3e0,stroke:#ff9800';
437
- lines.push(` style ${sgId} ${style}`);
438
- }
439
-
440
- // Emit intermediate caller nodes (outside subgraphs)
441
- for (const key of intermediateKeys) {
442
- lines.push(` ${nodeIdMap.get(key)}["${nodeLabels.get(key)}"]`);
443
- }
444
-
445
- // Emit blast radius subgraph
446
- if (blastRadiusKeys.size > 0) {
447
- const sgId = `sg${sgCounter++}`;
448
- lines.push(` subgraph ${sgId}["Callers **(blast radius)**"]`);
449
- for (const key of blastRadiusKeys) {
450
- lines.push(` ${nodeIdMap.get(key)}["${nodeLabels.get(key)}"]`);
451
- }
452
- lines.push(' end');
453
- lines.push(` style ${sgId} fill:#f3e5f5,stroke:#9c27b0`);
454
- }
455
-
456
- // Emit edges (impact flows from changed fn toward callers)
457
- for (const edgeKey of allEdges) {
458
- const [from, to] = edgeKey.split('|');
459
- lines.push(` ${nodeIdMap.get(from)} --> ${nodeIdMap.get(to)}`);
460
- }
461
-
462
- return lines.join('\n');
463
- }