# How the Graph-Reviewer Agent Validates Referential Integrity in Understand Anything

> Discover how the graph-reviewer agent validates referential integrity in Understand Anything. Learn how it checks for dangling references and ensures data accuracy for your KnowledgeGraph.

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

---

**The graph-reviewer agent validates referential integrity by verifying that every edge source, edge target, layer node ID, and tour step node ID in the KnowledgeGraph JSON references an existing node, logging any dangling references as critical warnings.**

The final quality gate in the Egonex-AI/Understand-Anything pipeline employs a deterministic validation script to ensure the assembled knowledge graph contains no broken links. This process, defined as Tier 3 validation in the agent's specification, systematically checks that all structural references point to valid entities before the graph is approved for downstream use.

## The Five-Tier Referential Integrity Check

According to the specification in [`agents/graph-reviewer.md`](https://github.com/Egonex-AI/Understand-Anything/blob/main/agents/graph-reviewer.md) (lines 63-70), the graph-reviewer agent performs five distinct checks to ensure referential integrity. Each check targets a specific vector through which dangling references could corrupt the graph structure.

### Edge Source Validation

Every edge in the knowledge graph must originate from a valid node. The validation script verifies that each edge's `source` ID exists within the set of valid node IDs. When `nodeIds.has(e.source)` returns false, the agent logs a dangling reference warning containing the edge index and the missing identifier.

### Edge Target Validation

Similarly, every edge must terminate at an existing node. The script checks that `e.target` matches a known node ID. Failures here are reported with the same granularity as source validation, capturing the specific edge index and the orphaned target reference.

### Layer Node ID Validation

The knowledge graph supports layered visualizations where each layer references specific nodes via `nodeIds` arrays. The validation iterates through `graph.layers`, verifying that every ID listed in `layer.nodeIds` corresponds to an actual node. Missing references trigger warnings that include the layer number and the invalid node ID.

### Tour Step Node ID Validation

Interactive tours consist of steps that reference nodes to highlight or explain. The script validates `graph.tour.steps`, ensuring each `step.nodeIds` entry points to a valid graph node. As with layer validation, failures log the specific step number and the unknown node reference.

### Orphan Detection

After validating all explicit references, the script performs a reverse check to identify orphan nodes. Any node that is never referenced as a source or target in any edge, layer, or tour step is flagged. While these do not represent dangling references per se, they are reported as warnings under "Broken referential integrity" to ensure data completeness.

## Implementation in the Validation Script

The deterministic validation script parses the `KnowledgeGraph` JSON and builds a lookup set of all valid node IDs before performing any reference checks. This approach ensures **O(1)** membership testing during the validation loops.

The core validation logic, as implemented in the graph-reviewer agent's Phase 1 script, follows this pattern:

```typescript
// Parse the KnowledgeGraph JSON
const nodeIds = new Set(graph.nodes.map((n) => n.id));
const warnings: string[] = [];

// Validate all edges
graph.edges.forEach((e, idx) => {
  if (!nodeIds.has(e.source)) {
    warnings.push(`Edge #${idx} has missing source: ${e.source}`);
  }
  if (!nodeIds.has(e.target)) {
    warnings.push(`Edge #${idx} has missing target: ${e.target}`);
  }
});

// Validate layer references
graph.layers?.forEach((layer, lIdx) => {
  layer.nodeIds?.forEach((id) => {
    if (!nodeIds.has(id)) {
      warnings.push(`Layer #${lIdx} references unknown node: ${id}`);
    }
  });
});

// Validate tour step references
graph.tour?.steps?.forEach((step, sIdx) => {
  step.nodeIds?.forEach((id) => {
    if (!nodeIds.has(id)) {
      warnings.push(`Tour step #${sIdx} references unknown node: ${id}`);
    }
  });
});

```

The script writes accumulated warnings to `$PHASE_WARNINGS`, which the agent later includes in the final validation report.

## Tier 3 Validation Architecture

The referential integrity checks constitute **Tier 3** of the graph-reviewer's validation hierarchy, as defined in [`packages/core/src/schema.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/packages/core/src/schema.ts) (line 573). This tier specifically handles edge validation and structural integrity verification.

Unlike lower-tier checks that might validate syntax or schema compliance, Tier 3 requires the full graph context to resolve references. The validation script executes in **Phase 1** of the agent's operation, running deterministically before any AI-driven review begins. This ensures that broken references are caught immediately without consuming inference resources.

## Validation Report and Failure Handling

When the graph-reviewer agent encounters referential integrity violations, it categorizes them as critical failures according to the specification in [`agents/graph-reviewer.md`](https://github.com/Egonex-AI/Understand-Anything/blob/main/agents/graph-reviewer.md) (line 156). The agent lists "Broken referential integrity (dangling references)" as a validation failure type that will block graph approval.

To execute the validation manually:

```bash
node validate-graph.js ./knowledge-graph.json ./validation-report.json

```

The output [`validation-report.json`](https://github.com/Egonex-AI/Understand-Anything/blob/main/validation-report.json) contains all warnings generated during the Phase 1 checks. If any dangling references are detected, the graph-reviewer renders a rejection decision, preventing the corrupted graph from proceeding to downstream consumers.

## Summary

- **The graph-reviewer agent** in Egonex-AI/Understand-Anything serves as the final quality gate for knowledge graph integrity.
- **Five specific checks** validate that edge sources, edge targets, layer node IDs, tour step node IDs, and orphan nodes maintain proper references.
- **Tier 3 validation** performs these checks deterministically in Phase 1 before AI review, using a Set-based lookup for **O(1)** node ID verification.
- **Critical failures** are logged to `$PHASE_WARNINGS` and reported as "Broken referential integrity (dangling references)" in the validation report.
- **Key files** include [`agents/graph-reviewer.md`](https://github.com/Egonex-AI/Understand-Anything/blob/main/agents/graph-reviewer.md) (lines 63-70, 156) and [`packages/core/src/schema.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/packages/core/src/schema.ts) (line 573).

## Frequently Asked Questions

### What happens if the graph-reviewer finds a dangling reference?

The graph-reviewer logs the specific missing ID and its location (edge index, layer number, or tour step) to the `$PHASE_WARNINGS` list. Because referential integrity violations are classified as critical failures in the Tier 3 validation phase, the agent will reject the knowledge graph and prevent it from advancing to downstream processing or AI-driven review stages.

### How does the validation script achieve efficient referential checking?

The script first builds a JavaScript `Set` containing all valid node IDs from `graph.nodes.map((n) => n.id)`. This allows **O(1)** constant-time lookups when validating edges, layers, and tour steps, ensuring the entire graph can be validated in linear time relative to the number of references.

### What is the difference between a dangling reference and an orphan node?

A **dangling reference** occurs when an edge, layer, or tour step points to a node ID that does not exist in the graph. An **orphan node** is a valid node that exists in the graph but is never referenced by any edge, layer, or tour step. While dangling references represent broken integrity, orphan nodes are flagged as warnings to ensure the graph contains no unused or disconnected entities.

### Where is the referential integrity logic defined in the source code?

The validation rules are specified in [`agents/graph-reviewer.md`](https://github.com/Egonex-AI/Understand-Anything/blob/main/agents/graph-reviewer.md) (lines 63-70), which describes the five check types. The Tier 3 classification appears in [`packages/core/src/schema.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/packages/core/src/schema.ts) (line 573). The actual implementation resides in the deterministic validation script referenced in the graph-reviewer agent's Phase 1 execution pipeline.