akbo-cli 0.0.0-stage → 2.0.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.
- package/README.md +786 -2
- package/dist/catalog_store.d.ts +131 -0
- package/dist/catalog_store.js +506 -0
- package/dist/cleaner.d.ts +11 -0
- package/dist/cleaner.js +92 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +1961 -0
- package/dist/dream_engine.d.ts +61 -0
- package/dist/dream_engine.js +330 -0
- package/dist/extractors/base.d.ts +35 -0
- package/dist/extractors/base.js +17 -0
- package/dist/extractors/custom_extractor.d.ts +55 -0
- package/dist/extractors/custom_extractor.js +198 -0
- package/dist/extractors/dotnet_extractor.d.ts +11 -0
- package/dist/extractors/dotnet_extractor.js +579 -0
- package/dist/extractors/golang_extractor.d.ts +11 -0
- package/dist/extractors/golang_extractor.js +73 -0
- package/dist/extractors/index.d.ts +14 -0
- package/dist/extractors/index.js +30 -0
- package/dist/extractors/jvm_extractor.d.ts +11 -0
- package/dist/extractors/jvm_extractor.js +319 -0
- package/dist/extractors/node_extractor.d.ts +11 -0
- package/dist/extractors/node_extractor.js +306 -0
- package/dist/extractors/proto_graphql_extractor.d.ts +11 -0
- package/dist/extractors/proto_graphql_extractor.js +125 -0
- package/dist/extractors/python_extractor.d.ts +11 -0
- package/dist/extractors/python_extractor.js +298 -0
- package/dist/extractors/rust_extractor.d.ts +11 -0
- package/dist/extractors/rust_extractor.js +66 -0
- package/dist/graph_builder.d.ts +87 -0
- package/dist/graph_builder.js +1516 -0
- package/dist/guard_service.d.ts +33 -0
- package/dist/guard_service.js +167 -0
- package/dist/harvester.d.ts +38 -0
- package/dist/harvester.js +461 -0
- package/dist/hook_generator.d.ts +34 -0
- package/dist/hook_generator.js +269 -0
- package/dist/importers/skill_importer.d.ts +43 -0
- package/dist/importers/skill_importer.js +470 -0
- package/dist/index.d.ts +20 -0
- package/dist/index.js +20 -0
- package/dist/indexer.d.ts +19 -0
- package/dist/indexer.js +108 -0
- package/dist/init_service.d.ts +37 -0
- package/dist/init_service.js +246 -0
- package/dist/mcp_server.d.ts +10 -0
- package/dist/mcp_server.js +846 -0
- package/dist/pool_resolver.d.ts +40 -0
- package/dist/pool_resolver.js +84 -0
- package/dist/provider.d.ts +135 -0
- package/dist/provider.js +880 -0
- package/dist/query_service.d.ts +33 -0
- package/dist/query_service.js +161 -0
- package/dist/schema_generator.d.ts +236 -0
- package/dist/schema_generator.js +264 -0
- package/dist/standards_loader.d.ts +7 -0
- package/dist/standards_loader.js +33 -0
- package/dist/types.d.ts +323 -0
- package/dist/types.js +123 -0
- package/dist/unit_synthesizer.d.ts +22 -0
- package/dist/unit_synthesizer.js +196 -0
- package/dist/validator.d.ts +13 -0
- package/dist/validator.js +152 -0
- package/dist/version.d.ts +6 -0
- package/dist/version.js +16 -0
- package/dist/watcher.d.ts +38 -0
- package/dist/watcher.js +132 -0
- package/package.json +56 -6
- package/schemas/index-schema.json +98 -0
- package/schemas/knowledge-unit.json +154 -0
|
@@ -0,0 +1,1516 @@
|
|
|
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
|
+
supersedes: unit.supersedes,
|
|
476
|
+
superseded_by: unit.superseded_by,
|
|
477
|
+
valid_from: unit.valid_from,
|
|
478
|
+
status: unit.status
|
|
479
|
+
}
|
|
480
|
+
});
|
|
481
|
+
}
|
|
482
|
+
// 6. Deprecation pattern tagging from .akb/standards.yaml
|
|
483
|
+
const standards = StandardsLoader.load(this.repoRoot, this.poolConfig.poolDir);
|
|
484
|
+
if (standards?.standards?.deprecated_patterns && standards.standards.deprecated_patterns.length > 0) {
|
|
485
|
+
for (const node of nodes) {
|
|
486
|
+
for (const dep of standards.standards.deprecated_patterns) {
|
|
487
|
+
try {
|
|
488
|
+
const reg = new RegExp(dep.pattern, 'i');
|
|
489
|
+
if (reg.test(node.label) || (node.file && reg.test(node.file)) || (node.metadata?.signature && reg.test(node.metadata.signature))) {
|
|
490
|
+
node.metadata = {
|
|
491
|
+
...node.metadata,
|
|
492
|
+
deprecated: true,
|
|
493
|
+
deprecationReason: dep.reason || 'Pattern marked as deprecated'
|
|
494
|
+
};
|
|
495
|
+
break;
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
catch { }
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
// ==========================================
|
|
503
|
+
// PASS 2: EDGES (All target nodes now exist!)
|
|
504
|
+
// ==========================================
|
|
505
|
+
// 1. Domain -> Project & Domain -> Invariant (CONTAINS)
|
|
506
|
+
for (const node of nodes) {
|
|
507
|
+
if (node.domain && (node.type === 'project' || node.type === 'invariant')) {
|
|
508
|
+
const domainId = `domain:${node.domain.toLowerCase()}`;
|
|
509
|
+
if (nodeSet.has(domainId)) {
|
|
510
|
+
addEdge({ source: domainId, target: node.id, type: 'CONTAINS' });
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
// 2. Project -> Project Dependencies (DEPENDS_ON from projectReferences)
|
|
515
|
+
for (const manifest of skeleton.manifests) {
|
|
516
|
+
const projId = `project:${manifest.path.replace(/\\/g, '/')}`;
|
|
517
|
+
if (manifest.contentSummary.projectReferences && Array.isArray(manifest.contentSummary.projectReferences)) {
|
|
518
|
+
for (const refName of manifest.contentSummary.projectReferences) {
|
|
519
|
+
const matchingProj = skeleton.manifests.find(m => path.basename(m.path).toLowerCase() === refName.toLowerCase());
|
|
520
|
+
if (matchingProj) {
|
|
521
|
+
addEdge({
|
|
522
|
+
source: projId,
|
|
523
|
+
target: `project:${matchingProj.path.replace(/\\/g, '/')}`,
|
|
524
|
+
type: 'DEPENDS_ON'
|
|
525
|
+
});
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
// Maven reactor modules
|
|
530
|
+
if (manifest.type === 'maven' && Array.isArray(manifest.contentSummary.modules)) {
|
|
531
|
+
for (const mod of manifest.contentSummary.modules) {
|
|
532
|
+
const modProj = skeleton.manifests.find(m => {
|
|
533
|
+
const rel = path.relative(path.dirname(manifest.path), path.dirname(m.path)).replace(/\\/g, '/');
|
|
534
|
+
return rel === mod || path.basename(path.dirname(m.path)) === mod;
|
|
535
|
+
});
|
|
536
|
+
if (modProj) {
|
|
537
|
+
addEdge({
|
|
538
|
+
source: `project:${modProj.path.replace(/\\/g, '/')}`,
|
|
539
|
+
target: projId,
|
|
540
|
+
type: 'DEPENDS_ON'
|
|
541
|
+
});
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
// npm workspace dependencies (e.g. packages in pnpm, yarn, lerna monorepos)
|
|
546
|
+
if (manifest.type === 'npm' && manifest.contentSummary.name) {
|
|
547
|
+
const allDeps = [
|
|
548
|
+
...(manifest.contentSummary.dependencies || []),
|
|
549
|
+
...(manifest.contentSummary.devDependencies || [])
|
|
550
|
+
];
|
|
551
|
+
for (const dep of allDeps) {
|
|
552
|
+
const depProj = skeleton.manifests.find(m => m.type === 'npm' && m.contentSummary.name === dep);
|
|
553
|
+
if (depProj && depProj.path !== manifest.path) {
|
|
554
|
+
addEdge({
|
|
555
|
+
source: projId,
|
|
556
|
+
target: `project:${depProj.path.replace(/\\/g, '/')}`,
|
|
557
|
+
type: 'DEPENDS_ON'
|
|
558
|
+
});
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
// 3. Solution Manifest -> Sub-Projects (CONTAINS) & Project -> Endpoints / Schemas (EXPOSES / CONTAINS)
|
|
564
|
+
// 3a. Wire Solution manifest (.sln) to contained sub-projects (.csproj)
|
|
565
|
+
for (const solProj of nodes.filter(n => n.type === 'project' && n.metadata?.kind === 'solution')) {
|
|
566
|
+
const solProjects = solProj.metadata?.projects;
|
|
567
|
+
if (Array.isArray(solProjects)) {
|
|
568
|
+
for (const sp of solProjects) {
|
|
569
|
+
const spNorm = (sp.path || '').replace(/\\/g, '/');
|
|
570
|
+
const spFilename = path.basename(spNorm).toLowerCase();
|
|
571
|
+
const targetProj = nodes.find(n => n.type === 'project' && n.metadata?.kind !== 'solution' && n.file && (n.file === spNorm ||
|
|
572
|
+
n.file.endsWith('/' + spNorm) ||
|
|
573
|
+
path.basename(n.file).toLowerCase() === spFilename));
|
|
574
|
+
if (targetProj) {
|
|
575
|
+
addEdge({ source: solProj.id, target: targetProj.id, type: 'CONTAINS' });
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
// 3b. Wire Project -> Endpoints & Project -> Schemas (EXPOSES / CONTAINS)
|
|
581
|
+
// Exclude solution manifests to prevent solution node from falsely claiming every endpoint in the repo
|
|
582
|
+
const nonSolutionProjects = nodes.filter(n => n.type === 'project' && n.metadata?.kind !== 'solution');
|
|
583
|
+
const projectDirList = nonSolutionProjects
|
|
584
|
+
.map(p => ({
|
|
585
|
+
id: p.id,
|
|
586
|
+
dir: p.file ? path.dirname(p.file).replace(/\\/g, '/') : ''
|
|
587
|
+
}))
|
|
588
|
+
.sort((a, b) => b.dir.length - a.dir.length);
|
|
589
|
+
const findOwningProjectId = (filePath) => {
|
|
590
|
+
const norm = filePath.replace(/\\/g, '/');
|
|
591
|
+
let fallbackRootId = null;
|
|
592
|
+
for (const p of projectDirList) {
|
|
593
|
+
if (!p.dir || p.dir === '.') {
|
|
594
|
+
fallbackRootId = p.id;
|
|
595
|
+
}
|
|
596
|
+
else if (norm.startsWith(p.dir + '/') || norm === p.dir) {
|
|
597
|
+
return p.id;
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
return fallbackRootId;
|
|
601
|
+
};
|
|
602
|
+
const serverEndpoints = nodes.filter(n => n.type === 'endpoint' && !n.metadata?.isClient);
|
|
603
|
+
for (const ep of serverEndpoints) {
|
|
604
|
+
if (ep.file) {
|
|
605
|
+
const ownerId = findOwningProjectId(ep.file);
|
|
606
|
+
if (ownerId) {
|
|
607
|
+
addEdge({ source: ownerId, target: ep.id, type: 'EXPOSES' });
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
const schemaNodes = nodes.filter(n => n.type === 'schema');
|
|
612
|
+
for (const sc of schemaNodes) {
|
|
613
|
+
if (sc.file) {
|
|
614
|
+
const ownerId = findOwningProjectId(sc.file);
|
|
615
|
+
if (ownerId) {
|
|
616
|
+
addEdge({ source: ownerId, target: sc.id, type: 'CONTAINS' });
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
// Pre-index schema models for O(1) persistence matching
|
|
621
|
+
const allModels = [];
|
|
622
|
+
const seenModels = new Set();
|
|
623
|
+
for (const schema of skeleton.schemas) {
|
|
624
|
+
for (const model of schema.tablesOrModels) {
|
|
625
|
+
const lower = model.toLowerCase();
|
|
626
|
+
if (!seenModels.has(lower)) {
|
|
627
|
+
seenModels.add(lower);
|
|
628
|
+
allModels.push({ model, lower, targetId: `schema:${model}` });
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
const addPersistsEdges = (sourceId, sig, ident) => {
|
|
633
|
+
const combined = `${sig} ${ident}`.toLowerCase();
|
|
634
|
+
for (const m of allModels) {
|
|
635
|
+
if (combined.includes(m.lower)) {
|
|
636
|
+
addEdge({ source: sourceId, target: m.targetId, type: 'PERSISTS' });
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
};
|
|
640
|
+
// 4. Handlers -> Messages (HANDLES) & Handlers -> Schemas (PERSISTS)
|
|
641
|
+
for (const item of skeleton.routesAndCommands) {
|
|
642
|
+
if (item.framework === 'MassTransit' || item.framework === 'NServiceBus' || item.framework === 'Wolverine') {
|
|
643
|
+
const handlerId = `handler:${item.identifier}`;
|
|
644
|
+
const msgMatch = item.signature.match(/(?:IConsumer|IHandleMessages)<([^>]+)>/) ||
|
|
645
|
+
item.signature.match(/Handle\(([\p{L}\p{N}_]+)/u);
|
|
646
|
+
if (msgMatch) {
|
|
647
|
+
addEdge({ source: handlerId, target: `message:${msgMatch[1].trim()}`, type: 'HANDLES' });
|
|
648
|
+
}
|
|
649
|
+
addPersistsEdges(handlerId, item.signature, item.identifier);
|
|
650
|
+
}
|
|
651
|
+
else if (item.framework === 'Kafka' || item.framework === 'RabbitMQ') {
|
|
652
|
+
const handlerId = `handler:${item.identifier}`;
|
|
653
|
+
const topicMatch = item.signature.match(/(?:topic|queue):\s*["']?([^"'\s]+)["']?/);
|
|
654
|
+
if (topicMatch) {
|
|
655
|
+
addEdge({ source: handlerId, target: `message:${topicMatch[1]}`, type: 'CONSUMES_EVENT' });
|
|
656
|
+
}
|
|
657
|
+
addPersistsEdges(handlerId, item.signature, item.identifier);
|
|
658
|
+
}
|
|
659
|
+
else if (item.framework === 'FluentValidation') {
|
|
660
|
+
const validatorId = `validator:${item.identifier}`;
|
|
661
|
+
const targetMatch = item.signature.match(/AbstractValidator<([\p{L}\p{N}_]+)>/u);
|
|
662
|
+
if (targetMatch) {
|
|
663
|
+
addEdge({ source: validatorId, target: `message:${targetMatch[1].trim()}`, type: 'VALIDATES' });
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
else if (item.framework === 'BullMQ') {
|
|
667
|
+
if (item.method !== 'QUEUE') {
|
|
668
|
+
const handlerId = `handler:${item.identifier}`;
|
|
669
|
+
const queueMatch = item.signature.match(/(?:Worker|Processor):\s*([A-Za-z0-9_.-]+)/i);
|
|
670
|
+
if (queueMatch) {
|
|
671
|
+
addEdge({ source: handlerId, target: `message:${queueMatch[1]}`, type: 'CONSUMES_EVENT' });
|
|
672
|
+
}
|
|
673
|
+
addPersistsEdges(handlerId, item.signature, item.identifier);
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
else if (item.framework === 'Celery' || item.framework === 'Dramatiq') {
|
|
677
|
+
const handlerId = `handler:${item.identifier}`;
|
|
678
|
+
addEdge({
|
|
679
|
+
source: handlerId,
|
|
680
|
+
target: `message:${item.identifier}`,
|
|
681
|
+
type: 'CONSUMES_EVENT'
|
|
682
|
+
});
|
|
683
|
+
addPersistsEdges(handlerId, item.signature, item.identifier);
|
|
684
|
+
}
|
|
685
|
+
else if (item.framework !== 'MediatR') {
|
|
686
|
+
const epId = `endpoint:${item.signature}`;
|
|
687
|
+
if (item.framework === 'AzureFunctions') {
|
|
688
|
+
const queueMatch = item.signature.match(/(?:ServiceBus|Queue):([A-Za-z0-9_.-]+)/);
|
|
689
|
+
if (queueMatch) {
|
|
690
|
+
addEdge({ source: epId, target: `message:${queueMatch[1]}`, type: 'CONSUMES_EVENT' });
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
addPersistsEdges(epId, item.signature, '');
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
// 5. Endpoints -> Messages (DISPATCHES) with Canonical Event Support
|
|
697
|
+
const messages = nodes.filter(n => n.type === 'message');
|
|
698
|
+
for (const ep of serverEndpoints) {
|
|
699
|
+
const epSig = (ep.metadata?.signature || ep.label).toLowerCase();
|
|
700
|
+
for (const msg of messages) {
|
|
701
|
+
const msgLabelLower = msg.label.toLowerCase();
|
|
702
|
+
const canonMsg = this.canonicalEventName(msg.label);
|
|
703
|
+
if (epSig.includes(msgLabelLower) || epSig.includes(canonMsg)) {
|
|
704
|
+
addEdge({ source: ep.id, target: msg.id, type: 'DISPATCHES' });
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
// 6. Canonical Event Matching & Cross-Language Messaging (RELATES_TO)
|
|
709
|
+
const canonicalGroups = new Map();
|
|
710
|
+
for (const msg of messages) {
|
|
711
|
+
const canon = this.canonicalEventName(msg.label);
|
|
712
|
+
if (!canonicalGroups.has(canon)) {
|
|
713
|
+
canonicalGroups.set(canon, []);
|
|
714
|
+
}
|
|
715
|
+
canonicalGroups.get(canon).push(msg);
|
|
716
|
+
}
|
|
717
|
+
for (const [canon, group] of canonicalGroups.entries()) {
|
|
718
|
+
if (group.length > 1) {
|
|
719
|
+
for (let i = 0; i < group.length; i++) {
|
|
720
|
+
for (let j = i + 1; j < group.length; j++) {
|
|
721
|
+
addEdge({
|
|
722
|
+
source: group[i].id,
|
|
723
|
+
target: group[j].id,
|
|
724
|
+
type: 'RELATES_TO',
|
|
725
|
+
metadata: { canonicalEvent: canon }
|
|
726
|
+
});
|
|
727
|
+
addEdge({
|
|
728
|
+
source: group[j].id,
|
|
729
|
+
target: group[i].id,
|
|
730
|
+
type: 'RELATES_TO',
|
|
731
|
+
metadata: { canonicalEvent: canon }
|
|
732
|
+
});
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
// 7. Cross-Boundary HTTP Calls (CALLS_HTTP)
|
|
738
|
+
const clientHttpNodes = nodes.filter(n => n.type === 'endpoint' && n.metadata?.framework === 'HttpClient');
|
|
739
|
+
for (const client of clientHttpNodes) {
|
|
740
|
+
const clientUrl = client.label;
|
|
741
|
+
const clientMethod = client.metadata?.method;
|
|
742
|
+
for (const serverEp of serverEndpoints) {
|
|
743
|
+
const serverRoute = this.extractEndpointRoute(serverEp.metadata?.signature || serverEp.label);
|
|
744
|
+
if (serverRoute) {
|
|
745
|
+
const methodMatches = !clientMethod || clientMethod === 'ANY' || serverRoute.method === 'ANY' || serverRoute.method === 'ALL' || clientMethod === serverRoute.method;
|
|
746
|
+
if (methodMatches && this.routesMatch(clientUrl, serverRoute.route)) {
|
|
747
|
+
// Wire from client call node to server endpoint
|
|
748
|
+
addEdge({
|
|
749
|
+
source: client.id,
|
|
750
|
+
target: serverEp.id,
|
|
751
|
+
type: 'CALLS_HTTP'
|
|
752
|
+
});
|
|
753
|
+
// Wire from most specific caller project to server endpoint
|
|
754
|
+
let callerProj;
|
|
755
|
+
let maxPrefixLen = -1;
|
|
756
|
+
for (const proj of nodes.filter(n => n.type === 'project' && n.metadata?.kind !== 'solution')) {
|
|
757
|
+
if (proj.file && client.file) {
|
|
758
|
+
const projDir = path.dirname(proj.file).replace(/\\/g, '/');
|
|
759
|
+
if (projDir === '.' || client.file.startsWith(projDir + '/') || client.file === proj.file) {
|
|
760
|
+
if (projDir.length > maxPrefixLen) {
|
|
761
|
+
maxPrefixLen = projDir.length;
|
|
762
|
+
callerProj = proj;
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
if (callerProj) {
|
|
768
|
+
addEdge({
|
|
769
|
+
source: callerProj.id,
|
|
770
|
+
target: serverEp.id,
|
|
771
|
+
type: 'CALLS_HTTP'
|
|
772
|
+
});
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
// 8. Cross-Boundary gRPC Calls (CALLS_GRPC)
|
|
779
|
+
const clientGrpcNodes = nodes.filter(n => n.type === 'endpoint' && n.metadata?.framework === 'GrpcClient');
|
|
780
|
+
const serverRpcs = nodes.filter(n => n.type === 'endpoint' && (n.metadata?.framework === 'gRPC/Protobuf' ||
|
|
781
|
+
n.metadata?.framework === 'gRPC' ||
|
|
782
|
+
n.metadata?.framework === 'gRPC/.NET' ||
|
|
783
|
+
n.metadata?.framework === 'gRPC/Java' ||
|
|
784
|
+
n.metadata?.method === 'RPC') && !n.metadata?.isClient);
|
|
785
|
+
for (const client of clientGrpcNodes) {
|
|
786
|
+
const clientRpcName = client.label.toLowerCase();
|
|
787
|
+
for (const serverRpc of serverRpcs) {
|
|
788
|
+
const serverRpcName = (serverRpc.label || '').toLowerCase();
|
|
789
|
+
const serverSig = (serverRpc.metadata?.signature || '').toLowerCase();
|
|
790
|
+
if (serverRpcName === clientRpcName || serverSig.includes(`.${clientRpcName}(`) || serverSig.includes(` ${clientRpcName}(`)) {
|
|
791
|
+
addEdge({
|
|
792
|
+
source: client.id,
|
|
793
|
+
target: serverRpc.id,
|
|
794
|
+
type: 'CALLS_GRPC'
|
|
795
|
+
});
|
|
796
|
+
let callerProj;
|
|
797
|
+
let maxPrefixLen = -1;
|
|
798
|
+
for (const proj of nodes.filter(n => n.type === 'project' && n.metadata?.kind !== 'solution')) {
|
|
799
|
+
if (proj.file && client.file) {
|
|
800
|
+
const projDir = path.dirname(proj.file).replace(/\\/g, '/');
|
|
801
|
+
if (projDir === '.' || client.file.startsWith(projDir + '/') || client.file === proj.file) {
|
|
802
|
+
if (projDir.length > maxPrefixLen) {
|
|
803
|
+
maxPrefixLen = projDir.length;
|
|
804
|
+
callerProj = proj;
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
if (callerProj) {
|
|
810
|
+
addEdge({
|
|
811
|
+
source: callerProj.id,
|
|
812
|
+
target: serverRpc.id,
|
|
813
|
+
type: 'CALLS_GRPC'
|
|
814
|
+
});
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
// 9. Cross-Boundary RPC / Custom Contract Calls (CALLS_RPC)
|
|
820
|
+
const clientRpcNodes = nodes.filter(n => n.type === 'endpoint' && n.metadata?.isClient && (n.metadata?.callType === 'CALLS_RPC' || n.metadata?.framework === 'RpcClient'));
|
|
821
|
+
const serverTargets = nodes.filter(n => (n.type === 'endpoint' || n.type === 'handler') && !n.metadata?.isClient);
|
|
822
|
+
for (const client of clientRpcNodes) {
|
|
823
|
+
const clientTarget = client.label.toLowerCase();
|
|
824
|
+
for (const server of serverTargets) {
|
|
825
|
+
const serverLabel = (server.label || '').toLowerCase();
|
|
826
|
+
const serverSig = (server.metadata?.signature || '').toLowerCase();
|
|
827
|
+
const serverId = server.id.toLowerCase();
|
|
828
|
+
if (serverLabel === clientTarget ||
|
|
829
|
+
serverLabel.endsWith(clientTarget) ||
|
|
830
|
+
clientTarget.endsWith(serverLabel) ||
|
|
831
|
+
serverSig.includes(clientTarget) ||
|
|
832
|
+
serverId.includes(clientTarget)) {
|
|
833
|
+
addEdge({
|
|
834
|
+
source: client.id,
|
|
835
|
+
target: server.id,
|
|
836
|
+
type: 'CALLS_RPC'
|
|
837
|
+
});
|
|
838
|
+
let callerProj;
|
|
839
|
+
let maxPrefixLen = -1;
|
|
840
|
+
for (const proj of nodes.filter(n => n.type === 'project' && n.metadata?.kind !== 'solution')) {
|
|
841
|
+
if (proj.file && client.file) {
|
|
842
|
+
const projDir = path.dirname(proj.file).replace(/\\/g, '/');
|
|
843
|
+
if (projDir === '.' || client.file.startsWith(projDir + '/') || client.file === proj.file) {
|
|
844
|
+
if (projDir.length > maxPrefixLen) {
|
|
845
|
+
maxPrefixLen = projDir.length;
|
|
846
|
+
callerProj = proj;
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
if (callerProj) {
|
|
852
|
+
addEdge({
|
|
853
|
+
source: callerProj.id,
|
|
854
|
+
target: server.id,
|
|
855
|
+
type: 'CALLS_RPC'
|
|
856
|
+
});
|
|
857
|
+
}
|
|
858
|
+
// Wire caller handler/endpoint located in the same file as client call
|
|
859
|
+
const fileCallers = nodes.filter(n => (n.type === 'handler' || n.type === 'endpoint') && !n.metadata?.isClient && n.file && n.file === client.file);
|
|
860
|
+
for (const fc of fileCallers) {
|
|
861
|
+
addEdge({
|
|
862
|
+
source: fc.id,
|
|
863
|
+
target: server.id,
|
|
864
|
+
type: 'CALLS_RPC'
|
|
865
|
+
});
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
// 10. Handler Implementation of Interfaces/Contracts (IMPLEMENTS)
|
|
871
|
+
for (const item of skeleton.routesAndCommands) {
|
|
872
|
+
if (item.implements && item.implements.length > 0) {
|
|
873
|
+
const handlerId = `handler:${item.identifier}`;
|
|
874
|
+
for (const iface of item.implements) {
|
|
875
|
+
addEdge({
|
|
876
|
+
source: handlerId,
|
|
877
|
+
target: `handler:${iface}`,
|
|
878
|
+
type: 'IMPLEMENTS'
|
|
879
|
+
});
|
|
880
|
+
}
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
// 6. Invariants -> Invariants (RELATES_TO) & Invariants -> Projects (CONSTRAINS)
|
|
884
|
+
for (const unit of units) {
|
|
885
|
+
const invId = `invariant:${unit.id}`;
|
|
886
|
+
for (const rel of unit.related_items || []) {
|
|
887
|
+
addEdge({ source: invId, target: `invariant:${rel}`, type: 'RELATES_TO' });
|
|
888
|
+
}
|
|
889
|
+
if (unit.supersedes) {
|
|
890
|
+
addEdge({ source: invId, target: `invariant:${unit.supersedes}`, type: 'SUPERSEDES' });
|
|
891
|
+
}
|
|
892
|
+
if (unit.superseded_by) {
|
|
893
|
+
addEdge({ source: `invariant:${unit.superseded_by}`, target: invId, type: 'SUPERSEDES' });
|
|
894
|
+
}
|
|
895
|
+
for (const proj of nonSolutionProjects) {
|
|
896
|
+
const projFile = proj.file || '';
|
|
897
|
+
const projDir = projFile ? path.dirname(projFile) : '';
|
|
898
|
+
const isGlobal = !unit.applies_to || unit.applies_to.length === 0 || unit.applies_to.some(p => p === '**/*' || p === '*' || p === 'src/**/*');
|
|
899
|
+
const matchesProj = isGlobal ||
|
|
900
|
+
(projFile && this.matchesAppliesTo(unit, projFile)) ||
|
|
901
|
+
(projDir && this.matchesAppliesTo(unit, `${projDir}/dummy.ts`));
|
|
902
|
+
if (matchesProj) {
|
|
903
|
+
addEdge({ source: invId, target: proj.id, type: 'CONSTRAINS' });
|
|
904
|
+
}
|
|
905
|
+
}
|
|
906
|
+
}
|
|
907
|
+
const graph = {
|
|
908
|
+
timestamp: new Date().toISOString(),
|
|
909
|
+
repoPath: this.repoRoot,
|
|
910
|
+
nodes,
|
|
911
|
+
edges
|
|
912
|
+
};
|
|
913
|
+
if (useCache && !hasCustomUnits) {
|
|
914
|
+
GraphBuilder.inMemoryCache.set(this.repoRoot, { graphKey: keyString, graph });
|
|
915
|
+
try {
|
|
916
|
+
fs.mkdirSync(path.dirname(cacheFile), { recursive: true });
|
|
917
|
+
let cacheData = {};
|
|
918
|
+
if (fs.existsSync(cacheFile)) {
|
|
919
|
+
try {
|
|
920
|
+
cacheData = JSON.parse(fs.readFileSync(cacheFile, 'utf-8')) || {};
|
|
921
|
+
}
|
|
922
|
+
catch { }
|
|
923
|
+
}
|
|
924
|
+
cacheData.graphKey = currentKey;
|
|
925
|
+
cacheData.graph = graph;
|
|
926
|
+
fs.writeFileSync(cacheFile, JSON.stringify(cacheData), 'utf-8');
|
|
927
|
+
}
|
|
928
|
+
catch { }
|
|
929
|
+
}
|
|
930
|
+
return graph;
|
|
931
|
+
}
|
|
932
|
+
/**
|
|
933
|
+
* Traverses the graph and extracts the 1-hop and 2-hop topological neighborhood
|
|
934
|
+
* surrounding a target node, formatted as an LLM-ready prompt slice.
|
|
935
|
+
*/
|
|
936
|
+
extractNeighborhood(graph, targetSearch, maxHops = 2) {
|
|
937
|
+
const searchLower = targetSearch.toLowerCase().replace(/\\/g, '/');
|
|
938
|
+
// Find center node matching search term (prefer exact ID/label, then substring match)
|
|
939
|
+
let centerNode = graph.nodes.find(n => n.id.toLowerCase() === searchLower || n.label.toLowerCase() === searchLower) ||
|
|
940
|
+
graph.nodes.find(n => n.id.toLowerCase().includes(searchLower) || n.label.toLowerCase().includes(searchLower)) ||
|
|
941
|
+
graph.nodes.find(n => n.file && n.file.toLowerCase().includes(searchLower));
|
|
942
|
+
// Fallback: If no node matches directly and targetSearch looks like a file path or exists on disk,
|
|
943
|
+
// resolve to the owning project: node (longest matching path.dirname(proj.file) prefix).
|
|
944
|
+
let resolvedViaProjectFallback = false;
|
|
945
|
+
if (!centerNode) {
|
|
946
|
+
const normTarget = path.isAbsolute(targetSearch)
|
|
947
|
+
? path.relative(this.repoRoot, targetSearch).replace(/\\/g, '/')
|
|
948
|
+
: targetSearch.replace(/\\/g, '/');
|
|
949
|
+
const isFilePathLike = normTarget.includes('/') ||
|
|
950
|
+
normTarget.includes('\\') ||
|
|
951
|
+
/\.[a-zA-Z][a-zA-Z0-9]{0,7}$/.test(normTarget) ||
|
|
952
|
+
fs.existsSync(path.resolve(this.repoRoot, targetSearch));
|
|
953
|
+
if (isFilePathLike) {
|
|
954
|
+
const nonSolutionProjects = graph.nodes.filter(n => n.type === 'project' && n.file && n.metadata?.kind !== 'solution');
|
|
955
|
+
let bestProj;
|
|
956
|
+
let maxPrefixLen = -1;
|
|
957
|
+
const targetDir = path.dirname(normTarget).replace(/\\/g, '/');
|
|
958
|
+
const hasSpecificDir = targetDir !== '.' && targetDir !== '';
|
|
959
|
+
for (const proj of nonSolutionProjects) {
|
|
960
|
+
if (!proj.file)
|
|
961
|
+
continue;
|
|
962
|
+
const projDir = path.dirname(proj.file).replace(/\\/g, '/');
|
|
963
|
+
const isDirectMatch = normTarget === proj.file ||
|
|
964
|
+
projDir === '.' ||
|
|
965
|
+
projDir === '' ||
|
|
966
|
+
normTarget.startsWith(projDir + '/') ||
|
|
967
|
+
normTarget.toLowerCase().includes(projDir.toLowerCase() + '/');
|
|
968
|
+
const isSubdirMatch = hasSpecificDir && projDir.toLowerCase().includes(targetDir.toLowerCase());
|
|
969
|
+
// For bare filenames (e.g. MyHelper.cs where targetDir is '.'),
|
|
970
|
+
// verify if the file actually exists inside this project directory on disk
|
|
971
|
+
const isBareFileInProject = !hasSpecificDir &&
|
|
972
|
+
fs.existsSync(path.resolve(this.repoRoot, projDir, normTarget));
|
|
973
|
+
if (isDirectMatch || isSubdirMatch || isBareFileInProject) {
|
|
974
|
+
if (projDir.length > maxPrefixLen) {
|
|
975
|
+
maxPrefixLen = projDir.length;
|
|
976
|
+
bestProj = proj;
|
|
977
|
+
}
|
|
978
|
+
}
|
|
979
|
+
}
|
|
980
|
+
if (!bestProj && nonSolutionProjects.length === 0) {
|
|
981
|
+
bestProj = graph.nodes.find(n => n.type === 'project');
|
|
982
|
+
}
|
|
983
|
+
if (bestProj) {
|
|
984
|
+
centerNode = bestProj;
|
|
985
|
+
resolvedViaProjectFallback = true;
|
|
986
|
+
}
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
if (!centerNode) {
|
|
990
|
+
return null;
|
|
991
|
+
}
|
|
992
|
+
const visitedNodes = new Set([centerNode.id]);
|
|
993
|
+
const includedEdges = [];
|
|
994
|
+
let currentLevel = [centerNode.id];
|
|
995
|
+
for (let hop = 0; hop < maxHops; hop++) {
|
|
996
|
+
const nextLevel = [];
|
|
997
|
+
for (const nodeId of currentLevel) {
|
|
998
|
+
// Collect outbound and inbound edges
|
|
999
|
+
for (const edge of graph.edges) {
|
|
1000
|
+
if (edge.source === nodeId && !visitedNodes.has(edge.target)) {
|
|
1001
|
+
visitedNodes.add(edge.target);
|
|
1002
|
+
includedEdges.push(edge);
|
|
1003
|
+
nextLevel.push(edge.target);
|
|
1004
|
+
}
|
|
1005
|
+
else if (edge.target === nodeId && !visitedNodes.has(edge.source)) {
|
|
1006
|
+
visitedNodes.add(edge.source);
|
|
1007
|
+
includedEdges.push(edge);
|
|
1008
|
+
nextLevel.push(edge.source);
|
|
1009
|
+
}
|
|
1010
|
+
else if ((edge.source === nodeId || edge.target === nodeId) && !includedEdges.includes(edge)) {
|
|
1011
|
+
includedEdges.push(edge);
|
|
1012
|
+
}
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
currentLevel = nextLevel;
|
|
1016
|
+
if (currentLevel.length === 0)
|
|
1017
|
+
break;
|
|
1018
|
+
}
|
|
1019
|
+
const neighborhoodNodes = graph.nodes.filter(n => visitedNodes.has(n.id));
|
|
1020
|
+
// Detect any deprecation warnings in neighborhood
|
|
1021
|
+
const deprecationWarnings = [];
|
|
1022
|
+
for (const n of neighborhoodNodes) {
|
|
1023
|
+
if (n.metadata?.deprecated) {
|
|
1024
|
+
deprecationWarnings.push(`Entity [${n.type}] "${n.label}" is flagged as deprecated: ${n.metadata.deprecationReason || 'Avoid in modern code'}`);
|
|
1025
|
+
}
|
|
1026
|
+
}
|
|
1027
|
+
// Resolve all active Knowledge Units governing this neighborhood
|
|
1028
|
+
const allUnits = this.loadKnowledgeUnits();
|
|
1029
|
+
const activeInvariants = [];
|
|
1030
|
+
const normFiles = neighborhoodNodes
|
|
1031
|
+
.map(n => n.file)
|
|
1032
|
+
.filter((f) => Boolean(f))
|
|
1033
|
+
.map(f => f.toLowerCase());
|
|
1034
|
+
if (centerNode.file)
|
|
1035
|
+
normFiles.push(centerNode.file.toLowerCase());
|
|
1036
|
+
normFiles.push(searchLower);
|
|
1037
|
+
for (const unit of allUnits) {
|
|
1038
|
+
// 1. Direct node match in neighborhood
|
|
1039
|
+
const directNodeMatch = neighborhoodNodes.some(n => n.id === `invariant:${unit.id}` || n.label.includes(unit.id));
|
|
1040
|
+
if (directNodeMatch) {
|
|
1041
|
+
if (!activeInvariants.some(u => u.id === unit.id))
|
|
1042
|
+
activeInvariants.push(unit);
|
|
1043
|
+
continue;
|
|
1044
|
+
}
|
|
1045
|
+
// 2. Domain match with centerNode
|
|
1046
|
+
if (centerNode.domain && unit.domain && centerNode.domain.toLowerCase() === unit.domain.toLowerCase()) {
|
|
1047
|
+
if (!activeInvariants.some(u => u.id === unit.id))
|
|
1048
|
+
activeInvariants.push(unit);
|
|
1049
|
+
continue;
|
|
1050
|
+
}
|
|
1051
|
+
// 3. applies_to glob pattern match
|
|
1052
|
+
if (unit.applies_to && unit.applies_to.length > 0 && normFiles.length > 0) {
|
|
1053
|
+
const matchesAnyFile = normFiles.some(f => this.matchesAppliesTo(unit, f));
|
|
1054
|
+
if (matchesAnyFile) {
|
|
1055
|
+
if (!activeInvariants.some(u => u.id === unit.id))
|
|
1056
|
+
activeInvariants.push(unit);
|
|
1057
|
+
continue;
|
|
1058
|
+
}
|
|
1059
|
+
}
|
|
1060
|
+
}
|
|
1061
|
+
// Invalidate/warn if any active invariant is superseded
|
|
1062
|
+
for (const inv of activeInvariants) {
|
|
1063
|
+
if (inv.superseded_by && !deprecationWarnings.some(w => w.includes(inv.id))) {
|
|
1064
|
+
deprecationWarnings.push(`Invariant ${inv.id} is SUPERSEDED by ${inv.superseded_by}. All new implementations must conform to ${inv.superseded_by}.`);
|
|
1065
|
+
}
|
|
1066
|
+
}
|
|
1067
|
+
// Build structured Markdown prompt slice
|
|
1068
|
+
const lines = [];
|
|
1069
|
+
if (deprecationWarnings.length > 0) {
|
|
1070
|
+
lines.push('### ⚠️ Architectural Deprecation Warnings');
|
|
1071
|
+
for (const warn of deprecationWarnings) {
|
|
1072
|
+
lines.push(`- **WARNING**: ${warn}`);
|
|
1073
|
+
}
|
|
1074
|
+
lines.push('');
|
|
1075
|
+
}
|
|
1076
|
+
lines.push(`## Architectural Context: [${centerNode.type.toUpperCase()}] ${centerNode.label}`);
|
|
1077
|
+
if (resolvedViaProjectFallback) {
|
|
1078
|
+
lines.push(`- **Resolved Target File**: \`${targetSearch}\` (via owning project \`${centerNode.label}\`)`);
|
|
1079
|
+
}
|
|
1080
|
+
if (centerNode.file)
|
|
1081
|
+
lines.push(`- **File**: \`${centerNode.file}\``);
|
|
1082
|
+
if (centerNode.domain)
|
|
1083
|
+
lines.push(`- **Domain**: \`${centerNode.domain}\``);
|
|
1084
|
+
if (centerNode.metadata?.signature)
|
|
1085
|
+
lines.push(`- **Signature**: \`${centerNode.metadata.signature}\``);
|
|
1086
|
+
if (centerNode.metadata?.rule)
|
|
1087
|
+
lines.push(`- **Rule**: ${centerNode.metadata.rule}`);
|
|
1088
|
+
lines.push('\n### Connected Topological Entities');
|
|
1089
|
+
for (const edge of includedEdges) {
|
|
1090
|
+
const src = graph.nodes.find(n => n.id === edge.source);
|
|
1091
|
+
const tgt = graph.nodes.find(n => n.id === edge.target);
|
|
1092
|
+
if (src && tgt) {
|
|
1093
|
+
lines.push(`- [${src.type}] \`${src.label}\` --**${edge.type}**--> [${tgt.type}] \`${tgt.label}\``);
|
|
1094
|
+
}
|
|
1095
|
+
}
|
|
1096
|
+
if (activeInvariants.length > 0) {
|
|
1097
|
+
lines.push('\n### Active Architectural Invariants & Target Patterns');
|
|
1098
|
+
for (const inv of activeInvariants) {
|
|
1099
|
+
lines.push(`\n#### [${inv.id}] ${inv.title}`);
|
|
1100
|
+
if (inv.rule)
|
|
1101
|
+
lines.push(`- **Rule**: ${inv.rule}`);
|
|
1102
|
+
if (inv.skill_file) {
|
|
1103
|
+
let absSkill = inv.skill_file;
|
|
1104
|
+
if (!path.isAbsolute(inv.skill_file)) {
|
|
1105
|
+
const inPool = path.join(this.poolConfig.poolDir, inv.skill_file);
|
|
1106
|
+
const inRepo = path.join(this.repositoryRoot, inv.skill_file);
|
|
1107
|
+
if (fs.existsSync(inPool)) {
|
|
1108
|
+
absSkill = inPool;
|
|
1109
|
+
}
|
|
1110
|
+
else if (fs.existsSync(inRepo)) {
|
|
1111
|
+
absSkill = inRepo;
|
|
1112
|
+
}
|
|
1113
|
+
else {
|
|
1114
|
+
absSkill = path.resolve(this.repositoryRoot, inv.skill_file);
|
|
1115
|
+
}
|
|
1116
|
+
}
|
|
1117
|
+
absSkill = path.resolve(absSkill).replace(/\\/g, '/');
|
|
1118
|
+
lines.push(`- **Skill Specification**: [\`${inv.skill_file}\`](file:///${absSkill})`);
|
|
1119
|
+
}
|
|
1120
|
+
if (inv.reference_files && inv.reference_files.length > 0) {
|
|
1121
|
+
const refLinks = inv.reference_files.map(rf => {
|
|
1122
|
+
let absRef = rf;
|
|
1123
|
+
if (!path.isAbsolute(rf)) {
|
|
1124
|
+
const inPool = path.join(this.poolConfig.poolDir, rf);
|
|
1125
|
+
const inRepo = path.join(this.repositoryRoot, rf);
|
|
1126
|
+
if (fs.existsSync(inPool)) {
|
|
1127
|
+
absRef = inPool;
|
|
1128
|
+
}
|
|
1129
|
+
else if (fs.existsSync(inRepo)) {
|
|
1130
|
+
absRef = inRepo;
|
|
1131
|
+
}
|
|
1132
|
+
else {
|
|
1133
|
+
absRef = path.resolve(this.repositoryRoot, rf);
|
|
1134
|
+
}
|
|
1135
|
+
}
|
|
1136
|
+
absRef = path.resolve(absRef).replace(/\\/g, '/');
|
|
1137
|
+
return `[\`${path.basename(rf)}\`](file:///${absRef})`;
|
|
1138
|
+
}).join(', ');
|
|
1139
|
+
lines.push(`- **Reference Guides**: ${refLinks}`);
|
|
1140
|
+
}
|
|
1141
|
+
if (inv.workflow_gates && inv.workflow_gates.length > 0) {
|
|
1142
|
+
lines.push(`- **Workflow Gates**:`);
|
|
1143
|
+
for (let i = 0; i < inv.workflow_gates.length; i++) {
|
|
1144
|
+
lines.push(` ${i + 1}. ${inv.workflow_gates[i]}`);
|
|
1145
|
+
}
|
|
1146
|
+
}
|
|
1147
|
+
if (inv.do && inv.do.length > 0) {
|
|
1148
|
+
lines.push(`- **Target Patterns (DO)**:`);
|
|
1149
|
+
for (const item of inv.do)
|
|
1150
|
+
lines.push(` • ${item}`);
|
|
1151
|
+
}
|
|
1152
|
+
if (inv.dont && inv.dont.length > 0) {
|
|
1153
|
+
lines.push(`- **Forbidden Anti-Patterns (DONT)**:`);
|
|
1154
|
+
for (const item of inv.dont)
|
|
1155
|
+
lines.push(` • ${item}`);
|
|
1156
|
+
}
|
|
1157
|
+
if (inv.reason)
|
|
1158
|
+
lines.push(`- **Reason**: ${inv.reason}`);
|
|
1159
|
+
}
|
|
1160
|
+
}
|
|
1161
|
+
return {
|
|
1162
|
+
centerNode,
|
|
1163
|
+
nodes: neighborhoodNodes,
|
|
1164
|
+
edges: includedEdges,
|
|
1165
|
+
formattedContext: lines.join('\n'),
|
|
1166
|
+
activeInvariants: activeInvariants.length > 0 ? activeInvariants : undefined,
|
|
1167
|
+
deprecationWarnings: deprecationWarnings.length > 0 ? deprecationWarnings : undefined
|
|
1168
|
+
};
|
|
1169
|
+
}
|
|
1170
|
+
/**
|
|
1171
|
+
* Generates a valid GitHub-flavored Mermaid graph diagram from the graph.
|
|
1172
|
+
* Supports domain/project subgraph clustering to provide high-level architectural structure.
|
|
1173
|
+
*/
|
|
1174
|
+
exportMermaid(graph, filterNodesOrOptions, filterEdges, options) {
|
|
1175
|
+
let actualNodes;
|
|
1176
|
+
let actualEdges = filterEdges;
|
|
1177
|
+
let actualOptions = options;
|
|
1178
|
+
if (filterNodesOrOptions && !Array.isArray(filterNodesOrOptions)) {
|
|
1179
|
+
actualOptions = filterNodesOrOptions;
|
|
1180
|
+
actualNodes = undefined;
|
|
1181
|
+
actualEdges = undefined;
|
|
1182
|
+
}
|
|
1183
|
+
else if (Array.isArray(filterNodesOrOptions)) {
|
|
1184
|
+
actualNodes = filterNodesOrOptions;
|
|
1185
|
+
}
|
|
1186
|
+
const maxNodes = actualOptions?.maxNodes !== undefined ? actualOptions.maxNodes : 40;
|
|
1187
|
+
let candidateNodes = [...graph.nodes];
|
|
1188
|
+
if (actualOptions?.nodeTypes) {
|
|
1189
|
+
const allowed = Array.isArray(actualOptions.nodeTypes)
|
|
1190
|
+
? actualOptions.nodeTypes.map(t => t.trim().toLowerCase())
|
|
1191
|
+
: actualOptions.nodeTypes.split(',').map(t => t.trim().toLowerCase());
|
|
1192
|
+
if (allowed.length > 0) {
|
|
1193
|
+
candidateNodes = candidateNodes.filter(n => allowed.includes(n.type.toLowerCase()));
|
|
1194
|
+
}
|
|
1195
|
+
}
|
|
1196
|
+
// Edge degree calculation to prioritize connected entities
|
|
1197
|
+
const degreeMap = new Map();
|
|
1198
|
+
for (const edge of graph.edges) {
|
|
1199
|
+
degreeMap.set(edge.source, (degreeMap.get(edge.source) || 0) + 1);
|
|
1200
|
+
degreeMap.set(edge.target, (degreeMap.get(edge.target) || 0) + 1);
|
|
1201
|
+
}
|
|
1202
|
+
// Prioritize connected project, endpoint, handler, and schema nodes over empty domain directory nodes
|
|
1203
|
+
const typeWeight = (type) => {
|
|
1204
|
+
switch (type) {
|
|
1205
|
+
case 'endpoint': return 50;
|
|
1206
|
+
case 'handler': return 50;
|
|
1207
|
+
case 'schema': return 45;
|
|
1208
|
+
case 'project': return 40;
|
|
1209
|
+
case 'message': return 35;
|
|
1210
|
+
case 'invariant': return 30;
|
|
1211
|
+
case 'domain': return 0;
|
|
1212
|
+
default: return 10;
|
|
1213
|
+
}
|
|
1214
|
+
};
|
|
1215
|
+
candidateNodes.sort((a, b) => {
|
|
1216
|
+
const degA = degreeMap.get(a.id) || 0;
|
|
1217
|
+
const degB = degreeMap.get(b.id) || 0;
|
|
1218
|
+
const scoreA = typeWeight(a.type) + (degA > 0 ? 100 : 0) + degA * 2;
|
|
1219
|
+
const scoreB = typeWeight(b.type) + (degB > 0 ? 100 : 0) + degB * 2;
|
|
1220
|
+
return scoreB - scoreA;
|
|
1221
|
+
});
|
|
1222
|
+
const nodes = actualNodes || (maxNodes > 0 ? candidateNodes.slice(0, maxNodes) : candidateNodes);
|
|
1223
|
+
const edges = actualEdges || graph.edges.filter(e => nodes.some(n => n.id === e.source) && nodes.some(n => n.id === e.target));
|
|
1224
|
+
const lines = ['flowchart TD'];
|
|
1225
|
+
const clustered = actualOptions?.clustered ?? true;
|
|
1226
|
+
if (clustered) {
|
|
1227
|
+
const domainGroups = new Map();
|
|
1228
|
+
const unassigned = [];
|
|
1229
|
+
for (const node of nodes) {
|
|
1230
|
+
if (node.type !== 'domain' && node.domain) {
|
|
1231
|
+
const d = node.domain.toLowerCase();
|
|
1232
|
+
if (!domainGroups.has(d))
|
|
1233
|
+
domainGroups.set(d, []);
|
|
1234
|
+
domainGroups.get(d).push(node);
|
|
1235
|
+
}
|
|
1236
|
+
else {
|
|
1237
|
+
unassigned.push(node);
|
|
1238
|
+
}
|
|
1239
|
+
}
|
|
1240
|
+
// Output domain subgraphs
|
|
1241
|
+
for (const [dom, groupNodes] of domainGroups.entries()) {
|
|
1242
|
+
const subId = `sub_${dom.replace(/[^a-zA-Z0-9_]/g, '_')}`;
|
|
1243
|
+
const title = dom.charAt(0).toUpperCase() + dom.slice(1);
|
|
1244
|
+
lines.push(` subgraph ${subId} ["Domain: ${title}"]`);
|
|
1245
|
+
for (const node of groupNodes) {
|
|
1246
|
+
const sanitizedId = node.id.replace(/[^a-zA-Z0-9_]/g, '_');
|
|
1247
|
+
const cleanLabel = node.label.replace(/"/g, "'").replace(/[\[\]]/g, '');
|
|
1248
|
+
const depClass = node.metadata?.deprecated ? ':::deprecated' : '';
|
|
1249
|
+
const depPrefix = node.metadata?.deprecated ? '⚠️ ' : '';
|
|
1250
|
+
lines.push(` ${sanitizedId}["${depPrefix}[${node.type}] ${cleanLabel}"]${depClass}`);
|
|
1251
|
+
}
|
|
1252
|
+
lines.push(' end');
|
|
1253
|
+
}
|
|
1254
|
+
// Output top-level / unassigned nodes
|
|
1255
|
+
for (const node of unassigned) {
|
|
1256
|
+
const sanitizedId = node.id.replace(/[^a-zA-Z0-9_]/g, '_');
|
|
1257
|
+
const cleanLabel = node.label.replace(/"/g, "'").replace(/[\[\]]/g, '');
|
|
1258
|
+
const depClass = node.metadata?.deprecated ? ':::deprecated' : '';
|
|
1259
|
+
const depPrefix = node.metadata?.deprecated ? '⚠️ ' : '';
|
|
1260
|
+
lines.push(` ${sanitizedId}["${depPrefix}[${node.type}] ${cleanLabel}"]${depClass}`);
|
|
1261
|
+
}
|
|
1262
|
+
}
|
|
1263
|
+
else {
|
|
1264
|
+
for (const node of nodes) {
|
|
1265
|
+
const sanitizedId = node.id.replace(/[^a-zA-Z0-9_]/g, '_');
|
|
1266
|
+
const cleanLabel = node.label.replace(/"/g, "'").replace(/[\[\]]/g, '');
|
|
1267
|
+
const depClass = node.metadata?.deprecated ? ':::deprecated' : '';
|
|
1268
|
+
const depPrefix = node.metadata?.deprecated ? '⚠️ ' : '';
|
|
1269
|
+
lines.push(` ${sanitizedId}["${depPrefix}[${node.type}] ${cleanLabel}"]${depClass}`);
|
|
1270
|
+
}
|
|
1271
|
+
}
|
|
1272
|
+
for (const edge of edges) {
|
|
1273
|
+
const srcId = edge.source.replace(/[^a-zA-Z0-9_]/g, '_');
|
|
1274
|
+
const tgtId = edge.target.replace(/[^a-zA-Z0-9_]/g, '_');
|
|
1275
|
+
lines.push(` ${srcId} -->|${edge.type}| ${tgtId}`);
|
|
1276
|
+
}
|
|
1277
|
+
const hasDeprecated = nodes.some(n => n.metadata?.deprecated);
|
|
1278
|
+
if (hasDeprecated) {
|
|
1279
|
+
lines.push(' classDef deprecated fill:#ffebee,stroke:#d32f2f,stroke-width:2px,stroke-dasharray: 5 5;');
|
|
1280
|
+
}
|
|
1281
|
+
return lines.join('\n');
|
|
1282
|
+
}
|
|
1283
|
+
loadKnowledgeUnits() {
|
|
1284
|
+
const localKDir = path.join(this.repoRoot, 'knowledge');
|
|
1285
|
+
const knowledgeDir = fs.existsSync(localKDir) ? localKDir : this.poolConfig.knowledgeDir;
|
|
1286
|
+
if (!fs.existsSync(knowledgeDir))
|
|
1287
|
+
return [];
|
|
1288
|
+
const currentMtime = this.getKnowledgeMaxMtime();
|
|
1289
|
+
const cacheKey = fs.existsSync(localKDir) ? this.repoRoot : this.poolConfig.poolDir;
|
|
1290
|
+
const cached = GraphBuilder.knowledgeUnitsCache.get(cacheKey);
|
|
1291
|
+
if (cached && cached.mtime === currentMtime) {
|
|
1292
|
+
return cached.units;
|
|
1293
|
+
}
|
|
1294
|
+
const units = [];
|
|
1295
|
+
const findYamls = (dir) => {
|
|
1296
|
+
const entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
1297
|
+
for (const entry of entries) {
|
|
1298
|
+
const full = path.join(dir, entry.name);
|
|
1299
|
+
if (entry.isDirectory()) {
|
|
1300
|
+
findYamls(full);
|
|
1301
|
+
}
|
|
1302
|
+
else if (entry.isFile() && (entry.name.endsWith('.yaml') || entry.name.endsWith('.yml')) && entry.name !== 'index.yaml') {
|
|
1303
|
+
try {
|
|
1304
|
+
const content = YAML.parse(fs.readFileSync(full, 'utf-8'));
|
|
1305
|
+
if (content && content.id && (content.rule || content.decision)) {
|
|
1306
|
+
if (!content.rule && content.decision) {
|
|
1307
|
+
content.rule = content.decision;
|
|
1308
|
+
}
|
|
1309
|
+
units.push(content);
|
|
1310
|
+
}
|
|
1311
|
+
}
|
|
1312
|
+
catch { }
|
|
1313
|
+
}
|
|
1314
|
+
}
|
|
1315
|
+
};
|
|
1316
|
+
findYamls(knowledgeDir);
|
|
1317
|
+
GraphBuilder.knowledgeUnitsCache.set(cacheKey, { mtime: currentMtime, units });
|
|
1318
|
+
return units;
|
|
1319
|
+
}
|
|
1320
|
+
/**
|
|
1321
|
+
* Evaluates if a Knowledge Unit applies to a given file path using dual-path matching
|
|
1322
|
+
* (both targetDir-relative and repositoryRoot-relative) with case-insensitive glob support.
|
|
1323
|
+
*/
|
|
1324
|
+
matchesAppliesTo(unit, filePath) {
|
|
1325
|
+
if (!unit.applies_to || unit.applies_to.length === 0)
|
|
1326
|
+
return true;
|
|
1327
|
+
const absF = path.isAbsolute(filePath) ? filePath : path.resolve(this.repoRoot, filePath);
|
|
1328
|
+
const relToTarget = path.relative(this.repoRoot, absF).replace(/\\/g, '/');
|
|
1329
|
+
const relToRepo = path.relative(this.repositoryRoot, absF).replace(/\\/g, '/');
|
|
1330
|
+
const repoBase = path.basename(this.repositoryRoot).toLowerCase();
|
|
1331
|
+
const sanitizedAppliesTo = unit.applies_to.map(pat => {
|
|
1332
|
+
let p = pat.replace(/\\/g, '/').replace(/^\.\//, '');
|
|
1333
|
+
if (repoBase && p.toLowerCase().startsWith(`${repoBase}/`)) {
|
|
1334
|
+
p = p.slice(repoBase.length + 1);
|
|
1335
|
+
}
|
|
1336
|
+
return p;
|
|
1337
|
+
});
|
|
1338
|
+
const ig = ignore();
|
|
1339
|
+
ig.add(sanitizedAppliesTo);
|
|
1340
|
+
if (relToTarget && !relToTarget.startsWith('../') && ig.ignores(relToTarget))
|
|
1341
|
+
return true;
|
|
1342
|
+
if (relToRepo && !relToRepo.startsWith('../') && ig.ignores(relToRepo))
|
|
1343
|
+
return true;
|
|
1344
|
+
// Substring / wildcard-stripped fallback with case-insensitivity
|
|
1345
|
+
const lowerTarget = relToTarget.toLowerCase();
|
|
1346
|
+
const lowerRepo = relToRepo.toLowerCase();
|
|
1347
|
+
return sanitizedAppliesTo.some(pat => {
|
|
1348
|
+
const pClean = pat.toLowerCase().replace(/[*]/g, '').trim();
|
|
1349
|
+
return pClean.length >= 3 && (lowerTarget.includes(pClean) || lowerRepo.includes(pClean));
|
|
1350
|
+
});
|
|
1351
|
+
}
|
|
1352
|
+
extractEndpointRoute(signature) {
|
|
1353
|
+
const m = signature.match(/^([A-Z]+)\s+([^\s->]+)/);
|
|
1354
|
+
if (m) {
|
|
1355
|
+
return {
|
|
1356
|
+
method: m[1].toUpperCase(),
|
|
1357
|
+
route: this.normalizeRoutePath(m[2])
|
|
1358
|
+
};
|
|
1359
|
+
}
|
|
1360
|
+
const djangoMatch = signature.match(/^Django\s+([^\s->]+)/);
|
|
1361
|
+
if (djangoMatch) {
|
|
1362
|
+
return {
|
|
1363
|
+
method: 'ANY',
|
|
1364
|
+
route: this.normalizeRoutePath(djangoMatch[1])
|
|
1365
|
+
};
|
|
1366
|
+
}
|
|
1367
|
+
return null;
|
|
1368
|
+
}
|
|
1369
|
+
normalizeRoutePath(rawPath) {
|
|
1370
|
+
let p = rawPath.replace(/^https?:\/\/[^\/]+/, '');
|
|
1371
|
+
p = p.split('?')[0];
|
|
1372
|
+
if (!p.startsWith('/'))
|
|
1373
|
+
p = `/${p}`;
|
|
1374
|
+
if (p.length > 1 && p.endsWith('/'))
|
|
1375
|
+
p = p.slice(0, -1);
|
|
1376
|
+
return p.toLowerCase();
|
|
1377
|
+
}
|
|
1378
|
+
routesMatch(clientPath, serverPath) {
|
|
1379
|
+
const cNorm = this.normalizeRoutePath(clientPath);
|
|
1380
|
+
const sNorm = this.normalizeRoutePath(serverPath);
|
|
1381
|
+
if (cNorm === sNorm)
|
|
1382
|
+
return true;
|
|
1383
|
+
const serverPattern = sNorm
|
|
1384
|
+
.replace(/:[a-zA-Z0-9_]+/g, '[^/]+')
|
|
1385
|
+
.replace(/\{[a-zA-Z0-9_]+\}/g, '[^/]+');
|
|
1386
|
+
try {
|
|
1387
|
+
if (new RegExp(`^${serverPattern}$`, 'i').test(cNorm))
|
|
1388
|
+
return true;
|
|
1389
|
+
}
|
|
1390
|
+
catch { }
|
|
1391
|
+
const clientPattern = cNorm
|
|
1392
|
+
.replace(/:[a-zA-Z0-9_]+/g, '[^/]+')
|
|
1393
|
+
.replace(/\{[a-zA-Z0-9_]+\}/g, '[^/]+');
|
|
1394
|
+
try {
|
|
1395
|
+
if (new RegExp(`^${clientPattern}$`, 'i').test(sNorm))
|
|
1396
|
+
return true;
|
|
1397
|
+
}
|
|
1398
|
+
catch { }
|
|
1399
|
+
return false;
|
|
1400
|
+
}
|
|
1401
|
+
canonicalEventName(name) {
|
|
1402
|
+
return name.replace(/[-_.:/]/g, '').toLowerCase();
|
|
1403
|
+
}
|
|
1404
|
+
/**
|
|
1405
|
+
* Fast 0-token symbol/node search across the graph.
|
|
1406
|
+
*/
|
|
1407
|
+
searchNodes(graph, params) {
|
|
1408
|
+
const query = params.query.toLowerCase().trim();
|
|
1409
|
+
const targetType = params.type || 'all';
|
|
1410
|
+
const limit = params.limit || 20;
|
|
1411
|
+
const matches = [];
|
|
1412
|
+
for (const node of graph.nodes) {
|
|
1413
|
+
if (targetType !== 'all' && node.type !== targetType)
|
|
1414
|
+
continue;
|
|
1415
|
+
if (params.domain && node.domain && node.domain.toLowerCase() !== params.domain.toLowerCase())
|
|
1416
|
+
continue;
|
|
1417
|
+
let score = 0;
|
|
1418
|
+
const idLower = node.id.toLowerCase();
|
|
1419
|
+
const labelLower = node.label.toLowerCase();
|
|
1420
|
+
const fileLower = (node.file || '').toLowerCase();
|
|
1421
|
+
const sigLower = (node.metadata?.signature || '').toLowerCase();
|
|
1422
|
+
if (idLower === query || labelLower === query) {
|
|
1423
|
+
score = 100;
|
|
1424
|
+
}
|
|
1425
|
+
else if (idLower.startsWith(query) || labelLower.startsWith(query)) {
|
|
1426
|
+
score = 80;
|
|
1427
|
+
}
|
|
1428
|
+
else if (idLower.includes(query) || labelLower.includes(query)) {
|
|
1429
|
+
score = 50;
|
|
1430
|
+
}
|
|
1431
|
+
else if (sigLower.includes(query)) {
|
|
1432
|
+
score = 40;
|
|
1433
|
+
}
|
|
1434
|
+
else if (fileLower.includes(query)) {
|
|
1435
|
+
score = 30;
|
|
1436
|
+
}
|
|
1437
|
+
if (score > 0) {
|
|
1438
|
+
matches.push({ node, score });
|
|
1439
|
+
}
|
|
1440
|
+
}
|
|
1441
|
+
matches.sort((a, b) => b.score - a.score);
|
|
1442
|
+
return matches.slice(0, limit).map(m => ({
|
|
1443
|
+
id: m.node.id,
|
|
1444
|
+
label: m.node.label,
|
|
1445
|
+
type: m.node.type,
|
|
1446
|
+
file: m.node.file,
|
|
1447
|
+
signature: m.node.metadata?.signature,
|
|
1448
|
+
domain: m.node.domain
|
|
1449
|
+
}));
|
|
1450
|
+
}
|
|
1451
|
+
/**
|
|
1452
|
+
* Blast-radius and inbound dependent calculation.
|
|
1453
|
+
*/
|
|
1454
|
+
calculateInboundImpact(graph, targetSearch, options = {}) {
|
|
1455
|
+
const maxDepth = options.maxDepth || 3;
|
|
1456
|
+
const target = targetSearch.toLowerCase().trim();
|
|
1457
|
+
// Resolve target to a node (prefer exact ID, then non-client endpoint/handler, then general match)
|
|
1458
|
+
const node = graph.nodes.find(n => n.id.toLowerCase() === target) ||
|
|
1459
|
+
graph.nodes.find(n => n.label.toLowerCase() === target && !n.metadata?.isClient) ||
|
|
1460
|
+
graph.nodes.find(n => n.label.toLowerCase() === target) ||
|
|
1461
|
+
graph.nodes.find(n => n.file && n.file.toLowerCase().includes(target));
|
|
1462
|
+
if (!node) {
|
|
1463
|
+
return {
|
|
1464
|
+
targetNode: targetSearch,
|
|
1465
|
+
directCallers: [],
|
|
1466
|
+
affectedEndpoints: [],
|
|
1467
|
+
topologicalProjects: [],
|
|
1468
|
+
invariants: []
|
|
1469
|
+
};
|
|
1470
|
+
}
|
|
1471
|
+
const nodeMap = new Map();
|
|
1472
|
+
for (const n of graph.nodes) {
|
|
1473
|
+
nodeMap.set(n.id, n);
|
|
1474
|
+
}
|
|
1475
|
+
const visited = new Set();
|
|
1476
|
+
const queue = [{ id: node.id, depth: 0 }];
|
|
1477
|
+
const directCallers = new Set();
|
|
1478
|
+
const affectedEndpoints = new Set();
|
|
1479
|
+
const affectedProjects = new Set();
|
|
1480
|
+
const invariants = new Set();
|
|
1481
|
+
while (queue.length > 0) {
|
|
1482
|
+
const { id, depth } = queue.shift();
|
|
1483
|
+
if (visited.has(id) || depth >= maxDepth)
|
|
1484
|
+
continue;
|
|
1485
|
+
visited.add(id);
|
|
1486
|
+
// Inbound edges: caller --EDGE--> id (plus bidirectional traversal for IMPLEMENTS)
|
|
1487
|
+
const inboundEdges = graph.edges.filter(e => e.target === id || (e.type === 'IMPLEMENTS' && e.source === id));
|
|
1488
|
+
for (const edge of inboundEdges) {
|
|
1489
|
+
const callerId = edge.target === id ? edge.source : edge.target;
|
|
1490
|
+
const callerNode = nodeMap.get(callerId);
|
|
1491
|
+
if (depth === 0) {
|
|
1492
|
+
directCallers.add(callerId);
|
|
1493
|
+
}
|
|
1494
|
+
if (callerNode) {
|
|
1495
|
+
if (callerNode.type === 'endpoint' || callerNode.type === 'handler') {
|
|
1496
|
+
affectedEndpoints.add(callerId);
|
|
1497
|
+
}
|
|
1498
|
+
else if (callerNode.type === 'project') {
|
|
1499
|
+
affectedProjects.add(callerId);
|
|
1500
|
+
}
|
|
1501
|
+
else if (callerNode.type === 'invariant') {
|
|
1502
|
+
invariants.add(callerId);
|
|
1503
|
+
}
|
|
1504
|
+
}
|
|
1505
|
+
queue.push({ id: callerId, depth: depth + 1 });
|
|
1506
|
+
}
|
|
1507
|
+
}
|
|
1508
|
+
return {
|
|
1509
|
+
targetNode: node.id,
|
|
1510
|
+
directCallers: Array.from(directCallers),
|
|
1511
|
+
affectedEndpoints: Array.from(affectedEndpoints),
|
|
1512
|
+
topologicalProjects: Array.from(affectedProjects),
|
|
1513
|
+
invariants: Array.from(invariants)
|
|
1514
|
+
};
|
|
1515
|
+
}
|
|
1516
|
+
}
|