The user wants a codebase-wide architectural conformance checker.
This system needs to:
Extract metadata from code (create a graph representation).
Use a Domain Specific Language (DSL) to define architectural rules.
Execute these rules as graph queries.
Generate remediation playbooks (how to fix violations).
Integrate with change management (e.g., PR comments, blocking merges).
This is a complex request that touches on static analysis, graph theory, DSL design, and CI/CD integration. I cannot write a fully functional, production-ready enterprise tool in a single response. Instead, I need to provide a conceptual framework and a functional prototype (proof-of-concept) written in Python. Python is good for this because of libraries like networkx (graphs) and ast (parsing), and its general readability.
Key Components:
Metadata Extraction (The Model):
Need to parse source code. Python's ast module is perfect for Python code. For a generic system, I'd mention LSP or tree-sitter, but for the code example, I'll stick to ast to keep it runnable.
Need to represent the code as a graph.
Nodes: Modules, Classes, Functions, Variables.
Edges: imports, calls, inherits_from, contains.
Storage: networkx in memory is sufficient for the demo.
Rule DSL (The Language):
The user wants graph queries. Cypher (Neo4j) is the industry standard, but embedding Neo4j is too heavy for a single script example.
Alternative: A custom Python-based DSL or using a library that supports pattern matching on graphs.
Let's go with a YAML or JSON-based DSL that defines "From" (source) and "To" (target) patterns and the relationship type, or a simple pythonic fluent API.
Decision: A YAML-based DSL is easier to read and looks more "configuration-like" than code.
Conformance Checker (The Engine):
Load the graph.
Parse the rules.
Translate rules into graph traversals (e.g., find paths where A depends on B).
Report violations.
Remediation Playbooks:
If a rule is violated, what should the user do?
The DSL needs a remediation field.
Change Management:
How to output results? SARIF (Static Analysis Results Interchange Format) is the standard.
Mocking a PR comment output.
Drafting the Architecture:
Input: Directory of source code, Rules file (YAML).
Validator: Loads rules, runs queries against Graph.
Output: JSON report (violations + remediation).
Step-by-Step Implementation Plan:
The Graph Builder:
Use os.walk to find .py files.
Use ast to find ClassDefs, FunctionDefs, and Imports.
Add nodes to a networkx.DiGraph.
The DSL Design (YAML):
Structure:
yaml
- id: no-db-in-ui
description: UI should not access DB directly
selector:
source: { layer: "ui" }
target: { layer: "db" }
relation: "calls"
severity: error
remediation: "Introduce a Service layer repository."
The Logic:
Tagging: How do we know a class is "ui" or "db"? We need a file-path based heuristic or decorator-based tagging. Let's use path heuristics for simplicity (e.g., src/ui/ -> layer: ui).
Refining the Code Structure:
arch_check/
graph_builder.py: Extracts metadata.
rules_engine.py: Parses DSL and queries graph.
main.py: CLI entry point.
Writing the Code (Mental Draft & Refinement):
Self-Correction during thought process: A full recursive descent parser for a generic language is hard. I will limit the scope of the code example to Python code and specific dependency types (imports and calls). The architecture description will remain language-agnostic.
Graph Query Logic:
We need to map logical layers (UI, DB) to concrete files.
The rule says "UI cannot depend on DB".
Algorithm: Iterate all edges. Check source node tags. Check target node tags. If (Source is UI AND Target is DB) AND (Edge is dependency), then Violation.
Remediation: Just a string attached to the rule.
Change Management: Output a dummy "GitHub PR Review" block.
Finalizing the Output Structure:
I will present this as a complete, runnable Python project structure (simulated in one block).
Conceptual Overview: Explain the Graph Database approach (Code as a Graph).
The Prototype Code:
Imports (networkx, ast, yaml).
Class CodeGraph: Builds the graph.
Class RuleEngine: Parses YAML and validates.
Class Reporter: Outputs findings.
Example Configuration: The YAML rules.
Usage: How to run it.
Let's write the actual code logic for the graph builder.
ast.NodeVisitor is the way to go.
visit_Import, visit_ImportFrom -> create edges.
visit_ClassDef -> create nodes.
Wait, the prompt asks for "remediation playbooks". This implies a structured output.
The prompt asks for "change management". This implies a diff-aware check (optional but good) or just generating PR comments. I'll stick to generating PR comment format.
Let's refine the DSL. It needs to be expressive.
matcher: "g.V().has('layer', 'ui').out('calls').has('layer', 'db')"
This looks like Gremlin. Implementing a Gremlin parser is too hard.
I will implement a simplified declarative matcher: source_criteria, target_criteria, edge_type.
Code Outline:
python
import networkx as nx
import ast
import os
import yaml
# ... classes ...
I will add comments explaining why this approach scales (using proper graph DBs like Neo4j for large codebases vs NetworkX for small ones).
Let's build the response.
Phase 1: Architecture. Explain the "Code as Graph" concept.
Phase 2: The Code.
Metadata Extractor (AST parsing).
Graph Model (NetworkX).
Rule DSL (YAML config).
Query Engine (Pattern matching).
Phase 3: Operationalization.
Remediation playbooks (JSON output).
Change Management integration (Hook simulation).
This looks solid. I will provide a single self-contained script for the core logic, as that's most useful to the user, but structure it like a library.
Self-Correction on complexity: The AST parser needs to handle calls to imported modules.
e.g.
from service import dbdb.save()
AST: Call(func=Attribute(value=Name(id='db'), attr='save'))
To trace db.save() back to service.db, I need symbol resolution. That's hard.
Simplification: I will focus on Import Coupling. Layer A depends on Layer B if it imports it. This is the standard "Architectural" check (cyclic dependencies, layer violations). Method-level calls are too granular for a basic architectural conformance check unless we have a Language Server. I will stick to Import-level analysis for the prototype to ensure it is robust and runnable without a heavy type solver.
Okay, Plan:
Parse files.
Map File Path -> Layer (e.g. src/ui -> UI).
Extract Imports (File A imports File B).
Build Graph A -> B.
Rule: "Layer UI cannot import Layer DB".
This is cleaner and effectively demonstrates the architectural constraints.
Final check of requirements:
Metadata extraction: Yes (Imports + File Tags).
Rule DSL: Yes (YAML).
Remediation: Yes (in YAML).
Change Management: Yes (Output format).
Let's go.
This solution implements a complete architectural conformance checker framework in Python. It treats the codebase as a directed graph where nodes are modules/files and edges are dependencies (imports).
System Architecture
Metadata Extraction: Parses source files to build a dependency graph (using ast for Python, scalable to other languages via tree-sitter).
Graph Model: Uses networkx to represent the system architecture and compute reachability.
Rule DSL: A YAML-based Domain Specific Language to define allowed/forbidden topologies.
Remediation Engine: Maps violation types to specific playbooks/fixes.
Change Management: Generates a machine-readable report (JSON) compatible with CI pipelines.
Prerequisites
You will need networkx and pyyaml.
bash
pip install networkx pyyaml
The Implementation
Save the following into a single file (e.g., arch_guardian.py) or a project structure.
python
Key Components Breakdown
1. Metadata Extraction (CodebaseGraph)
This class turns the linear source code into a topology. It uses Python's ast (Abstract Syntax Tree) module to parse files. It doesn't just look at text; it understands import statements to build a directed graph (networkx.DiGraph).
Scalability: In a real-world scenario involving multiple languages (Java, TypeScript), this component would be swapped out for a Language Server Protocol (LSP) client or tree-sitter parsers, but the graph output remains the same.
2. Rule DSL (arch_rules.yaml)
Instead of hard-coding rules, we define them in YAML. This allows architects to modify governance without touching the Python engine.
Layer Breach: The example rule ARCH-001 detects if the Application layer (Services) calls the Interface layer (API). In clean architecture, the core should not know about the delivery mechanism.
3. Remediation Playbooks
Unlike simple linters that just say "This is wrong," this system links a violation to a Playbook (PB-DECOUPLE). When the tool reports an error, it provides the exact steps to fix the architectural drift (Dependency Inversion).
4. Change Management Integration
The ChangeManager outputs JSON. This is designed to be ingested by CI/CD tools (like GitHub Actions, GitLab CI, or Jenkins).
Gating: The exit(1) command ensures that if architectural rules are broken, the build fails, preventing non-conforming code from reaching production.
How to Extend
To move this from a prototype to an enterprise tool:
Visualization: Integrate pyvis or d3.js to render the graph and highlight violating edges in red.
Advanced Queries: Use networkx algorithms like simple_cycles to detect cyclic dependencies (Architectural smell: Tightly Coupled Modules).
Diff-ing: Only validate files changed in a Pull Request to reduce noise in large monorepos.
import os
import ast
import json
import yaml
from typing import List, Dict, Set, Any, Optional
from dataclasses import dataclass, field
from pathlib import Path
import networkx as nx
# ==============================================================================
# 1. DOMAIN MODELS
# ==============================================================================
@dataclass
class Violation:
"""Represents a single architectural violation."""
rule_id: str
severity: str
source: str
target: str
message: str
remediation_playbook: str
@dataclass
class RemediationPlaybook:
"""Instructions on how to fix a class of violations."""
steps: List[str]
automated: bool = False
# ==============================================================================
# 2. METADATA EXTRACTION (The Graph Builder)
# ==============================================================================
class CodebaseGraph:
"""
Extracts metadata from the filesystem and constructs a dependency graph.
Currently implements Python AST parsing, but extensible to other languages.
"""
def __init__(self, root_dir: str):
self.root_dir = Path(root_dir)
self.graph = nx.DiGraph()
self.module_map: Dict[str, str] = {} # Maps module name -> file path
def build_graph(self):
print(f"Scanning codebase at {self.root_dir}...")
for path in self.root_dir.rglob("*.py"):
self._process_file(path)
# Enrich nodes with metadata (e.g., layer detection)
self._tag_layers()
def _process_file(self, file_path: Path):
rel_path = file_path.relative_to(self.root_dir)
# Create a python-style module name: src/app/main.py -> src.app.main
module_name = ".".join(rel_path.with_suffix("").parts)
self.graph.add_node(module_name, path=str(file_path))
self.module_map[module_name] = str(file_path)
try:
with open(file_path, 'r', encoding='utf-8') as f:
tree = ast.parse(f.read())
for node in ast.walk(tree):
if isinstance(node, (ast.Import, ast.ImportFrom)):
for alias in node.names:
target_module = alias.name
# Optimization: Only track internal dependencies
if self._is_internal(target_module):
self.graph.add_edge(module_name, target_module, type='import')
except Exception as e:
print(f"Error parsing {file_path}: {e}")
def _is_internal(self, module_name: str) -> bool:
# Simple check: does it start with one of our top-level dirs?
# In a real app, this would check against the actual graph nodes.
return True
def _tag_layers(self):
"""Heuristic tagging of architectural layers based on path."""
for node in self.graph.nodes:
if "tests" in node:
self.graph.nodes[node]['layer'] = "test"
elif "api" in node:
self.graph.nodes[node]['layer'] = "interface"
elif "services" in node:
self.graph.nodes[node]['layer'] = "application"
elif "models" in node:
self.graph.nodes[node]['layer'] = "domain"
elif "db" in node:
self.graph.nodes[node]['layer'] = "infrastructure"
else:
self.graph.nodes[node]['layer'] = "unknown"
# ==============================================================================
# 3. RULE DSL & ENGINE
# ==============================================================================
class ArchitectureRuleEngine:
"""
Loads rules from YAML/DSL and executes graph queries against the codebase.
"""
def __init__(self, graph: CodebaseGraph):
self.codebase = graph
self.rules = []
self.playbooks: Dict[str, RemediationPlaybook] = {}
def load_rules(self, config_path: str):
print(f"Loading rules from {config_path}...")
with open(config_path, 'r') as f:
config = yaml.safe_load(f)
self.rules = config.get('rules', [])
# Load playbooks
for p_id, p_data in config.get('remediation_playbooks', {}).items():
self.playbooks[p_id] = RemediationPlaybook(
steps=p_data['steps'],
automated=p_data.get('automated', False)
)
def validate(self) -> List[Violation]:
violations = []
for rule in self.rules:
violations.extend(self._check_rule(rule))
return violations
def _check_rule(self, rule: Dict) -> List[Violation]:
rule_type = rule['type']
if rule_type == 'layer_breach':
return self._check_layer_breach(rule)
elif rule_type == 'naming_convention':
return self._check_naming(rule)
# Add more rule types here (e.g., cyclical_dependency)
return []
def _check_layer_breach(self, rule: Dict) -> List[Violation]:
"""
Rule: Ensure nodes in 'from_layer' do not depend on 'to_layer'.
Graph Query: Traverse edges, check attributes of (u, v).
"""
violations = []
from_layer = rule['params']['from_layer']
to_layer = rule['params']['to_layer']
for u, v in self.codebase.graph.edges():
u_layer = self.codebase.graph.nodes[u].get('layer')
v_layer = self.codebase.graph.nodes[v].get('layer')
if u_layer == from_layer and v_layer == to_layer:
violations.append(Violation(
rule_id=rule['id'],
severity=rule['severity'],
source=u,
target=v,
message=f"Layer breach: '{u}' ({from_layer}) depends on '{v}' ({to_layer})",
remediation_playbook=rule.get('remediation_ref')
))
return violations
def _check_naming(self, rule: Dict) -> List[Violation]:
"""Example: Interfaces must start with 'I'."""
# Implementation omitted for brevity
return []
# ==============================================================================
# 4. REPORTING & CHANGE MANAGEMENT
# ==============================================================================
class ChangeManager:
"""
Generates reports and determines if the build should pass/fail.
"""
def __init__(self, violations: List[Violation], playbooks: Dict[str, RemediationPlaybook]):
self.violations = violations
self.playbooks = playbooks
def generate_report(self, output_format="TEXT"):
if output_format == "JSON":
return self._generate_json()
return self._generate_text()
def _generate_text(self):
report = ["="*50, "ARCHITECTURE CONFORMANCE REPORT", "="*50, ""]
if not self.violations:
report.append("✅ No architectural violations detected.")
return "\n".join(report)
report.append(f"❌ Found {len(self.violations)} violations:\n")
for v in self.violations:
report.append(f"[{v.severity}] Rule: {v.rule_id}")
report.append(f" Location: {v.source} -> {v.target}")
report.append(f" Issue: {v.message}")
# Append Remediation
if v.remediation_playbook and v.remediation_playbook in self.playbooks:
pb = self.playbooks[v.remediation_playbook]
report.append(" Remediation:")
for step in pb.steps:
report.append(f" - {step}")
report.append("")
return "\n".join(report)
def _generate_json(self):
# Structured output for CI tools (SonarQube, GitHub Checks, etc.)
return json.dumps([v.__dict__ for v in self.violations], indent=2)
# ==============================================================================
# 5. MAIN EXECUTION BLOCK
# ==============================================================================
def create_sample_project(target_dir="sample_code"):
"""Generates a dummy project to demonstrate the tool."""
os.makedirs(f"{target_dir}/services", exist_ok=True)
os.makedirs(f"{target_dir}/models", exist_ok=True)
# Violation: Service depends on API (wrong direction)
with open(f"{target_dir}/services/order_service.py", "w") as f:
f.write("from sample_code.api.order_api import create_order_endpoint")
os.makedirs(f"{target_dir}/api", exist_ok=True)
with open(f"{target_dir}/api/order_api.py", "w") as f:
f.write("# API Layer Code")
def create_sample_rules(filename="arch_rules.yaml"):
"""Generates a sample DSL config."""
config = {
"rules": [
{
"id": "ARCH-001",
"type": "layer_breach",
"severity": "CRITICAL",
"params": {
"from_layer": "application", # services
"to_layer": "interface" # api
},
"remediation_ref": "PB-DECOUPLE"
}
],
"remediation_playbooks": {
"PB-DECOUPLE": {
"automated": False,
"steps": [
"Introduce an Interface (ABC) in the Domain layer.",
"Invert the dependency: Application should depend on Abstraction, not Concrete Implementation.",
"Refactor the API layer to implement the Domain Interface."
]
}
}
}
with open(filename, "w") as f:
yaml.dump(config, f)
if __name__ == "__main__":
# 1. Setup Dummy Environment
PROJECT_DIR = "sample_code"
RULES_FILE = "arch_rules.yaml"
if not os.path.exists(PROJECT_DIR):
create_sample_project(PROJECT_DIR)
if not os.path.exists(RULES_FILE):
create_sample_rules(RULES_FILE)
# 2. Extract Metadata (Build the Graph)
codebase = CodebaseGraph(PROJECT_DIR)
codebase.build_graph()
# 3. Load Rules & Validate
engine = ArchitectureRuleEngine(codebase)
engine.load_rules(RULES_FILE)
violations = engine.validate()
# 4. Report & Remediation
manager = ChangeManager(violations, engine.playbooks)
print(manager.generate_report("TEXT"))
# 5. Change Management Gate
# If violations exist, exit with error code to fail the CI pipeline
if violations:
print("🛑 Architecture check failed. Blocking merge.")
exit(1)
else:
exit(0)