build-knowledge-graph.spec.js 5.31 KB
const fs = require("node:fs");
const path = require("node:path");

const fixtureRoot = path.resolve(__dirname, "__fixtures__/vue2-app");
const builderPath = path.resolve(__dirname, "build-knowledge-graph.js");

function loadBuilder() {
	expect(fs.existsSync(builderPath)).toBe(true);
	return require(builderPath);
}

function findEdge(graph, type, fromIncludes, toIncludes) {
	return graph.edges.find(edge => edge.type === type
		&& edge.from.includes(fromIncludes)
		&& edge.to.includes(toIncludes));
}

describe("vue2 知识图谱构建", () => {
	it("应从路由、SFC、Vuex、API、测试和文档生成公开图谱契约", () => {
		const { buildKnowledgeGraph } = loadBuilder();
		const graph = buildKnowledgeGraph({ rootDir: fixtureRoot });

		expect(Object.keys(graph)).toEqual([
			"schemaVersion",
			"nodes",
			"edges",
			"unresolved",
			"stats",
		]);
		expect(graph.schemaVersion).toBe("1.0.0");

		const nodeTypes = new Set(graph.nodes.map(node => node.type));
		[
			"domain",
			"route",
			"view",
			"component",
			"module",
			"function",
			"apiOperation",
			"endpoint",
			"vuexState",
			"vuexGetter",
			"vuexAction",
			"vuexMutation",
			"permission",
			"event",
			"test",
			"document",
		].forEach(type => expect(nodeTypes.has(type)).toBe(true));

		expect(findEdge(graph, "renders", "route:90301", "views/goods/list.vue")).toBeTruthy();
		expect(findEdge(graph, "requiresPermission", "route:90301", "permission:9030101")).toBeTruthy();
		expect(findEdge(graph, "usesComponent", "views/goods/list.vue", "components/SharedCard.vue")).toBeTruthy();
		expect(findEdge(graph, "listensEvent", "views/goods/list.vue", "event:select")).toBeTruthy();
		expect(findEdge(graph, "emitsEvent", "components/SharedCard.vue", "event:select")).toBeTruthy();
		expect(findEdge(graph, "calls", "#created", "#loadGoods")).toBeTruthy();
		expect(findEdge(graph, "navigatesTo", "#openDetail", "route:90302")).toBeTruthy();
		expect(findEdge(graph, "callsApi", "#loadGoods", "api/goods.js#listGoods")).toBeTruthy();
		expect(findEdge(graph, "callsEndpoint", "api/goods.js#listGoods", "dj.api.smartcarlife.product.list")).toBeTruthy();
		expect(findEdge(graph, "readsState", "views/goods/list.vue", "catalog.items")).toBeTruthy();
		expect(findEdge(graph, "readsGetter", "views/goods/list.vue", "catalog.itemCount")).toBeTruthy();
		expect(findEdge(graph, "dispatchesAction", "#loadGoods", "catalog/load")).toBeTruthy();
		expect(findEdge(graph, "commitsMutation", "#loadGoods", "catalog/setItems")).toBeTruthy();
		expect(findEdge(graph, "coveredBy", "views/goods/list.vue", "tests/goods-list.spec.js")).toBeTruthy();
		expect(findEdge(graph, "documentedBy", "views/goods/list.vue", ".ai/docs/knowledge/903-product.md")).toBeTruthy();

		graph.edges.forEach((edge) => {
			expect(typeof edge.confidence).toBe("number");
			expect(edge.evidence.path).not.toContain("\\");
			expect(Number.isInteger(edge.evidence.line)).toBe(true);
			expect(Number.isInteger(edge.evidence.column)).toBe(true);
		});
	});

	it("应记录动态表达式但不复制源码和敏感字面量", () => {
		const { buildKnowledgeGraph } = loadBuilder();
		const graph = buildKnowledgeGraph({ rootDir: fixtureRoot });
		const serialized = JSON.stringify(graph);

		expect(graph.unresolved).toEqual(expect.arrayContaining([
			expect.objectContaining({
				kind: "route",
				path: "src/views/goods/list.vue",
				known: true,
			}),
			expect.objectContaining({
				kind: "document-link",
				path: ".ai/docs/knowledge/903-product.md",
				known: false,
			}),
		]));
		expect(serialized).not.toContain("fixture-password");
		expect(serialized).not.toContain("this.$router.push(target)");
		expect(serialized).not.toContain("https://private.example.com");
	});

	it("known gaps 必须按结构化证据精确匹配", () => {
		const { markKnownGaps } = loadBuilder();
		const gaps = [{
			kind: "route",
			path: "src/views/goods/list.vue",
			line: 38,
			column: 3,
			reason: "dynamic-expression",
		}];

		expect(markKnownGaps(gaps, { gaps })[0].known).toBe(true);
		expect(markKnownGaps([{ ...gaps[0], line: 39 }], { gaps })[0].known).toBe(false);
	});

	it("无效扫描目录应明确失败", () => {
		const { buildKnowledgeGraph } = loadBuilder();
		expect(() => buildKnowledgeGraph({ rootDir: path.join(fixtureRoot, "missing") }))
			.toThrow("Invalid root directory");
	});

	it("overlay 应只重扫指定文件并保留动态关系告警", () => {
		const { buildKnowledgeGraph, buildKnowledgeOverlay } = loadBuilder();
		const baseGraph = buildKnowledgeGraph({ rootDir: fixtureRoot });
		const overlay = buildKnowledgeOverlay({
			rootDir: fixtureRoot,
			baseGraph,
			files: ["src/views/goods/list.vue"],
		});

		expect(overlay.nodes.some(node => node.path === "src/views/goods/list.vue")).toBe(true);
		expect(overlay.nodes.some(node => node.path === "src/views/goods/detail.vue")).toBe(false);
		expect(overlay.unresolved).toEqual(expect.arrayContaining([
			expect.objectContaining({ path: "src/views/goods/list.vue", known: true }),
		]));
	});

	it("应连续产生字节一致且以换行结尾的输出", () => {
		const { buildKnowledgeGraph, serializeGraph } = loadBuilder();
		const first = serializeGraph(buildKnowledgeGraph({ rootDir: fixtureRoot }));
		const second = serializeGraph(buildKnowledgeGraph({ rootDir: fixtureRoot }));

		expect(first).toBe(second);
		expect(first.endsWith("\n")).toBe(true);
	});
});