# How to Debug Egonex Graph-Reviewer Referential Integrity Failures

> Debug Egonex graph-reviewer referential integrity failures by running understand full review. Inspect knowledge-graph.json edge indices to find missing nodes, ensuring schema validation.

- Repository: [Egonex/Understand-Anything](https://github.com/Egonex-AI/Understand-Anything)
- Tags: how-to-guide
- Published: 2026-06-21

---

**Run the graph-reviewer with `understand --full --review` to surface `invalid-reference` errors, then inspect the specific edge indices in [`knowledge-graph.json`](https://github.com/Egonex-AI/Understand-Anything/blob/main/knowledge-graph.json) to locate missing source or target nodes that fail validation in [`packages/core/src/schema.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/packages/core/src/schema.ts).**

The Egonex graph-reviewer in the Understand-Anything repository validates knowledge graphs through a three-stage pipeline that checks referential integrity between nodes and edges. When edges reference non-existent node IDs, the reviewer emits `invalid-reference` failures that indicate data corruption in your extraction pipeline. Understanding how to trace these errors back to their source allows you to fix malformed graphs at the generator level.

## How Referential Integrity Validation Works

### The Three-Stage Validation Pipeline

The graph-reviewer processes every knowledge graph through sanitization, auto-fixing, and schema validation before final approval.

1. **Sanitization** – The `sanitizeGraph` function removes null values and normalizes string fields to ensure consistent data types.
2. **Auto-fix** – The `autoFixGraph` function supplies default values for missing required fields such as `type`, `direction`, and `weight`.
3. **Schema validation** – The `validateGraph` function defined in [`packages/core/src/schema.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/packages/core/src/schema.ts) runs a Zod schema check and performs referential integrity verification.

### The Tier 3 Referential Integrity Check

During the Tier 3 validation phase (lines 889-906 of [`packages/core/src/schema.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/packages/core/src/schema.ts)), the reviewer verifies that every edge's `source` and `target` properties reference existing node IDs:

```ts
const nodeIds = new Set(validNodes.map(n => n.id));

if (!nodeIds.has(result.data.source)) {
  // source missing → dropped + issue reported
}
if (!nodeIds.has(result.data.target)) {
  // target missing → dropped + issue reported
}

```

When an edge references a missing node, the reviewer generates an issue with category **`invalid-reference`** and a message like "edges[3]: source **foo** does not exist in nodes — removed".

## Step-by-Step Debugging Guide

### 1. Enable Full Diagnostic Output

Run the graph-reviewer with the `--review` flag to force the LLM-backed sub-agent to print the complete issue list:

```bash
understand --full --review

```

This executes the validation pipeline and exposes all `invalid-reference` errors detected by `validateGraph`.

### 2. Capture Raw Validation Output Programmatically

Import the core validator directly to inspect the failure details:

```ts
import { validateGraph } from '@understand-anything/core';

const result = validateGraph(graph);
console.log(JSON.stringify(result, null, 2));

```

The returned `issues` array contains the exact edge index, missing ID, and error category.

### 3. Locate the Offending Edge

Check the edge index reported in the error (e.g., `edges[7]`) within [`.understand-anything/knowledge-graph.json`](https://github.com/Egonex-AI/Understand-Anything/blob/main/.understand-anything/knowledge-graph.json). This reveals the specific edge object that references a non-existent node.

### 4. Verify Node Existence

Search the `nodes` array for the missing ID to confirm absence:

```ts
const missingNode = graph.nodes.find(n => n.id === "missing-id");

```

If `undefined`, the extractor failed to create the node or generated an incorrect identifier.

### 5. Fix the Source Data

- **If the node should exist**: Adjust the extractor to emit the correct `id` format.
- **If the edge is spurious**: Remove or correct the edge in the graph-generation step.

### 6. Re-run the Reviewer

Repeat the validation command to confirm the issue list shrinks or disappears.

### 7. Add Preventative Sanity Checks

Insert pre-validation checks in custom extractors to catch missing nodes early:

```ts
if (!nodeIds.has(edge.source)) {
  throw new Error(`Orphaned edge references missing node: ${edge.source}`);
}

```

## Common Causes of Referential Integrity Failures

### Incorrect ID Generation

When extractors create IDs like `"src/foo.ts:42"` but later trim paths to `"foo.ts"`, edges reference the full path while nodes use the trimmed version. Fix by normalizing ID creation using `path.relative(projectRoot, filePath)`.

### Nodes Filtered by Auto-Fix

If `autoFixGraph` defaults a missing `type` field to `"file"`, but a language-specific extractor later expects `"function"` and drops the node, edges pointing to that node become orphaned. Ensure required fields (`type`, `complexity`, `tags`) are present before graph construction.

### Duplicate Node IDs

When two nodes share the same `id`, the second is dropped during validation, leaving edges that reference the removed duplicate. Enforce uniqueness by checking against the `nodeIds` Set during graph building.

### Edge Creation Before Node Commitment

Some parsers emit edges eagerly before collecting all nodes. Buffer edges until the node collection phase completes, then validate referential integrity before serialization.

## Manual Interrogation Snippet for Deep Debugging

Use this standalone script to audit [`knowledge-graph.json`](https://github.com/Egonex-AI/Understand-Anything/blob/main/knowledge-graph.json) files without running the full pipeline:

```ts
import { validateGraph } from '@understand-anything/core';
import fs from 'node:fs';

// Load a previously generated graph
const rawGraph = JSON.parse(
  fs.readFileSync('.understand-anything/knowledge-graph.json', 'utf-8')
);

// Run the core validator
const { success, issues, data } = validateGraph(rawGraph);

if (!success) {
  console.error('Graph validation failed');
  issues?.forEach(i => console.warn(`[${i.level}] ${i.message}`));
}

// Spot missing node references
issues
  ?.filter(i => i.category === 'invalid-reference')
  .forEach(i => console.log('Problematic edge →', i.path));

```

This outputs exact edge indices and missing node IDs, allowing direct navigation to problematic entries in the JSON file.

## Summary

- **Referential integrity** in Egonex is enforced during Tier 3 validation in [`packages/core/src/schema.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/packages/core/src/schema.ts) by verifying that edge `source` and `target` IDs exist in the validated node set.
- **Debug workflow**: Run `understand --full --review`, capture the `invalid-reference` issues, locate the edge index in [`knowledge-graph.json`](https://github.com/Egonex-AI/Understand-Anything/blob/main/knowledge-graph.json), and trace the missing node back to the extractor.
- **Common fixes**: Normalize ID generation in extractors, ensure required node fields are present before auto-fixing, and buffer edges until all nodes are collected.
- **Prevention**: Add lightweight pre-validation checks in custom extractors to catch orphaned edges before they reach the graph-reviewer.

## Frequently Asked Questions

### Why does the graph-reviewer drop edges instead of fixing them?

The reviewer prioritizes graph integrity over preservation of potentially corrupted relationships. When `validateGraph` detects an `invalid-reference`, it removes the edge to prevent downstream tools from traversing into non-existent nodes, ensuring the knowledge graph remains structurally sound according to the schema defined in [`packages/core/src/schema.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/packages/core/src/schema.ts).

### How can I identify which extractor generated a problematic edge?

Examine the edge's metadata in [`.understand-anything/knowledge-graph.json`](https://github.com/Egonex-AI/Understand-Anything/blob/main/.understand-anything/knowledge-graph.json) for fields like `extractor` or `sourceFile`. If metadata is absent, match the edge's index against the parser's output logs, or add logging to your custom extractors that records the edge index during creation.

### What is the difference between Tier 3 validation and the LLM review?

Tier 3 validation refers to the programmatic schema and referential integrity checks performed by `validateGraph` in [`packages/core/src/schema.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/packages/core/src/schema.ts). The LLM review (triggered by `--review`) is an additional layer that uses agent-based analysis defined in [`agents/graph-reviewer.md`](https://github.com/Egonex-AI/Understand-Anything/blob/main/agents/graph-reviewer.md) to assess semantic completeness and logical consistency beyond structural validation.

### Can I disable referential integrity checks during development?

No, the `invalid-reference` validation is hardcoded in the `validateGraph` function and cannot be bypassed without modifying the source in [`packages/core/src/schema.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/packages/core/src/schema.ts). However, you can configure extractors to skip edge generation until nodes are fully validated, effectively preventing these errors during iterative development.