akbo-cli 0.0.0-stage → 1.9.4

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 (66) hide show
  1. package/README.md +706 -2
  2. package/dist/catalog_store.d.ts +78 -0
  3. package/dist/catalog_store.js +375 -0
  4. package/dist/cleaner.d.ts +11 -0
  5. package/dist/cleaner.js +92 -0
  6. package/dist/cli.d.ts +2 -0
  7. package/dist/cli.js +1596 -0
  8. package/dist/extractors/base.d.ts +35 -0
  9. package/dist/extractors/base.js +17 -0
  10. package/dist/extractors/custom_extractor.d.ts +55 -0
  11. package/dist/extractors/custom_extractor.js +198 -0
  12. package/dist/extractors/dotnet_extractor.d.ts +11 -0
  13. package/dist/extractors/dotnet_extractor.js +579 -0
  14. package/dist/extractors/golang_extractor.d.ts +11 -0
  15. package/dist/extractors/golang_extractor.js +73 -0
  16. package/dist/extractors/index.d.ts +14 -0
  17. package/dist/extractors/index.js +30 -0
  18. package/dist/extractors/jvm_extractor.d.ts +11 -0
  19. package/dist/extractors/jvm_extractor.js +319 -0
  20. package/dist/extractors/node_extractor.d.ts +11 -0
  21. package/dist/extractors/node_extractor.js +306 -0
  22. package/dist/extractors/proto_graphql_extractor.d.ts +11 -0
  23. package/dist/extractors/proto_graphql_extractor.js +125 -0
  24. package/dist/extractors/python_extractor.d.ts +11 -0
  25. package/dist/extractors/python_extractor.js +298 -0
  26. package/dist/extractors/rust_extractor.d.ts +11 -0
  27. package/dist/extractors/rust_extractor.js +66 -0
  28. package/dist/graph_builder.d.ts +87 -0
  29. package/dist/graph_builder.js +1498 -0
  30. package/dist/harvester.d.ts +38 -0
  31. package/dist/harvester.js +461 -0
  32. package/dist/hook_generator.d.ts +26 -0
  33. package/dist/hook_generator.js +203 -0
  34. package/dist/importers/skill_importer.d.ts +43 -0
  35. package/dist/importers/skill_importer.js +470 -0
  36. package/dist/index.d.ts +17 -0
  37. package/dist/index.js +17 -0
  38. package/dist/indexer.d.ts +19 -0
  39. package/dist/indexer.js +108 -0
  40. package/dist/init_service.d.ts +37 -0
  41. package/dist/init_service.js +246 -0
  42. package/dist/mcp_server.d.ts +10 -0
  43. package/dist/mcp_server.js +632 -0
  44. package/dist/pool_resolver.d.ts +40 -0
  45. package/dist/pool_resolver.js +84 -0
  46. package/dist/provider.d.ts +135 -0
  47. package/dist/provider.js +880 -0
  48. package/dist/query_service.d.ts +33 -0
  49. package/dist/query_service.js +161 -0
  50. package/dist/schema_generator.d.ts +236 -0
  51. package/dist/schema_generator.js +264 -0
  52. package/dist/standards_loader.d.ts +7 -0
  53. package/dist/standards_loader.js +33 -0
  54. package/dist/types.d.ts +265 -0
  55. package/dist/types.js +105 -0
  56. package/dist/unit_synthesizer.d.ts +22 -0
  57. package/dist/unit_synthesizer.js +196 -0
  58. package/dist/validator.d.ts +13 -0
  59. package/dist/validator.js +152 -0
  60. package/dist/version.d.ts +6 -0
  61. package/dist/version.js +16 -0
  62. package/dist/watcher.d.ts +38 -0
  63. package/dist/watcher.js +132 -0
  64. package/package.json +56 -6
  65. package/schemas/index-schema.json +98 -0
  66. package/schemas/knowledge-unit.json +154 -0
