Egonex Graph Schema Validation: How It Prevents Malformed Knowledge Graphs

Egonex graph schema validation employs a four-tier pipeline—sanitization, normalization, auto-fixing, and strict Zod validation—to transform raw JSON inputs into type-safe knowledge graphs, automatically healing minor data issues while aborting on fatal structural errors.

Egonex graph schema validation in the Understand-Anything repository provides a robust defense against malformed knowledge graphs by enforcing type safety and referential integrity at every stage of ingestion. Located in packages/core/src/schema.ts, the validation system processes raw LLM outputs through a multi-tiered pipeline that sanitizes inputs, resolves aliases, applies intelligent defaults, and executes strict schema checks. This architecture ensures that only well-structured, semantically valid graphs reach the visualization dashboard or downstream analytics.

The Four-Tier Validation Pipeline

The validation architecture consists of four sequential phases, each targeting specific classes of data corruption.

Phase 1: Sanitization

The sanitizeGraph function (lines 48-93 in packages/core/src/schema.ts) performs initial cleaning of raw inputs. It converts null optional fields to undefined, forces enum-like strings to lowercase, and ensures that tour and layers collections are arrays. This phase eliminates obvious structural defects that would otherwise break strict type checks during later validation stages.

Phase 2: Normalization

Before structural validation begins, normalizeGraph (lines 62-94) resolves LLM-generated aliases into canonical values. Using NODE_TYPE_ALIASES and EDGE_TYPE_ALIASES maps, it transforms values like "func" into "function" and ensures the schema receives only standardized enum values. This normalization guarantees that subsequent validation steps operate on consistent, predictable data.

Phase 3: Auto-Fixing (Tier 2)

The autoFixGraph function (lines 96-250) implements intelligent recovery by supplying sensible defaults and coercing types. It adds missing type, complexity, tags, summary, direction, and weight fields, maps alias values (e.g., "low" → "simple"), converts string weights to numbers, and clamps weights to the [0, 1] range. Every modification generates a GraphIssue with level: "auto-corrected", creating an audit trail of changes.

Phase 4: Strict Validation (Tier 3-4)

The final validateGraph function (lines 494-662) executes rigorous Zod schema validation. It performs fatal checks for non-object inputs, missing project metadata, or invalid top-level collections. Valid nodes must conform to GraphNodeSchema; invalid nodes are dropped with level: "dropped" issues. Edges must match GraphEdgeSchema and reference existing node IDs—dangling references are removed. If no valid nodes remain after filtering, the pipeline aborts with a fatal error.

Defense Mechanisms in Egonex Graph Schema Validation

Egonex graph schema validation prevents corrupted knowledge graphs through six specific defense mechanisms:

  • Early sanitization removes null fields that would break strict type checks, converting them to undefined before validation begins.

  • Alias normalization ensures the schema only receives canonical enum values, preventing "unknown type" failures caused by LLM-generated synonyms like "func" or "TO".

  • Auto-fix defaults heal missing data by applying standard values (e.g., type: "file", direction: "forward", weight: 0.5), with every change logged as a GraphIssue for auditability.

  • Strict Zod validation drops any element violating the schema after auto-fixes, preventing illegal values from persisting to the dashboard.

  • Referential integrity checks verify that edges connect only existing node IDs, eliminating dangling references that would corrupt graph traversal.

  • Fatal aborts stop the entire pipeline when recovery is impossible, such as when no valid nodes remain or top-level collections are not arrays.

Implementation Example

The following example demonstrates how the validator processes a malformed LLM output:

import { validateGraph } from "@understand-anything/core";

/* Raw graph with type aliases, null values, and invalid weight */
const raw = {
  version: "1.0.0",
  project: { /* … */ },
  nodes: [{ id: "n1", type: "func", name: "calc", tags: null }],
  edges: [{ source: "n1", target: "n1", type: "calls", direction: "TO", weight: "1.2" }],
};

/* Run the validator */
const result = validateGraph(raw);

if (result.success) {
  console.log("Clean graph:", result.data);
  console.log("Auto-corrected issues:", result.issues);
} else {
  console.error("Fatal validation error:", result.fatal);
}

The validator automatically performs the following corrections:

  • Converts type: "func" to "function" via alias normalization
  • Replaces tags: null with an empty array
  • Transforms direction: "TO" to "forward"
  • Coerces weight: "1.2" to number 1.0 (clamped to valid range)

Summary

Egonex graph schema validation in the Understand-Anything repository provides comprehensive protection against malformed knowledge graphs through:

  • Four-tier processing: Sanitization, normalization, auto-fixing, and strict Zod validation
  • Intelligent recovery: Automatic application of defaults for missing fields with full audit logging via GraphIssue objects
  • Type safety: Enforcement of GraphNodeSchema and GraphEdgeSchema constraints
  • Referential integrity: Validation that edges connect only existing nodes
  • Graceful degradation: Dropping invalid individual elements while aborting only on unrecoverable structural failures

Frequently Asked Questions

What happens to individual nodes that fail validation?

Nodes that violate GraphNodeSchema after auto-fixing are dropped from the graph rather than causing complete validation failure. The system records a GraphIssue with level: "dropped" and continues processing remaining valid nodes, ensuring partial data recovery instead of total rejection.

How does Egonex handle LLM-generated type aliases?

The normalizeGraph function resolves aliases using NODE_TYPE_ALIASES and EDGE_TYPE_ALIASES maps before strict validation occurs. For example, "func" becomes "function" and "TO" becomes "forward", ensuring the Zod schema receives only canonical values and preventing validation failures from synonymous terminology.

What constitutes a fatal validation error in Egonex?

Fatal errors occur when the graph is structurally unrecoverable. Specific conditions include: non-object input types, missing project metadata, top-level collections that are not arrays, or complete absence of valid nodes after filtering. These trigger immediate pipeline abortion with a fatal error message.

Can the validation pipeline recover graphs with missing metadata?

Yes, the autoFixGraph function supplies sensible defaults for missing optional fields. It adds missing type, complexity, tags, summary, direction, and weight values, and coerces incorrect types. However, missing required project metadata constitutes a fatal error that cannot be auto-corrected.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →