# How Egonex AI Automatically Identifies Architectural Layers from Code Structure

> Egonex AI automatically identifies architectural layers using heuristic pattern matching and optional LLM analysis. Understand your code structure effortlessly.

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

---

**Egonex AI automatically identifies architectural layers by applying heuristic pattern matching against directory names, then optionally refining results with LLM-driven analysis when folder conventions are ambiguous.**

The **Understand-Anything** repository provides an automated architecture analysis engine that maps physical file structures to logical architectural layers. This capability enables developers to visualize codebase organization without manual documentation. The system combines fast static analysis with intelligent fallback mechanisms to handle both conventional and unconventional project layouts.

## Heuristic Pattern Matching

The core detection engine relies on predefined folder-name conventions to categorize files into architectural tiers. This approach provides deterministic, high-speed classification suitable for most standard codebases.

### Static Pattern Definitions

The [`layer-detector.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/layer-detector.ts) file defines a static mapping called **`LAYER_PATTERNS`** that associates common directory names with human-readable layer classifications. This configuration maps patterns like `routes`, `service`, `model`, and `component` to architectural concepts such as *API Layer*, *Service Layer*, *Data Layer*, and *UI Layer*.

According to the source code in [`packages/core/src/analyzer/layer-detector.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/packages/core/src/analyzer/layer-detector.ts) (lines 16-66), these patterns cover conventional MVC, microservice, and frontend framework layouts without requiring configuration.

### Path-to-Layer Resolution

For each file node in the knowledge graph, the **`matchFileToLayer()`** function normalizes file paths and splits them into directory segments. The algorithm checks each segment against `LAYER_PATTERNS` in order, assigning the first matching layer to the file. Files that fail to match any pattern automatically fall into a default **"Core"** layer, ensuring complete graph coverage without orphaning utilities or configuration files.

This implementation appears in [`packages/core/src/analyzer/layer-detector.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/packages/core/src/analyzer/layer-detector.ts) (lines 80-95) and executes in linear time relative to directory depth.

### Layer Construction

The **`detectLayers()`** function orchestrates the classification process by iterating through every `file`-type node in the knowledge graph. It groups node IDs by their resolved layer names, then constructs a `Layer[]` array containing:

- A unique identifier for the layer
- The human-readable layer name
- A descriptive explanation (sourced from `LAYER_PATTERNS`)
- The complete list of node IDs belonging to that layer

This aggregation logic resides in [`packages/core/src/analyzer/layer-detector.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/packages/core/src/analyzer/layer-detector.ts) (lines 105-144).

## LLM-Enhanced Detection

When projects use non-standard naming conventions or custom architectural patterns, the system invokes an optional LLM refinement phase.

### Prompt Engineering

The **`buildLayerDetectionPrompt()`** function generates a structured prompt containing the complete list of file paths from the knowledge graph. This prompt requests a JSON array defining custom layers with specific file patterns, allowing the model to infer architectural intent from the actual directory structure rather than relying on hardcoded heuristics.

The prompt construction logic is implemented in [`packages/core/src/analyzer/layer-detector.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/packages/core/src/analyzer/layer-detector.ts) (lines 150-167).

### Response Integration

After receiving the LLM response, **`parseLayerDetectionResponse()`** validates and extracts the proposed layer definitions. The **`applyLLMLayers()`** function then remaps file nodes to layers based on the LLM-provided `filePatterns`, effectively overriding or extending the heuristic results.

This refinement pipeline appears in [`packages/core/src/analyzer/layer-detector.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/packages/core/src/analyzer/layer-detector.ts) (lines 170-224), providing a fallback mechanism when static patterns prove insufficient.

## Performance Optimization

For dashboard visualization, **`computeLayerStats()`** in [`packages/dashboard/src/utils/layerStats.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/packages/dashboard/src/utils/layerStats.ts) calculates node counts and complexity metrics for each layer. The implementation achieves **O(number of layer.nodeIds)** time complexity by iterating only over the pre-grouped node lists rather than scanning the entire knowledge graph, ensuring responsive UI updates even for large codebases.

## Implementation Example

The following example demonstrates how to analyze a codebase and optionally apply LLM refinement:

```typescript
import { GraphBuilder, detectLayers } from "@understand-anything/core";

// 1️⃣ Build a knowledge graph from a source folder (simplified)
const builder = new GraphBuilder({ root: "./my-app/src" });
const graph = await builder.build();   // graph: KnowledgeGraph

// 2️⃣ Run the built‑in heuristic detector
const layers = detectLayers(graph);
console.log(layers.map(l => `${l.name} → ${l.nodeIds.length} files`).join("\n"));
/*
API Layer → 12 files
Service Layer → 8 files
Data Layer → 5 files
UI Layer → 20 files
Core → 3 files
*/

// 3️⃣ (Optional) Let an LLM refine the layers
import { buildLayerDetectionPrompt, parseLayerDetectionResponse, applyLLMLayers } from "@understand-anything/core";

const prompt = buildLayerDetectionPrompt(graph);
// Send `prompt` to your LLM of choice and obtain `llmResponse` (JSON array)

// Parse the LLM response
const llmLayers = parseLayerDetectionResponse(llmResponse);
if (llmLayers) {
  const refinedLayers = applyLLMLayers(graph, llmLayers);
  console.log("Refined layers:", refinedLayers.map(l => l.name));
}

```

## Summary

- **Egonex AI** uses a two-stage approach to automatically identify architectural layers: fast heuristic matching followed by optional LLM refinement.
- The **`LAYER_PATTERNS`** static map in [`layer-detector.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/layer-detector.ts) associates common folder names like `routes`, `service`, and `model` with architectural concepts.
- **Unmatched files** default to a "Core" layer, ensuring complete graph coverage.
- **`detectLayers()`** aggregates file nodes into layer objects containing metadata and node ID lists.
- **LLM enhancement** via `buildLayerDetectionPrompt()` and `applyLLMLayers()` handles unconventional project structures.
- **`computeLayerStats()`** provides O(n) performance for dashboard statistics by operating on pre-grouped layer data.

## Frequently Asked Questions

### What happens if a file path doesn't match any predefined layer pattern?

The **`matchFileToLayer()`** function assigns unmatched files to a default **"Core"** layer. This ensures that utility files, configuration scripts, and other miscellaneous code remain visible in the architecture graph rather than being excluded from analysis.

### How does the LLM enhancement improve layer detection accuracy?

When folder naming conventions deviate from standard patterns (such as custom prefixes or domain-specific organizational schemes), **`buildLayerDetectionPrompt()`** sends the complete file tree to an LLM. The model identifies logical groupings that static heuristics might miss, and **`applyLLMLayers()`** remaps files accordingly, providing context-aware architectural insights.

### What is the computational complexity of the layer statistics calculation?

The **`computeLayerStats()`** function operates in **O(number of layer.nodeIds)** time. It avoids expensive full-graph traversals by calculating metrics only over the pre-grouped node lists associated with each detected layer, making it suitable for interactive dashboard rendering.

### Can developers customize the layer detection patterns?

While the source analysis focuses on the static **`LAYER_PATTERNS`** defined in the core analyzer, the modular architecture allows for extension. Developers can modify the [`layer-detector.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/layer-detector.ts) file to add custom patterns, or utilize the LLM enhancement pipeline to dynamically inject project-specific layer definitions without hardcoding changes.