How the Egonex-AI Architecture-Analyzer Agent Assigns Architectural Layers
The architecture-analyzer agent transforms raw file-import graphs into 3-10 logical architectural layers by running a structural analysis script, applying pattern-based heuristics, and optionally refining assignments with an LLM to ensure every node maps to exactly one layer.
The architecture-analyzer agent is a core component of the /understand skill in the Egonex-AI/Understand-Anything repository. Positioned as the third stage in a five-agent pipeline, it bridges low-level file analysis and high-level visualization by converting a raw knowledge graph into a structured set of architectural layers. This agent ensures that every file node—whether source code, configuration, or documentation—is assigned to exactly one logical layer based on structural signals and semantic patterns.
The Role of the Architecture-Analyzer in the Pipeline
The agent sits between the file-analyzer and tour-builder in the sequence: project-scanner → file-analyzer → architecture-analyzer → tour-builder → graph-reviewer. It consumes a KnowledgeGraph containing file nodes, summaries, tags, and import edges, then emits a JSON array of Layer objects. Each layer includes an id (following the layer:<kebab-case> convention), name, description, and the nodeIds assigned to it. This output feeds directly into the tour-builder to generate interactive dashboard tours.
The Two-Phase Layer Assignment Process
The architecture-analyzer operates in two distinct phases to ensure deterministic yet flexible layer classification.
Phase 1: Structural Analysis Script
In the first phase, the agent generates and executes a Node.js script that consumes a JSON dump of fileNodes, importEdges, and allEdges. As defined in agents/architecture-analyzer.md (lines 23-99), this script computes structural cues including directory grouping, adjacency matrices, cross-category dependency counts, intra-group density metrics, and pattern matches for known directory names. It also detects deployment topologies, data pipelines, and documentation coverage. The script writes a detailed results JSON file containing these metrics for downstream processing.
Phase 2: Semantic Layer Assignment
The second phase interprets the script's output to establish 3-10 logical layers. According to agents/architecture-analyzer.md (lines 124-285), the process first maps directory groups to candidate layers, then refines them using pattern labels, intra-group density scores, and import-direction data. Non-code nodes—such as Dockerfiles, Terraform configurations, CI/CD workflows, data schemas, and README files—are automatically routed to dedicated layers like Infrastructure, CI/CD, Data, or Documentation. The agent enforces a strict constraint that every file node must belong to exactly one layer.
How Layers Are Determined
Layer boundaries emerge from a combination of deterministic heuristics, pattern matching, and optional LLM refinement.
Structural Cues and Import Density
The analyzer evaluates directory grouping based on top-level or first-subdirectory segments. It applies pattern matching to map folders like routes to an API layer or services to a Service layer. Intra-group import density exceeding 0.3 indicates a cohesive group that warrants its own layer, while inter-group import direction reveals foundational versus higher-level relationships (e.g., imports flowing from routes to services suggest an API layer sitting above a Service layer).
Non-Code Layer Detection
The agent automatically identifies infrastructure and documentation assets. The presence of Dockerfiles, Terraform files, CI/CD workflows, database migrations, or markdown documentation triggers the creation of specialized layers. As detailed in agents/architecture-analyzer.md (lines 448-530), these non-code layers ensure that configuration and operational concerns remain visible in the final architecture diagram alongside application code.
LLM Refinement and Heuristic Fallback
When semantic ambiguity exists, the agent invokes an LLM via the Layer Detection Prompt defined in layer-detector.ts. The prompt requests a JSON array containing layer names, descriptions, and file-pattern prefixes. The parseLayerDetectionResponse function extracts these suggestions, and applyLLMLayers applies them to the graph. If the LLM provides no valid match, the system falls back to the deterministic detectLayers function, which matches file paths against predefined LAYER_PATTERNS and assigns unmatched files to a generic Core layer.
Implementation Examples
The following examples demonstrate how to interact with the architecture-analyzer's components programmatically.
Running the Structural Analysis Script
To generate structural metrics from a knowledge graph:
# Create input JSON (simplified)
cat > .understand-anything/tmp/ua-arch-input.json <<'ENDJSON'
{
"fileNodes":[
{"id":"file:src/routes/index.ts","type":"file","filePath":"src/routes/index.ts"},
{"id":"file:src/services/auth.ts","type":"file","filePath":"src/services/auth.ts"},
{"id":"config:tsconfig.json","type":"config","filePath":"tsconfig.json"}
],
"importEdges":[
{"source":"file:src/routes/index.ts","target":"file:src/services/auth.ts","type":"imports"}
],
"allEdges":[
{"source":"config:tsconfig.json","target":"file:src/index.ts","type":"configures"}
]
}
ENDJSON
# Execute the generated Node.js analyzer
node .understand-anything/tmp/ua-arch-analyze.js \
.understand-anything/tmp/ua-arch-input.json \
.understand-anything/tmp/ua-arch-results.json
This produces a results JSON containing groups, densities, and pattern matches used for layer assignment.
Using the Fallback Heuristic
For deterministic layer detection without LLM invocation:
import { detectLayers } from '@understand-anything/core/analyzer/layer-detector';
import { readGraph } from './graph-loader';
const graph = await readGraph(); // KnowledgeGraph with nodes & edges
const layers = detectLayers(graph); // Returns Layer[] based on LAYER_PATTERNS
console.log(layers);
The detectLayers function, implemented in layer-detector.ts (lines 16-65), walks each file node's filePath and matches directory segments against LAYER_PATTERNS, placing unmatched files into a Core layer.
Building the LLM Layer Detection Prompt
To construct a prompt for LLM-based layer suggestions:
import { buildLayerDetectionPrompt } from '@understand-anything/core/analyzer/layer-detector';
const prompt = buildLayerDetectionPrompt(graph);
console.log(prompt);
This generates a prompt listing all file paths and requesting a structured JSON response with name, description, and filePatterns fields, as defined in layer-detector.ts (lines 150-166).
Key Source Files
The architecture-analyzer implementation spans multiple files across the repository:
agents/architecture-analyzer.md: Defines the agent's two-phase execution model, script requirements, layer-assignment rules, and critical constraints ensuring one-layer-per-node enforcement.packages/core/src/analyzer/layer-detector.ts: Implements heuristic fallback logic (detectLayers), LLM prompt construction (buildLayerDetectionPrompt), response parsing (parseLayerDetectionResponse), and layer application (applyLLMLayers).packages/core/src/types.ts: Contains TypeScript definitions forKnowledgeGraph,Layer, and related interfaces used throughout the pipeline.packages/core/src/analyzer/graph-builder.ts: Generates the initial knowledge graph consumed by the architecture-analyzer.packages/core/src/analyzer/llm-analyzer.ts: Orchestrates LLM calls for the architecture-analyzer and integrates the returned layer definitions.
Summary
- The architecture-analyzer agent is the third stage in the Egonex-AI
/understandpipeline, converting raw knowledge graphs into logical architectural layers. - It operates in two phases: a generated structural analysis script extracts metrics, followed by semantic assignment that maps directory groups and non-code assets to 3-10 layers.
- Layer determination relies on directory patterns, import density thresholds (>0.3), import directionality, and automatic detection of infrastructure and documentation files.
- LLM refinement via
layer-detector.tsprovides intelligent layer naming and pattern matching, with deterministicLAYER_PATTERNSheuristics serving as a fallback. - Every file node must be assigned to exactly one layer (e.g.,
layer:api,layer:infrastructure) to satisfy downstreamtour-builderrequirements.
Frequently Asked Questions
What is the architecture-analyzer agent in Egonex-AI?
The architecture-analyzer agent is a specialized component in the Egonex-AI/Understand-Anything repository that transforms low-level file and import relationships into high-level architectural layers. It consumes the output of the file-analyzer and produces structured layer definitions that the tour-builder uses to generate interactive architecture diagrams.
How does the architecture-analyzer determine layer boundaries?
The agent determines boundaries by analyzing directory groupings, calculating intra-group import density (cohesive groups above 0.3 density become layers), and evaluating import directions to establish foundational versus consumer relationships. It also scans for non-code files like Dockerfiles and CI/CD configurations to create dedicated infrastructure and documentation layers.
What happens if the LLM fails to suggest valid layers?
If the LLM response cannot be parsed or contains invalid layer definitions, the system falls back to the deterministic heuristic implemented in detectLayers within layer-detector.ts. This function matches file paths against predefined LAYER_PATTERNS and assigns unmatched nodes to a default Core layer, ensuring the pipeline always produces valid output.
Where are the constraints for layer assignment defined?
The critical constraint that every file node must belong to exactly one layer is defined in agents/architecture-analyzer.md within the "Critical Constraints" section. This specification ensures that the downstream tour-builder receives a non-overlapping, comprehensive layer definition suitable for visualization.
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 →