@@ -0,0 +1,1498 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import YAML from 'yaml';
4
+ import ignore from 'ignore';
5
+ import { StandardsLoader } from './standards_loader.js';
6
+ import { VERSION as CLI_VERSION } from './version.js';
7
+ import { KnowledgePoolResolver } from './pool_resolver.js';
8
+ export class GraphBuilder {
9
+ repoRoot;
10
+ poolConfig;
11
+ repositoryRoot;
12
+ static inMemoryCache = new Map();
13
+ static knowledgeUnitsCache = new Map();
14
+ static clearCache() {
15
+ GraphBuilder.inMemoryCache.clear();
16
+ GraphBuilder.knowledgeUnitsCache.clear();
17
+ }
18
+ constructor(repoRoot, poolDir) {
19
+ this.repoRoot = path.resolve(repoRoot).replace(/\\/g, '/');
20
+ this.poolConfig = KnowledgePoolResolver.resolve(this.repoRoot, { explicitPoolDir: poolDir });
21
+ this.repositoryRoot = this.detectRepositoryRoot();
22
+ }
23
+ detectRepositoryRoot() {
24
+ const indexPath = path.join(this.poolConfig.knowledgeDir, 'index.yaml');
25
+ if (fs.existsSync(indexPath)) {
26
+ try {
27
+ const doc = YAML.parse(fs.readFileSync(indexPath, 'utf-8'));
28
+ if (doc && doc.repository_root && fs.existsSync(doc.repository_root)) {
29
+ return path.resolve(doc.repository_root).replace(/\\/g, '/');
30
+ }
31
+ }
32
+ catch { }
33
+ }
34
+ const nearest = KnowledgePoolResolver.findNearestPool(this.repoRoot);
35
+ return (nearest || this.repoRoot).replace(/\\/g, '/');
36
+ }
37
+ getKnowledgeMaxMtime() {
38
+ let maxMtime = 0;
39
+ const localKDir = path.join(this.repoRoot, 'knowledge');
40
+ const kDir = fs.existsSync(localKDir) ? localKDir : this.poolConfig.knowledgeDir;
41
+ if (!fs.existsSync(kDir))
42
+ return 0;
43
+ const walk = (d) => {
44
+ try {
45
+ for (const entry of fs.readdirSync(d, { withFileTypes: true })) {
46
+ const full = path.join(d, entry.name);
47
+ if (entry.isDirectory()) {
48
+ walk(full);
49
+ }
50
+ else if (entry.isFile() && (entry.name.endsWith('.yaml') || entry.name.endsWith('.yml'))) {
51
+ try {
52
+ const mt = fs.statSync(full).mtimeMs;
53
+ if (mt > maxMtime)
54
+ maxMtime = mt;
55
+ }
56
+ catch { }
57
+ }
58
+ }
59
+ }
60
+ catch { }
61
+ };
62
+ walk(kDir);
63
+ return maxMtime;
64
+ }
65
+ getStandardsMtime() {
66
+ const candidatePaths = [
67
+ this.poolConfig.standardsFile,
68
+ path.join(this.poolConfig.poolDir, '.akb', 'standards.yml'),
69
+ path.join(this.repoRoot, '.akb', 'standards.yaml'),
70
+ path.join(this.repoRoot, '.akb', 'standards.yml')
71
+ ];
72
+ for (const p of candidatePaths) {
73
+ if (fs.existsSync(p)) {
74
+ try {
75
+ return fs.statSync(p).mtimeMs;
76
+ }
77
+ catch { }
78
+ }
79
+ }
80
+ return 0;
81
+ }
82
+ /**
83
+ * Resolves a file path relative to repositoryRoot when scanning a narrow subproject,
84
+ * ensuring consistent top-level bounded context domain tagging across monorepos.
85
+ */
86
+ resolveRelativePathAndDomain(filePath) {
87
+ const norm = filePath.replace(/\\/g, '/');
88
+ const absRepo = path.resolve(this.repoRoot).replace(/\\/g, '/').toLowerCase();
89
+ const absRoot = path.resolve(this.repositoryRoot).replace(/\\/g, '/').toLowerCase();
90
+ const isInsideRepoRoot = this.repositoryRoot &&
91
+ absRepo !== absRoot &&
92
+ absRepo.startsWith(absRoot + '/');
93
+ if (isInsideRepoRoot) {
94
+ const abs = path.resolve(this.repoRoot, norm);
95
+ const relToRepo = path.relative(this.repositoryRoot, abs).replace(/\\/g, '/');
96
+ const domain = relToRepo.includes('/') ? relToRepo.split('/')[0] : (norm.includes('/') ? norm.split('/')[0] : undefined);
97
+ return { relPath: relToRepo, domain };
98
+ }
99
+ const domain = norm.includes('/') ? norm.split('/')[0] : undefined;
100
+ return { relPath: norm, domain };
101
+ }
102
+ /**
103
+ * Deterministically builds a Codebase Knowledge Graph (CKG) from the harvested
104
+ * skeleton and loaded Knowledge Units (0 LLM tokens).
105
+ */
106
+ async buildGraph(skeleton, customUnits, options) {
107
+ const useCache = options?.useCache ?? true;
108
+ const cacheFile = path.resolve(options?.cachePath || this.poolConfig.cacheFile);
109
+ const hasCustomUnits = Boolean(customUnits && customUnits.length > 0);
110
+ const currentKey = {
111
+ cliVersion: CLI_VERSION,
112
+ skeletonTimestamp: skeleton.timestamp,
113
+ totalFiles: skeleton.topology.totalFiles,
114
+ knowledgeMtime: this.getKnowledgeMaxMtime(),
115
+ standardsMtime: this.getStandardsMtime(),
116
+ repoPath: this.repoRoot
117
+ };
118
+ const keyString = JSON.stringify(currentKey);
119
+ if (useCache && !hasCustomUnits) {
120
+ // 1. Check in-memory cache
121
+ const memCached = GraphBuilder.inMemoryCache.get(this.repoRoot);
122
+ if (memCached && memCached.graphKey === keyString) {
123
+ return memCached.graph;
124
+ }
125
+ // 2. Check disk cache (.akb/cache.json)
126
+ if (fs.existsSync(cacheFile)) {
127
+ try {
128
+ const diskRaw = JSON.parse(fs.readFileSync(cacheFile, 'utf-8'));
129
+ if (diskRaw && diskRaw.graphKey && diskRaw.graph) {
130
+ const gk = diskRaw.graphKey;
131
+ if (gk.cliVersion === currentKey.cliVersion &&
132
+ gk.skeletonTimestamp === currentKey.skeletonTimestamp &&
133
+ gk.totalFiles === currentKey.totalFiles &&
134
+ gk.knowledgeMtime === currentKey.knowledgeMtime &&
135
+ gk.standardsMtime === currentKey.standardsMtime &&
136
+ gk.repoPath === currentKey.repoPath) {
137
+ GraphBuilder.inMemoryCache.set(this.repoRoot, { graphKey: keyString, graph: diskRaw.graph });
138
+ return diskRaw.graph;
139
+ }
140
+ }
141
+ }
142
+ catch { }
143
+ }
144
+ }
145
+ const nodes = [];
146
+ const edges = [];
147
+ const nodeSet = new Set();
148
+ const edgeSet = new Set();
149
+ const addNode = (node) => {
150
+ if (!nodeSet.has(node.id)) {
151
+ nodeSet.add(node.id);
152
+ nodes.push(node);
153
+ }
154
+ };
155
+ const addEdge = (edge) => {
156
+ // Ensure source and target nodes exist before adding edge
157
+ if (nodeSet.has(edge.source) && nodeSet.has(edge.target)) {
158
+ const edgeKey = `${edge.source}->${edge.type}->${edge.target}`;
159
+ if (!edgeSet.has(edgeKey)) {
160
+ edgeSet.add(edgeKey);
161
+ edges.push(edge);
162
+ }
163
+ }
164
+ };
165
+ // ==========================================
166
+ // PASS 1: NODES
167
+ // ==========================================
168
+ // 1. Domain Nodes (Bounded Contexts & Top-Level Directories)
169
+ for (const topDir of skeleton.topology.topLevelDirectories) {
170
+ addNode({
171
+ id: `domain:${topDir.toLowerCase()}`,
172
+ type: 'domain',
173
+ label: topDir,
174
+ domain: topDir.toLowerCase()
175
+ });
176
+ }
177
+ // 2. Project Nodes (from manifests)
178
+ for (const manifest of skeleton.manifests) {
179
+ const normPath = manifest.path.replace(/\\/g, '/');
180
+ const filename = path.basename(normPath);
181
+ const projId = `project:${normPath}`;
182
+ const { relPath, domain } = this.resolveRelativePathAndDomain(normPath);
183
+ addNode({
184
+ id: projId,
185
+ type: 'project',
186
+ label: filename,
187
+ file: relPath,
188
+ domain,
189
+ metadata: {
190
+ manifestType: manifest.type,
191
+ ...manifest.contentSummary
192
+ }
193
+ });
194
+ }
195
+ // 3. Schema Nodes (Database models, EF Core, Protobuf, Drizzle, etc.)
196
+ for (const schema of skeleton.schemas) {
197
+ const normFile = schema.file.replace(/\\/g, '/');
198
+ const { relPath, domain } = this.resolveRelativePathAndDomain(normFile);
199
+ for (const model of schema.tablesOrModels) {
200
+ addNode({
201
+ id: `schema:${model}`,
202
+ type: 'schema',
203
+ label: model,
204
+ file: relPath,
205
+ domain,
206
+ metadata: { schemaType: schema.type }
207
+ });
208
+ }
209
+ }
210
+ // 4. Endpoints & Messaging Nodes (from routesAndCommands)
211
+ for (const item of skeleton.routesAndCommands) {
212
+ const normFile = item.file.replace(/\\/g, '/');
213
+ const { relPath, domain } = this.resolveRelativePathAndDomain(normFile);
214
+ if (item.framework === 'MediatR') {
215
+ addNode({
216
+ id: `message:${item.identifier}`,
217
+ type: 'message',
218
+ label: item.identifier,
219
+ file: relPath,
220
+ domain,
221
+ metadata: { signature: item.signature }
222
+ });
223
+ }
224
+ else if (item.framework === 'MassTransit' || item.framework === 'NServiceBus' || item.framework === 'Wolverine') {
225
+ addNode({
226
+ id: `handler:${item.identifier}`,
227
+ type: 'handler',
228
+ label: item.identifier,
229
+ file: relPath,
230
+ domain,
231
+ metadata: { framework: item.framework, signature: item.signature }
232
+ });
233
+ const msgMatch = item.signature.match(/(?:IConsumer|IHandleMessages)<([^>]+)>/) ||
234
+ item.signature.match(/Handle\(([\p{L}\p{N}_]+)/u);
235
+ if (msgMatch) {
236
+ const msgName = msgMatch[1].trim();
237
+ addNode({
238
+ id: `message:${msgName}`,
239
+ type: 'message',
240
+ label: msgName,
241
+ file: relPath,
242
+ domain
243
+ });
244
+ }
245
+ }
246
+ else if (item.framework === 'FluentValidation') {
247
+ addNode({
248
+ id: `validator:${item.identifier}`,
249
+ type: 'handler',
250
+ label: item.identifier,
251
+ file: relPath,
252
+ domain,
253
+ metadata: { framework: 'FluentValidation', signature: item.signature }
254
+ });
255
+ const targetMatch = item.signature.match(/AbstractValidator<([\p{L}\p{N}_]+)>/u);
256
+ if (targetMatch) {
257
+ const targetName = targetMatch[1].trim();
258
+ addNode({
259
+ id: `message:${targetName}`,
260
+ type: 'message',
261
+ label: targetName,
262
+ file: relPath,
263
+ domain
264
+ });
265
+ }
266
+ }
267
+ else if (item.framework === 'Kafka' || item.framework === 'RabbitMQ') {
268
+ addNode({
269
+ id: `handler:${item.identifier}`,
270
+ type: 'handler',
271
+ label: item.identifier,
272
+ file: relPath,
273
+ domain,
274
+ metadata: { framework: item.framework, signature: item.signature }
275
+ });
276
+ const topicMatch = item.signature.match(/(?:topic|queue):\s*["']?([^"'\s]+)["']?/);
277
+ if (topicMatch) {
278
+ const eventTarget = topicMatch[1];
279
+ addNode({
280
+ id: `message:${eventTarget}`,
281
+ type: 'message',
282
+ label: eventTarget,
283
+ file: relPath,
284
+ domain
285
+ });
286
+ }
287
+ }
288
+ else if (item.framework === 'BullMQ') {
289
+ if (item.method === 'QUEUE') {
290
+ const queueName = item.signature.replace(/^Queue:\s*/, '').trim();
291
+ addNode({
292
+ id: `message:${queueName}`,
293
+ type: 'message',
294
+ label: queueName,
295
+ file: relPath,
296
+ domain
297
+ });
298
+ }
299
+ else {
300
+ addNode({
301
+ id: `handler:${item.identifier}`,
302
+ type: 'handler',
303
+ label: item.identifier,
304
+ file: relPath,
305
+ domain,
306
+ metadata: { framework: 'BullMQ', signature: item.signature }
307
+ });
308
+ const queueMatch = item.signature.match(/(?:Worker|Processor):\s*([A-Za-z0-9_.-]+)/i);
309
+ if (queueMatch) {
310
+ const queueName = queueMatch[1];
311
+ addNode({
312
+ id: `message:${queueName}`,
313
+ type: 'message',
314
+ label: queueName,
315
+ file: relPath,
316
+ domain
317
+ });
318
+ }
319
+ }
320
+ }
321
+ else if (item.framework === 'Celery' || item.framework === 'Dramatiq') {
322
+ addNode({
323
+ id: `handler:${item.identifier}`,
324
+ type: 'handler',
325
+ label: item.identifier,
326
+ file: relPath,
327
+ domain,
328
+ metadata: { framework: item.framework, signature: item.signature }
329
+ });
330
+ addNode({
331
+ id: `message:${item.identifier}`,
332
+ type: 'message',
333
+ label: item.identifier,
334
+ file: relPath,
335
+ domain
336
+ });
337
+ }
338
+ else if (item.framework === 'HttpClient') {
339
+ addNode({
340
+ id: `client:${item.signature}`,
341
+ type: 'endpoint',
342
+ label: item.identifier,
343
+ file: relPath,
344
+ domain,
345
+ metadata: {
346
+ framework: 'HttpClient',
347
+ method: item.method,
348
+ signature: item.signature,
349
+ isClient: true
350
+ }
351
+ });
352
+ }
353
+ else if (item.framework === 'GrpcClient') {
354
+ addNode({
355
+ id: `client:${item.signature}`,
356
+ type: 'endpoint',
357
+ label: item.identifier,
358
+ file: relPath,
359
+ domain,
360
+ metadata: {
361
+ framework: 'GrpcClient',
362
+ method: 'RPC',
363
+ signature: item.signature,
364
+ isClient: true
365
+ }
366
+ });
367
+ }
368
+ else if (item.framework === 'RpcClient' || item.method === 'RPC_CLIENT') {
369
+ addNode({
370
+ id: `client:${item.signature}`,
371
+ type: 'endpoint',
372
+ label: item.identifier,
373
+ file: relPath,
374
+ domain,
375
+ metadata: {
376
+ framework: item.framework || 'RpcClient',
377
+ method: 'RPC',
378
+ signature: item.signature,
379
+ isClient: true,
380
+ callType: 'CALLS_RPC'
381
+ }
382
+ });
383
+ }
384
+ else if (item.framework === 'CustomHandler' ||
385
+ item.framework?.endsWith('Handler') ||
386
+ item.framework?.endsWith('VO') ||
387
+ (item.implements && item.implements.length > 0)) {
388
+ addNode({
389
+ id: `handler:${item.identifier}`,
390
+ type: 'handler',
391
+ label: item.identifier,
392
+ file: relPath,
393
+ domain,
394
+ metadata: {
395
+ framework: item.framework,
396
+ signature: item.signature
397
+ }
398
+ });
399
+ }
400
+ else {
401
+ addNode({
402
+ id: `endpoint:${item.signature}`,
403
+ type: 'endpoint',
404
+ label: item.identifier,
405
+ file: relPath,
406
+ domain,
407
+ metadata: {
408
+ framework: item.framework,
409
+ method: item.method,
410
+ signature: item.signature,
411
+ isClient: false
412
+ }
413
+ });
414
+ // If endpoint publishes events, register them as message nodes
415
+ if (item.signature.includes('[publishes:')) {
416
+ const pubMatch = item.signature.match(/\[publishes:\s*([^\]]+)\]/);
417
+ if (pubMatch) {
418
+ const events = pubMatch[1].split(',').map(s => s.trim());
419
+ for (const evt of events) {
420
+ if (evt) {
421
+ addNode({
422
+ id: `message:${evt}`,
423
+ type: 'message',
424
+ label: evt,
425
+ file: relPath,
426
+ domain
427
+ });
428
+ }
429
+ }
430
+ }
431
+ }
432
+ // If Azure Functions trigger consumes a queue/topic, register that message node
433
+ if (item.framework === 'AzureFunctions') {
434
+ const queueMatch = item.signature.match(/(?:ServiceBus|Queue):([A-Za-z0-9_.-]+)/);
435
+ if (queueMatch) {
436
+ addNode({
437
+ id: `message:${queueMatch[1]}`,
438
+ type: 'message',
439
+ label: queueMatch[1],
440
+ file: relPath,
441
+ domain
442
+ });
443
+ }
444
+ }
445
+ }
446
+ // If item declares implemented interfaces/contracts, register interface nodes
447
+ if (item.implements && item.implements.length > 0) {
448
+ for (const iface of item.implements) {
449
+ addNode({
450
+ id: `handler:${iface}`,
451
+ type: 'handler',
452
+ label: iface,
453
+ file: relPath,
454
+ domain,
455
+ metadata: {
456
+ isInterface: true,
457
+ framework: item.framework || 'CustomHandler'
458
+ }
459
+ });
460
+ }
461
+ }
462
+ }
463
+ // 5. Invariant Nodes (from knowledge/ units)
464
+ const units = customUnits || this.loadKnowledgeUnits();
465
+ for (const unit of units) {
466
+ addNode({
467
+ id: `invariant:${unit.id}`,
468
+ type: 'invariant',
469
+ label: `${unit.id}: ${unit.title}`,
470
+ domain: unit.domain,
471
+ metadata: {
472
+ rule: unit.rule,
473
+ reason: unit.reason,
474
+ applies_to: unit.applies_to
475
+ }
476
+ });
477
+ }
478
+ // 6. Deprecation pattern tagging from .akb/standards.yaml
479
+ const standards = StandardsLoader.load(this.repoRoot, this.poolConfig.poolDir);
480
+ if (standards?.standards?.deprecated_patterns && standards.standards.deprecated_patterns.length > 0) {
481
+ for (const node of nodes) {
482
+ for (const dep of standards.standards.deprecated_patterns) {
483
+ try {
484
+ const reg = new RegExp(dep.pattern, 'i');
485
+ if (reg.test(node.label) || (node.file && reg.test(node.file)) || (node.metadata?.signature && reg.test(node.metadata.signature))) {
486
+ node.metadata = {
487
+ ...node.metadata,
488
+ deprecated: true,
489
+ deprecationReason: dep.reason || 'Pattern marked as deprecated'
490
+ };
491
+ break;
492
+ }
493
+ }
494
+ catch { }
495
+ }
496
+ }
497
+ }
498
+ // ==========================================
499
+ // PASS 2: EDGES (All target nodes now exist!)
500
+ // ==========================================
501
+ // 1. Domain -> Project & Domain -> Invariant (CONTAINS)
502
+ for (const node of nodes) {
503
+ if (node.domain && (node.type === 'project' || node.type === 'invariant')) {
504
+ const domainId = `domain:${node.domain.toLowerCase()}`;
505
+ if (nodeSet.has(domainId)) {
506
+ addEdge({ source: domainId, target: node.id, type: 'CONTAINS' });
507
+ }
508
+ }
509
+ }
510
+ // 2. Project -> Project Dependencies (DEPENDS_ON from projectReferences)
511
+ for (const manifest of skeleton.manifests) {
512
+ const projId = `project:${manifest.path.replace(/\\/g, '/')}`;
513
+ if (manifest.contentSummary.projectReferences && Array.isArray(manifest.contentSummary.projectReferences)) {
514
+ for (const refName of manifest.contentSummary.projectReferences) {
515
+ const matchingProj = skeleton.manifests.find(m => path.basename(m.path).toLowerCase() === refName.toLowerCase());
516
+ if (matchingProj) {
517
+ addEdge({
518
+ source: projId,
519
+ target: `project:${matchingProj.path.replace(/\\/g, '/')}`,
520
+ type: 'DEPENDS_ON'
521
+ });
522
+ }
523
+ }
524
+ }
525
+ // Maven reactor modules
526
+ if (manifest.type === 'maven' && Array.isArray(manifest.contentSummary.modules)) {
527
+ for (const mod of manifest.contentSummary.modules) {
528
+ const modProj = skeleton.manifests.find(m => {
529
+ const rel = path.relative(path.dirname(manifest.path), path.dirname(m.path)).replace(/\\/g, '/');
530
+ return rel === mod || path.basename(path.dirname(m.path)) === mod;
531
+ });
532
+ if (modProj) {
533
+ addEdge({
534
+ source: `project:${modProj.path.replace(/\\/g, '/')}`,
535
+ target: projId,
536
+ type: 'DEPENDS_ON'
537
+ });
538
+ }
539
+ }
540
+ }
541
+ // npm workspace dependencies (e.g. packages in pnpm, yarn, lerna monorepos)
542
+ if (manifest.type === 'npm' && manifest.contentSummary.name) {
543
+ const allDeps = [
544
+ ...(manifest.contentSummary.dependencies || []),
545
+ ...(manifest.contentSummary.devDependencies || [])
546
+ ];
547
+ for (const dep of allDeps) {
548
+ const depProj = skeleton.manifests.find(m => m.type === 'npm' && m.contentSummary.name === dep);
549
+ if (depProj && depProj.path !== manifest.path) {
550
+ addEdge({
551
+ source: projId,
552
+ target: `project:${depProj.path.replace(/\\/g, '/')}`,
553
+ type: 'DEPENDS_ON'
554
+ });
555
+ }
556
+ }
557
+ }
558
+ }
559
+ // 3. Solution Manifest -> Sub-Projects (CONTAINS) & Project -> Endpoints / Schemas (EXPOSES / CONTAINS)
560
+ // 3a. Wire Solution manifest (.sln) to contained sub-projects (.csproj)
561
+ for (const solProj of nodes.filter(n => n.type === 'project' && n.metadata?.kind === 'solution')) {
562
+ const solProjects = solProj.metadata?.projects;
563
+ if (Array.isArray(solProjects)) {
564
+ for (const sp of solProjects) {
565
+ const spNorm = (sp.path || '').replace(/\\/g, '/');
566
+ const spFilename = path.basename(spNorm).toLowerCase();
567
+ const targetProj = nodes.find(n => n.type === 'project' && n.metadata?.kind !== 'solution' && n.file && (n.file === spNorm ||
568
+ n.file.endsWith('/' + spNorm) ||
569
+ path.basename(n.file).toLowerCase() === spFilename));
570
+ if (targetProj) {
571
+ addEdge({ source: solProj.id, target: targetProj.id, type: 'CONTAINS' });
572
+ }
573
+ }
574
+ }
575
+ }
576
+ // 3b. Wire Project -> Endpoints & Project -> Schemas (EXPOSES / CONTAINS)
577
+ // Exclude solution manifests to prevent solution node from falsely claiming every endpoint in the repo
578
+ const nonSolutionProjects = nodes.filter(n => n.type === 'project' && n.metadata?.kind !== 'solution');
579
+ const projectDirList = nonSolutionProjects
580
+ .map(p => ({
581
+ id: p.id,
582
+ dir: p.file ? path.dirname(p.file).replace(/\\/g, '/') : ''
583
+ }))
584
+ .sort((a, b) => b.dir.length - a.dir.length);
585
+ const findOwningProjectId = (filePath) => {
586
+ const norm = filePath.replace(/\\/g, '/');
587
+ let fallbackRootId = null;
588
+ for (const p of projectDirList) {
589
+ if (!p.dir || p.dir === '.') {
590
+ fallbackRootId = p.id;
591
+ }
592
+ else if (norm.startsWith(p.dir + '/') || norm === p.dir) {
593
+ return p.id;
594
+ }
595
+ }
596
+ return fallbackRootId;
597
+ };
598
+ const serverEndpoints = nodes.filter(n => n.type === 'endpoint' && !n.metadata?.isClient);
599
+ for (const ep of serverEndpoints) {
600
+ if (ep.file) {
601
+ const ownerId = findOwningProjectId(ep.file);
602
+ if (ownerId) {
603
+ addEdge({ source: ownerId, target: ep.id, type: 'EXPOSES' });
604
+ }
605
+ }
606
+ }
607
+ const schemaNodes = nodes.filter(n => n.type === 'schema');
608
+ for (const sc of schemaNodes) {
609
+ if (sc.file) {
610
+ const ownerId = findOwningProjectId(sc.file);
611
+ if (ownerId) {
612
+ addEdge({ source: ownerId, target: sc.id, type: 'CONTAINS' });
613
+ }
614
+ }
615
+ }
616
+ // Pre-index schema models for O(1) persistence matching
617
+ const allModels = [];
618
+ const seenModels = new Set();
619
+ for (const schema of skeleton.schemas) {
620
+ for (const model of schema.tablesOrModels) {
621
+ const lower = model.toLowerCase();
622
+ if (!seenModels.has(lower)) {
623
+ seenModels.add(lower);
624
+ allModels.push({ model, lower, targetId: `schema:${model}` });
625
+ }
626
+ }
627
+ }
628
+ const addPersistsEdges = (sourceId, sig, ident) => {
629
+ const combined = `${sig} ${ident}`.toLowerCase();
630
+ for (const m of allModels) {
631
+ if (combined.includes(m.lower)) {
632
+ addEdge({ source: sourceId, target: m.targetId, type: 'PERSISTS' });
633
+ }
634
+ }
635
+ };
636
+ // 4. Handlers -> Messages (HANDLES) & Handlers -> Schemas (PERSISTS)
637
+ for (const item of skeleton.routesAndCommands) {
638
+ if (item.framework === 'MassTransit' || item.framework === 'NServiceBus' || item.framework === 'Wolverine') {
639
+ const handlerId = `handler:${item.identifier}`;
640
+ const msgMatch = item.signature.match(/(?:IConsumer|IHandleMessages)<([^>]+)>/) ||
641
+ item.signature.match(/Handle\(([\p{L}\p{N}_]+)/u);
642
+ if (msgMatch) {
643
+ addEdge({ source: handlerId, target: `message:${msgMatch[1].trim()}`, type: 'HANDLES' });
644
+ }
645
+ addPersistsEdges(handlerId, item.signature, item.identifier);
646
+ }
647
+ else if (item.framework === 'Kafka' || item.framework === 'RabbitMQ') {
648
+ const handlerId = `handler:${item.identifier}`;
649
+ const topicMatch = item.signature.match(/(?:topic|queue):\s*["']?([^"'\s]+)["']?/);
650
+ if (topicMatch) {
651
+ addEdge({ source: handlerId, target: `message:${topicMatch[1]}`, type: 'CONSUMES_EVENT' });
652
+ }
653
+ addPersistsEdges(handlerId, item.signature, item.identifier);
654
+ }
655
+ else if (item.framework === 'FluentValidation') {
656
+ const validatorId = `validator:${item.identifier}`;
657
+ const targetMatch = item.signature.match(/AbstractValidator<([\p{L}\p{N}_]+)>/u);
658
+ if (targetMatch) {
659
+ addEdge({ source: validatorId, target: `message:${targetMatch[1].trim()}`, type: 'VALIDATES' });
660
+ }
661
+ }
662
+ else if (item.framework === 'BullMQ') {
663
+ if (item.method !== 'QUEUE') {
664
+ const handlerId = `handler:${item.identifier}`;
665
+ const queueMatch = item.signature.match(/(?:Worker|Processor):\s*([A-Za-z0-9_.-]+)/i);
666
+ if (queueMatch) {
667
+ addEdge({ source: handlerId, target: `message:${queueMatch[1]}`, type: 'CONSUMES_EVENT' });
668
+ }
669
+ addPersistsEdges(handlerId, item.signature, item.identifier);
670
+ }
671
+ }
672
+ else if (item.framework === 'Celery' || item.framework === 'Dramatiq') {
673
+ const handlerId = `handler:${item.identifier}`;
674
+ addEdge({
675
+ source: handlerId,
676
+ target: `message:${item.identifier}`,
677
+ type: 'CONSUMES_EVENT'
678
+ });
679
+ addPersistsEdges(handlerId, item.signature, item.identifier);
680
+ }
681
+ else if (item.framework !== 'MediatR') {
682
+ const epId = `endpoint:${item.signature}`;
683
+ if (item.framework === 'AzureFunctions') {
684
+ const queueMatch = item.signature.match(/(?:ServiceBus|Queue):([A-Za-z0-9_.-]+)/);
685
+ if (queueMatch) {
686
+ addEdge({ source: epId, target: `message:${queueMatch[1]}`, type: 'CONSUMES_EVENT' });
687
+ }
688
+ }
689
+ addPersistsEdges(epId, item.signature, '');
690
+ }
691
+ }
692
+ // 5. Endpoints -> Messages (DISPATCHES) with Canonical Event Support
693
+ const messages = nodes.filter(n => n.type === 'message');
694
+ for (const ep of serverEndpoints) {
695
+ const epSig = (ep.metadata?.signature || ep.label).toLowerCase();
696
+ for (const msg of messages) {
697
+ const msgLabelLower = msg.label.toLowerCase();
698
+ const canonMsg = this.canonicalEventName(msg.label);
699
+ if (epSig.includes(msgLabelLower) || epSig.includes(canonMsg)) {
700
+ addEdge({ source: ep.id, target: msg.id, type: 'DISPATCHES' });
701
+ }
702
+ }
703
+ }
704
+ // 6. Canonical Event Matching & Cross-Language Messaging (RELATES_TO)
705
+ const canonicalGroups = new Map();
706
+ for (const msg of messages) {
707
+ const canon = this.canonicalEventName(msg.label);
708
+ if (!canonicalGroups.has(canon)) {
709
+ canonicalGroups.set(canon, []);
710
+ }
711
+ canonicalGroups.get(canon).push(msg);
712
+ }
713
+ for (const [canon, group] of canonicalGroups.entries()) {
714
+ if (group.length > 1) {
715
+ for (let i = 0; i < group.length; i++) {
716
+ for (let j = i + 1; j < group.length; j++) {
717
+ addEdge({
718
+ source: group[i].id,
719
+ target: group[j].id,
720
+ type: 'RELATES_TO',
721
+ metadata: { canonicalEvent: canon }
722
+ });
723
+ addEdge({
724
+ source: group[j].id,
725
+ target: group[i].id,
726
+ type: 'RELATES_TO',
727
+ metadata: { canonicalEvent: canon }
728
+ });
729
+ }
730
+ }
731
+ }
732
+ }
733
+ // 7. Cross-Boundary HTTP Calls (CALLS_HTTP)
734
+ const clientHttpNodes = nodes.filter(n => n.type === 'endpoint' && n.metadata?.framework === 'HttpClient');
735
+ for (const client of clientHttpNodes) {
736
+ const clientUrl = client.label;
737
+ const clientMethod = client.metadata?.method;
738
+ for (const serverEp of serverEndpoints) {
739
+ const serverRoute = this.extractEndpointRoute(serverEp.metadata?.signature || serverEp.label);
740
+ if (serverRoute) {
741
+ const methodMatches = !clientMethod || clientMethod === 'ANY' || serverRoute.method === 'ANY' || serverRoute.method === 'ALL' || clientMethod === serverRoute.method;
742
+ if (methodMatches && this.routesMatch(clientUrl, serverRoute.route)) {
743
+ // Wire from client call node to server endpoint
744
+ addEdge({
745
+ source: client.id,
746
+ target: serverEp.id,
747
+ type: 'CALLS_HTTP'
748
+ });
749
+ // Wire from most specific caller project to server endpoint
750
+ let callerProj;
751
+ let maxPrefixLen = -1;
752
+ for (const proj of nodes.filter(n => n.type === 'project' && n.metadata?.kind !== 'solution')) {
753
+ if (proj.file && client.file) {
754
+ const projDir = path.dirname(proj.file).replace(/\\/g, '/');
755
+ if (projDir === '.' || client.file.startsWith(projDir + '/') || client.file === proj.file) {
756
+ if (projDir.length > maxPrefixLen) {
757
+ maxPrefixLen = projDir.length;
758
+ callerProj = proj;
759
+ }
760
+ }
761
+ }
762
+ }
763
+ if (callerProj) {
764
+ addEdge({
765
+ source: callerProj.id,
766
+ target: serverEp.id,
767
+ type: 'CALLS_HTTP'
768
+ });
769
+ }
770
+ }
771
+ }
772
+ }
773
+ }
774
+ // 8. Cross-Boundary gRPC Calls (CALLS_GRPC)
775
+ const clientGrpcNodes = nodes.filter(n => n.type === 'endpoint' && n.metadata?.framework === 'GrpcClient');
776
+ const serverRpcs = nodes.filter(n => n.type === 'endpoint' && (n.metadata?.framework === 'gRPC/Protobuf' ||
777
+ n.metadata?.framework === 'gRPC' ||
778
+ n.metadata?.framework === 'gRPC/.NET' ||
779
+ n.metadata?.framework === 'gRPC/Java' ||
780
+ n.metadata?.method === 'RPC') && !n.metadata?.isClient);
781
+ for (const client of clientGrpcNodes) {
782
+ const clientRpcName = client.label.toLowerCase();
783
+ for (const serverRpc of serverRpcs) {
784
+ const serverRpcName = (serverRpc.label || '').toLowerCase();
785
+ const serverSig = (serverRpc.metadata?.signature || '').toLowerCase();
786
+ if (serverRpcName === clientRpcName || serverSig.includes(`.${clientRpcName}(`) || serverSig.includes(` ${clientRpcName}(`)) {
787
+ addEdge({
788
+ source: client.id,
789
+ target: serverRpc.id,
790
+ type: 'CALLS_GRPC'
791
+ });
792
+ let callerProj;
793
+ let maxPrefixLen = -1;
794
+ for (const proj of nodes.filter(n => n.type === 'project' && n.metadata?.kind !== 'solution')) {
795
+ if (proj.file && client.file) {
796
+ const projDir = path.dirname(proj.file).replace(/\\/g, '/');
797
+ if (projDir === '.' || client.file.startsWith(projDir + '/') || client.file === proj.file) {
798
+ if (projDir.length > maxPrefixLen) {
799
+ maxPrefixLen = projDir.length;
800
+ callerProj = proj;
801
+ }
802
+ }
803
+ }
804
+ }
805
+ if (callerProj) {
806
+ addEdge({
807
+ source: callerProj.id,
808
+ target: serverRpc.id,
809
+ type: 'CALLS_GRPC'
810
+ });
811
+ }
812
+ }
813
+ }
814
+ }
815
+ // 9. Cross-Boundary RPC / Custom Contract Calls (CALLS_RPC)
816
+ const clientRpcNodes = nodes.filter(n => n.type === 'endpoint' && n.metadata?.isClient && (n.metadata?.callType === 'CALLS_RPC' || n.metadata?.framework === 'RpcClient'));
817
+ const serverTargets = nodes.filter(n => (n.type === 'endpoint' || n.type === 'handler') && !n.metadata?.isClient);
818
+ for (const client of clientRpcNodes) {
819
+ const clientTarget = client.label.toLowerCase();
820
+ for (const server of serverTargets) {
821
+ const serverLabel = (server.label || '').toLowerCase();
822
+ const serverSig = (server.metadata?.signature || '').toLowerCase();
823
+ const serverId = server.id.toLowerCase();
824
+ if (serverLabel === clientTarget ||
825
+ serverLabel.endsWith(clientTarget) ||
826
+ clientTarget.endsWith(serverLabel) ||
827
+ serverSig.includes(clientTarget) ||
828
+ serverId.includes(clientTarget)) {
829
+ addEdge({
830
+ source: client.id,
831
+ target: server.id,
832
+ type: 'CALLS_RPC'
833
+ });
834
+ let callerProj;
835
+ let maxPrefixLen = -1;
836
+ for (const proj of nodes.filter(n => n.type === 'project' && n.metadata?.kind !== 'solution')) {
837
+ if (proj.file && client.file) {
838
+ const projDir = path.dirname(proj.file).replace(/\\/g, '/');
839
+ if (projDir === '.' || client.file.startsWith(projDir + '/') || client.file === proj.file) {
840
+ if (projDir.length > maxPrefixLen) {
841
+ maxPrefixLen = projDir.length;
842
+ callerProj = proj;
843
+ }
844
+ }
845
+ }
846
+ }
847
+ if (callerProj) {
848
+ addEdge({
849
+ source: callerProj.id,
850
+ target: server.id,
851
+ type: 'CALLS_RPC'
852
+ });
853
+ }
854
+ // Wire caller handler/endpoint located in the same file as client call
855
+ const fileCallers = nodes.filter(n => (n.type === 'handler' || n.type === 'endpoint') && !n.metadata?.isClient && n.file && n.file === client.file);
856
+ for (const fc of fileCallers) {
857
+ addEdge({
858
+ source: fc.id,
859
+ target: server.id,
860
+ type: 'CALLS_RPC'
861
+ });
862
+ }
863
+ }
864
+ }
865
+ }
866
+ // 10. Handler Implementation of Interfaces/Contracts (IMPLEMENTS)
867
+ for (const item of skeleton.routesAndCommands) {
868
+ if (item.implements && item.implements.length > 0) {
869
+ const handlerId = `handler:${item.identifier}`;
870
+ for (const iface of item.implements) {
871
+ addEdge({
872
+ source: handlerId,
873
+ target: `handler:${iface}`,
874
+ type: 'IMPLEMENTS'
875
+ });
876
+ }
877
+ }
878
+ }
879
+ // 6. Invariants -> Invariants (RELATES_TO) & Invariants -> Projects (CONSTRAINS)
880
+ for (const unit of units) {
881
+ const invId = `invariant:${unit.id}`;
882
+ for (const rel of unit.related_items || []) {
883
+ addEdge({ source: invId, target: `invariant:${rel}`, type: 'RELATES_TO' });
884
+ }
885
+ for (const proj of nonSolutionProjects) {
886
+ const projFile = proj.file || '';
887
+ const projDir = projFile ? path.dirname(projFile) : '';
888
+ const isGlobal = !unit.applies_to || unit.applies_to.length === 0 || unit.applies_to.some(p => p === '**/*' || p === '*' || p === 'src/**/*');
889
+ const matchesProj = isGlobal ||
890
+ (projFile && this.matchesAppliesTo(unit, projFile)) ||
891
+ (projDir && this.matchesAppliesTo(unit, `${projDir}/dummy.ts`));
892
+ if (matchesProj) {
893
+ addEdge({ source: invId, target: proj.id, type: 'CONSTRAINS' });
894
+ }
895
+ }
896
+ }
897
+ const graph = {
898
+ timestamp: new Date().toISOString(),
899
+ repoPath: this.repoRoot,
900
+ nodes,
901
+ edges
902
+ };
903
+ if (useCache && !hasCustomUnits) {
904
+ GraphBuilder.inMemoryCache.set(this.repoRoot, { graphKey: keyString, graph });
905
+ try {
906
+ fs.mkdirSync(path.dirname(cacheFile), { recursive: true });
907
+ let cacheData = {};
908
+ if (fs.existsSync(cacheFile)) {
909
+ try {
910
+ cacheData = JSON.parse(fs.readFileSync(cacheFile, 'utf-8')) || {};
911
+ }
912
+ catch { }
913
+ }
914
+ cacheData.graphKey = currentKey;
915
+ cacheData.graph = graph;
916
+ fs.writeFileSync(cacheFile, JSON.stringify(cacheData), 'utf-8');
917
+ }
918
+ catch { }
919
+ }
920
+ return graph;
921
+ }
922
+ /**
923
+ * Traverses the graph and extracts the 1-hop and 2-hop topological neighborhood
924
+ * surrounding a target node, formatted as an LLM-ready prompt slice.
925
+ */
926
+ extractNeighborhood(graph, targetSearch, maxHops = 2) {
927
+ const searchLower = targetSearch.toLowerCase().replace(/\\/g, '/');
928
+ // Find center node matching search term (prefer exact ID/label, then substring match)
929
+ let centerNode = graph.nodes.find(n => n.id.toLowerCase() === searchLower || n.label.toLowerCase() === searchLower) ||
930
+ graph.nodes.find(n => n.id.toLowerCase().includes(searchLower) || n.label.toLowerCase().includes(searchLower)) ||
931
+ graph.nodes.find(n => n.file && n.file.toLowerCase().includes(searchLower));
932
+ // Fallback: If no node matches directly and targetSearch looks like a file path or exists on disk,
933
+ // resolve to the owning project: node (longest matching path.dirname(proj.file) prefix).
934
+ let resolvedViaProjectFallback = false;
935
+ if (!centerNode) {
936
+ const normTarget = path.isAbsolute(targetSearch)
937
+ ? path.relative(this.repoRoot, targetSearch).replace(/\\/g, '/')
938
+ : targetSearch.replace(/\\/g, '/');
939
+ const isFilePathLike = normTarget.includes('/') ||
940
+ normTarget.includes('\\') ||
941
+ /\.[a-zA-Z][a-zA-Z0-9]{0,7}$/.test(normTarget) ||
942
+ fs.existsSync(path.resolve(this.repoRoot, targetSearch));
943
+ if (isFilePathLike) {
944
+ const nonSolutionProjects = graph.nodes.filter(n => n.type === 'project' && n.file && n.metadata?.kind !== 'solution');
945
+ let bestProj;
946
+ let maxPrefixLen = -1;
947
+ const targetDir = path.dirname(normTarget).replace(/\\/g, '/');
948
+ const hasSpecificDir = targetDir !== '.' && targetDir !== '';
949
+ for (const proj of nonSolutionProjects) {
950
+ if (!proj.file)
951
+ continue;
952
+ const projDir = path.dirname(proj.file).replace(/\\/g, '/');
953
+ const isDirectMatch = normTarget === proj.file ||
954
+ normTarget.startsWith(projDir + '/') ||
955
+ normTarget.toLowerCase().includes(projDir.toLowerCase() + '/');
956
+ const isSubdirMatch = hasSpecificDir && projDir.toLowerCase().includes(targetDir.toLowerCase());
957
+ // For bare filenames (e.g. MyHelper.cs where targetDir is '.'),
958
+ // verify if the file actually exists inside this project directory on disk
959
+ const isBareFileInProject = !hasSpecificDir &&
960
+ fs.existsSync(path.resolve(this.repoRoot, projDir, normTarget));
961
+ if (isDirectMatch || isSubdirMatch || isBareFileInProject) {
962
+ if (projDir.length > maxPrefixLen) {
963
+ maxPrefixLen = projDir.length;
964
+ bestProj = proj;
965
+ }
966
+ }
967
+ }
968
+ if (!bestProj && nonSolutionProjects.length === 0) {
969
+ bestProj = graph.nodes.find(n => n.type === 'project');
970
+ }
971
+ if (bestProj) {
972
+ centerNode = bestProj;
973
+ resolvedViaProjectFallback = true;
974
+ }
975
+ }
976
+ }
977
+ if (!centerNode) {
978
+ return null;
979
+ }
980
+ const visitedNodes = new Set([centerNode.id]);
981
+ const includedEdges = [];
982
+ let currentLevel = [centerNode.id];
983
+ for (let hop = 0; hop < maxHops; hop++) {
984
+ const nextLevel = [];
985
+ for (const nodeId of currentLevel) {
986
+ // Collect outbound and inbound edges
987
+ for (const edge of graph.edges) {
988
+ if (edge.source === nodeId && !visitedNodes.has(edge.target)) {
989
+ visitedNodes.add(edge.target);
990
+ includedEdges.push(edge);
991
+ nextLevel.push(edge.target);
992
+ }
993
+ else if (edge.target === nodeId && !visitedNodes.has(edge.source)) {
994
+ visitedNodes.add(edge.source);
995
+ includedEdges.push(edge);
996
+ nextLevel.push(edge.source);
997
+ }
998
+ else if ((edge.source === nodeId || edge.target === nodeId) && !includedEdges.includes(edge)) {
999
+ includedEdges.push(edge);
1000
+ }
1001
+ }
1002
+ }
1003
+ currentLevel = nextLevel;
1004
+ if (currentLevel.length === 0)
1005
+ break;
1006
+ }
1007
+ const neighborhoodNodes = graph.nodes.filter(n => visitedNodes.has(n.id));
1008
+ // Detect any deprecation warnings in neighborhood
1009
+ const deprecationWarnings = [];
1010
+ for (const n of neighborhoodNodes) {
1011
+ if (n.metadata?.deprecated) {
1012
+ deprecationWarnings.push(`Entity [${n.type}] "${n.label}" is flagged as deprecated: ${n.metadata.deprecationReason || 'Avoid in modern code'}`);
1013
+ }
1014
+ }
1015
+ // Resolve all active Knowledge Units governing this neighborhood
1016
+ const allUnits = this.loadKnowledgeUnits();
1017
+ const activeInvariants = [];
1018
+ const normFiles = neighborhoodNodes
1019
+ .map(n => n.file)
1020
+ .filter((f) => Boolean(f))
1021
+ .map(f => f.toLowerCase());
1022
+ if (centerNode.file)
1023
+ normFiles.push(centerNode.file.toLowerCase());
1024
+ normFiles.push(searchLower);
1025
+ for (const unit of allUnits) {
1026
+ // 1. Direct node match in neighborhood
1027
+ const directNodeMatch = neighborhoodNodes.some(n => n.id === `invariant:${unit.id}` || n.label.includes(unit.id));
1028
+ if (directNodeMatch) {
1029
+ if (!activeInvariants.some(u => u.id === unit.id))
1030
+ activeInvariants.push(unit);
1031
+ continue;
1032
+ }
1033
+ // 2. Domain match with centerNode
1034
+ if (centerNode.domain && unit.domain && centerNode.domain.toLowerCase() === unit.domain.toLowerCase()) {
1035
+ if (!activeInvariants.some(u => u.id === unit.id))
1036
+ activeInvariants.push(unit);
1037
+ continue;
1038
+ }
1039
+ // 3. applies_to glob pattern match
1040
+ if (unit.applies_to && unit.applies_to.length > 0 && normFiles.length > 0) {
1041
+ const matchesAnyFile = normFiles.some(f => this.matchesAppliesTo(unit, f));
1042
+ if (matchesAnyFile) {
1043
+ if (!activeInvariants.some(u => u.id === unit.id))
1044
+ activeInvariants.push(unit);
1045
+ continue;
1046
+ }
1047
+ }
1048
+ }
1049
+ // Build structured Markdown prompt slice
1050
+ const lines = [];
1051
+ if (deprecationWarnings.length > 0) {
1052
+ lines.push('### ⚠️ Architectural Deprecation Warnings');
1053
+ for (const warn of deprecationWarnings) {
1054
+ lines.push(`- **WARNING**: ${warn}`);
1055
+ }
1056
+ lines.push('');
1057
+ }
1058
+ lines.push(`## Architectural Context: [${centerNode.type.toUpperCase()}] ${centerNode.label}`);
1059
+ if (resolvedViaProjectFallback) {
1060
+ lines.push(`- **Resolved Target File**: \`${targetSearch}\` (via owning project \`${centerNode.label}\`)`);
1061
+ }
1062
+ if (centerNode.file)
1063
+ lines.push(`- **File**: \`${centerNode.file}\``);
1064
+ if (centerNode.domain)
1065
+ lines.push(`- **Domain**: \`${centerNode.domain}\``);
1066
+ if (centerNode.metadata?.signature)
1067
+ lines.push(`- **Signature**: \`${centerNode.metadata.signature}\``);
1068
+ if (centerNode.metadata?.rule)
1069
+ lines.push(`- **Rule**: ${centerNode.metadata.rule}`);
1070
+ lines.push('\n### Connected Topological Entities');
1071
+ for (const edge of includedEdges) {
1072
+ const src = graph.nodes.find(n => n.id === edge.source);
1073
+ const tgt = graph.nodes.find(n => n.id === edge.target);
1074
+ if (src && tgt) {
1075
+ lines.push(`- [${src.type}] \`${src.label}\` --**${edge.type}**--> [${tgt.type}] \`${tgt.label}\``);
1076
+ }
1077
+ }
1078
+ if (activeInvariants.length > 0) {
1079
+ lines.push('\n### Active Architectural Invariants & Target Patterns');
1080
+ for (const inv of activeInvariants) {
1081
+ lines.push(`\n#### [${inv.id}] ${inv.title}`);
1082
+ if (inv.rule)
1083
+ lines.push(`- **Rule**: ${inv.rule}`);
1084
+ if (inv.skill_file) {
1085
+ let absSkill = inv.skill_file;
1086
+ if (!path.isAbsolute(inv.skill_file)) {
1087
+ const inPool = path.join(this.poolConfig.poolDir, inv.skill_file);
1088
+ const inRepo = path.join(this.repositoryRoot, inv.skill_file);
1089
+ if (fs.existsSync(inPool)) {
1090
+ absSkill = inPool;
1091
+ }
1092
+ else if (fs.existsSync(inRepo)) {
1093
+ absSkill = inRepo;
1094
+ }
1095
+ else {
1096
+ absSkill = path.resolve(this.repositoryRoot, inv.skill_file);
1097
+ }
1098
+ }
1099
+ absSkill = path.resolve(absSkill).replace(/\\/g, '/');
1100
+ lines.push(`- **Skill Specification**: [\`${inv.skill_file}\`](file:///${absSkill})`);
1101
+ }
1102
+ if (inv.reference_files && inv.reference_files.length > 0) {
1103
+ const refLinks = inv.reference_files.map(rf => {
1104
+ let absRef = rf;
1105
+ if (!path.isAbsolute(rf)) {
1106
+ const inPool = path.join(this.poolConfig.poolDir, rf);
1107
+ const inRepo = path.join(this.repositoryRoot, rf);
1108
+ if (fs.existsSync(inPool)) {
1109
+ absRef = inPool;
1110
+ }
1111
+ else if (fs.existsSync(inRepo)) {
1112
+ absRef = inRepo;
1113
+ }
1114
+ else {
1115
+ absRef = path.resolve(this.repositoryRoot, rf);
1116
+ }
1117
+ }
1118
+ absRef = path.resolve(absRef).replace(/\\/g, '/');
1119
+ return `[\`${path.basename(rf)}\`](file:///${absRef})`;
1120
+ }).join(', ');
1121
+ lines.push(`- **Reference Guides**: ${refLinks}`);
1122
+ }
1123
+ if (inv.workflow_gates && inv.workflow_gates.length > 0) {
1124
+ lines.push(`- **Workflow Gates**:`);
1125
+ for (let i = 0; i < inv.workflow_gates.length; i++) {
1126
+ lines.push(` ${i + 1}. ${inv.workflow_gates[i]}`);
1127
+ }
1128
+ }
1129
+ if (inv.do && inv.do.length > 0) {
1130
+ lines.push(`- **Target Patterns (DO)**:`);
1131
+ for (const item of inv.do)
1132
+ lines.push(` • ${item}`);
1133
+ }
1134
+ if (inv.dont && inv.dont.length > 0) {
1135
+ lines.push(`- **Forbidden Anti-Patterns (DONT)**:`);
1136
+ for (const item of inv.dont)
1137
+ lines.push(` • ${item}`);
1138
+ }
1139
+ if (inv.reason)
1140
+ lines.push(`- **Reason**: ${inv.reason}`);
1141
+ }
1142
+ }
1143
+ return {
1144
+ centerNode,
1145
+ nodes: neighborhoodNodes,
1146
+ edges: includedEdges,
1147
+ formattedContext: lines.join('\n'),
1148
+ activeInvariants: activeInvariants.length > 0 ? activeInvariants : undefined,
1149
+ deprecationWarnings: deprecationWarnings.length > 0 ? deprecationWarnings : undefined
1150
+ };
1151
+ }
1152
+ /**
1153
+ * Generates a valid GitHub-flavored Mermaid graph diagram from the graph.
1154
+ * Supports domain/project subgraph clustering to provide high-level architectural structure.
1155
+ */
1156
+ exportMermaid(graph, filterNodesOrOptions, filterEdges, options) {
1157
+ let actualNodes;
1158
+ let actualEdges = filterEdges;
1159
+ let actualOptions = options;
1160
+ if (filterNodesOrOptions && !Array.isArray(filterNodesOrOptions)) {
1161
+ actualOptions = filterNodesOrOptions;
1162
+ actualNodes = undefined;
1163
+ actualEdges = undefined;
1164
+ }
1165
+ else if (Array.isArray(filterNodesOrOptions)) {
1166
+ actualNodes = filterNodesOrOptions;
1167
+ }
1168
+ const maxNodes = actualOptions?.maxNodes !== undefined ? actualOptions.maxNodes : 40;
1169
+ let candidateNodes = [...graph.nodes];
1170
+ if (actualOptions?.nodeTypes) {
1171
+ const allowed = Array.isArray(actualOptions.nodeTypes)
1172
+ ? actualOptions.nodeTypes.map(t => t.trim().toLowerCase())
1173
+ : actualOptions.nodeTypes.split(',').map(t => t.trim().toLowerCase());
1174
+ if (allowed.length > 0) {
1175
+ candidateNodes = candidateNodes.filter(n => allowed.includes(n.type.toLowerCase()));
1176
+ }
1177
+ }
1178
+ // Edge degree calculation to prioritize connected entities
1179
+ const degreeMap = new Map();
1180
+ for (const edge of graph.edges) {
1181
+ degreeMap.set(edge.source, (degreeMap.get(edge.source) || 0) + 1);
1182
+ degreeMap.set(edge.target, (degreeMap.get(edge.target) || 0) + 1);
1183
+ }
1184
+ // Prioritize connected project, endpoint, handler, and schema nodes over empty domain directory nodes
1185
+ const typeWeight = (type) => {
1186
+ switch (type) {
1187
+ case 'endpoint': return 50;
1188
+ case 'handler': return 50;
1189
+ case 'schema': return 45;
1190
+ case 'project': return 40;
1191
+ case 'message': return 35;
1192
+ case 'invariant': return 30;
1193
+ case 'domain': return 0;
1194
+ default: return 10;
1195
+ }
1196
+ };
1197
+ candidateNodes.sort((a, b) => {
1198
+ const degA = degreeMap.get(a.id) || 0;
1199
+ const degB = degreeMap.get(b.id) || 0;
1200
+ const scoreA = typeWeight(a.type) + (degA > 0 ? 100 : 0) + degA * 2;
1201
+ const scoreB = typeWeight(b.type) + (degB > 0 ? 100 : 0) + degB * 2;
1202
+ return scoreB - scoreA;
1203
+ });
1204
+ const nodes = actualNodes || (maxNodes > 0 ? candidateNodes.slice(0, maxNodes) : candidateNodes);
1205
+ const edges = actualEdges || graph.edges.filter(e => nodes.some(n => n.id === e.source) && nodes.some(n => n.id === e.target));
1206
+ const lines = ['flowchart TD'];
1207
+ const clustered = actualOptions?.clustered ?? true;
1208
+ if (clustered) {
1209
+ const domainGroups = new Map();
1210
+ const unassigned = [];
1211
+ for (const node of nodes) {
1212
+ if (node.type !== 'domain' && node.domain) {
1213
+ const d = node.domain.toLowerCase();
1214
+ if (!domainGroups.has(d))
1215
+ domainGroups.set(d, []);
1216
+ domainGroups.get(d).push(node);
1217
+ }
1218
+ else {
1219
+ unassigned.push(node);
1220
+ }
1221
+ }
1222
+ // Output domain subgraphs
1223
+ for (const [dom, groupNodes] of domainGroups.entries()) {
1224
+ const subId = `sub_${dom.replace(/[^a-zA-Z0-9_]/g, '_')}`;
1225
+ const title = dom.charAt(0).toUpperCase() + dom.slice(1);
1226
+ lines.push(` subgraph ${subId} ["Domain: ${title}"]`);
1227
+ for (const node of groupNodes) {
1228
+ const sanitizedId = node.id.replace(/[^a-zA-Z0-9_]/g, '_');
1229
+ const cleanLabel = node.label.replace(/"/g, "'").replace(/[\[\]]/g, '');
1230
+ const depClass = node.metadata?.deprecated ? ':::deprecated' : '';
1231
+ const depPrefix = node.metadata?.deprecated ? '⚠️ ' : '';
1232
+ lines.push(` ${sanitizedId}["${depPrefix}[${node.type}] ${cleanLabel}"]${depClass}`);
1233
+ }
1234
+ lines.push(' end');
1235
+ }
1236
+ // Output top-level / unassigned nodes
1237
+ for (const node of unassigned) {
1238
+ const sanitizedId = node.id.replace(/[^a-zA-Z0-9_]/g, '_');
1239
+ const cleanLabel = node.label.replace(/"/g, "'").replace(/[\[\]]/g, '');
1240
+ const depClass = node.metadata?.deprecated ? ':::deprecated' : '';
1241
+ const depPrefix = node.metadata?.deprecated ? '⚠️ ' : '';
1242
+ lines.push(` ${sanitizedId}["${depPrefix}[${node.type}] ${cleanLabel}"]${depClass}`);
1243
+ }
1244
+ }
1245
+ else {
1246
+ for (const node of nodes) {
1247
+ const sanitizedId = node.id.replace(/[^a-zA-Z0-9_]/g, '_');
1248
+ const cleanLabel = node.label.replace(/"/g, "'").replace(/[\[\]]/g, '');
1249
+ const depClass = node.metadata?.deprecated ? ':::deprecated' : '';
1250
+ const depPrefix = node.metadata?.deprecated ? '⚠️ ' : '';
1251
+ lines.push(` ${sanitizedId}["${depPrefix}[${node.type}] ${cleanLabel}"]${depClass}`);
1252
+ }
1253
+ }
1254
+ for (const edge of edges) {
1255
+ const srcId = edge.source.replace(/[^a-zA-Z0-9_]/g, '_');
1256
+ const tgtId = edge.target.replace(/[^a-zA-Z0-9_]/g, '_');
1257
+ lines.push(` ${srcId} -->|${edge.type}| ${tgtId}`);
1258
+ }
1259
+ const hasDeprecated = nodes.some(n => n.metadata?.deprecated);
1260
+ if (hasDeprecated) {
1261
+ lines.push(' classDef deprecated fill:#ffebee,stroke:#d32f2f,stroke-width:2px,stroke-dasharray: 5 5;');
1262
+ }
1263
+ return lines.join('\n');
1264
+ }
1265
+ loadKnowledgeUnits() {
1266
+ const localKDir = path.join(this.repoRoot, 'knowledge');
1267
+ const knowledgeDir = fs.existsSync(localKDir) ? localKDir : this.poolConfig.knowledgeDir;
1268
+ if (!fs.existsSync(knowledgeDir))
1269
+ return [];
1270
+ const currentMtime = this.getKnowledgeMaxMtime();
1271
+ const cacheKey = fs.existsSync(localKDir) ? this.repoRoot : this.poolConfig.poolDir;
1272
+ const cached = GraphBuilder.knowledgeUnitsCache.get(cacheKey);
1273
+ if (cached && cached.mtime === currentMtime) {
1274
+ return cached.units;
1275
+ }
1276
+ const units = [];
1277
+ const findYamls = (dir) => {
1278
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
1279
+ for (const entry of entries) {
1280
+ const full = path.join(dir, entry.name);
1281
+ if (entry.isDirectory()) {
1282
+ findYamls(full);
1283
+ }
1284
+ else if (entry.isFile() && (entry.name.endsWith('.yaml') || entry.name.endsWith('.yml')) && entry.name !== 'index.yaml') {
1285
+ try {
1286
+ const content = YAML.parse(fs.readFileSync(full, 'utf-8'));
1287
+ if (content && content.id && (content.rule || content.decision)) {
1288
+ if (!content.rule && content.decision) {
1289
+ content.rule = content.decision;
1290
+ }
1291
+ units.push(content);
1292
+ }
1293
+ }
1294
+ catch { }
1295
+ }
1296
+ }
1297
+ };
1298
+ findYamls(knowledgeDir);
1299
+ GraphBuilder.knowledgeUnitsCache.set(cacheKey, { mtime: currentMtime, units });
1300
+ return units;
1301
+ }
1302
+ /**
1303
+ * Evaluates if a Knowledge Unit applies to a given file path using dual-path matching
1304
+ * (both targetDir-relative and repositoryRoot-relative) with case-insensitive glob support.
1305
+ */
1306
+ matchesAppliesTo(unit, filePath) {
1307
+ if (!unit.applies_to || unit.applies_to.length === 0)
1308
+ return true;
1309
+ const absF = path.isAbsolute(filePath) ? filePath : path.resolve(this.repoRoot, filePath);
1310
+ const relToTarget = path.relative(this.repoRoot, absF).replace(/\\/g, '/');
1311
+ const relToRepo = path.relative(this.repositoryRoot, absF).replace(/\\/g, '/');
1312
+ const repoBase = path.basename(this.repositoryRoot).toLowerCase();
1313
+ const sanitizedAppliesTo = unit.applies_to.map(pat => {
1314
+ let p = pat.replace(/\\/g, '/').replace(/^\.\//, '');
1315
+ if (repoBase && p.toLowerCase().startsWith(`${repoBase}/`)) {
1316
+ p = p.slice(repoBase.length + 1);
1317
+ }
1318
+ return p;
1319
+ });
1320
+ const ig = ignore();
1321
+ ig.add(sanitizedAppliesTo);
1322
+ if (relToTarget && !relToTarget.startsWith('../') && ig.ignores(relToTarget))
1323
+ return true;
1324
+ if (relToRepo && !relToRepo.startsWith('../') && ig.ignores(relToRepo))
1325
+ return true;
1326
+ // Substring / wildcard-stripped fallback with case-insensitivity
1327
+ const lowerTarget = relToTarget.toLowerCase();
1328
+ const lowerRepo = relToRepo.toLowerCase();
1329
+ return sanitizedAppliesTo.some(pat => {
1330
+ const pClean = pat.toLowerCase().replace(/[*]/g, '').trim();
1331
+ return pClean.length >= 3 && (lowerTarget.includes(pClean) || lowerRepo.includes(pClean));
1332
+ });
1333
+ }
1334
+ extractEndpointRoute(signature) {
1335
+ const m = signature.match(/^([A-Z]+)\s+([^\s->]+)/);
1336
+ if (m) {
1337
+ return {
1338
+ method: m[1].toUpperCase(),
1339
+ route: this.normalizeRoutePath(m[2])
1340
+ };
1341
+ }
1342
+ const djangoMatch = signature.match(/^Django\s+([^\s->]+)/);
1343
+ if (djangoMatch) {
1344
+ return {
1345
+ method: 'ANY',
1346
+ route: this.normalizeRoutePath(djangoMatch[1])
1347
+ };
1348
+ }
1349
+ return null;
1350
+ }
1351
+ normalizeRoutePath(rawPath) {
1352
+ let p = rawPath.replace(/^https?:\/\/[^\/]+/, '');
1353
+ p = p.split('?')[0];
1354
+ if (!p.startsWith('/'))
1355
+ p = `/${p}`;
1356
+ if (p.length > 1 && p.endsWith('/'))
1357
+ p = p.slice(0, -1);
1358
+ return p.toLowerCase();
1359
+ }
1360
+ routesMatch(clientPath, serverPath) {
1361
+ const cNorm = this.normalizeRoutePath(clientPath);
1362
+ const sNorm = this.normalizeRoutePath(serverPath);
1363
+ if (cNorm === sNorm)
1364
+ return true;
1365
+ const serverPattern = sNorm
1366
+ .replace(/:[a-zA-Z0-9_]+/g, '[^/]+')
1367
+ .replace(/\{[a-zA-Z0-9_]+\}/g, '[^/]+');
1368
+ try {
1369
+ if (new RegExp(`^${serverPattern}$`, 'i').test(cNorm))
1370
+ return true;
1371
+ }
1372
+ catch { }
1373
+ const clientPattern = cNorm
1374
+ .replace(/:[a-zA-Z0-9_]+/g, '[^/]+')
1375
+ .replace(/\{[a-zA-Z0-9_]+\}/g, '[^/]+');
1376
+ try {
1377
+ if (new RegExp(`^${clientPattern}$`, 'i').test(sNorm))
1378
+ return true;
1379
+ }
1380
+ catch { }
1381
+ return false;
1382
+ }
1383
+ canonicalEventName(name) {
1384
+ return name.replace(/[-_.:/]/g, '').toLowerCase();
1385
+ }
1386
+ /**
1387
+ * Fast 0-token symbol/node search across the graph.
1388
+ */
1389
+ searchNodes(graph, params) {
1390
+ const query = params.query.toLowerCase().trim();
1391
+ const targetType = params.type || 'all';
1392
+ const limit = params.limit || 20;
1393
+ const matches = [];
1394
+ for (const node of graph.nodes) {
1395
+ if (targetType !== 'all' && node.type !== targetType)
1396
+ continue;
1397
+ if (params.domain && node.domain && node.domain.toLowerCase() !== params.domain.toLowerCase())
1398
+ continue;
1399
+ let score = 0;
1400
+ const idLower = node.id.toLowerCase();
1401
+ const labelLower = node.label.toLowerCase();
1402
+ const fileLower = (node.file || '').toLowerCase();
1403
+ const sigLower = (node.metadata?.signature || '').toLowerCase();
1404
+ if (idLower === query || labelLower === query) {
1405
+ score = 100;
1406
+ }
1407
+ else if (idLower.startsWith(query) || labelLower.startsWith(query)) {
1408
+ score = 80;
1409
+ }
1410
+ else if (idLower.includes(query) || labelLower.includes(query)) {
1411
+ score = 50;
1412
+ }
1413
+ else if (sigLower.includes(query)) {
1414
+ score = 40;
1415
+ }
1416
+ else if (fileLower.includes(query)) {
1417
+ score = 30;
1418
+ }
1419
+ if (score > 0) {
1420
+ matches.push({ node, score });
1421
+ }
1422
+ }
1423
+ matches.sort((a, b) => b.score - a.score);
1424
+ return matches.slice(0, limit).map(m => ({
1425
+ id: m.node.id,
1426
+ label: m.node.label,
1427
+ type: m.node.type,
1428
+ file: m.node.file,
1429
+ signature: m.node.metadata?.signature,
1430
+ domain: m.node.domain
1431
+ }));
1432
+ }
1433
+ /**
1434
+ * Blast-radius and inbound dependent calculation.
1435
+ */
1436
+ calculateInboundImpact(graph, targetSearch, options = {}) {
1437
+ const maxDepth = options.maxDepth || 3;
1438
+ const target = targetSearch.toLowerCase().trim();
1439
+ // Resolve target to a node (prefer exact ID, then non-client endpoint/handler, then general match)
1440
+ const node = graph.nodes.find(n => n.id.toLowerCase() === target) ||
1441
+ graph.nodes.find(n => n.label.toLowerCase() === target && !n.metadata?.isClient) ||
1442
+ graph.nodes.find(n => n.label.toLowerCase() === target) ||
1443
+ graph.nodes.find(n => n.file && n.file.toLowerCase().includes(target));
1444
+ if (!node) {
1445
+ return {
1446
+ targetNode: targetSearch,
1447
+ directCallers: [],
1448
+ affectedEndpoints: [],
1449
+ topologicalProjects: [],
1450
+ invariants: []
1451
+ };
1452
+ }
1453
+ const nodeMap = new Map();
1454
+ for (const n of graph.nodes) {
1455
+ nodeMap.set(n.id, n);
1456
+ }
1457
+ const visited = new Set();
1458
+ const queue = [{ id: node.id, depth: 0 }];
1459
+ const directCallers = new Set();
1460
+ const affectedEndpoints = new Set();
1461
+ const affectedProjects = new Set();
1462
+ const invariants = new Set();
1463
+ while (queue.length > 0) {
1464
+ const { id, depth } = queue.shift();
1465
+ if (visited.has(id) || depth >= maxDepth)
1466
+ continue;
1467
+ visited.add(id);
1468
+ // Inbound edges: caller --EDGE--> id (plus bidirectional traversal for IMPLEMENTS)
1469
+ const inboundEdges = graph.edges.filter(e => e.target === id || (e.type === 'IMPLEMENTS' && e.source === id));
1470
+ for (const edge of inboundEdges) {
1471
+ const callerId = edge.target === id ? edge.source : edge.target;
1472
+ const callerNode = nodeMap.get(callerId);
1473
+ if (depth === 0) {
1474
+ directCallers.add(callerId);
1475
+ }
1476
+ if (callerNode) {
1477
+ if (callerNode.type === 'endpoint' || callerNode.type === 'handler') {
1478
+ affectedEndpoints.add(callerId);
1479
+ }
1480
+ else if (callerNode.type === 'project') {
1481
+ affectedProjects.add(callerId);
1482
+ }
1483
+ else if (callerNode.type === 'invariant') {
1484
+ invariants.add(callerId);
1485
+ }
1486
+ }
1487
+ queue.push({ id: callerId, depth: depth + 1 });
1488
+ }
1489
+ }
1490
+ return {
1491
+ targetNode: node.id,
1492
+ directCallers: Array.from(directCallers),
1493
+ affectedEndpoints: Array.from(affectedEndpoints),
1494
+ topologicalProjects: Array.from(affectedProjects),
1495
+ invariants: Array.from(invariants)
1496
+ };
1497
+ }
1498
+ }