@optave/codegraph 3.1.3 → 3.1.5

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