@esankhan3/anvil-knowledge-core 0.1.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 (126) hide show
  1. package/README.md +194 -0
  2. package/dist/__tests__/chunker.test.d.ts +10 -0
  3. package/dist/__tests__/chunker.test.d.ts.map +1 -0
  4. package/dist/__tests__/chunker.test.js +161 -0
  5. package/dist/__tests__/chunker.test.js.map +1 -0
  6. package/dist/__tests__/query-classifier.test.d.ts +5 -0
  7. package/dist/__tests__/query-classifier.test.d.ts.map +1 -0
  8. package/dist/__tests__/query-classifier.test.js +158 -0
  9. package/dist/__tests__/query-classifier.test.js.map +1 -0
  10. package/dist/__tests__/retriever-defaults.test.d.ts +12 -0
  11. package/dist/__tests__/retriever-defaults.test.d.ts.map +1 -0
  12. package/dist/__tests__/retriever-defaults.test.js +37 -0
  13. package/dist/__tests__/retriever-defaults.test.js.map +1 -0
  14. package/dist/__tests__/structural-hasher.test.d.ts +5 -0
  15. package/dist/__tests__/structural-hasher.test.d.ts.map +1 -0
  16. package/dist/__tests__/structural-hasher.test.js +185 -0
  17. package/dist/__tests__/structural-hasher.test.js.map +1 -0
  18. package/dist/ast-graph-builder.d.ts +38 -0
  19. package/dist/ast-graph-builder.d.ts.map +1 -0
  20. package/dist/ast-graph-builder.js +1041 -0
  21. package/dist/ast-graph-builder.js.map +1 -0
  22. package/dist/chunker.d.ts +47 -0
  23. package/dist/chunker.d.ts.map +1 -0
  24. package/dist/chunker.js +428 -0
  25. package/dist/chunker.js.map +1 -0
  26. package/dist/claude-runner.d.ts +10 -0
  27. package/dist/claude-runner.d.ts.map +1 -0
  28. package/dist/claude-runner.js +10 -0
  29. package/dist/claude-runner.js.map +1 -0
  30. package/dist/config.d.ts +36 -0
  31. package/dist/config.d.ts.map +1 -0
  32. package/dist/config.js +83 -0
  33. package/dist/config.js.map +1 -0
  34. package/dist/cross-repo-detector.d.ts +7 -0
  35. package/dist/cross-repo-detector.d.ts.map +1 -0
  36. package/dist/cross-repo-detector.js +990 -0
  37. package/dist/cross-repo-detector.js.map +1 -0
  38. package/dist/embedder.d.ts +84 -0
  39. package/dist/embedder.d.ts.map +1 -0
  40. package/dist/embedder.js +378 -0
  41. package/dist/embedder.js.map +1 -0
  42. package/dist/file-walker.d.ts +18 -0
  43. package/dist/file-walker.d.ts.map +1 -0
  44. package/dist/file-walker.js +221 -0
  45. package/dist/file-walker.js.map +1 -0
  46. package/dist/git-diff.d.ts +32 -0
  47. package/dist/git-diff.d.ts.map +1 -0
  48. package/dist/git-diff.js +145 -0
  49. package/dist/git-diff.js.map +1 -0
  50. package/dist/graph-metrics.d.ts +31 -0
  51. package/dist/graph-metrics.d.ts.map +1 -0
  52. package/dist/graph-metrics.js +277 -0
  53. package/dist/graph-metrics.js.map +1 -0
  54. package/dist/graph-query.d.ts +8 -0
  55. package/dist/graph-query.d.ts.map +1 -0
  56. package/dist/graph-query.js +79 -0
  57. package/dist/graph-query.js.map +1 -0
  58. package/dist/index.d.ts +27 -0
  59. package/dist/index.d.ts.map +1 -0
  60. package/dist/index.js +43 -0
  61. package/dist/index.js.map +1 -0
  62. package/dist/indexer.d.ts +98 -0
  63. package/dist/indexer.d.ts.map +1 -0
  64. package/dist/indexer.js +635 -0
  65. package/dist/indexer.js.map +1 -0
  66. package/dist/project-graph-builder-core.d.ts +48 -0
  67. package/dist/project-graph-builder-core.d.ts.map +1 -0
  68. package/dist/project-graph-builder-core.js +213 -0
  69. package/dist/project-graph-builder-core.js.map +1 -0
  70. package/dist/project-graph-builder.d.ts +39 -0
  71. package/dist/project-graph-builder.d.ts.map +1 -0
  72. package/dist/project-graph-builder.js +640 -0
  73. package/dist/project-graph-builder.js.map +1 -0
  74. package/dist/query-classifier.d.ts +38 -0
  75. package/dist/query-classifier.d.ts.map +1 -0
  76. package/dist/query-classifier.js +199 -0
  77. package/dist/query-classifier.js.map +1 -0
  78. package/dist/query-router.d.ts +82 -0
  79. package/dist/query-router.d.ts.map +1 -0
  80. package/dist/query-router.js +278 -0
  81. package/dist/query-router.js.map +1 -0
  82. package/dist/rag-evaluator.d.ts +53 -0
  83. package/dist/rag-evaluator.d.ts.map +1 -0
  84. package/dist/rag-evaluator.js +217 -0
  85. package/dist/rag-evaluator.js.map +1 -0
  86. package/dist/repo-profiler.d.ts +62 -0
  87. package/dist/repo-profiler.d.ts.map +1 -0
  88. package/dist/repo-profiler.js +488 -0
  89. package/dist/repo-profiler.js.map +1 -0
  90. package/dist/reranker.d.ts +8 -0
  91. package/dist/reranker.d.ts.map +1 -0
  92. package/dist/reranker.js +250 -0
  93. package/dist/reranker.js.map +1 -0
  94. package/dist/retriever.d.ts +42 -0
  95. package/dist/retriever.d.ts.map +1 -0
  96. package/dist/retriever.js +320 -0
  97. package/dist/retriever.js.map +1 -0
  98. package/dist/semantic-edge-detector.d.ts +28 -0
  99. package/dist/semantic-edge-detector.d.ts.map +1 -0
  100. package/dist/semantic-edge-detector.js +191 -0
  101. package/dist/semantic-edge-detector.js.map +1 -0
  102. package/dist/service-mesh-inferrer.d.ts +57 -0
  103. package/dist/service-mesh-inferrer.d.ts.map +1 -0
  104. package/dist/service-mesh-inferrer.js +322 -0
  105. package/dist/service-mesh-inferrer.js.map +1 -0
  106. package/dist/structural-hasher.d.ts +57 -0
  107. package/dist/structural-hasher.d.ts.map +1 -0
  108. package/dist/structural-hasher.js +350 -0
  109. package/dist/structural-hasher.js.map +1 -0
  110. package/dist/tree-sitter-parser.d.ts +71 -0
  111. package/dist/tree-sitter-parser.d.ts.map +1 -0
  112. package/dist/tree-sitter-parser.js +633 -0
  113. package/dist/tree-sitter-parser.js.map +1 -0
  114. package/dist/types.d.ts +179 -0
  115. package/dist/types.d.ts.map +1 -0
  116. package/dist/types.js +2 -0
  117. package/dist/types.js.map +1 -0
  118. package/dist/vector-store.d.ts +56 -0
  119. package/dist/vector-store.d.ts.map +1 -0
  120. package/dist/vector-store.js +299 -0
  121. package/dist/vector-store.js.map +1 -0
  122. package/dist/workspace-detector.d.ts +11 -0
  123. package/dist/workspace-detector.d.ts.map +1 -0
  124. package/dist/workspace-detector.js +587 -0
  125. package/dist/workspace-detector.js.map +1 -0
  126. package/package.json +41 -0
