# Egonex-AI Knowledge Graph JSON Schema: Complete Structure and Validation Guide

> Explore the Egonex-AI knowledge graph JSON schema structure. This guide details complete schema validation and the required KnowledgeGraphSchema object for your projects.

- Repository: [Egonex/Understand-Anything](https://github.com/Egonex-AI/Understand-Anything)
- Tags: api-reference
- Published: 2026-06-22

---

**The Egonex-AI knowledge graph validates against a Zod schema defined in [`packages/core/src/schema.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/packages/core/src/schema.ts), requiring a top-level `KnowledgeGraphSchema` object containing version metadata, project details, nodes, edges, layers, and tour steps.**

The Egonex-AI/Understand-Anything repository uses a strictly typed JSON format to represent codebases and domain knowledge as traversable graphs. This schema ensures consistency across ingestion pipelines, LLM outputs, and visualization layers by enforcing structure through runtime validation.

## Top-Level Structure (KnowledgeGraphSchema)

Every knowledge graph must conform to the `KnowledgeGraphSchema` defined at lines 21-29 of [`packages/core/src/schema.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/packages/core/src/schema.ts). The root object requires six primary properties:

- **`version`** (string, required): Graph format version identifier.
- **`kind`** (optional): Discriminates between `"codebase"` (software analysis) and `"knowledge"` (generic domain graphs).
- **`project`** (required): Metadata container following `ProjectMetaSchema`.
- **`nodes`** (required): Array of `GraphNodeSchema` objects representing entities.
- **`edges`** (required): Array of `GraphEdgeSchema` objects defining relationships.
- **`layers`** (required): Array of `LayerSchema` objects for logical node grouping.
- **`tour`** (required): Array of `TourStepSchema` objects for UI-guided navigation.

## Node Schema (GraphNodeSchema)

Individual entities are defined by the `GraphNodeSchema` (lines 68-86), which supports 20 distinct node types spanning code and knowledge domains.

**Required fields:**
- **`id`**: Unique string identifier.
- **`type`**: Enum value from `{"file", "function", "class", "module", "concept", "config", "document", "service", "table", "endpoint", "pipeline", "schema", "resource", "domain", "flow", "step", "article", "entity", "topic", "claim", "source"}`.
- **`name`**: Human-readable label.
- **`summary`**: Descriptive text explaining the node's purpose.
- **`tags`**: Array of classification strings.
- **`complexity`**: Enum value `"simple"`, `"moderate"`, or `"complex"` (defaults to `"moderate"`).

**Optional fields:**
- **`filePath`**: Source file location.
- **`lineRange`**: Tuple `[number, number]` indicating start and end lines.
- **`languageNotes`**: Implementation-specific details.
- **`domainMeta`**: Business domain metadata including `entities`, `businessRules`, and `crossDomainInteractions`.
- **`knowledgeMeta`**: Wikilink-style references with `wikilinks`, `backlinks`, `category`, and `content` fields.

## Edge Schema (GraphEdgeSchema)

Relationships connect nodes through directed edges defined in lines 88-94.

**Core properties:**
- **`source`**: ID of the origin node.
- **`target`**: ID of the destination node.
- **`type`**: String literal from `EdgeTypeSchema` covering 35 relationship types including `"imports"`, `"calls"`, `"depends_on"`, `"cites"`, and `"authored_by"`.
- **`direction`**: Enum `"forward"`, `"backward"`, or `"bidirectional"`.
- **`weight`**: Numeric confidence score between 0 and 1.
- **`description`**: Optional human-readable explanation of the relationship.

## Supporting Schemas

**ProjectMetaSchema** (lines 112-119) captures analysis context:
- `name`, `languages` (array), `frameworks` (array), `description`
- `analyzedAt` (ISO timestamp), `gitCommitHash`

**LayerSchema** (lines 96-110) organizes nodes into logical groups:
- `id`, `name`, `description`, `nodeIds` (array of node references)

**TourStepSchema** enables interactive exploration:
- `order` (number), `title`, `description`, `nodeIds`, `languageLesson` (optional)

## Validation Pipeline

The [`schema.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/schema.ts) file implements a four-stage validation pipeline to handle LLM-generated or manually constructed graphs:

1. **`sanitizeGraph`**: Normalizes `null` values to empty arrays, lowercases enum strings, and strips optional null fields.

2. **`normalizeGraph`**: Maps common aliases to canonical types using `NODE_TYPE_ALIASES` and `EDGE_TYPE_ALIASES` tables.

3. **`autoFixGraph`**: Injects defaults for missing required fields (`type: "file"`, `complexity: "moderate"`, `weight: 0.5`).

4. **`validateGraph`**: Executes Zod schema validation, returning a `ValidationResult` object containing `success` boolean, cleaned `data`, and `issues` array.

## Implementation Examples

### Minimal Valid Graph

```json
{
  "version": "1.0.0",
  "project": {
    "name": "my-app",
    "languages": ["typescript"],
    "frameworks": ["react"],
    "description": "Demo project",
    "analyzedAt": "2024-10-01T12:00:00Z",
    "gitCommitHash": "abc123"
  },
  "nodes": [
    {
      "id": "n1",
      "type": "file",
      "name": "src/index.ts",
      "summary": "Entry point",
      "tags": [],
      "complexity": "simple"
    },
    {
      "id": "n2",
      "type": "function",
      "name": "main",
      "summary": "Main function",
      "tags": [],
      "complexity": "moderate"
    }
  ],
  "edges": [
    {
      "source": "n1",
      "target": "n2",
      "type": "exports",
      "direction": "forward",
      "weight": 0.8
    }
  ],
  "layers": [],
  "tour": []
}

```

### Programmatic Validation

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

const raw = JSON.parse(fs.readFileSync("graph.json", "utf-8"));
const result = validateGraph(raw);

if (result.success) {
  console.log("Graph is valid!", result.data);
} else {
  console.error("Invalid graph:", result.issues);
}

```

## Summary

- The **Egonex-AI knowledge graph JSON schema** is defined in [`packages/core/src/schema.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/packages/core/src/schema.ts) using Zod for runtime type safety.
- **Top-level structure** requires `version`, `project`, `nodes`, `edges`, `layers`, and `tour` properties.
- **Nodes** support 20 types including code entities (`file`, `function`, `class`) and knowledge entities (`concept`, `topic`, `claim`).
- **Edges** define 35 relationship types with directional indicators and confidence weights.
- The **validation pipeline** automatically sanitizes, normalizes, and repairs graphs before strict schema validation.

## Frequently Asked Questions

### What file contains the schema definition for the Egonex-AI knowledge graph?

The complete schema definition resides in [`packages/core/src/schema.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/packages/core/src/schema.ts) within the Egonex-AI/Understand-Anything repository. This file contains the Zod schemas, alias mapping tables, and the four-stage validation pipeline (`sanitizeGraph`, `normalizeGraph`, `autoFixGraph`, `validateGraph`).

### What are the valid node types in the GraphNodeSchema?

The `type` field accepts 20 enum values: `"file"`, `"function"`, `"class"`, `"module"`, `"concept"`, `"config"`, `"document"`, `"service"`, `"table"`, `"endpoint"`, `"pipeline"`, `"schema"`, `"resource"`, `"domain"`, `"flow"`, `"step"`, `"article"`, `"entity"`, `"topic"`, `"claim"`, and `"source"`. These cover both software artifacts and domain knowledge entities.

### How does the validation pipeline handle malformed JSON?

The pipeline first runs `sanitizeGraph` to clean null values and normalize casing, then `normalizeGraph` to map aliases to canonical types, followed by `autoFixGraph` to inject defaults for missing fields. Finally, `validateGraph` performs strict Zod validation and returns a `ValidationResult` with detailed issue reporting for any remaining violations.

### Can I validate a graph programmatically instead of using the CLI?

Yes. Import `validateGraph` from `@understand-anything/core` and pass your parsed JSON object. The function returns an object with `success` (boolean), `data` (the cleaned graph), and `issues` (array of validation errors). Reference the test suite in [`packages/core/src/__tests__/schema.test.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/packages/core/src/__tests__/schema.test.ts) for additional usage examples.