# How the Layer Detection Algorithm Assigns Files to Architectural Layers in Egonex Understand-Anything

> Discover how the layer detection algorithm in Egonex Understand Anything assigns files to architectural layers like API, Service, and Data using pattern heuristics. Learn more about this intelligent categorization.

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

---

**The layer detection algorithm in Egonex Understand-Anything uses pattern-based heuristics on file paths to categorize source files into architectural layers like API, Service, or Data layers, falling back to a generic "Core" layer when no patterns match.**

The **layer detection algorithm** is a core component of the Egonex Understand-Anything knowledge graph analyzer. Located in the open-source `understand-anything-plugin` repository, this TypeScript implementation automatically organizes codebases into logical architectural views without requiring manual configuration or annotations.

## Pattern-Based Heuristic Classification

The algorithm relies entirely on **file-system naming conventions** to infer architectural intent. Rather than parsing code contents, it matches directory and file names against a predefined dictionary of layer indicators.

### The LAYER_PATTERNS Lookup Table

At the heart of the system lies the **`LAYER_PATTERNS`** constant defined in [`understand-anything-plugin/packages/core/src/analyzer/layer-detector.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/understand-anything-plugin/packages/core/src/analyzer/layer-detector.ts) (lines 16–67). This static array maps directory keywords to architectural layer names:

- `routes`, `controller`, `api` → **API Layer**
- `service`, `business` → **Service Layer**
- `model`, `repository`, `dao` → **Data Layer**
- `util`, `helper`, `common` → **Utility Layer**

The order of entries in `LAYER_PATTERNS` is significant: the algorithm applies the **first matching pattern** it encounters and stops scanning. This priority-based approach ensures that ambiguous paths resolve to the most specific layer definition available.

### Path Normalization and Matching Logic

The **`matchFileToLayer(filePath)`** function (lines 80–95) handles the actual path analysis:

1. **Normalizes** the input by replacing Windows backslashes with forward slashes and converting to lowercase.
2. **Splits** the path into individual segments.
3. **Scans** each segment against every pattern in `LAYER_PATTERNS`.
4. **Returns** the corresponding `layerName` if a segment equals a pattern string (or the pattern with a trailing "s" for pluralization handling).

If no segment matches any pattern, the function returns `null`, triggering the fallback logic.

## The Layer Detection Loop

The **`detectLayers(graph)`** function (lines 100–144) orchestrates the classification process across the entire knowledge graph.

### File Processing and Classification

The detection loop iterates over all nodes in the graph, applying specific rules to **file-type nodes**:

- Nodes with a `filePath` property are passed to `matchFileToLayer()`.
- When a match succeeds, the file is assigned to that layer.
- When the heuristic returns `null`, the file is forced into the **"Core"** layer.
- Nodes lacking a `filePath` property are automatically categorized as **"Core"**.

The function maintains a `Map<string, string[]>` to aggregate node IDs by layer name during processing.

### Layer ID Generation and Object Creation

For each discovered layer, the algorithm uses **`toLayerId(name)`** (lines 72–74) to generate stable identifiers. This utility transforms human-readable names like "API Layer" into machine-friendly IDs such as `layer:api-layer`.

The final output is an array of **Layer objects**, each containing:
- `id`: The generated layer identifier
- `name`: The human-readable layer name
- `description`: Either the description from `LAYER_PATTERNS` or a generic string for "Core"
- `nodeIds`: An array of all file node IDs belonging to that layer

## Integration with the Knowledge Graph

The layer detection results flow into multiple downstream systems. According to the source code in `Egonex-AI/Understand-Anything`, the [`onboard-builder.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/onboard-builder.ts) (lines 31–38) consumes these layers to render architectural sections in onboarding tours, while [`explain-builder.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/explain-builder.ts) (lines 140–144) adds "Architectural Layer" headings to node explanations. The dashboard module in [`packages/dashboard/src/utils/layerStats.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/packages/dashboard/src/utils/layerStats.ts) further aggregates these assignments to compute layer statistics and drive the UI visualization.

## Summary

- The **layer detection algorithm** operates entirely on file path patterns, not code content analysis.
- **`LAYER_PATTERNS`** in [`layer-detector.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/layer-detector.ts) defines the mapping between directory keywords and architectural layers.
- **`matchFileToLayer()`** normalizes paths and applies first-match-wins heuristics, including automatic pluralization handling.
- Files that fail pattern matching are assigned to the **"Core"** layer as a safe fallback.
- The system generates stable layer IDs via **`toLayerId()`** and returns structured Layer objects consumed by the dashboard and explanation builders.

## Frequently Asked Questions

### How does the layer detection algorithm handle Windows file paths?

The **`matchFileToLayer()`** function automatically normalizes Windows-style backslashes to forward slashes before processing. This ensures consistent matching across operating systems, as the `LAYER_PATTERNS` lookup table expects Unix-style path separators.

### What happens if a file path matches multiple layer patterns?

The algorithm uses a **first-match-wins** strategy. When scanning file path segments against `LAYER_PATTERNS`, it returns the layer name associated with the first matching pattern encountered in the array. To prioritize specific layers, place their patterns earlier in the `LAYER_PATTERNS` definition.

### Can I customize the LAYER_PATTERNS for my specific project structure?

Yes, the `LAYER_PATTERNS` array is defined as a constant in [`understand-anything-plugin/packages/core/src/analyzer/layer-detector.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/understand-anything-plugin/packages/core/src/analyzer/layer-detector.ts) (lines 16–67). You can modify this table to include domain-specific directory names (such as `graphql`, `middleware`, or `queries`) and map them to custom layer names before building the project.

### Where does the layer detection algorithm store its results?

The **`detectLayers()`** function returns an in-memory array of Layer objects containing IDs, names, descriptions, and node ID lists. These objects are consumed by the knowledge graph pipeline and surfaced in the dashboard via [`layerStats.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/layerStats.ts), as well as in documentation generators like [`onboard-builder.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/onboard-builder.ts) and [`explain-builder.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/explain-builder.ts). The results are not persisted to disk as the algorithm runs dynamically during analysis.