@@ -0,0 +1,990 @@
1
+ import { readFileSync, readdirSync, statSync } from 'node:fs';
2
+ import { join, extname } from 'node:path';
3
+ import { detectWorkspace } from './workspace-detector.js';
4
+ /** Recursively find files matching a predicate, skipping common non-source dirs */
5
+ function walkFiles(dir, match, maxFiles = 5000) {
6
+ const results = [];
7
+ const skipDirs = new Set(['node_modules', 'dist', '.git', '.next', 'build', 'coverage', '__pycache__', '.venv', 'vendor']);
8
+ function walk(currentDir) {
9
+ if (results.length >= maxFiles)
10
+ return;
11
+ let entries;
12
+ try {
13
+ entries = readdirSync(currentDir);
14
+ }
15
+ catch {
16
+ return;
17
+ }
18
+ for (const entry of entries) {
19
+ if (results.length >= maxFiles)
20
+ return;
21
+ if (skipDirs.has(entry))
22
+ continue;
23
+ const fullPath = join(currentDir, entry);
24
+ try {
25
+ const stat = statSync(fullPath);
26
+ if (stat.isDirectory()) {
27
+ walk(fullPath);
28
+ }
29
+ else if (stat.isFile() && match(fullPath)) {
30
+ results.push(fullPath);
31
+ }
32
+ }
33
+ catch {
34
+ // Skip inaccessible files
35
+ }
36
+ }
37
+ }
38
+ walk(dir);
39
+ return results;
40
+ }
41
+ /** Read file contents safely, returning empty string on failure */
42
+ function safeReadFile(filePath) {
43
+ try {
44
+ return readFileSync(filePath, 'utf-8');
45
+ }
46
+ catch {
47
+ return '';
48
+ }
49
+ }
50
+ // ---------------------------------------------------------------------------
51
+ // Strategy 1: Shared npm dependencies
52
+ // ---------------------------------------------------------------------------
53
+ function detectSharedNpmDeps(repos) {
54
+ const edges = [];
55
+ const repoDeps = new Map();
56
+ for (const repo of repos) {
57
+ const pkgPath = join(repo.path, 'package.json');
58
+ const content = safeReadFile(pkgPath);
59
+ if (!content)
60
+ continue;
61
+ try {
62
+ const pkg = JSON.parse(content);
63
+ const allDeps = new Set([
64
+ ...Object.keys(pkg.dependencies ?? {}),
65
+ ...Object.keys(pkg.devDependencies ?? {}),
66
+ ...Object.keys(pkg.peerDependencies ?? {}),
67
+ ]);
68
+ // Filter to scoped/workspace packages (likely internal)
69
+ const orgDeps = new Set([...allDeps].filter(d => d.startsWith('@')));
70
+ repoDeps.set(repo.name, orgDeps);
71
+ }
72
+ catch {
73
+ // Malformed package.json
74
+ }
75
+ }
76
+ const repoNames = [...repoDeps.keys()];
77
+ for (let i = 0; i < repoNames.length; i++) {
78
+ for (let j = i + 1; j < repoNames.length; j++) {
79
+ const nameA = repoNames[i];
80
+ const nameB = repoNames[j];
81
+ const depsA = repoDeps.get(nameA);
82
+ const depsB = repoDeps.get(nameB);
83
+ for (const dep of depsA) {
84
+ if (depsB.has(dep)) {
85
+ edges.push({
86
+ sourceRepo: nameA,
87
+ sourceNode: `package.json::${dep}`,
88
+ targetRepo: nameB,
89
+ targetNode: `package.json::${dep}`,
90
+ edgeType: 'npm-dep',
91
+ evidence: `Shared scoped dependency: ${dep}`,
92
+ confidence: 0.7,
93
+ });
94
+ }
95
+ }
96
+ }
97
+ }
98
+ return edges;
99
+ }
100
+ // ---------------------------------------------------------------------------
101
+ // Strategy 2: Shared TypeScript types
102
+ // ---------------------------------------------------------------------------
103
+ function detectSharedTypes(repos) {
104
+ const edges = [];
105
+ const typeExportPattern = /export\s+(?:interface|type)\s+(\w+)/g;
106
+ const repoTypes = new Map(); // repo -> typeName -> filePath
107
+ for (const repo of repos) {
108
+ const tsFiles = walkFiles(repo.path, (f) => {
109
+ const ext = extname(f);
110
+ return ext === '.ts' || ext === '.d.ts';
111
+ }, 2000);
112
+ const typeMap = new Map();
113
+ for (const filePath of tsFiles) {
114
+ const content = safeReadFile(filePath);
115
+ let match;
116
+ typeExportPattern.lastIndex = 0;
117
+ while ((match = typeExportPattern.exec(content)) !== null) {
118
+ const typeName = match[1];
119
+ if (!typeMap.has(typeName)) {
120
+ typeMap.set(typeName, filePath);
121
+ }
122
+ }
123
+ }
124
+ repoTypes.set(repo.name, typeMap);
125
+ }
126
+ const repoNames = [...repoTypes.keys()];
127
+ for (let i = 0; i < repoNames.length; i++) {
128
+ for (let j = i + 1; j < repoNames.length; j++) {
129
+ const nameA = repoNames[i];
130
+ const nameB = repoNames[j];
131
+ const typesA = repoTypes.get(nameA);
132
+ const typesB = repoTypes.get(nameB);
133
+ for (const [typeName, fileA] of typesA) {
134
+ const fileB = typesB.get(typeName);
135
+ if (fileB) {
136
+ edges.push({
137
+ sourceRepo: nameA,
138
+ sourceNode: `${fileA}::${typeName}`,
139
+ targetRepo: nameB,
140
+ targetNode: `${fileB}::${typeName}`,
141
+ edgeType: 'shared-type',
142
+ evidence: `Shared type: ${typeName}`,
143
+ confidence: 0.9,
144
+ });
145
+ }
146
+ }
147
+ }
148
+ }
149
+ return edges;
150
+ }
151
+ // ---------------------------------------------------------------------------
152
+ // Strategy 3: Environment variable correlation
153
+ // ---------------------------------------------------------------------------
154
+ function detectEnvVarCorrelation(repos) {
155
+ const edges = [];
156
+ const envFileNames = ['.env.example', '.env.template', '.env.sample'];
157
+ const envVarPattern = /^([A-Z][A-Z0-9_]{2,})=/gm;
158
+ const repoEnvVars = new Map();
159
+ for (const repo of repos) {
160
+ const vars = new Set();
161
+ for (const envFile of envFileNames) {
162
+ const content = safeReadFile(join(repo.path, envFile));
163
+ if (!content)
164
+ continue;
165
+ let match;
166
+ envVarPattern.lastIndex = 0;
167
+ while ((match = envVarPattern.exec(content)) !== null) {
168
+ vars.add(match[1]);
169
+ }
170
+ }
171
+ if (vars.size > 0) {
172
+ repoEnvVars.set(repo.name, vars);
173
+ }
174
+ }
175
+ const repoNames = [...repoEnvVars.keys()];
176
+ for (let i = 0; i < repoNames.length; i++) {
177
+ for (let j = i + 1; j < repoNames.length; j++) {
178
+ const nameA = repoNames[i];
179
+ const nameB = repoNames[j];
180
+ const varsA = repoEnvVars.get(nameA);
181
+ const varsB = repoEnvVars.get(nameB);
182
+ for (const v of varsA) {
183
+ if (varsB.has(v)) {
184
+ edges.push({
185
+ sourceRepo: nameA,
186
+ sourceNode: `env::${v}`,
187
+ targetRepo: nameB,
188
+ targetNode: `env::${v}`,
189
+ edgeType: 'env-var',
190
+ evidence: `Shared env var: ${v}`,
191
+ confidence: 0.6,
192
+ });
193
+ }
194
+ }
195
+ }
196
+ }
197
+ return edges;
198
+ }
199
+ // ---------------------------------------------------------------------------
200
+ // Strategy 4: Event schema detection (topics, channels, events in constants)
201
+ // ---------------------------------------------------------------------------
202
+ function detectEventSchemas(repos) {
203
+ const edges = [];
204
+ // Match patterns like: TOPIC = 'user.created', channel: 'orders', event: 'payment_completed'
205
+ const eventPatterns = [
206
+ /(?:topic|TOPIC|channel|CHANNEL|event|EVENT)\s*[:=]\s*['"`]([a-zA-Z0-9._-]+)['"`]/g,
207
+ /(?:subscribe|publish|emit|on)\s*\(\s*['"`]([a-zA-Z0-9._-]+)['"`]/g,
208
+ ];
209
+ const repoEvents = new Map(); // repo -> eventName -> filePath
210
+ for (const repo of repos) {
211
+ const sourceFiles = walkFiles(repo.path, (f) => {
212
+ const ext = extname(f);
213
+ return ['.ts', '.js', '.py', '.go', '.java'].includes(ext);
214
+ }, 3000);
215
+ const eventMap = new Map();
216
+ for (const filePath of sourceFiles) {
217
+ const content = safeReadFile(filePath);
218
+ for (const pattern of eventPatterns) {
219
+ pattern.lastIndex = 0;
220
+ let match;
221
+ while ((match = pattern.exec(content)) !== null) {
222
+ const eventName = match[1];
223
+ // Filter out overly generic names
224
+ if (eventName.length > 3 && eventName.includes('.')) {
225
+ if (!eventMap.has(eventName)) {
226
+ eventMap.set(eventName, filePath);
227
+ }
228
+ }
229
+ }
230
+ }
231
+ }
232
+ repoEvents.set(repo.name, eventMap);
233
+ }
234
+ const repoNames = [...repoEvents.keys()];
235
+ for (let i = 0; i < repoNames.length; i++) {
236
+ for (let j = i + 1; j < repoNames.length; j++) {
237
+ const nameA = repoNames[i];
238
+ const nameB = repoNames[j];
239
+ const eventsA = repoEvents.get(nameA);
240
+ const eventsB = repoEvents.get(nameB);
241
+ for (const [eventName, fileA] of eventsA) {
242
+ const fileB = eventsB.get(eventName);
243
+ if (fileB) {
244
+ edges.push({
245
+ sourceRepo: nameA,
246
+ sourceNode: `${fileA}::${eventName}`,
247
+ targetRepo: nameB,
248
+ targetNode: `${fileB}::${eventName}`,
249
+ edgeType: 'event-schema',
250
+ evidence: `Shared event/topic: ${eventName}`,
251
+ confidence: 0.85,
252
+ });
253
+ }
254
+ }
255
+ }
256
+ }
257
+ return edges;
258
+ }
259
+ // ---------------------------------------------------------------------------
260
+ // Strategy 5: API endpoint matching (route defs vs HTTP client calls)
261
+ // ---------------------------------------------------------------------------
262
+ function detectApiEndpoints(repos) {
263
+ const edges = [];
264
+ // Route definition patterns
265
+ const routeDefPatterns = [
266
+ /(?:app|router)\.(get|post|put|patch|delete)\s*\(\s*['"`](\/[a-zA-Z0-9/:._-]+)['"`]/g,
267
+ /@(Get|Post|Put|Patch|Delete)\s*\(\s*['"`](\/[a-zA-Z0-9/:._-]+)['"`]/g,
268
+ ];
269
+ // HTTP client call patterns
270
+ const httpCallPatterns = [
271
+ /(?:axios|fetch|http|client)\.(get|post|put|patch|delete)\s*\(\s*[`'"](?:https?:\/\/[^/]*?)?(\/[a-zA-Z0-9/:._-]+)['"`]/g,
272
+ /fetch\s*\(\s*[`'"](?:https?:\/\/[^/]*?)?(\/[a-zA-Z0-9/:._-]+)['"`]/g,
273
+ ];
274
+ const repoRoutes = new Map(); // repo -> path -> file
275
+ const repoClients = new Map(); // repo -> path -> file
276
+ for (const repo of repos) {
277
+ const sourceFiles = walkFiles(repo.path, (f) => {
278
+ const ext = extname(f);
279
+ return ['.ts', '.js'].includes(ext);
280
+ }, 3000);
281
+ const routes = new Map();
282
+ const clients = new Map();
283
+ for (const filePath of sourceFiles) {
284
+ const content = safeReadFile(filePath);
285
+ for (const pattern of routeDefPatterns) {
286
+ pattern.lastIndex = 0;
287
+ let match;
288
+ while ((match = pattern.exec(content)) !== null) {
289
+ // Normalize path: strip params to base pattern
290
+ const routePath = match[2].replace(/:[a-zA-Z]+/g, ':param');
291
+ if (!routes.has(routePath)) {
292
+ routes.set(routePath, filePath);
293
+ }
294
+ }
295
+ }
296
+ for (const pattern of httpCallPatterns) {
297
+ pattern.lastIndex = 0;
298
+ let match;
299
+ while ((match = pattern.exec(content)) !== null) {
300
+ const clientPath = match[2].replace(/:[a-zA-Z]+/g, ':param');
301
+ if (!clients.has(clientPath)) {
302
+ clients.set(clientPath, filePath);
303
+ }
304
+ }
305
+ }
306
+ }
307
+ repoRoutes.set(repo.name, routes);
308
+ repoClients.set(repo.name, clients);
309
+ }
310
+ // Match routes in one repo to client calls in another
311
+ for (const [routeRepo, routes] of repoRoutes) {
312
+ for (const [clientRepo, clients] of repoClients) {
313
+ if (routeRepo === clientRepo)
314
+ continue;
315
+ for (const [routePath, routeFile] of routes) {
316
+ const clientFile = clients.get(routePath);
317
+ if (clientFile) {
318
+ edges.push({
319
+ sourceRepo: clientRepo,
320
+ sourceNode: `${clientFile}::${routePath}`,
321
+ targetRepo: routeRepo,
322
+ targetNode: `${routeFile}::${routePath}`,
323
+ edgeType: 'http',
324
+ evidence: `API endpoint: ${routePath}`,
325
+ confidence: 0.8,
326
+ });
327
+ }
328
+ }
329
+ }
330
+ }
331
+ return edges;
332
+ }
333
+ // ---------------------------------------------------------------------------
334
+ // Strategy 6: Workspace package dependencies (monorepo sibling packages)
335
+ // ---------------------------------------------------------------------------
336
+ function detectWorkspaceDeps(repos, workspaceMaps) {
337
+ const edges = [];
338
+ for (const repo of repos) {
339
+ const wsMap = workspaceMaps?.get(repo.name) ?? detectWorkspace(repo.path);
340
+ if (wsMap.packages.length < 2)
341
+ continue; // not a meaningful workspace
342
+ // For each package, check if its manifest deps reference a sibling package
343
+ for (const pkg of wsMap.packages) {
344
+ for (const depName of pkg.dependencies) {
345
+ const target = wsMap.nameToPackage.get(depName);
346
+ if (target && target.name !== pkg.name) {
347
+ edges.push({
348
+ sourceRepo: repo.name,
349
+ sourceNode: `pkg::${pkg.name}`,
350
+ targetRepo: repo.name,
351
+ targetNode: `pkg::${target.name}`,
352
+ edgeType: 'workspace-dep',
353
+ evidence: `${pkg.name} depends on ${target.name} (${pkg.manifestFile})`,
354
+ confidence: 1.0,
355
+ });
356
+ }
357
+ }
358
+ }
359
+ }
360
+ return edges;
361
+ }
362
+ // ---------------------------------------------------------------------------
363
+ // Strategy 7: gRPC/Proto Service Detection
364
+ // ---------------------------------------------------------------------------
365
+ function detectGrpcServices(repos) {
366
+ const edges = [];
367
+ const serviceDefPattern = /service\s+(\w+)\s*\{[^}]*rpc\s+(\w+)/gs;
368
+ const tsClientPattern = /import\s*\{[^}]*(\w+)Client[^}]*\}\s*from\s*['"][^'"]*_grpc_pb['"]/g;
369
+ const goClientPattern = /pb\.New(\w+)Client\s*\(/g;
370
+ // repo -> Set<serviceName>
371
+ const repoServiceDefs = new Map();
372
+ const repoServiceClients = new Map();
373
+ for (const repo of repos) {
374
+ // Scan .proto files for service definitions
375
+ const protoFiles = walkFiles(repo.path, (f) => extname(f) === '.proto', 500);
376
+ const serviceDefs = new Map();
377
+ for (const filePath of protoFiles) {
378
+ const content = safeReadFile(filePath);
379
+ serviceDefPattern.lastIndex = 0;
380
+ let match;
381
+ while ((match = serviceDefPattern.exec(content)) !== null) {
382
+ serviceDefs.set(match[1], filePath);
383
+ }
384
+ }
385
+ repoServiceDefs.set(repo.name, serviceDefs);
386
+ // Scan source files for client usage
387
+ const sourceFiles = walkFiles(repo.path, (f) => {
388
+ const ext = extname(f);
389
+ return ['.ts', '.js', '.go'].includes(ext);
390
+ }, 3000);
391
+ const serviceClients = new Map();
392
+ for (const filePath of sourceFiles) {
393
+ const content = safeReadFile(filePath);
394
+ tsClientPattern.lastIndex = 0;
395
+ let match;
396
+ while ((match = tsClientPattern.exec(content)) !== null) {
397
+ serviceClients.set(match[1], filePath);
398
+ }
399
+ goClientPattern.lastIndex = 0;
400
+ while ((match = goClientPattern.exec(content)) !== null) {
401
+ serviceClients.set(match[1], filePath);
402
+ }
403
+ }
404
+ repoServiceClients.set(repo.name, serviceClients);
405
+ }
406
+ // Match service defs in one repo with client usage in another
407
+ for (const [defRepo, defs] of repoServiceDefs) {
408
+ for (const [clientRepo, clients] of repoServiceClients) {
409
+ if (defRepo === clientRepo)
410
+ continue;
411
+ for (const [serviceName, defFile] of defs) {
412
+ const clientFile = clients.get(serviceName);
413
+ if (clientFile) {
414
+ edges.push({
415
+ sourceRepo: clientRepo,
416
+ sourceNode: `${clientFile}::${serviceName}Client`,
417
+ targetRepo: defRepo,
418
+ targetNode: `${defFile}::${serviceName}`,
419
+ edgeType: 'grpc',
420
+ evidence: `gRPC service: ${serviceName}`,
421
+ confidence: 0.9,
422
+ });
423
+ }
424
+ }
425
+ }
426
+ }
427
+ return edges;
428
+ }
429
+ // ---------------------------------------------------------------------------
430
+ // Strategy 8: Database Schema Correlation
431
+ // ---------------------------------------------------------------------------
432
+ function detectDatabaseSchemas(repos) {
433
+ const edges = [];
434
+ const sqlCreatePattern = /CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?["`]?(\w+)["`]?/gi;
435
+ const sqlQueryPattern = /(?:FROM|INTO|JOIN|UPDATE)\s+["`]?(\w+)["`]?/gi;
436
+ const typeormPattern = /@Entity\s*\(\s*['"`](\w+)['"`]\s*\)/g;
437
+ const gormPattern = /TableName\s*\(\s*\)\s*string\s*\{\s*return\s*["'](\w+)["']/g;
438
+ const sequelizePattern = /sequelize\.define\s*\(\s*['"`](\w+)['"`]/g;
439
+ const repoTables = new Map(); // repo -> tableName -> filePath
440
+ for (const repo of repos) {
441
+ const tableMap = new Map();
442
+ // SQL migration files
443
+ const sqlFiles = walkFiles(repo.path, (f) => {
444
+ const lower = f.toLowerCase();
445
+ return lower.endsWith('.sql') || lower.includes('migration');
446
+ }, 1000);
447
+ // Source files for ORM patterns and raw queries
448
+ const sourceFiles = walkFiles(repo.path, (f) => {
449
+ const ext = extname(f);
450
+ return ['.ts', '.js', '.go', '.py', '.java'].includes(ext);
451
+ }, 3000);
452
+ const allFiles = [...sqlFiles, ...sourceFiles];
453
+ const patterns = [sqlCreatePattern, sqlQueryPattern, typeormPattern, gormPattern, sequelizePattern];
454
+ const skipTables = new Set(['information_schema', 'pg_catalog', 'dual', 'sqlite_master', 'schema_migrations']);
455
+ for (const filePath of allFiles) {
456
+ const content = safeReadFile(filePath);
457
+ for (const pattern of patterns) {
458
+ pattern.lastIndex = 0;
459
+ let match;
460
+ while ((match = pattern.exec(content)) !== null) {
461
+ const tableName = match[1].toLowerCase();
462
+ if (tableName.length > 2 && !skipTables.has(tableName)) {
463
+ if (!tableMap.has(tableName)) {
464
+ tableMap.set(tableName, filePath);
465
+ }
466
+ }
467
+ }
468
+ }
469
+ }
470
+ repoTables.set(repo.name, tableMap);
471
+ }
472
+ const repoNames = [...repoTables.keys()];
473
+ for (let i = 0; i < repoNames.length; i++) {
474
+ for (let j = i + 1; j < repoNames.length; j++) {
475
+ const nameA = repoNames[i];
476
+ const nameB = repoNames[j];
477
+ const tablesA = repoTables.get(nameA);
478
+ const tablesB = repoTables.get(nameB);
479
+ for (const [tableName, fileA] of tablesA) {
480
+ const fileB = tablesB.get(tableName);
481
+ if (fileB) {
482
+ edges.push({
483
+ sourceRepo: nameA,
484
+ sourceNode: `${fileA}::${tableName}`,
485
+ targetRepo: nameB,
486
+ targetNode: `${fileB}::${tableName}`,
487
+ edgeType: 'database',
488
+ evidence: `Shared table: ${tableName}`,
489
+ confidence: 0.85,
490
+ });
491
+ }
492
+ }
493
+ }
494
+ }
495
+ return edges;
496
+ }
497
+ // ---------------------------------------------------------------------------
498
+ // Strategy 9: Redis Key Pattern Detection
499
+ // ---------------------------------------------------------------------------
500
+ function detectRedisKeyPatterns(repos) {
501
+ const edges = [];
502
+ const redisPatterns = [
503
+ /(?:redis|cache|rdb)\.(get|set|del|hget|hset|sadd|srem)\s*\(\s*(?:ctx,\s*)?['"`]([a-zA-Z0-9_:-]+)/g,
504
+ /(?:redis|cache|rdb)\.(?:Get|Set|Del|HGet|HSet)\s*\(\s*ctx\s*,\s*["']([a-zA-Z0-9_:-]+)/g,
505
+ ];
506
+ const repoKeyPrefixes = new Map(); // repo -> prefix -> filePath
507
+ for (const repo of repos) {
508
+ const sourceFiles = walkFiles(repo.path, (f) => {
509
+ const ext = extname(f);
510
+ return ['.ts', '.js', '.go', '.py', '.java'].includes(ext);
511
+ }, 3000);
512
+ const prefixMap = new Map();
513
+ for (const filePath of sourceFiles) {
514
+ const content = safeReadFile(filePath);
515
+ for (const pattern of redisPatterns) {
516
+ pattern.lastIndex = 0;
517
+ let match;
518
+ while ((match = pattern.exec(content)) !== null) {
519
+ // Extract the key — could be in group 2 (first pattern) or group 1 (second pattern)
520
+ const key = match[2] ?? match[1];
521
+ // Extract prefix: everything before first interpolation marker or take full key up to second colon
522
+ const colonParts = key.split(':');
523
+ const prefix = colonParts.length >= 2
524
+ ? `${colonParts[0]}:${colonParts[1]}`
525
+ : key;
526
+ if (prefix.length > 3 && !prefixMap.has(prefix)) {
527
+ prefixMap.set(prefix, filePath);
528
+ }
529
+ }
530
+ }
531
+ }
532
+ repoKeyPrefixes.set(repo.name, prefixMap);
533
+ }
534
+ const repoNames = [...repoKeyPrefixes.keys()];
535
+ for (let i = 0; i < repoNames.length; i++) {
536
+ for (let j = i + 1; j < repoNames.length; j++) {
537
+ const nameA = repoNames[i];
538
+ const nameB = repoNames[j];
539
+ const prefixesA = repoKeyPrefixes.get(nameA);
540
+ const prefixesB = repoKeyPrefixes.get(nameB);
541
+ for (const [prefix, fileA] of prefixesA) {
542
+ const fileB = prefixesB.get(prefix);
543
+ if (fileB) {
544
+ edges.push({
545
+ sourceRepo: nameA,
546
+ sourceNode: `${fileA}::redis:${prefix}`,
547
+ targetRepo: nameB,
548
+ targetNode: `${fileB}::redis:${prefix}`,
549
+ edgeType: 'redis',
550
+ evidence: `Shared Redis key prefix: ${prefix}`,
551
+ confidence: 0.75,
552
+ });
553
+ }
554
+ }
555
+ }
556
+ }
557
+ return edges;
558
+ }
559
+ // ---------------------------------------------------------------------------
560
+ // Strategy 10: S3/GCS Bucket Detection
561
+ // ---------------------------------------------------------------------------
562
+ function detectS3Buckets(repos) {
563
+ const edges = [];
564
+ const s3Patterns = [
565
+ /s3\.(?:putObject|getObject|deleteObject|upload|headObject)\s*\(\s*\{[^}]*Bucket\s*:\s*['"`]([a-zA-Z0-9._-]+)['"`]/gs,
566
+ /new\s+(?:S3|AWS\.S3)\s*\([^)]*\)[^;]*\.(?:putObject|getObject)\s*\(\s*\{[^}]*Bucket\s*:\s*['"`]([a-zA-Z0-9._-]+)['"`]/gs,
567
+ /storage\.bucket\s*\(\s*['"`]([a-zA-Z0-9._-]+)['"`]\s*\)/g,
568
+ ];
569
+ const envBucketPattern = /(?:S3_BUCKET|GCS_BUCKET|BUCKET_NAME|AWS_BUCKET)\s*=\s*['"`]?([a-zA-Z0-9._-]+)['"`]?/g;
570
+ const repoBuckets = new Map(); // repo -> bucketName -> filePath
571
+ for (const repo of repos) {
572
+ const bucketMap = new Map();
573
+ const sourceFiles = walkFiles(repo.path, (f) => {
574
+ const ext = extname(f);
575
+ return ['.ts', '.js', '.go', '.py', '.java', '.env', '.yaml', '.yml'].includes(ext)
576
+ || f.endsWith('.env.example') || f.endsWith('.env.template');
577
+ }, 3000);
578
+ for (const filePath of sourceFiles) {
579
+ const content = safeReadFile(filePath);
580
+ for (const pattern of s3Patterns) {
581
+ pattern.lastIndex = 0;
582
+ let match;
583
+ while ((match = pattern.exec(content)) !== null) {
584
+ const bucket = match[1];
585
+ if (bucket && !bucketMap.has(bucket)) {
586
+ bucketMap.set(bucket, filePath);
587
+ }
588
+ }
589
+ }
590
+ envBucketPattern.lastIndex = 0;
591
+ let match;
592
+ while ((match = envBucketPattern.exec(content)) !== null) {
593
+ const bucket = match[1];
594
+ if (bucket && bucket.length > 3 && !bucketMap.has(bucket)) {
595
+ bucketMap.set(bucket, filePath);
596
+ }
597
+ }
598
+ }
599
+ repoBuckets.set(repo.name, bucketMap);
600
+ }
601
+ const repoNames = [...repoBuckets.keys()];
602
+ for (let i = 0; i < repoNames.length; i++) {
603
+ for (let j = i + 1; j < repoNames.length; j++) {
604
+ const nameA = repoNames[i];
605
+ const nameB = repoNames[j];
606
+ const bucketsA = repoBuckets.get(nameA);
607
+ const bucketsB = repoBuckets.get(nameB);
608
+ for (const [bucket, fileA] of bucketsA) {
609
+ const fileB = bucketsB.get(bucket);
610
+ if (fileB) {
611
+ edges.push({
612
+ sourceRepo: nameA,
613
+ sourceNode: `${fileA}::s3:${bucket}`,
614
+ targetRepo: nameB,
615
+ targetNode: `${fileB}::s3:${bucket}`,
616
+ edgeType: 's3',
617
+ evidence: `Shared bucket: ${bucket}`,
618
+ confidence: 0.8,
619
+ });
620
+ }
621
+ }
622
+ }
623
+ }
624
+ return edges;
625
+ }
626
+ // ---------------------------------------------------------------------------
627
+ // Strategy 11: OpenAPI Schema References
628
+ // ---------------------------------------------------------------------------
629
+ function detectOpenApiSchemas(repos) {
630
+ const edges = [];
631
+ const openApiFileNames = ['openapi.yaml', 'openapi.yml', 'openapi.json', 'swagger.yaml', 'swagger.yml', 'swagger.json'];
632
+ const pathPattern = /^\s*(?:\/[a-zA-Z0-9/:._{}*-]+)\s*:/gm;
633
+ const jsonPathPattern = /"(\/[a-zA-Z0-9/:._{}*-]+)"\s*:/g;
634
+ // repo -> endpoint paths -> filePath
635
+ const repoApiPaths = new Map();
636
+ // HTTP client patterns (complement to Strategy 5)
637
+ const httpCallPatterns = [
638
+ /(?:axios|fetch|http|client|httpGet|httpPost|httpPut|httpDelete)\s*\(\s*[^,]*?,?\s*['"`](\/[a-zA-Z0-9/:._-]+)['"`]/g,
639
+ /fetch\s*\(\s*[`'"](?:https?:\/\/[^/]*?)?(\/[a-zA-Z0-9/:._-]+)['"`]/g,
640
+ ];
641
+ const repoHttpCalls = new Map();
642
+ for (const repo of repos) {
643
+ const apiPaths = new Map();
644
+ // Find OpenAPI spec files
645
+ const specFiles = walkFiles(repo.path, (f) => {
646
+ const basename = f.split('/').pop() ?? '';
647
+ return openApiFileNames.includes(basename);
648
+ }, 200);
649
+ for (const filePath of specFiles) {
650
+ const content = safeReadFile(filePath);
651
+ if (filePath.endsWith('.json')) {
652
+ jsonPathPattern.lastIndex = 0;
653
+ let match;
654
+ while ((match = jsonPathPattern.exec(content)) !== null) {
655
+ const path = match[1].replace(/\{[^}]+\}/g, ':param');
656
+ if (!apiPaths.has(path)) {
657
+ apiPaths.set(path, filePath);
658
+ }
659
+ }
660
+ }
661
+ else {
662
+ pathPattern.lastIndex = 0;
663
+ let match;
664
+ while ((match = pathPattern.exec(content)) !== null) {
665
+ const rawPath = match[0].trim().replace(/:$/, '').trim();
666
+ if (rawPath.startsWith('/')) {
667
+ const normalized = rawPath.replace(/\{[^}]+\}/g, ':param');
668
+ if (!apiPaths.has(normalized)) {
669
+ apiPaths.set(normalized, filePath);
670
+ }
671
+ }
672
+ }
673
+ }
674
+ }
675
+ repoApiPaths.set(repo.name, apiPaths);
676
+ // Scan for HTTP client calls
677
+ const sourceFiles = walkFiles(repo.path, (f) => {
678
+ const ext = extname(f);
679
+ return ['.ts', '.js'].includes(ext);
680
+ }, 3000);
681
+ const httpCalls = new Map();
682
+ for (const filePath of sourceFiles) {
683
+ const content = safeReadFile(filePath);
684
+ for (const pattern of httpCallPatterns) {
685
+ pattern.lastIndex = 0;
686
+ let match;
687
+ while ((match = pattern.exec(content)) !== null) {
688
+ const callPath = (match[2] ?? match[1]).replace(/:[a-zA-Z]+/g, ':param');
689
+ if (!httpCalls.has(callPath)) {
690
+ httpCalls.set(callPath, filePath);
691
+ }
692
+ }
693
+ }
694
+ }
695
+ repoHttpCalls.set(repo.name, httpCalls);
696
+ }
697
+ // Match API spec paths in one repo with HTTP calls in another
698
+ for (const [specRepo, apiPaths] of repoApiPaths) {
699
+ for (const [clientRepo, httpCalls] of repoHttpCalls) {
700
+ if (specRepo === clientRepo)
701
+ continue;
702
+ for (const [apiPath, specFile] of apiPaths) {
703
+ const clientFile = httpCalls.get(apiPath);
704
+ if (clientFile) {
705
+ edges.push({
706
+ sourceRepo: clientRepo,
707
+ sourceNode: `${clientFile}::${apiPath}`,
708
+ targetRepo: specRepo,
709
+ targetNode: `${specFile}::${apiPath}`,
710
+ edgeType: 'api-contract',
711
+ evidence: `OpenAPI endpoint: ${apiPath}`,
712
+ confidence: 0.9,
713
+ });
714
+ }
715
+ }
716
+ }
717
+ }
718
+ return edges;
719
+ }
720
+ // ---------------------------------------------------------------------------
721
+ // Strategy 12: Docker Compose Service Links
722
+ // ---------------------------------------------------------------------------
723
+ function detectDockerComposeLinks(repos) {
724
+ const edges = [];
725
+ const composeFiles = ['docker-compose.yml', 'docker-compose.yaml', 'compose.yml', 'compose.yaml'];
726
+ // Extract service names and their dependencies from compose files
727
+ // Simplified YAML parsing via regex (no YAML parser dependency)
728
+ const serviceBlockPattern = /^\s{2}(\w[\w.-]*)\s*:/gm;
729
+ const dependsOnPattern = /depends_on\s*:\s*\n((?:\s+-\s+\w[\w.-]*\n?)+)/gm;
730
+ const dependsOnItemPattern = /^\s+-\s+(\w[\w.-]*)/gm;
731
+ const linksPattern = /links\s*:\s*\n((?:\s+-\s+\w[\w.-]*(?::\w[\w.-]*)?\n?)+)/gm;
732
+ const linksItemPattern = /^\s+-\s+(\w[\w.-]*)/gm;
733
+ // Normalize service name for matching against repo names
734
+ function normalizeServiceName(name) {
735
+ return name.toLowerCase().replace(/[-_.]/g, '-');
736
+ }
737
+ // Build a map of repo names (normalized) to actual repo names
738
+ const repoNameMap = new Map();
739
+ for (const repo of repos) {
740
+ repoNameMap.set(normalizeServiceName(repo.name), repo.name);
741
+ // Also add suffixed variants: "mta-routing-engine" matches "routing-engine"
742
+ const parts = repo.name.split(/[-_]/);
743
+ if (parts.length > 1) {
744
+ for (let k = 1; k < parts.length; k++) {
745
+ const suffix = parts.slice(k).join('-');
746
+ if (suffix.length > 3) {
747
+ repoNameMap.set(normalizeServiceName(suffix), repo.name);
748
+ }
749
+ }
750
+ }
751
+ }
752
+ for (const repo of repos) {
753
+ const foundFiles = walkFiles(repo.path, (f) => {
754
+ const basename = f.split('/').pop() ?? '';
755
+ return composeFiles.includes(basename);
756
+ }, 50);
757
+ for (const filePath of foundFiles) {
758
+ const content = safeReadFile(filePath);
759
+ // Extract all service names from the compose file
760
+ serviceBlockPattern.lastIndex = 0;
761
+ const services = new Set();
762
+ let match;
763
+ while ((match = serviceBlockPattern.exec(content)) !== null) {
764
+ services.add(match[1]);
765
+ }
766
+ // Extract depends_on links
767
+ dependsOnPattern.lastIndex = 0;
768
+ while ((match = dependsOnPattern.exec(content)) !== null) {
769
+ const block = match[1];
770
+ dependsOnItemPattern.lastIndex = 0;
771
+ let dep;
772
+ while ((dep = dependsOnItemPattern.exec(block)) !== null) {
773
+ const depService = dep[1];
774
+ const normalizedDep = normalizeServiceName(depService);
775
+ const targetRepo = repoNameMap.get(normalizedDep);
776
+ if (targetRepo && targetRepo !== repo.name) {
777
+ edges.push({
778
+ sourceRepo: repo.name,
779
+ sourceNode: `${filePath}::compose`,
780
+ targetRepo,
781
+ targetNode: `service::${depService}`,
782
+ edgeType: 'http',
783
+ evidence: `Docker Compose depends_on: ${depService}`,
784
+ confidence: 0.85,
785
+ });
786
+ }
787
+ }
788
+ }
789
+ // Extract links
790
+ linksPattern.lastIndex = 0;
791
+ while ((match = linksPattern.exec(content)) !== null) {
792
+ const block = match[1];
793
+ linksItemPattern.lastIndex = 0;
794
+ let link;
795
+ while ((link = linksItemPattern.exec(block)) !== null) {
796
+ const linkService = link[1];
797
+ const normalizedLink = normalizeServiceName(linkService);
798
+ const targetRepo = repoNameMap.get(normalizedLink);
799
+ if (targetRepo && targetRepo !== repo.name) {
800
+ edges.push({
801
+ sourceRepo: repo.name,
802
+ sourceNode: `${filePath}::compose`,
803
+ targetRepo,
804
+ targetNode: `service::${linkService}`,
805
+ edgeType: 'http',
806
+ evidence: `Docker Compose link: ${linkService}`,
807
+ confidence: 0.85,
808
+ });
809
+ }
810
+ }
811
+ }
812
+ }
813
+ }
814
+ return edges;
815
+ }
816
+ // ---------------------------------------------------------------------------
817
+ // Strategy 13: Kubernetes Service References
818
+ // ---------------------------------------------------------------------------
819
+ function detectK8sServiceRefs(repos) {
820
+ const edges = [];
821
+ const k8sServicePattern = /kind:\s*Service\s[\s\S]*?name:\s*["']?(\w[\w.-]*)["']?/gm;
822
+ const k8sDeployPattern = /kind:\s*Deployment\s[\s\S]*?name:\s*["']?(\w[\w.-]*)["']?/gm;
823
+ const svcRefPattern = /["'](\w[\w.-]*)\.(\w[\w.-]*)\.svc(?:\.cluster\.local)?["']/g;
824
+ const envServiceUrlPattern = /(?:SERVICE_HOST|SERVICE_URL|_HOST|_URL)\s*:\s*["']?(\w[\w.-]*)(?:\.[\w.-]+)?\.svc/g;
825
+ // Normalize for repo matching
826
+ function normalizeK8sName(name) {
827
+ return name.toLowerCase().replace(/[-_.]/g, '-');
828
+ }
829
+ const repoNameMap = new Map();
830
+ for (const repo of repos) {
831
+ repoNameMap.set(normalizeK8sName(repo.name), repo.name);
832
+ const parts = repo.name.split(/[-_]/);
833
+ if (parts.length > 1) {
834
+ for (let k = 1; k < parts.length; k++) {
835
+ const suffix = parts.slice(k).join('-');
836
+ if (suffix.length > 3) {
837
+ repoNameMap.set(normalizeK8sName(suffix), repo.name);
838
+ }
839
+ }
840
+ }
841
+ }
842
+ for (const repo of repos) {
843
+ const k8sFiles = walkFiles(repo.path, (f) => {
844
+ const ext = extname(f);
845
+ if (ext !== '.yaml' && ext !== '.yml')
846
+ return false;
847
+ const lower = f.toLowerCase();
848
+ return lower.includes('k8s') || lower.includes('deploy') || lower.includes('manifests')
849
+ || lower.includes('kustomiz') || lower.includes('kubernetes') || lower.includes('helm');
850
+ }, 500);
851
+ for (const filePath of k8sFiles) {
852
+ const content = safeReadFile(filePath);
853
+ // Extract service references via .svc DNS
854
+ svcRefPattern.lastIndex = 0;
855
+ let match;
856
+ while ((match = svcRefPattern.exec(content)) !== null) {
857
+ const svcName = match[1];
858
+ const normalized = normalizeK8sName(svcName);
859
+ const targetRepo = repoNameMap.get(normalized);
860
+ if (targetRepo && targetRepo !== repo.name) {
861
+ edges.push({
862
+ sourceRepo: repo.name,
863
+ sourceNode: `${filePath}::k8s-ref`,
864
+ targetRepo,
865
+ targetNode: `k8s-service::${svcName}`,
866
+ edgeType: 'http',
867
+ evidence: `K8s service DNS: ${svcName}.${match[2]}.svc`,
868
+ confidence: 0.8,
869
+ });
870
+ }
871
+ }
872
+ // Extract env var service references
873
+ envServiceUrlPattern.lastIndex = 0;
874
+ while ((match = envServiceUrlPattern.exec(content)) !== null) {
875
+ const svcName = match[1];
876
+ const normalized = normalizeK8sName(svcName);
877
+ const targetRepo = repoNameMap.get(normalized);
878
+ if (targetRepo && targetRepo !== repo.name) {
879
+ edges.push({
880
+ sourceRepo: repo.name,
881
+ sourceNode: `${filePath}::k8s-env`,
882
+ targetRepo,
883
+ targetNode: `k8s-service::${svcName}`,
884
+ edgeType: 'http',
885
+ evidence: `K8s env service ref: ${svcName}`,
886
+ confidence: 0.8,
887
+ });
888
+ }
889
+ }
890
+ }
891
+ }
892
+ return edges;
893
+ }
894
+ // ---------------------------------------------------------------------------
895
+ // Strategy 14: Shared Constants & Magic Strings
896
+ // ---------------------------------------------------------------------------
897
+ function detectSharedConstants(repos) {
898
+ const edges = [];
899
+ const tsConstPattern = /export\s+const\s+(\w+)\s*=\s*['"`]([^'"`]+)['"`]/g;
900
+ const goConstPattern = /(?:const|var)\s+(\w+)\s*=\s*["']([^"']+)["']/g;
901
+ // A string constant is "interesting" if it looks like an identifier
902
+ function isInterestingConstant(value) {
903
+ if (value.length < 8)
904
+ return false;
905
+ // Must contain dots, slashes, or colons — signals structured identifiers
906
+ return /[./:]+/.test(value);
907
+ }
908
+ // repo -> constValue -> { name, filePath }
909
+ const repoConstants = new Map();
910
+ for (const repo of repos) {
911
+ const sourceFiles = walkFiles(repo.path, (f) => {
912
+ const ext = extname(f);
913
+ return ['.ts', '.js', '.go'].includes(ext);
914
+ }, 3000);
915
+ const constMap = new Map();
916
+ for (const filePath of sourceFiles) {
917
+ const content = safeReadFile(filePath);
918
+ const patterns = [tsConstPattern, goConstPattern];
919
+ for (const pattern of patterns) {
920
+ pattern.lastIndex = 0;
921
+ let match;
922
+ while ((match = pattern.exec(content)) !== null) {
923
+ const constName = match[1];
924
+ const constValue = match[2];
925
+ if (isInterestingConstant(constValue) && !constMap.has(constValue)) {
926
+ constMap.set(constValue, { name: constName, filePath });
927
+ }
928
+ }
929
+ }
930
+ }
931
+ repoConstants.set(repo.name, constMap);
932
+ }
933
+ const repoNames = [...repoConstants.keys()];
934
+ for (let i = 0; i < repoNames.length; i++) {
935
+ for (let j = i + 1; j < repoNames.length; j++) {
936
+ const nameA = repoNames[i];
937
+ const nameB = repoNames[j];
938
+ const constsA = repoConstants.get(nameA);
939
+ const constsB = repoConstants.get(nameB);
940
+ for (const [value, infoA] of constsA) {
941
+ const infoB = constsB.get(value);
942
+ if (infoB) {
943
+ edges.push({
944
+ sourceRepo: nameA,
945
+ sourceNode: `${infoA.filePath}::${infoA.name}`,
946
+ targetRepo: nameB,
947
+ targetNode: `${infoB.filePath}::${infoB.name}`,
948
+ edgeType: 'shared-constant',
949
+ evidence: `Shared constant value: "${value}" (${infoA.name} / ${infoB.name})`,
950
+ confidence: 0.7,
951
+ });
952
+ }
953
+ }
954
+ }
955
+ }
956
+ return edges;
957
+ }
958
+ // ---------------------------------------------------------------------------
959
+ // Main entry point
960
+ // ---------------------------------------------------------------------------
961
+ export async function detectCrossRepoEdges(repos, workspaceMaps) {
962
+ const allEdges = [];
963
+ const strategies = [
964
+ { name: 'shared-npm-deps', fn: () => detectSharedNpmDeps(repos) },
965
+ { name: 'shared-types', fn: () => detectSharedTypes(repos) },
966
+ { name: 'env-var-correlation', fn: () => detectEnvVarCorrelation(repos) },
967
+ { name: 'event-schemas', fn: () => detectEventSchemas(repos) },
968
+ { name: 'api-endpoints', fn: () => detectApiEndpoints(repos) },
969
+ { name: 'workspace-deps', fn: () => detectWorkspaceDeps(repos, workspaceMaps) },
970
+ { name: 'grpc-services', fn: () => detectGrpcServices(repos) },
971
+ { name: 'database-schemas', fn: () => detectDatabaseSchemas(repos) },
972
+ { name: 'redis-key-patterns', fn: () => detectRedisKeyPatterns(repos) },
973
+ { name: 's3-buckets', fn: () => detectS3Buckets(repos) },
974
+ { name: 'openapi-schemas', fn: () => detectOpenApiSchemas(repos) },
975
+ { name: 'docker-compose-links', fn: () => detectDockerComposeLinks(repos) },
976
+ { name: 'k8s-service-refs', fn: () => detectK8sServiceRefs(repos) },
977
+ { name: 'shared-constants', fn: () => detectSharedConstants(repos) },
978
+ ];
979
+ for (const strategy of strategies) {
980
+ try {
981
+ const edges = strategy.fn();
982
+ allEdges.push(...edges);
983
+ }
984
+ catch {
985
+ // Individual strategy failure should not block others
986
+ }
987
+ }
988
+ return allEdges;
989
+ }
990
+ //# sourceMappingURL=cross-repo-detector.js.map