build-knowledge-graph.js
6.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
const fs = require("node:fs");
const path = require("node:path");
const process = require("node:process");
const { GraphStore } = require("./graph-store");
const { collectFiles } = require("./path-utils");
const {
finalizeRouteLinks,
scanRouterFile,
scanRouterInfrastructure,
} = require("./scan-router");
const {
scanContractFile,
scanDocument,
scanJavaScriptFile,
scanVueFile,
} = require("./scan-sources");
function readJson(filePath, fallback) {
if (!fs.existsSync(filePath)) {
return fallback;
}
return JSON.parse(fs.readFileSync(filePath, "utf8"));
}
function loadDomainCatalog(rootDir) {
const catalogPath = path.join(rootDir, ".ai/knowledge/domain-catalog.json");
const catalog = readJson(catalogPath, { schemaVersion: 1, domains: [] });
if (catalog.schemaVersion !== 1 || !Array.isArray(catalog.domains)) {
throw new Error("Invalid domain catalog");
}
return catalog;
}
function loadKnownGaps(rootDir) {
const knownGapsPath = path.join(rootDir, ".ai/knowledge/known-gaps.json");
const knownGaps = readJson(knownGapsPath, { schemaVersion: 1, gaps: [] });
if (knownGaps.schemaVersion !== 1 || !Array.isArray(knownGaps.gaps)) {
throw new Error("Invalid known gaps configuration");
}
return knownGaps;
}
function markKnownGaps(unresolved, knownGaps) {
const keys = ["kind", "path", "line", "column", "reason"];
return unresolved.map(item => ({
...item,
known: knownGaps.gaps.some(gap => keys.every(key => gap[key] === item[key])),
}));
}
function createContext() {
return {
constants: new Map(),
currentRouterModuleId: null,
pendingRouteLinks: [],
routesByAuthId: new Map(),
routesByName: new Map(),
routesByPath: new Map(),
routeViewPaths: new Set(),
};
}
function hydrateContext(baseGraph) {
const context = createContext();
for (const node of baseGraph?.nodes || []) {
if (node.type !== "route") {
continue;
}
if (node.meta?.authId) {
context.routesByAuthId.set(String(node.meta.authId), node.id);
}
if (node.meta?.routeName) {
context.routesByName.set(String(node.meta.routeName), node.id);
}
if (node.meta?.routePath) {
context.routesByPath.set(String(node.meta.routePath), node.id);
}
}
for (const edge of baseGraph?.edges || []) {
if (edge.type === "renders") {
const target = baseGraph.nodes.find(node => node.id === edge.to);
if (target?.path) {
context.routeViewPaths.add(target.path);
}
}
}
return context;
}
function addDomainNodes(store, catalog) {
for (const domain of catalog.domains) {
store.addNode({
id: `domain:${domain.id}`,
type: "domain",
name: domain.title || domain.name || String(domain.id),
path: domain.routeModule,
domainIds: [String(domain.id)],
meta: {
aliases: domain.aliases || [],
entrypoints: domain.entrypoints || [],
roots: domain.roots || [],
documents: domain.documents || [],
riskKeywords: domain.riskKeywords || [],
},
});
}
}
function validateDomainCatalog(rootDir, store, catalog) {
for (const domain of catalog.domains) {
for (const configuredPath of [
domain.routeModule,
...(domain.roots || []),
...(domain.entrypoints || []),
...(domain.documents || []),
].filter(Boolean)) {
if (!fs.existsSync(path.join(rootDir, configuredPath))) {
store.addUnresolved({
kind: "catalog-path",
path: configuredPath,
reason: "missing-target",
expressionKind: "DomainCatalog",
});
}
}
}
}
function buildKnowledgeGraph(options = {}) {
const rootDir = path.resolve(options.rootDir || process.cwd());
if (!fs.existsSync(rootDir) || !fs.statSync(rootDir).isDirectory()) {
throw new Error(`Invalid root directory: ${rootDir}`);
}
const catalog = loadDomainCatalog(rootDir);
const knownGaps = loadKnownGaps(rootDir);
const store = new GraphStore(catalog);
const context = createContext();
addDomainNodes(store, catalog);
validateDomainCatalog(rootDir, store, catalog);
const files = collectFiles(rootDir);
const routerFiles = files.filter(file => /^src\/router\/modules\/.*\.js$/.test(file));
routerFiles.forEach(file => scanRouterFile(rootDir, file, store, context));
if (files.includes("src/router/routes.js")) {
scanRouterInfrastructure(rootDir, "src/router/routes.js", store, context);
}
finalizeRouteLinks(store, context);
for (const file of files) {
if (routerFiles.includes(file) || file.startsWith(".ai/knowledge/")) {
continue;
}
if (file.endsWith(".vue")) {
scanVueFile(rootDir, file, store, context);
} else if (file.endsWith(".js")) {
scanJavaScriptFile(rootDir, file, store, context);
} else if (file.endsWith(".contract.json")) {
scanContractFile(rootDir, file, store, context);
} else if (file.endsWith(".md")) {
scanDocument(rootDir, file, store, context);
}
}
const graph = store.toGraph();
graph.unresolved = markKnownGaps(graph.unresolved, knownGaps);
return graph;
}
function buildKnowledgeOverlay(options = {}) {
const rootDir = path.resolve(options.rootDir || process.cwd());
if (!fs.existsSync(rootDir) || !fs.statSync(rootDir).isDirectory()) {
throw new Error(`Invalid root directory: ${rootDir}`);
}
const catalog = loadDomainCatalog(rootDir);
const knownGaps = loadKnownGaps(rootDir);
const store = new GraphStore(catalog);
const context = hydrateContext(options.baseGraph);
addDomainNodes(store, catalog);
const files = [...new Set((options.files || []).map(file => file.replace(/\\/g, "/")))]
.filter(file => fs.existsSync(path.join(rootDir, file)))
.sort();
const routerFiles = files.filter(file => /^src\/router\/modules\/.*\.js$/.test(file));
routerFiles.forEach(file => scanRouterFile(rootDir, file, store, context));
if (files.includes("src/router/routes.js")) {
scanRouterInfrastructure(rootDir, "src/router/routes.js", store, context);
}
finalizeRouteLinks(store, context);
for (const file of files) {
if (routerFiles.includes(file) || file === "src/router/routes.js" || file.startsWith(".ai/knowledge/")) {
continue;
}
if (file.endsWith(".vue")) {
scanVueFile(rootDir, file, store, context);
} else if (file.endsWith(".js")) {
scanJavaScriptFile(rootDir, file, store, context);
} else if (file.endsWith(".contract.json")) {
scanContractFile(rootDir, file, store, context);
} else if (file.endsWith(".md")) {
scanDocument(rootDir, file, store, context);
}
}
const graph = store.toGraph();
graph.unresolved = markKnownGaps(graph.unresolved, knownGaps);
return graph;
}
function serializeGraph(graph) {
return `${JSON.stringify(graph)}\n`;
}
module.exports = {
buildKnowledgeGraph,
buildKnowledgeOverlay,
loadDomainCatalog,
loadKnownGaps,
markKnownGaps,
serializeGraph,
};