How Automatic Layer Visualization Groups Code by Architectural Layer
Automatic layer visualization assigns every file in a codebase to logical architectural layers through a hybrid pipeline that combines fast heuristic pattern matching with optional LLM-driven refinement.
The Egonex-AI/Understand-Anything repository provides an intelligent code analysis plugin that transforms raw file structures into meaningful architectural views. By implementing automatic layer visualization, the system categorizes each file-type node into recognizable buckets such as API, Service, or Data layers, enabling developers to instantly grasp project architecture through visual clustering and interactive dashboards.
The Two-Stage Layer Detection Process
The layer detection system operates through a sequential pipeline defined in understand-anything-plugin/packages/core/src/analyzer/layer-detector.ts. This approach balances computational efficiency with semantic accuracy by first applying rule-based heuristics, then optionally refining results with AI.
Stage 1: Heuristic Pattern Matching
The detectLayers function performs initial classification by scanning file paths against a prioritized constant array called LAYER_PATTERNS. These patterns define common architectural buckets including:
- API Layer – matches directories like
routes/,api/, orendpoints/ - Service Layer – matches
services/,business/, orlogic/directories - Data Layer – matches
data/,db/,models/, orrepository/paths - UI Layer – matches
components/,ui/,views/, orfrontend/folders
The algorithm implements a "first match wins" strategy. When processing a file under src/routes/user.ts, the system places it in the API Layer upon encountering the routes pattern. Files that fail to match any predefined pattern automatically fall back to a generic Core layer, ensuring complete graph coverage without manual intervention.
Stage 2: LLM-Driven Refinement
When language model augmentation is enabled, the system invokes buildLayerDetectionPrompt to craft a structured prompt containing the current file list and existing heuristic assignments. The LLM returns a JSON response suggesting logical layer reorganizations based on semantic content rather than mere path strings.
The parseLayerDetectionResponse function validates this JSON, extracting layer objects that contain filePatterns arrays specifying prefixes or substrings. The applyLLMLayers function then reassigns files to these LLM-suggested layers, with any unassigned files placed in an Other layer. This refinement captures architectural nuances that path-based heuristics might miss, such as distinguishing between infrastructure utilities and domain services located in similarly named directories.
Core Data Structures and Type Definitions
The architectural layer system relies on strict TypeScript interfaces defined in understand-anything-plugin/packages/core/src/types.ts. Each Layer object contains:
id– A unique identifier formatted aslayer:<kebab-case-name>(e.g.,layer:api-layer)name– Human-readable display text (e.g., "API Layer")description– Concise explanation of the layer's architectural responsibilitynodeIds– Array of graph node IDs referencing the files assigned to this layer
The KnowledgeGraph interface, constructed by graph-builder.ts, serves as the input for layer detection, containing all file-type nodes with their associated paths and metadata.
Implementing Automatic Layer Detection
To leverage automatic layer visualization in your own analysis pipeline, import the core detection functions and process your knowledge graph:
import {
detectLayers,
buildLayerDetectionPrompt,
parseLayerDetectionResponse,
applyLLMLayers,
} from '@understand-anything/core';
// Assume `graph` is a KnowledgeGraph obtained from the analyzer
const heuristicLayers = detectLayers(graph);
// heuristicLayers now holds layers such as API, Service, Data, UI, etc.
// If you want LLM‑augmented layers:
const prompt = buildLayerDetectionPrompt(graph);
// Send `prompt` to the LLM and receive `llmResponse`
const llmLayers = parseLayerDetectionResponse(llmResponse);
if (llmLayers) {
const refinedLayers = applyLLMLayers(graph, llmLayers);
// refinedLayers contains the LLM‑suggested grouping
}
This implementation allows you to toggle between fast heuristic-only mode and comprehensive LLM-enhanced analysis depending on performance requirements and accuracy needs.
Visualizing Layers in the Dashboard
Once layers are established, the dashboard renders them using utilities in understand-anything-plugin/packages/dashboard/src/utils/layerStats.ts. This module computes aggregate statistics for each layer and maps layer IDs to visual styles.
In the graph view, nodes belonging to the same layer share standardized colors and clustering behaviors. Users can toggle entire layers on or off, collapse complex architectures into high-level views, or drill down into specific architectural tiers. The automatic layer visualization thus transforms static file trees into interactive architectural diagrams that reflect the actual separation of concerns within the codebase.
Summary
- Automatic layer visualization in Understand Anything uses a two-stage pipeline: heuristic pattern matching followed by optional LLM refinement.
- The
detectLayersfunction inlayer-detector.tsprioritizesLAYER_PATTERNSto assign files to API, Service, Data, UI, or Core layers. - LLM integration via
buildLayerDetectionPromptandapplyLLMLayersenables semantic reorganization based on file content rather than path structure. - Each
Layerobject contains standardized metadata (id,name,description,nodeIds) defined intypes.ts. - Dashboard utilities in
layerStats.tsconvert layer data into visually distinct, interactive graph clusters.
Frequently Asked Questions
What happens if a file matches multiple layer patterns?
The heuristic detector assigns the file to the first matching pattern in the LAYER_PATTERNS array. Patterns are ordered by specificity, with more precise architectural directories listed before generic ones, ensuring that a file in src/api/routes/ receives the API Layer designation rather than falling into a broader category.
Can the system operate without LLM access?
Yes. The detectLayers function provides complete standalone functionality using only path-based heuristics. LLM refinement through buildLayerDetectionPrompt and parseLayerDetectionResponse is optional and can be skipped when processing speed is prioritized over semantic accuracy, or when API costs must be minimized.
How does the dashboard distinguish between different layers visually?
The layerStats.ts utility maps each layer ID to specific color schemes and clustering algorithms. Nodes within the same layer receive identical visual styling, enabling instant pattern recognition. The system also calculates node density and connection statistics per layer, which inform the layout engine's clustering behavior in the graph view.
What file types does automatic layer visualization analyze?
The system specifically targets file-type nodes within the KnowledgeGraph, which includes source code files, configuration files, and documentation. Binary assets and empty directories are typically excluded from the graph builder's output, ensuring that layer assignments only reflect meaningful architectural components.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →