Skip to content

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.

feat(core): permissive graph validation with tiered auto-fix pipeline

Lum110428e3bd163175
diff --git a/understand-anything-plugin/packages/core/src/__tests__/schema.test.ts b/understand-anything-plugin/packages/core/src/__tests__/schema.test.ts
index 24edb518..e2ffe69f 100644
--- a/understand-anything-plugin/packages/core/src/__tests__/schema.test.ts
+++ b/understand-anything-plugin/packages/core/src/__tests__/schema.test.ts
@@ -2,6 +2,8 @@ import { describe, it, expect } from "vitest";
import {
validateGraph,
normalizeGraph,
+ sanitizeGraph,
+ autoFixGraph,
NODE_TYPE_ALIASES,
EDGE_TYPE_ALIASES,
} from "../schema.js";
@@ -32,7 +34,7 @@ const validGraph: KnowledgeGraph = {
edges: [
{
source: "node-1",
- target: "node-2",
+ target: "node-1",
type: "imports",
direction: "forward",
weight: 0.8,
@@ -62,57 +64,60 @@ describe("schema validation", () => {
expect(result.success).toBe(true);
expect(result.data).toBeDefined();
expect(result.data!.version).toBe("1.0.0");
- expect(result.errors).toBeUndefined();
+ expect(result.issues).toEqual([]);
});
it("rejects graph with missing required fields", () => {
- const incomplete = {
- version: "1.0.0",
- // missing project, nodes, edges, layers, tour
- };
-
+ const incomplete = { version: "1.0.0" };
const result = validateGraph(incomplete);
expect(result.success).toBe(false);
- expect(result.errors).toBeDefined();
- expect(result.errors!.length).toBeGreaterThan(0);
+ expect(result.fatal).toBeDefined();
});
- it("rejects node with invalid type", () => {
+ it("rejects node with invalid type — drops node, fatal if none remain", () => {
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);
+ expect(result.fatal).toContain("No valid nodes");
+ expect(result.issues).toContainEqual(
+ expect.objectContaining({ level: "dropped", category: "invalid-node" })
+ );
});
- it("rejects edge with invalid EdgeType", () => {
+ it("drops edge with invalid EdgeType but loads graph", () => {
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);
+ expect(result.success).toBe(true);
+ expect(result.data!.edges.length).toBe(0);
+ expect(result.issues).toContainEqual(
+ expect.objectContaining({ level: "dropped", category: "invalid-edge" })
+ );
});
- it("rejects weight out of range (>1)", () => {
+ it("auto-corrects weight >1 by clamping", () => {
const graph = structuredClone(validGraph);
graph.edges[0].weight = 1.5;
const result = validateGraph(graph);
- expect(result.success).toBe(false);
- expect(result.errors).toBeDefined();
+ expect(result.success).toBe(true);
+ expect(result.issues).toContainEqual(
+ expect.objectContaining({ level: "auto-corrected", category: "out-of-range" })
+ );
});
- it("rejects weight out of range (<0)", () => {
+ it("auto-corrects weight <0 by clamping", () => {
const graph = structuredClone(validGraph);
graph.edges[0].weight = -0.1;
const result = validateGraph(graph);
- expect(result.success).toBe(false);
- expect(result.errors).toBeDefined();
+ expect(result.success).toBe(true);
+ expect(result.issues).toContainEqual(
+ expect.objectContaining({ level: "auto-corrected", category: "out-of-range" })
+ );
});
it('normalizes "func" node type to "function"', () => {
@@ -229,20 +234,28 @@ describe("schema validation", () => {
expect(result.data!.edges[0].type).toBe("depends_on");
});
- it('rejects "tests" edge type — direction-inverting alias is unsafe', () => {
+ it('drops "tests" edge type — direction-inverting alias is unsafe', () => {
const graph = structuredClone(validGraph);
(graph.edges[0] as any).type = "tests";
const result = validateGraph(graph);
- expect(result.success).toBe(false);
+ expect(result.success).toBe(true);
+ expect(result.data!.edges.length).toBe(0);
+ expect(result.issues).toContainEqual(
+ expect.objectContaining({ level: "dropped" })
+ );
});
- it("still rejects truly invalid edge types after normalization", () => {
+ it("drops truly invalid edge types after normalization", () => {
const graph = structuredClone(validGraph);
(graph.edges[0] as any).type = "totally_bogus";
const result = validateGraph(graph);
- expect(result.success).toBe(false);
+ expect(result.success).toBe(true);
+ expect(result.data!.edges.length).toBe(0);
+ expect(result.issues).toContainEqual(
+ expect.objectContaining({ level: "dropped" })
+ );
});
it("NODE_TYPE_ALIASES values are never alias keys (no chains)", () => {
@@ -263,3 +276,362 @@ describe("schema validation", () => {
}
});
});
+
+describe("sanitizeGraph", () => {
+ it("converts null optional node fields to undefined", () => {
+ const graph = structuredClone(validGraph);
+ (graph.nodes[0] as any).filePath = null;
+ (graph.nodes[0] as any).lineRange = null;
+ (graph.nodes[0] as any).languageNotes = null;
+
+ const result = sanitizeGraph(graph as any);
+ const node = (result as any).nodes[0];
+ expect(node.filePath).toBeUndefined();
+ expect(node.lineRange).toBeUndefined();
+ expect(node.languageNotes).toBeUndefined();
+ });
+
+ it("converts null optional edge fields to undefined", () => {
+ const graph = structuredClone(validGraph);
+ (graph.edges[0] as any).description = null;
+
+ const result = sanitizeGraph(graph as any);
+ const edge = (result as any).edges[0];
+ expect(edge.description).toBeUndefined();
+ });
+
+ it("lowercases enum-like strings on nodes", () => {
+ const graph = structuredClone(validGraph);
+ (graph.nodes[0] as any).type = "FILE";
+ (graph.nodes[0] as any).complexity = "Simple";
+
+ const result = sanitizeGraph(graph as any);
+ const node = (result as any).nodes[0];
+ expect(node.type).toBe("file");
+ expect(node.complexity).toBe("simple");
+ });
+
+ it("lowercases enum-like strings on edges", () => {
+ const graph = structuredClone(validGraph);
+ (graph.edges[0] as any).type = "IMPORTS";
+ (graph.edges[0] as any).direction = "Forward";
+
+ const result = sanitizeGraph(graph as any);
+ const edge = (result as any).edges[0];
+ expect(edge.type).toBe("imports");
+ expect(edge.direction).toBe("forward");
+ });
+
+ it("converts null tour/layers to empty arrays", () => {
+ const graph = structuredClone(validGraph);
+ (graph as any).tour = null;
+ (graph as any).layers = null;
+
+ const result = sanitizeGraph(graph as any);
+ expect((result as any).tour).toEqual([]);
+ expect((result as any).layers).toEqual([]);
+ });
+
+ it("converts null optional tour step fields to undefined", () => {
+ const graph = structuredClone(validGraph);
+ (graph.tour[0] as any).languageLesson = null;
+
+ const result = sanitizeGraph(graph as any);
+ expect((result as any).tour[0].languageLesson).toBeUndefined();
+ });
+
+ it("passes through non-object node/edge items unchanged", () => {
+ const graph = { nodes: [null, "garbage", 42], edges: [null], tour: [], layers: [] };
+ const result = sanitizeGraph(graph as any);
+ expect((result as any).nodes).toEqual([null, "garbage", 42]);
+ expect((result as any).edges).toEqual([null]);
+ });
+});
+
+describe("autoFixGraph", () => {
+ it("defaults missing complexity to moderate with issue", () => {
+ const graph = structuredClone(validGraph);
+ delete (graph.nodes[0] as any).complexity;
+
+ const { data, issues } = autoFixGraph(graph as any);
+ expect((data as any).nodes[0].complexity).toBe("moderate");
+ expect(issues).toContainEqual(
+ expect.objectContaining({ level: "auto-corrected", category: "missing-field", path: "nodes[0].complexity" })
+ );
+ });
+
+ it("maps complexity aliases with issue", () => {
+ const graph = structuredClone(validGraph);
+ (graph.nodes[0] as any).complexity = "low";
+
+ const { data, issues } = autoFixGraph(graph as any);
+ expect((data as any).nodes[0].complexity).toBe("simple");
+ expect(issues.length).toBe(1);
+ expect(issues[0].level).toBe("auto-corrected");
+ });
+
+ it("maps all complexity aliases correctly", () => {
+ const mapping: Record<string, string> = {
+ low: "simple", easy: "simple",
+ medium: "moderate", intermediate: "moderate",
+ high: "complex", hard: "complex", difficult: "complex",
+ };
+ for (const [alias, expected] of Object.entries(mapping)) {
+ const graph = structuredClone(validGraph);
+ (graph.nodes[0] as any).complexity = alias;
+ const { data } = autoFixGraph(graph as any);
+ expect((data as any).nodes[0].complexity).toBe(expected);
+ }
+ });
+
+ it("defaults missing tags to empty array with issue", () => {
+ const graph = structuredClone(validGraph);
+ delete (graph.nodes[0] as any).tags;
+
+ const { data, issues } = autoFixGraph(graph as any);
+ expect((data as any).nodes[0].tags).toEqual([]);
+ expect(issues).toContainEqual(
+ expect.objectContaining({ level: "auto-corrected", category: "missing-field", path: "nodes[0].tags" })
+ );
+ });
+
+ it("defaults missing summary to node name with issue", () => {
+ const graph = structuredClone(validGraph);
+ delete (graph.nodes[0] as any).summary;
+
+ const { data, issues } = autoFixGraph(graph as any);
+ expect((data as any).nodes[0].summary).toBe("index.ts");
+ expect(issues).toContainEqual(
+ expect.objectContaining({ level: "auto-corrected", category: "missing-field", path: "nodes[0].summary" })
+ );
+ });
+
+ it("defaults missing node type to file with issue", () => {
+ const graph = structuredClone(validGraph);
+ delete (graph.nodes[0] as any).type;
+
+ const { data, issues } = autoFixGraph(graph as any);
+ expect((data as any).nodes[0].type).toBe("file");
+ expect(issues).toContainEqual(
+ expect.objectContaining({ level: "auto-corrected", category: "missing-field", path: "nodes[0].type" })
+ );
+ });
+
+ it("defaults missing direction to forward with issue", () => {
+ const graph = structuredClone(validGraph);
+ delete (graph.edges[0] as any).direction;
+
+ const { data, issues } = autoFixGraph(graph as any);
+ expect((data as any).edges[0].direction).toBe("forward");
+ expect(issues).toContainEqual(
+ expect.objectContaining({ level: "auto-corrected", category: "missing-field", path: "edges[0].direction" })
+ );
+ });
+
+ it("maps direction aliases with issue", () => {
+ const mapping: Record<string, string> = {
+ to: "forward", outbound: "forward",
+ from: "backward", inbound: "backward",
+ both: "bidirectional", mutual: "bidirectional",
+ };
+ for (const [alias, expected] of Object.entries(mapping)) {
+ const graph = structuredClone(validGraph);
+ (graph.edges[0] as any).direction = alias;
+ const { data } = autoFixGraph(graph as any);
+ expect((data as any).edges[0].direction).toBe(expected);
+ }
+ });
+
+ it("defaults missing weight to 0.5 with issue", () => {
+ const graph = structuredClone(validGraph);
+ delete (graph.edges[0] as any).weight;
+
+ const { data, issues } = autoFixGraph(graph as any);
+ expect((data as any).edges[0].weight).toBe(0.5);
+ expect(issues).toContainEqual(
+ expect.objectContaining({ level: "auto-corrected", category: "missing-field", path: "edges[0].weight" })
+ );
+ });
+
+ it("coerces string weight to number with issue", () => {
+ const graph = structuredClone(validGraph);
+ (graph.edges[0] as any).weight = "0.8";
+
+ const { data, issues } = autoFixGraph(graph as any);
+ expect((data as any).edges[0].weight).toBe(0.8);
+ expect(issues).toContainEqual(
+ expect.objectContaining({ level: "auto-corrected", category: "type-coercion", path: "edges[0].weight" })
+ );
+ });
+
+ it("clamps out-of-range weight with issue", () => {
+ const graph = structuredClone(validGraph);
+ (graph.edges[0] as any).weight = 1.5;
+
+ const { data, issues } = autoFixGraph(graph as any);
+ expect((data as any).edges[0].weight).toBe(1);
+ expect(issues).toContainEqual(
+ expect.objectContaining({ level: "auto-corrected", category: "out-of-range", path: "edges[0].weight" })
+ );
+ });
+
+ it("defaults missing edge type to depends_on with issue", () => {
+ const graph = structuredClone(validGraph);
+ delete (graph.edges[0] as any).type;
+
+ const { data, issues } = autoFixGraph(graph as any);
+ expect((data as any).edges[0].type).toBe("depends_on");
+ expect(issues).toContainEqual(
+ expect.objectContaining({ level: "auto-corrected", category: "missing-field", path: "edges[0].type" })
+ );
+ });
+
+ it("returns no issues for a valid graph", () => {
+ const { issues } = autoFixGraph(validGraph as any);
+ expect(issues).toEqual([]);
+ });
+
+ it("passes through non-object node/edge items unchanged", () => {
+ const graph = { nodes: [null, "garbage"], edges: [null], tour: [], layers: [] };
+ const { data, issues } = autoFixGraph(graph as any);
+ expect((data as any).nodes).toEqual([null, "garbage"]);
+ expect((data as any).edges).toEqual([null]);
+ expect(issues).toEqual([]);
+ });
+});
+
+describe("permissive validation", () => {
+ it("drops nodes missing id with dropped issue", () => {
+ const graph = structuredClone(validGraph);
+ delete (graph.nodes[0] as any).id;
+ // Add a second valid node so graph isn't fatal
+ graph.nodes.push({
+ id: "node-2", type: "file", name: "other.ts",
+ summary: "Other file", tags: ["util"], complexity: "simple",
+ });
+
+ const result = validateGraph(graph);
+ expect(result.success).toBe(true);
+ expect(result.data!.nodes.length).toBe(1);
+ expect(result.data!.nodes[0].id).toBe("node-2");
+ expect(result.issues).toContainEqual(
+ expect.objectContaining({ level: "dropped", category: "invalid-node" })
+ );
+ });
+
+ it("drops edges referencing non-existent nodes with dropped issue", () => {
+ const graph = structuredClone(validGraph);
+ graph.edges[0].target = "non-existent-node";
+
+ const result = validateGraph(graph);
+ expect(result.success).toBe(true);
+ expect(result.data!.edges.length).toBe(0);
+ expect(result.issues).toContainEqual(
+ expect.objectContaining({ level: "dropped", category: "invalid-reference" })
+ );
+ });
+
+ it("returns fatal when 0 valid nodes remain", () => {
+ const graph = structuredClone(validGraph);
+ delete (graph.nodes[0] as any).id;
+
+ const result = validateGraph(graph);
+ expect(result.success).toBe(false);
+ expect(result.fatal).toContain("No valid nodes");
+ });
+
+ it("returns fatal when project metadata is missing", () => {
+ const graph = structuredClone(validGraph);
+ delete (graph as any).project;
+
+ const result = validateGraph(graph);
+ expect(result.success).toBe(false);
+ expect(result.fatal).toContain("project metadata");
+ });
+
+ it("returns fatal when input is not an object", () => {
+ const result = validateGraph("not an object");
+ expect(result.success).toBe(false);
+ expect(result.fatal).toContain("Invalid input");
+ });
+
+ it("loads graph with mixed good and bad nodes", () => {
+ const graph = structuredClone(validGraph);
+ // Add a good node
+ graph.nodes.push({
+ id: "node-2", type: "function", name: "doThing",
+ summary: "Does a thing", tags: ["util"], complexity: "moderate",
+ });
+ // Add a bad node (missing id AND name -- unrecoverable)
+ (graph.nodes as any[]).push({ type: "file", summary: "broken" });
+
+ const result = validateGraph(graph);
+ expect(result.success).toBe(true);
+ expect(result.data!.nodes.length).toBe(2);
+ expect(result.issues.some((i) => i.level === "dropped")).toBe(true);
+ });
+
+ it("filters dangling nodeIds from layers", () => {
+ const graph = structuredClone(validGraph);
+ graph.layers[0].nodeIds.push("non-existent-node");
+
+ const result = validateGraph(graph);
+ expect(result.success).toBe(true);
+ expect(result.data!.layers[0].nodeIds).toEqual(["node-1"]);
+ });
+
+ it("filters dangling nodeIds from tour steps", () => {
+ const graph = structuredClone(validGraph);
+ graph.tour[0].nodeIds.push("non-existent-node");
+
+ const result = validateGraph(graph);
+ expect(result.success).toBe(true);
+ expect(result.data!.tour[0].nodeIds).toEqual(["node-1"]);
+ });
+
+ it("returns empty issues array for a perfect graph", () => {
+ const result = validateGraph(validGraph);
+ expect(result.success).toBe(true);
+ expect(result.issues).toEqual([]);
+ });
+
+ it("auto-corrects and loads graph that would have failed strict validation", () => {
+ // Graph with many Tier 2 issues: missing complexity, weight as string, null filePath
+ const messy = {
+ version: "1.0.0",
+ project: validGraph.project,
+ nodes: [{
+ id: "n1", type: "FILE", name: "app.ts",
+ filePath: null, summary: "App entry",
+ tags: null, complexity: "HIGH",
+ }],
+ edges: [{
+ source: "n1", target: "n1", type: "CALLS",
+ direction: "TO", weight: "0.9",
+ }],
+ layers: [{ id: "l1", name: "Core", description: "Core", nodeIds: ["n1"] }],
+ tour: [],
+ };
+
+ const result = validateGraph(messy);
+ expect(result.success).toBe(true);
+ expect(result.data!.nodes[0].complexity).toBe("complex");
+ expect(result.data!.nodes[0].tags).toEqual([]);
+ expect(result.data!.edges[0].weight).toBe(0.9);
+ expect(result.data!.edges[0].direction).toBe("forward");
+ expect(result.issues.length).toBeGreaterThan(0);
+ expect(result.issues.every((i) => i.level === "auto-corrected")).toBe(true);
+ });
+
+ it("handles non-parseable string weight by defaulting to 0.5", () => {
+ const graph = structuredClone(validGraph);
+ (graph.edges[0] as any).weight = "not_a_number";
+
+ const result = validateGraph(graph);
+ expect(result.success).toBe(true);
+ expect(result.data!.edges[0].weight).toBe(0.5);
+ expect(result.issues).toContainEqual(
+ expect.objectContaining({ level: "auto-corrected", category: "type-coercion" })
+ );
+ });
+});
diff --git a/understand-anything-plugin/packages/core/src/index.ts b/understand-anything-plugin/packages/core/src/index.ts
index 64387209..1dfcf66f 100644
--- a/understand-anything-plugin/packages/core/src/index.ts
+++ b/understand-anything-plugin/packages/core/src/index.ts
@@ -1,6 +1,15 @@
export * from "./types.js";
export * from "./persistence/index.js";
-export { KnowledgeGraphSchema, validateGraph, type ValidationResult } from "./schema.js";
+export {
+ KnowledgeGraphSchema,
+ validateGraph,
+ sanitizeGraph,
+ autoFixGraph,
+ COMPLEXITY_ALIASES,
+ DIRECTION_ALIASES,
+ type ValidationResult,
+ type GraphIssue,
+} from "./schema.js";
export { TreeSitterPlugin } from "./plugins/tree-sitter-plugin.js";
export { GraphBuilder } from "./analyzer/graph-builder.js";
export {
diff --git a/understand-anything-plugin/packages/core/src/persistence/index.ts b/understand-anything-plugin/packages/core/src/persistence/index.ts
index 36ba5cf0..6c8fc673 100644
--- a/understand-anything-plugin/packages/core/src/persistence/index.ts
+++ b/understand-anything-plugin/packages/core/src/persistence/index.ts
@@ -33,7 +33,7 @@ export function loadGraph(
const result = validateGraph(data);
if (!result.success) {
throw new Error(
- `Invalid knowledge graph: ${result.errors!.join("; ")}`,
+ `Invalid knowledge graph: ${result.fatal ?? "unknown error"}`,
);
}
return result.data as KnowledgeGraph;
diff --git a/understand-anything-plugin/packages/core/src/persistence/persistence.test.ts b/understand-anything-plugin/packages/core/src/persistence/persistence.test.ts
index ce159d4b..97681bce 100644
--- a/understand-anything-plugin/packages/core/src/persistence/persistence.test.ts
+++ b/understand-anything-plugin/packages/core/src/persistence/persistence.test.ts
@@ -41,7 +41,7 @@ describe("persistence", () => {
edges: [
{
source: "node-1",
- target: "node-2",
+ target: "node-1",
type: "imports",
direction: "forward",
weight: 0.8,
diff --git a/understand-anything-plugin/packages/core/src/schema.ts b/understand-anything-plugin/packages/core/src/schema.ts
index c42af9ea..68d3507a 100644
--- a/understand-anything-plugin/packages/core/src/schema.ts
+++ b/understand-anything-plugin/packages/core/src/schema.ts
@@ -38,6 +38,232 @@ export const EDGE_TYPE_ALIASES: Record<string, string> = {
subscribe: "subscribes",
};
+// Aliases for complexity values LLMs commonly generate
+export const COMPLEXITY_ALIASES: Record<string, string> = {
+ low: "simple",
+ easy: "simple",
+ medium: "moderate",
+ intermediate: "moderate",
+ high: "complex",
+ hard: "complex",
+ difficult: "complex",
+};
+
+// Aliases for direction values LLMs commonly generate
+export const DIRECTION_ALIASES: Record<string, string> = {
+ to: "forward",
+ outbound: "forward",
+ from: "backward",
+ inbound: "backward",
+ both: "bidirectional",
+ mutual: "bidirectional",
+};
+
+export function sanitizeGraph(data: Record<string, unknown>): Record<string, unknown> {
+ const result = { ...data };
+
+ // Null → empty array for top-level collections
+ if (data.tour === null || data.tour === undefined) result.tour = [];
+ if (data.layers === null || data.layers === undefined) result.layers = [];
+
+ // Sanitize nodes
+ if (Array.isArray(data.nodes)) {
+ result.nodes = (data.nodes as Record<string, unknown>[]).map((node) => {
+ if (typeof node !== "object" || node === null) return node;
+ const n = { ...node };
+ // Null → undefined for optional fields
+ if (n.filePath === null) delete n.filePath;
+ if (n.lineRange === null) delete n.lineRange;
+ if (n.languageNotes === null) delete n.languageNotes;
+ // Lowercase enum-like strings
+ if (typeof n.type === "string") n.type = n.type.toLowerCase();
+ if (typeof n.complexity === "string") n.complexity = n.complexity.toLowerCase();
+ return n;
+ });
+ }
+
+ // Sanitize edges
+ if (Array.isArray(data.edges)) {
+ result.edges = (data.edges as Record<string, unknown>[]).map((edge) => {
+ if (typeof edge !== "object" || edge === null) return edge;
+ const e = { ...edge };
+ if (e.description === null) delete e.description;
+ if (typeof e.type === "string") e.type = e.type.toLowerCase();
+ if (typeof e.direction === "string") e.direction = e.direction.toLowerCase();
+ return e;
+ });
+ }
+
+ // Sanitize tour steps
+ if (Array.isArray(result.tour)) {
+ result.tour = (result.tour as Record<string, unknown>[]).map((step) => {
+ if (typeof step !== "object" || step === null) return step;
+ const s = { ...step };
+ if (s.languageLesson === null) delete s.languageLesson;
+ return s;
+ });
+ }
+
+ return result;
+}
+
+export function autoFixGraph(data: Record<string, unknown>): {
+ data: Record<string, unknown>;
+ issues: GraphIssue[];
+} {
+ const issues: GraphIssue[] = [];
+ const result = { ...data };
+
+ if (Array.isArray(data.nodes)) {
+ result.nodes = (data.nodes as Record<string, unknown>[]).map((node, i) => {
+ if (typeof node !== "object" || node === null) return node;
+ const n = { ...node };
+ const name = (n.name as string) || (n.id as string) || `index ${i}`;
+
+ // Missing or empty type
+ if (!n.type || typeof n.type !== "string") {
+ n.type = "file";
+ issues.push({
+ level: "auto-corrected",
+ category: "missing-field",
+ message: `nodes[${i}] ("${name}"): missing "type" — defaulted to "file"`,
+ path: `nodes[${i}].type`,
+ });
+ }
+
+ // Missing or empty complexity
+ if (!n.complexity || n.complexity === "") {
+ n.complexity = "moderate";
+ issues.push({
+ level: "auto-corrected",
+ category: "missing-field",
+ message: `nodes[${i}] ("${name}"): missing "complexity" — defaulted to "moderate"`,
+ path: `nodes[${i}].complexity`,
+ });
+ } else if (typeof n.complexity === "string" && n.complexity in COMPLEXITY_ALIASES) {
+ const original = n.complexity;
+ n.complexity = COMPLEXITY_ALIASES[n.complexity];
+ issues.push({
+ level: "auto-corrected",
+ category: "alias",
+ message: `nodes[${i}] ("${name}"): complexity "${original}" — mapped to "${n.complexity}"`,
+ path: `nodes[${i}].complexity`,
+ });
+ }
+
+ // Missing tags
+ if (!Array.isArray(n.tags)) {
+ n.tags = [];
+ issues.push({
+ level: "auto-corrected",
+ category: "missing-field",
+ message: `nodes[${i}] ("${name}"): missing "tags" — defaulted to []`,
+ path: `nodes[${i}].tags`,
+ });
+ }
+
+ // Missing summary
+ if (!n.summary || typeof n.summary !== "string") {
+ n.summary = (n.name as string) || "No summary";
+ issues.push({
+ level: "auto-corrected",
+ category: "missing-field",
+ message: `nodes[${i}] ("${name}"): missing "summary" — defaulted to name`,
+ path: `nodes[${i}].summary`,
+ });
+ }
+
+ return n;
+ });
+ }
+
+ if (Array.isArray(data.edges)) {
+ result.edges = (data.edges as Record<string, unknown>[]).map((edge, i) => {
+ if (typeof edge !== "object" || edge === null) return edge;
+ const e = { ...edge };
+
+ // Missing type
+ if (!e.type || typeof e.type !== "string") {
+ e.type = "depends_on";
+ issues.push({
+ level: "auto-corrected",
+ category: "missing-field",
+ message: `edges[${i}]: missing "type" — defaulted to "depends_on"`,
+ path: `edges[${i}].type`,
+ });
+ }
+
+ // Missing direction
+ if (!e.direction || typeof e.direction !== "string") {
+ e.direction = "forward";
+ issues.push({
+ level: "auto-corrected",
+ category: "missing-field",
+ message: `edges[${i}]: missing "direction" — defaulted to "forward"`,
+ path: `edges[${i}].direction`,
+ });
+ } else if (e.direction in DIRECTION_ALIASES) {
+ const original = e.direction;
+ e.direction = DIRECTION_ALIASES[e.direction as string];
+ issues.push({
+ level: "auto-corrected",
+ category: "alias",
+ message: `edges[${i}]: direction "${original}" — mapped to "${e.direction}"`,
+ path: `edges[${i}].direction`,
+ });
+ }
+
+ // Missing weight
+ if (e.weight === undefined || e.weight === null) {
+ e.weight = 0.5;
+ issues.push({
+ level: "auto-corrected",
+ category: "missing-field",
+ message: `edges[${i}]: missing "weight" — defaulted to 0.5`,
+ path: `edges[${i}].weight`,
+ });
+ } else if (typeof e.weight === "string") {
+ const parsed = parseFloat(e.weight as string);
+ if (!isNaN(parsed)) {
+ const original = e.weight;
+ e.weight = parsed;
+ issues.push({
+ level: "auto-corrected",
+ category: "type-coercion",
+ message: `edges[${i}]: weight was string "${original}" — coerced to number`,
+ path: `edges[${i}].weight`,
+ });
+ } else {
+ const original = e.weight;
+ e.weight = 0.5;
+ issues.push({
+ level: "auto-corrected",
+ category: "type-coercion",
+ message: `edges[${i}]: weight "${original}" is not a valid number — defaulted to 0.5`,
+ path: `edges[${i}].weight`,
+ });
+ }
+ }
+
+ // Clamp weight to [0, 1]
+ if (typeof e.weight === "number" && (e.weight < 0 || e.weight > 1)) {
+ const original = e.weight;
+ e.weight = Math.max(0, Math.min(1, e.weight));
+ issues.push({
+ level: "auto-corrected",
+ category: "out-of-range",
+ message: `edges[${i}]: weight ${original} clamped to ${e.weight}`,
+ path: `edges[${i}].weight`,
+ });
+ }
+
+ return e;
+ });
+ }
+
+ return { data: result, issues };
+}
+
export const GraphNodeSchema = z.object({
id: z.string(),
type: z.enum(["file", "function", "class", "module", "concept"]),
@@ -92,10 +318,18 @@ export const KnowledgeGraphSchema = z.object({
tour: z.array(TourStepSchema),
});
+export interface GraphIssue {
+ level: "auto-corrected" | "dropped" | "fatal";
+ category: string;
+ message: string;
+ path?: string;
+}
+
export interface ValidationResult {
success: boolean;
data?: z.infer<typeof KnowledgeGraphSchema>;
- errors?: string[];
+ issues: GraphIssue[];
+ fatal?: string;
}
export function normalizeGraph(data: unknown): unknown {
@@ -136,16 +370,149 @@ export function normalizeGraph(data: unknown): unknown {
}
export function validateGraph(data: unknown): ValidationResult {
- const result = KnowledgeGraphSchema.safeParse(normalizeGraph(data));
+ // Tier 4: Fatal — not even an object
+ if (typeof data !== "object" || data === null) {
+ return { success: false, issues: [], fatal: "Invalid input: not an object" };
+ }
+
+ const raw = data as Record<string, unknown>;
+
+ // Tier 1: Sanitize
+ const sanitized = sanitizeGraph(raw);
+
+ // Existing: Normalize type aliases
+ const normalized = normalizeGraph(sanitized) as Record<string, unknown>;
- if (result.success) {
- return { success: true, data: result.data };
+ // Tier 2: Auto-fix defaults and coercion
+ const { data: fixed, issues } = autoFixGraph(normalized);
+
+ // Tier 4: Fatal — missing project metadata
+ const projectResult = ProjectMetaSchema.safeParse(fixed.project);
+ if (!projectResult.success) {
+ return {
+ success: false,
+ issues,
+ fatal: "Missing or invalid project metadata",
+ };
+ }
+
+ // Tier 3: Validate nodes individually, drop broken
+ const validNodes: z.infer<typeof GraphNodeSchema>[] = [];
+ if (Array.isArray(fixed.nodes)) {
+ for (let i = 0; i < fixed.nodes.length; i++) {
+ const node = fixed.nodes[i] as Record<string, unknown>;
+ const result = GraphNodeSchema.safeParse(node);
+ if (result.success) {
+ validNodes.push(result.data);
+ } else {
+ const name = node?.name || node?.id || `index ${i}`;
+ issues.push({
+ level: "dropped",
+ category: "invalid-node",
+ message: `nodes[${i}] ("${name}"): ${result.error.issues[0]?.message ?? "validation failed"} — removed`,
+ path: `nodes[${i}]`,
+ });
+ }
+ }
+ }
+
+ // Tier 4: Fatal — no valid nodes
+ if (validNodes.length === 0) {
+ return {
+ success: false,
+ issues,
+ fatal: "No valid nodes found in knowledge graph",
+ };
+ }
+
+ // Tier 3: Validate edges + referential integrity
+ const nodeIds = new Set(validNodes.map((n) => n.id));
+ const validEdges: z.infer<typeof GraphEdgeSchema>[] = [];
+ if (Array.isArray(fixed.edges)) {
+ for (let i = 0; i < fixed.edges.length; i++) {
+ const edge = fixed.edges[i] as Record<string, unknown>;
+ const result = GraphEdgeSchema.safeParse(edge);
+ if (!result.success) {
+ issues.push({
+ level: "dropped",
+ category: "invalid-edge",
+ message: `edges[${i}]: ${result.error.issues[0]?.message ?? "validation failed"} — removed`,
+ path: `edges[${i}]`,
+ });
+ continue;
+ }
+ if (!nodeIds.has(result.data.source)) {
+ issues.push({
+ level: "dropped",
+ category: "invalid-reference",
+ message: `edges[${i}]: source "${result.data.source}" does not exist in nodes — removed`,
+ path: `edges[${i}].source`,
+ });
+ continue;
+ }
+ if (!nodeIds.has(result.data.target)) {
+ issues.push({
+ level: "dropped",
+ category: "invalid-reference",
+ message: `edges[${i}]: target "${result.data.target}" does not exist in nodes — removed`,
+ path: `edges[${i}].target`,
+ });
+ continue;
+ }
+ validEdges.push(result.data);
+ }
+ }
+
+ // Validate layers (drop broken, filter dangling nodeIds)
+ const validLayers: z.infer<typeof LayerSchema>[] = [];
+ if (Array.isArray(fixed.layers)) {
+ for (let i = 0; i < (fixed.layers as unknown[]).length; i++) {
+ const result = LayerSchema.safeParse((fixed.layers as unknown[])[i]);
+ if (result.success) {
+ validLayers.push({
+ ...result.data,
+ nodeIds: result.data.nodeIds.filter((id) => nodeIds.has(id)),
+ });
+ } else {
+ issues.push({
+ level: "dropped",
+ category: "invalid-layer",
+ message: `layers[${i}]: ${result.error.issues[0]?.message ?? "validation failed"} — removed`,
+ path: `layers[${i}]`,
+ });
+ }
+ }
+ }
+
+ // Validate tour steps (drop broken, filter dangling nodeIds)
+ const validTour: z.infer<typeof TourStepSchema>[] = [];
+ if (Array.isArray(fixed.tour)) {
+ for (let i = 0; i < (fixed.tour as unknown[]).length; i++) {
+ const result = TourStepSchema.safeParse((fixed.tour as unknown[])[i]);
+ if (result.success) {
+ validTour.push({
+ ...result.data,
+ nodeIds: result.data.nodeIds.filter((id) => nodeIds.has(id)),
+ });
+ } else {
+ issues.push({
+ level: "dropped",
+ category: "invalid-tour-step",
+ message: `tour[${i}]: ${result.error.issues[0]?.message ?? "validation failed"} — removed`,
+ path: `tour[${i}]`,
+ });
+ }
+ }
}
- const errors = result.error.issues.map((issue) => {
- const path = issue.path.join(".");
- return path ? `${path}: ${issue.message}` : issue.message;
- });
+ const graph = {
+ version: typeof fixed.version === "string" ? fixed.version : "1.0.0",
+ project: projectResult.data,
+ nodes: validNodes,
+ edges: validEdges,
+ layers: validLayers,
+ tour: validTour,
+ };
- return { success: false, errors };
+ return { success: true, data: graph, issues };
}