build-knowledge-graph.js 6.51 KB
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,
};