# Understanding the knowledge-graph.json Schema and Programmatic Consumption

> Explore the knowledge-graph.json schema, Learn how to programmatically consume this validated JSON artifact representing codebases and knowledge graphs with @understand-anything/core.

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

---

**The [`knowledge-graph.json`](https://github.com/Egonex-AI/Understand-Anything/blob/main/knowledge-graph.json) file is a validated JSON artifact produced by Understand Anything that represents a complete codebase or knowledge graph using a strict schema with nodes, edges, layers, and metadata, which can be consumed programmatically using the `@understand-anything/core` validation utilities.**

The [`knowledge-graph.json`](https://github.com/Egonex-AI/Understand-Anything/blob/main/knowledge-graph.json) schema defines the canonical data structure used by the **Understand Anything** platform to serialize project analysis results. This JSON format captures everything from file hierarchies and function dependencies to high-level architectural layers and guided tours. According to the Egonex-AI/Understand-Anything source code, the schema is enforced using Zod validators and includes automatic sanitization, normalization, and auto-fixing capabilities to ensure data integrity.

## Schema Structure and Top-Level Fields

The [`knowledge-graph.json`](https://github.com/Egonex-AI/Understand-Anything/blob/main/knowledge-graph.json) file must conform to the **`KnowledgeGraphSchema`** defined in [`packages/core/src/schema.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/packages/core/src/schema.ts). The top-level structure contains six primary fields that organize the graph data.

### Core Metadata Fields

- **version**: A semantic version string identifying the graph format version.
- **kind**: An optional discriminator (`"codebase"` or `"knowledge"`) indicating whether the graph describes source code or pure knowledge domains.
- **project**: A **`ProjectMetaSchema`** object containing metadata including `name`, `languages`, `frameworks`, `description`, `analyzedAt` timestamp, and `gitCommitHash`.

### Graph Data Fields

- **nodes**: An array of **`GraphNodeSchema`** objects representing entities like files, functions, classes, and modules. Each node requires `id`, `type`, `name`, `summary`, `tags`, and `complexity` fields, with optional properties for `filePath`, `lineRange`, `languageNotes`, `domainMeta`, and `knowledgeMeta`.
- **edges**: An array of **`GraphEdgeSchema`** objects defining directed relationships between nodes. Required fields include `source`, `target`, `type`, `direction`, and `weight` (clamped to `[0, 1]`), with an optional `description`. The `type` field is validated against **`EdgeTypeSchema`**, which enumerates 35 distinct relationship types.
- **layers**: An array of **`LayerSchema`** objects for logical node groupings (e.g., "frontend" vs. "backend"), containing `id`, `name`, `description`, and `nodeIds`.
- **tour**: An array of **`TourStepSchema`** objects for UI-guided tours, with fields `order`, `title`, `description`, `nodeIds`, and optional `languageLesson`.

## Validation and Data Processing Pipeline

Before validation, the Understand Anything engine applies a multi-stage pipeline to ensure graph integrity. According to [`packages/core/src/schema.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/packages/core/src/schema.ts), the **`sanitizeGraph`**, **`normalizeGraph`**, and **`autoFixGraph`** functions process raw JSON through several transformation steps:

1. **Sanitization**: Converts null values to defaults and cleans malformed entries.
2. **Normalization**: Resolves aliases (e.g., converting `"func"` to `"function"` for node types).
3. **Auto-fixing**: Applies default values for missing required fields (setting missing `type` to `"file"`, missing `complexity` to `"moderate"`, and normalizing weights to the `[0, 1]` range).

The **`validateGraph`** function orchestrates this pipeline and returns a `ValidationResult` object containing either the validated `KnowledgeGraph` data or detailed error information about auto-corrected, dropped, or fatal issues.

## Consuming the Schema Programmatically

Developers can parse and validate [`knowledge-graph.json`](https://github.com/Egonex-AI/Understand-Anything/blob/main/knowledge-graph.json) files using the core library's TypeScript utilities or Zod schemas directly.

### Minimal Valid Graph Structure

A valid [`knowledge-graph.json`](https://github.com/Egonex-AI/Understand-Anything/blob/main/knowledge-graph.json) requires at minimum the `version`, `project`, and `nodes` fields:

```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 the Core Library

Import the validation function from `@understand-anything/core` to parse graph files with full error reporting:

```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

For custom validation workflows, import the Zod schema directly:

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

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

```

## Key Source Files

The schema implementation is distributed across these critical files in the Egonex-AI/Understand-Anything repository:

- **[`packages/core/src/schema.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/packages/core/src/schema.ts)**: Defines the complete Zod schema (`KnowledgeGraphSchema`, sub-schemas, and validation functions including `sanitizeGraph`, `normalizeGraph`, and `autoFixGraph`).
- **[`packages/core/src/types.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/packages/core/src/types.ts)**: Provides TypeScript interfaces that mirror the JSON schema (e.g., `KnowledgeGraph`, `GraphNode`, `GraphEdge`).
- **[`packages/core/src/persistence/index.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/packages/core/src/persistence/index.ts)**: Handles disk I/O operations for reading and writing [`knowledge-graph.json`](https://github.com/Egonex-AI/Understand-Anything/blob/main/knowledge-graph.json) files, invoking the validator automatically.
- **[`packages/dashboard/vite.config.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/packages/dashboard/vite.config.ts)**: Configures the development server to serve generated [`knowledge-graph.json`](https://github.com/Egonex-AI/Understand-Anything/blob/main/knowledge-graph.json) files to the dashboard UI.
- **[`packages/dashboard/public/knowledge-graph.json`](https://github.com/Egonex-AI/Understand-Anything/blob/main/packages/dashboard/public/knowledge-graph.json)**: Contains example static files used for UI development and testing.

## Summary

- The **[`knowledge-graph.json`](https://github.com/Egonex-AI/Understand-Anything/blob/main/knowledge-graph.json)** schema defines a standardized format for code and knowledge graphs with strict validation via Zod.
- The top-level structure includes **version**, **project** metadata, **nodes**, **edges**, **layers**, and **tour** arrays.
- The **`validateGraph`** function applies sanitization, normalization, and auto-fixing before validation, ensuring robust data integrity.
- Programmatic consumption requires importing validation utilities from `@understand-anything/core` or using the Zod schemas directly.
- Core implementation 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 is the difference between the `codebase` and `knowledge` kinds in knowledge-graph.json?

The optional **`kind`** field acts as a discriminator indicating the graph's domain. When set to `"codebase"`, the graph represents software source code with entities like files and functions. When set to `"knowledge"`, it represents abstract knowledge domains without code-specific metadata. This distinction helps the UI and analysis tools apply appropriate rendering and validation rules.

### How does Understand Anything handle invalid or missing fields in the JSON?

The validation pipeline automatically applies three correction stages before strict validation. **`sanitizeGraph`** removes nulls and applies defaults, **`normalizeGraph`** resolves type aliases (like converting `"func"` to `"function"`), and **`autoFixGraph`** populates missing required fields with sensible defaults (e.g., `"file"` for missing types, `"moderate"` for complexity). Only after these steps does **`validateGraph`** perform final schema checking.

### Can I extend the knowledge-graph.json schema with custom node or edge types?

While the schema defines strict **`EdgeTypeSchema`** with 35 enumerated values and specific node types, you can utilize the **`domainMeta`** and **`knowledgeMeta`** optional fields on nodes to store custom metadata. For fundamental schema extensions, you would need to modify the Zod definitions in [`packages/core/src/schema.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/packages/core/src/schema.ts) and rebuild the core package, as the validation functions enforce strict conformity to prevent data corruption.

### Where does the dashboard UI load the knowledge-graph.json file from?

The dashboard development server loads the file through the Vite configuration in [`packages/dashboard/vite.config.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/packages/dashboard/vite.config.ts), which serves the generated graph. In production or custom deployments, the **`persistence`** module in [`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 the JSON to disk, while the dashboard fetches it via HTTP requests to the served static file location.