# JSON Schema for knowledge-graph.json: Complete Reference Guide

> Explore the JSON schema for knowledge-graph.json with this comprehensive reference guide. Understand requirements like version, project, nodes, edges, and layers for data integrity.

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

---

**The [`knowledge-graph.json`](https://github.com/Egonex-AI/Understand-Anything/blob/main/knowledge-graph.json) file conforms to the `KnowledgeGraphSchema` defined in the Understand Anything core package, requiring `version`, `project`, `nodes`, `edges`, `layers`, and optional `tour` fields, with automatic sanitization and Zod validation ensuring data integrity.**

The [`knowledge-graph.json`](https://github.com/Egonex-AI/Understand-Anything/blob/main/knowledge-graph.json) file serves as the central artifact in the Egonex-AI/Understand-Anything repository, representing a complete, validated codebase or knowledge graph. This JSON structure standardizes how projects store metadata, node relationships, and navigational layers for analysis and visualization.

## Top-Level Schema Structure

The root object of every [`knowledge-graph.json`](https://github.com/Egonex-AI/Understand-Anything/blob/main/knowledge-graph.json) must contain six primary fields as defined in [`packages/core/src/schema.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/packages/core/src/schema.ts):

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `version` | `string` | Yes | Semantic version of the graph format (e.g., "1.0.0"). |
| `kind` | `"codebase"` \| `"knowledge"` | No | Indicates whether the graph describes source code or pure knowledge. |
| `project` | `ProjectMetaSchema` | Yes | Metadata about the analyzed project including timestamps and git info. |
| `nodes` | `GraphNodeSchema[]` | Yes | Array of graph entities (files, functions, classes, modules). |
| `edges` | `GraphEdgeSchema[]` | Yes | Array of directed relationships linking nodes. |
| `layers` | `LayerSchema[]` | Yes | Logical groupings of nodes for UI organization. |
| `tour` | `TourStepSchema[]` | Yes | Optional guided-tour steps (may be empty array). |

## Sub-Schema Definitions

### Project Metadata (ProjectMetaSchema)

As implemented in [`packages/core/src/schema.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/packages/core/src/schema.ts) at lines 421-429, the `project` object requires specific metadata fields:

- **`name`**: Project identifier string.
- **`languages`**: Array of programming languages detected.
- **`frameworks`**: Array of frameworks utilized.
- **`description`**: Human-readable project summary.
- **`analyzedAt`**: ISO timestamp of analysis.
- **`gitCommitHash`**: Current git commit reference.

### Graph Nodes (GraphNodeSchema)

According to lines 368-386 of the schema definition, each node in the `nodes` array must include:

**Required fields:**
- **`id`**: Unique identifier string.
- **`type`**: Node classification (e.g., "file", "function", "class").
- **`name`**: Display name.
- **`summary`**: Brief description.
- **`tags`**: Array of string labels.
- **`complexity`**: Complexity level ("simple", "moderate", or "complex").

**Optional fields:**
- `filePath`: Source file location.
- `lineRange`: Start and end line numbers.
- `languageNotes`: Language-specific metadata.
- `domainMeta`: Business domain information.
- `knowledgeMeta`: Knowledge-base specific attributes.

### Graph Edges and Types (GraphEdgeSchema)

The `edges` array connects nodes through directed relationships as defined at lines 88-114:

**Required fields:**
- **`source`**: Origin node ID.
- **`target`**: Destination node ID.
- **`type`**: Relationship classification validated against `EdgeTypeSchema`.
- **`direction`**: Flow direction indicator.
- **`weight`**: Numeric strength value (0-1 range).

**Optional fields:**
- `description`: Human-readable relationship context.

The `EdgeTypeSchema` enumerates **35 distinct relationship types** including imports, calls, contains, and semantic associations.

### Layers and Tours

**LayerSchema** (lines 397-401) organizes nodes into logical groups:
- `id`, `name`, `description`: Identification fields.
- `nodeIds`: Array of node IDs belonging to the layer.

**TourStepSchema** (lines 404-410) supports interactive UI guidance:
- `order`, `title`, `description`: Step sequencing and content.
- `nodeIds`: Relevant nodes to highlight.
- `languageLesson`: Optional educational content.

## Validation Pipeline

The Understand Anything core applies a four-stage validation pipeline before accepting a [`knowledge-graph.json`](https://github.com/Egonex-AI/Understand-Anything/blob/main/knowledge-graph.json) file, implemented in [`packages/core/src/schema.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/packages/core/src/schema.ts) between lines 447-509 and 990-1045.

**Stage 1: Sanitization**
The `sanitizeGraph` function converts null values to safe defaults and ensures all arrays exist.

**Stage 2: Normalization**
The `normalizeGraph` function standardizes type aliases—for example, converting `"func"` to `"function"` and normalizing edge type nomenclature.

**Stage 3: Auto-Fixing**
The `autoFixGraph` function applies intelligent defaults:
- Missing `type` fields default to `"file"`.
- Missing `complexity` values default to `"moderate"`.
- Edge `weight` values are clamped to the range `[0, 1]`.

**Stage 4: Zod Validation**
The `validateGraph` function validates the sanitized object against `KnowledgeGraphSchema`, returning a `ValidationResult` object containing the parsed data or detailed issue reports for auto-corrected, dropped, or fatal errors.

## Practical Implementation Examples

### Minimal Valid knowledge-graph.json

```json
{
  "version": "1.0.0",
  "project": {
    "name": "my-project",
    "languages": ["typescript"],
    "frameworks": ["react"],
    "description": "Example project",
    "analyzedAt": "2024-10-01T12:00:00Z",
    "gitCommitHash": "a1b2c3d"
  },
  "nodes": [
    {
      "id": "node-1",
      "type": "file",
      "name": "src/index.ts",
      "summary": "Entry point",
      "tags": [],
      "complexity": "simple"
    }
  ],
  "edges": [],
  "layers": [],
  "tour": []
}

```

### Validating with TypeScript

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

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

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

```

### Direct Zod Schema Usage

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

const parseResult = KnowledgeGraphSchema.safeParse(raw);
if (parseResult.success) {
  // raw conforms exactly to the JSON schema
  const validatedGraph = parseResult.data;
} else {
  console.error(parseResult.error);
}

```

## Key Source Files

- **[`packages/core/src/schema.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/packages/core/src/schema.ts)**: Contains the complete Zod schema definitions (`KnowledgeGraphSchema`, `GraphNodeSchema`, `GraphEdgeSchema`), sanitization logic, and validation functions.
- **[`packages/core/src/types.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/packages/core/src/types.ts)**: TypeScript interfaces mirroring the JSON schema for type-safe development.
- **[`packages/core/src/persistence/index.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/packages/core/src/persistence/index.ts)**: Handles reading and writing [`knowledge-graph.json`](https://github.com/Egonex-AI/Understand-Anything/blob/main/knowledge-graph.json) files with automatic validation.
- **[`packages/dashboard/public/knowledge-graph.json`](https://github.com/Egonex-AI/Understand-Anything/blob/main/packages/dashboard/public/knowledge-graph.json)**: Example static file for UI development and testing.

## Summary

- **[`knowledge-graph.json`](https://github.com/Egonex-AI/Understand-Anything/blob/main/knowledge-graph.json)** requires `version`, `project`, `nodes`, `edges`, `layers`, and `tour` at the root level.
- **Node definitions** mandate `id`, `type`, `name`, `summary`, `tags`, and `complexity` fields with optional metadata for files and domains.
- **Edge relationships** support 35 distinct types with required source/target identifiers and normalized weights between 0 and 1.
- **Validation pipeline** automatically sanitizes, normalizes aliases, applies defaults (missing types become "file"), and validates against Zod schemas.
- **Source truth** resides in [`packages/core/src/schema.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/packages/core/src/schema.ts) with type definitions in [`packages/core/src/types.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/packages/core/src/types.ts).

## Frequently Asked Questions

### What are the required fields in knowledge-graph.json?

The root object must contain `version` (string), `project` (object), `nodes` (array), `edges` (array), `layers` (array), and `tour` (array). The optional `kind` field accepts "codebase" or "knowledge" to indicate graph type. Every node requires `id`, `type`, `name`, `summary`, `tags`, and `complexity`, while edges require `source`, `target`, `type`, `direction`, and `weight`.

### How does Understand Anything handle invalid graph data?

The system runs `validateGraph` which first sanitizes null values, normalizes type aliases like "func" to "function", auto-fixes missing fields with defaults (type becomes "file", complexity becomes "moderate"), and clamps weights to [0,1]. Finally, it validates against Zod schemas and returns a `ValidationResult` detailing any auto-corrections, dropped fields, or fatal errors preventing validation.

### What edge types are supported in the graph schema?

The `EdgeTypeSchema` defined at lines 88-114 of [`schema.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/schema.ts) enumerates **35 specific relationship types** covering import relationships, function calls, class inheritance, module containment, and semantic associations. Common types include "imports", "calls", "contains", "extends", and "references", with the exact enumeration validated during the normalization stage.

### Where is the schema definition located in the repository?

The primary Zod schema definitions reside in [`packages/core/src/schema.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/packages/core/src/schema.ts) in the Egonex-AI/Understand-Anything repository. This file defines `KnowledgeGraphSchema` and all sub-schemas including `ProjectMetaSchema` (lines 421-429), `GraphNodeSchema` (lines 368-386), and `GraphEdgeSchema` (lines 88-114). TypeScript interfaces are available in [`packages/core/src/types.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/packages/core/src/types.ts).