# How the /understand-diff Command Analyzes Diff Impact and Identifies Affected Codebase Regions

> Discover how the /understand-diff command maps code changes to a knowledge graph, identifies affected codebase regions, and generates a markdown report.

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

---

**The `/understand-diff` command analyzes diff impact by mapping changed files to a knowledge graph, propagating changes through "contains" relationships, and performing a one-hop neighbor analysis to identify affected nodes, edges, and architectural layers before generating a structured markdown report.**

The `/understand-diff` command in the **Egonex-AI/Understand-Anything** repository provides precise diff impact analysis by transforming raw git changes into a semantic understanding of affected codebase regions. By leveraging a pre-built knowledge graph, the command traces how file modifications ripple through architectural layers and dependencies. This article examines the implementation in [`understand-anything-plugin/src/diff-analyzer.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/understand-anything-plugin/src/diff-analyzer.ts) to reveal exactly how the system calculates blast radius and structural impact.

## Mapping Changed Files to Knowledge Graph Nodes

The analysis begins in `buildDiffContext` by iterating over the array of changed file paths provided by `git diff`. For each file path, the algorithm searches the `KnowledgeGraph` for `GraphNode` objects where the `filePath` property matches exactly.

When a match is found, the node's `id` is added to the `changedNodeIds` set. Files that fail to map to any graph node are tracked separately in `unmappedFiles` for diagnostic purposes (lines 31-40).

```typescript
for (const file of changedFiles) {
  // Matching logic against graph nodes
}

```

This loop establishes the foundation of the impact analysis by anchoring filesystem changes to semantic graph entities.

## Propagating "Contains" Relationships

After direct file mapping, the analyzer expands the change set by traversing **"contains"** edges. This step ensures that parent-child relationships—such as folders containing files or modules containing functions—are properly accounted for in the impact calculation.

The algorithm walks all graph edges looking for relationships of type `"contains"` where the source node exists in `changedNodeIds`. When found, the target node (the child) is automatically added to the changed set (lines 44-48). This propagation guarantees that modifying a directory node implicitly marks its contents as changed.

## Identifying Directly Impacted Neighbors

With the complete set of changed nodes established, the analyzer performs a **one-hop downstream impact analysis** to identify affected codebase regions. This step reveals immediate dependencies and relationships that touch the modified code.

The system iterates over every `GraphEdge` in the graph. If either endpoint of an edge belongs to `changedNodeIds`, the edge is recorded in `impactedEdges`. The opposite endpoint—when not already marked as changed—is added to `affectedNodeIds`, capturing the direct blast radius of the modifications (lines 57-68).

## Deriving Affected Architectural Layers

The diff analyzer translates low-level file changes into high-level architectural impact by examining **layers**. Layers represent architectural boundaries or subsystems within the codebase.

Any layer whose `nodeIds` intersect with the union of `changedNodeIds` and `affectedNodeIds` is flagged as affected (lines 74-77). This provides stakeholders with a structural view of which subsystems require attention, moving beyond individual files to semantic architectural units.

## Building the DiffContext Object

All collected data is aggregated into a structured `DiffContext` object (lines 79-87). This object contains:

- Project name and changed file list
- Complete `changedNodes` array (filtered from the graph using `changedNodeIds`)
- `affectedNodes` array representing the one-hop impact zone
- `impactedEdges` showing specific relationships affected by changes
- `affectedLayers` identifying impacted architectural boundaries
- `unmappedFiles` tracking files outside the knowledge graph

## Formatting the Impact Report

The `formatDiffAnalysis` function transforms the `DiffContext` into a human-readable markdown report optimized for both developers and LLM consumption. The report includes sections for Changed Components, Affected Components, Affected Layers, Impacted Relationships, and Unmapped Files.

Additionally, the formatter generates a **Risk Assessment** section that summarizes complexity metrics, cross-layer spread, blast-radius size, and unmapped file counts to provide an immediate risk level indicator (lines 90-197).

## Programmatic Usage Example

You can invoke the same analysis pipeline programmatically using the exported functions from the diff analyzer module:

```typescript
import { buildDiffContext, formatDiffAnalysis } from "./diff-analyzer.js";
import type { KnowledgeGraph } from "@understand-anything/core";

async function runDiffCommand(graph: KnowledgeGraph, changedFiles: string[]) {
  // Build the semantic context from changed files
  const ctx = buildDiffContext(graph, changedFiles);
  
  // Generate markdown report
  const markdownReport = formatDiffAnalysis(ctx);
  console.log(markdownReport);
}

```

This pattern mirrors the internal implementation used by the CLI when processing `/understand-diff` commands.

## Key Implementation Files

| File | Role |
|------|------|
| [`understand-anything-plugin/src/diff-analyzer.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/understand-anything-plugin/src/diff-analyzer.ts) | Core implementation containing `buildDiffContext` and `formatDiffAnalysis` functions |
| [`understand-anything-plugin/src/__tests__/diff-analyzer.test.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/understand-anything-plugin/src/__tests__/diff-analyzer.test.ts) | Test suite validating mapping accuracy, neighbor discovery, and risk assessment logic |
| [`understand-anything-plugin/src/understand-chat.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/understand-anything-plugin/src/understand-chat.ts) | Integration layer converting diff contexts into LLM prompts |
| [`understand-anything-plugin/packages/core/src/types.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/understand-anything-plugin/packages/core/src/types.ts) | Type definitions for `KnowledgeGraph`, `GraphNode`, `GraphEdge`, and `Layer` |
| [`understand-anything-plugin/packages/core/src/graph-builder.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/understand-anything-plugin/packages/core/src/graph-builder.ts) | Knowledge graph construction consumed by the diff analyzer |

## Summary

- **Graph Mapping**: The command anchors filesystem changes to semantic `GraphNode` entities by matching `git diff` output against the knowledge graph's `filePath` properties.
- **Containment Propagation**: Changes automatically propagate through `"contains"` edges to capture parent-child relationships and ensure complete coverage of modified components.
- **One-Hop Impact Analysis**: The system identifies affected codebase regions by examining immediate neighbors of changed nodes, recording both `impactedEdges` and `affectedNodeIds`.
- **Architectural Layer Detection**: Impact is aggregated at the architectural level by intersecting changed/affected nodes with layer definitions, revealing which subsystems are touched.
- **Structured Reporting**: Results are packaged into a `DiffContext` object and formatted as markdown with risk assessment metrics for immediate actionable intelligence.

## Frequently Asked Questions

### How does the diff analyzer handle files not present in the knowledge graph?

Files that do not match any `GraphNode` `filePath` are collected in the `unmappedFiles` array within the `DiffContext`. These are included in the final report to highlight gaps in graph coverage or external dependencies that may require manual review.

### What types of relationships does the analyzer consider when calculating impact?

The analyzer specifically examines `"contains"` relationships for change propagation and inspects all edge types when identifying impacted neighbors. Any edge connecting a changed node to another entity—regardless of relationship type—is recorded in `impactedEdges` and contributes to the affected node set.

### Can the diff analysis detect transitive dependencies beyond one hop?

No, the current implementation in `buildDiffContext` performs a single-hop analysis only (lines 57-68). It captures direct neighbors of changed nodes but does not recursively traverse the graph to find second-order or transitive dependencies. The affected set represents immediate blast radius only.

### What information does the risk assessment section include?

The risk assessment generated by `formatDiffAnalysis` evaluates complexity indicators, cross-layer spread (how many architectural layers are affected), total blast-radius size (count of affected nodes), and the presence of unmapped files. These factors combine to produce a risk level banner in the markdown output.