Graphs that teach > graphs that impress. Turn any code into an interactive knowledge graph you can explore, search, and ask questions about. Works with Claude Code, Codex, Cursor, Copilot, Gemini CLI, and more.
TypeScript antigravity-skillsbusiness-knowledgeclaude-codeclaude-skillscodebase-analysiscodexcodex-skillsdeveloper-tools-ai-agentgemini-cli-skillskarpathy-llm-wikiknowledge-baseknowledge-graphmemoryopencode-skillspi-agentunderstandcodevibe-coding
feat(core): add Zod schema validation for knowledge graph loading
Lum1104c04123366e25
diff --git a/packages/core/package.json b/packages/core/package.jsonindex 4f419175..4d06a07b 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -16,6 +16,7 @@"dependencies": {"tree-sitter-javascript": "^0.25.0","tree-sitter-typescript": "^0.23.2",- "web-tree-sitter": "^0.26.6"+ "web-tree-sitter": "^0.26.6",+ "zod": "^4.3.6"}}diff --git a/packages/core/src/__tests__/schema.test.ts b/packages/core/src/__tests__/schema.test.tsnew file mode 100644index 00000000..ae3fd7ea--- /dev/null+++ b/packages/core/src/__tests__/schema.test.ts@@ -0,0 +1,112 @@+import { describe, it, expect } from "vitest";+import { validateGraph } from "../schema.js";+import type { KnowledgeGraph } from "../types.js";++const validGraph: KnowledgeGraph = {+ version: "1.0.0",+ project: {+ name: "test-project",+ languages: ["typescript"],+ frameworks: ["vitest"],+ description: "A test project",+ analyzedAt: "2026-03-14T00:00:00.000Z",+ gitCommitHash: "abc123",+ },+ nodes: [+ {+ id: "node-1",+ type: "file",+ name: "index.ts",+ filePath: "src/index.ts",+ lineRange: [1, 50],+ summary: "Entry point",+ tags: ["entry"],+ complexity: "simple",+ },+ ],+ edges: [+ {+ source: "node-1",+ target: "node-2",+ type: "imports",+ direction: "forward",+ weight: 0.8,+ },+ ],+ layers: [+ {+ id: "layer-1",+ name: "Core",+ description: "Core layer",+ nodeIds: ["node-1"],+ },+ ],+ tour: [+ {+ order: 1,+ title: "Start here",+ description: "Begin with the entry point",+ nodeIds: ["node-1"],+ },+ ],+};++describe("schema validation", () => {+ it("validates a correct knowledge graph", () => {+ const result = validateGraph(validGraph);+ expect(result.success).toBe(true);+ expect(result.data).toBeDefined();+ expect(result.data!.version).toBe("1.0.0");+ expect(result.errors).toBeUndefined();+ });++ it("rejects graph with missing required fields", () => {+ const incomplete = {+ version: "1.0.0",+ // missing project, nodes, edges, layers, tour+ };++ const result = validateGraph(incomplete);+ expect(result.success).toBe(false);+ expect(result.errors).toBeDefined();+ expect(result.errors!.length).toBeGreaterThan(0);+ });++ it("rejects node with invalid type", () => {+ const graph = structuredClone(validGraph);+ (graph.nodes[0] as any).type = "invalid_type";++ const result = validateGraph(graph);+ expect(result.success).toBe(false);+ expect(result.errors).toBeDefined();+ expect(result.errors!.some((e) => e.includes("type"))).toBe(true);+ });++ it("rejects edge with invalid EdgeType", () => {+ const graph = structuredClone(validGraph);+ (graph.edges[0] as any).type = "not_a_real_edge_type";++ const result = validateGraph(graph);+ expect(result.success).toBe(false);+ expect(result.errors).toBeDefined();+ expect(result.errors!.some((e) => e.includes("type"))).toBe(true);+ });++ it("rejects weight out of range (>1)", () => {+ const graph = structuredClone(validGraph);+ graph.edges[0].weight = 1.5;++ const result = validateGraph(graph);+ expect(result.success).toBe(false);+ expect(result.errors).toBeDefined();+ });++ it("rejects weight out of range (<0)", () => {+ const graph = structuredClone(validGraph);+ graph.edges[0].weight = -0.1;++ const result = validateGraph(graph);+ expect(result.success).toBe(false);+ expect(result.errors).toBeDefined();+ });+});diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 727dc439..c84b1c5b 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -1,5 +1,6 @@export * from "./types.js";export * from "./persistence/index.js";+export { KnowledgeGraphSchema, validateGraph, type ValidationResult } from "./schema.js";export { TreeSitterPlugin } from "./plugins/tree-sitter-plugin.js";export { GraphBuilder } from "./analyzer/graph-builder.js";export {diff --git a/packages/core/src/persistence/index.ts b/packages/core/src/persistence/index.tsindex 30965c01..f0262dad 100644--- a/packages/core/src/persistence/index.ts+++ b/packages/core/src/persistence/index.ts@@ -1,6 +1,7 @@import { readFileSync, writeFileSync, mkdirSync, existsSync } from "node:fs";import { join } from "node:path";import type { KnowledgeGraph, AnalysisMeta } from "../types.js";+import { validateGraph } from "../schema.js";const UA_DIR = ".understand-anything";const GRAPH_FILE = "knowledge-graph.json";@@ -19,10 +20,25 @@ export function saveGraph(projectRoot: string, graph: KnowledgeGraph): void {writeFileSync(join(dir, GRAPH_FILE), JSON.stringify(graph, null, 2), "utf-8");}-export function loadGraph(projectRoot: string): KnowledgeGraph | null {+export function loadGraph(+ projectRoot: string,+ options?: { validate?: boolean },+): KnowledgeGraph | null {const filePath = join(projectRoot, UA_DIR, GRAPH_FILE);if (!existsSync(filePath)) return null;- return JSON.parse(readFileSync(filePath, "utf-8")) as KnowledgeGraph;++ const data = JSON.parse(readFileSync(filePath, "utf-8"));++ if (options?.validate !== false) {+ const result = validateGraph(data);+ if (!result.success) {+ throw new Error(+ `Invalid knowledge graph: ${result.errors!.join("; ")}`,+ );+ }+ }++ return data as KnowledgeGraph;}export function saveMeta(projectRoot: string, meta: AnalysisMeta): void {diff --git a/packages/core/src/schema.ts b/packages/core/src/schema.tsnew file mode 100644index 00000000..2b66b1d5--- /dev/null+++ b/packages/core/src/schema.ts@@ -0,0 +1,85 @@+import { z } from "zod";++// Edge types (18 values across 5 categories)+export const EdgeTypeSchema = z.enum([+ "imports", "exports", "contains", "inherits", "implements", // Structural+ "calls", "subscribes", "publishes", "middleware", // Behavioral+ "reads_from", "writes_to", "transforms", "validates", // Data flow+ "depends_on", "tested_by", "configures", // Dependencies+ "related", "similar_to", // Semantic+]);++export const GraphNodeSchema = z.object({+ id: z.string(),+ type: z.enum(["file", "function", "class", "module", "concept"]),+ name: z.string(),+ filePath: z.string().optional(),+ lineRange: z.tuple([z.number(), z.number()]).optional(),+ summary: z.string(),+ tags: z.array(z.string()),+ complexity: z.enum(["simple", "moderate", "complex"]),+ languageNotes: z.string().optional(),+});++export const GraphEdgeSchema = z.object({+ source: z.string(),+ target: z.string(),+ type: EdgeTypeSchema,+ direction: z.enum(["forward", "backward", "bidirectional"]),+ description: z.string().optional(),+ weight: z.number().min(0).max(1),+});++export const LayerSchema = z.object({+ id: z.string(),+ name: z.string(),+ description: z.string(),+ nodeIds: z.array(z.string()),+});++export const TourStepSchema = z.object({+ order: z.number(),+ title: z.string(),+ description: z.string(),+ nodeIds: z.array(z.string()),+ languageLesson: z.string().optional(),+});++export const ProjectMetaSchema = z.object({+ name: z.string(),+ languages: z.array(z.string()),+ frameworks: z.array(z.string()),+ description: z.string(),+ analyzedAt: z.string(),+ gitCommitHash: z.string(),+});++export const KnowledgeGraphSchema = z.object({+ version: z.string(),+ project: ProjectMetaSchema,+ nodes: z.array(GraphNodeSchema),+ edges: z.array(GraphEdgeSchema),+ layers: z.array(LayerSchema),+ tour: z.array(TourStepSchema),+});++export interface ValidationResult {+ success: boolean;+ data?: z.infer<typeof KnowledgeGraphSchema>;+ errors?: string[];+}++export function validateGraph(data: unknown): ValidationResult {+ const result = KnowledgeGraphSchema.safeParse(data);++ if (result.success) {+ return { success: true, data: result.data };+ }++ const errors = result.error.issues.map((issue) => {+ const path = issue.path.join(".");+ return path ? `${path}: ${issue.message}` : issue.message;+ });++ return { success: false, errors };+}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 3aae63a3..dc1e00fc 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -26,6 +26,9 @@ importers:web-tree-sitter:specifier: ^0.26.6version: 0.26.6+ zod:+ specifier: ^4.3.6+ version: 4.3.6devDependencies:'@types/node':specifier: ^25.5.0@@ -1350,6 +1353,9 @@ packages:resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==}+ resolution: {integrity: sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==}+resolution: {integrity: sha512-CHOUy7mu3lbD6o6LJLfllpjkzhHXSBlX8B9+qPddUsIfeF5S/UZ5q0kmCsnRqT1UHFQZchNFDDzMbQsuesHWlw==}engines: {node: '>=12.7.0'}@@ -2443,6 +2449,8 @@ snapshots:+ [email protected]: {}+dependencies:use-sync-external-store: 1.6.0([email protected])