# arch-checker: Codebase-Wide Architectural Conformance Checker
# ========================================================
#
# Overview
# --------
# This is a complete, standalone Python codebase for an architectural conformance
# checker using graph-based queries. It supports:
# - **Metadata Extraction**: Multi-language code parsing with Tree-sitter to build
# a Code Property Graph (CPG) in-memory using NetworkX.
# - **Rule DSL**: YAML-based Domain-Specific Language for defining graph queries
# (using Cypher-inspired patterns translated to NetworkX traversals and matchers).
# - **Remediation Playbooks**: YAML-defined playbooks with automated fixes (e.g.,
# refactor templates, git patches) and manual guidance.
# - **Change Management**: Git integration to track architectural drift across
# commits, generate reports, and enforce via pre-commit hooks.
#
# Supported Languages: Python, JavaScript, Java, TypeScript, C++ (extensible).
# Dependencies: `pip install networkx tree-sitter tree-sitter-python tree-sitter-javascript ... pygithub pyyaml gitpython`
#
# Full install:
# pip install networkx tree-sitter tree-sitter-python tree-sitter-javascript tree-sitter-java tree-sitter-typescript tree-sitter-cpp pyyaml gitpython jinja2
#
# Usage:
# 1. Place `rules.yaml` and `playbooks.yaml` in project root.
# 2. Run `python main.py check` to validate.
# 3. Run `python main.py remediate` to apply fixes.
# 4. Run `python main.py drift --since HEAD~10` for change reports.
# 5. Pre-commit hook: `.git/hooks/pre-commit` -> `python main.py check --fail-fast`
#
# Project Structure:
# ├── main.py # CLI entrypoint
# ├── extractor.py # Graph extraction
# ├── dsl.py # Rule DSL parser & matcher
# ├── checker.py # Conformance checker
# ├── remediation.py # Playbook executor
# ├── change_mgmt.py # Git-based drift detection
# ├── graph_utils.py # Shared graph helpers
# ├── grammars/ # Tree-sitter grammars (auto-loaded)
# ├── examples/ # Sample codebase
# ├── rules.yaml # Sample rules
# └── playbooks.yaml # Sample playbooks
main.py
python
#!/usr/bin/env python3
import argparse
import sys
import yaml
from pathlib import Path
from extractor import extract_graph
from checker import check_conformance
from remediation import apply_remediations
from change_mgmt import detect_drift
from dsl import load_rules
def main():
parser = argparse.ArgumentParser(description="Architectural Conformance Checker")
subparsers = parser.add_subparsers(dest='command', required=True)
# Check command
check_p = subparsers.add_parser('check', help='Run conformance checks')
check_p.add_argument('root', nargs='?', default='.', help='Codebase root')
check_p.add_argument('--rules', default='rules.yaml', help='Rules file')
check_p.add_argument('--fail-fast', action='store_true', help='Exit on first violation')
# Remediate command
rem_p = subparsers.add_parser('remediate', help='Apply remediation playbooks')
rem_p.add_argument('root', nargs='?', default='.', help='Codebase root')
rem_p.add_argument('--playbooks', default='playbooks.yaml', help='Playbooks file')
rem_p.add_argument('--auto-apply', action='store_true', help='Auto-apply safe fixes')
# Drift command
drift_p = subparsers.add_parser('drift', help='Detect architectural drift')
drift_p.add_argument('root', nargs='?', default='.', help='Codebase root')
drift_p.add_argument('--since', default='HEAD~1', help='Git ref for baseline')
drift_p.add_argument('--output', '-o', help='Report output file')
args = parser.parse_args()
root = Path(args.root).resolve()
if not root.is_dir():
print(f"Error: {root} is not a directory", file=sys.stderr)
sys.exit(1)
if args.command == 'check':
rules = load_rules(args.rules)
graph = extract_graph(root)
violations = check_conformance(graph, rules)
if violations:
for v in violations:
print(f"VIOLATION: {v['name']} at {v['nodes']}")
sys.exit(1 if args.fail_fast else 0)
print("All checks passed!")
elif args.command == 'remediate':
playbooks = yaml.safe_load(Path(args.playbooks).read_text())
graph = extract_graph(root)
violations = check_conformance(graph, load_rules('rules.yaml')) # Re-run checks
apply_remediations(root, violations, playbooks, args.auto_apply)
elif args.command == 'drift':
baseline_graph = extract_graph(root, baseline=args.since)
current_graph = extract_graph(root)
drift_report = detect_drift(baseline_graph, current_graph)
output = args.output or 'drift-report.yaml'
with open(output, 'w') as f:
yaml.dump(drift_report, f)
print(f"Drift report saved to {output}")
if __name__ == '__main__':
main()
extractor.py
python
import networkx as nx
from pathlib import Path
from tree_sitter import Language, Parser
import tree_sitter_python as tspython # Similarly for other langs
# Note: Dynamically load grammars for JS, Java, etc.
# Language configs
LANGS = {
'.py': Language(tspython.language(), 'python'),
'.js': Language('path/to/tree_sitter_javascript.so', 'javascript'), # Pre-build .so
# Add .java, .ts, .cpp similarly
}
def extract_graph(root: Path, baseline: str = None) -> nx.MultiDiGraph:
"""
Extract Code Property Graph (CPG) from codebase.
Nodes: File, Namespace, Class, Function, Call, Variable, etc.
Edges: contains, calls, uses, imports, extends.
"""
graph = nx.MultiDiGraph()
root = Path(root)
for file_path in root.rglob('*'):
if not file_path.is_file():
continue
ext = file_path.suffix.lower()
if ext not in LANGS:
continue # Skip unsupported
parser = Parser()
parser.set_language(LANGS[ext])
with open(file_path, 'rb') as f:
tree = parser.parse(f.read())
# Add File node
file_id = f"file://{file_path}"
graph.add_node(file_id, type='File', path=str(file_path))
# Traverse AST to extract entities
extract_ast(graph, tree.root_node, file_id, parent_id=file_id)
return graph
def extract_ast(graph: nx.MultiDiGraph, node, parent_id: str, file_id: str, depth=0):
"""Recursive AST to CPG extraction (simplified)."""
if depth > 10: # Prevent deep recursion
return
node_id = f"{file_id}#{node.start_byte}-{node.end_byte}"
attrs = {
'type': node.type,
'text': node.text.decode(),
'start': node.start_point,
'end': node.end_point
}
graph.add_node(node_id, **attrs)
graph.add_edge(parent_id, node_id, type='contains')
# Entity-specific extraction
if node.type == 'function_definition': # Python example
name = node.child_by_field_name('name').text.decode() if node.named_children else 'anon'
graph.nodes[node_id]['entity'] = 'Function'
graph.nodes[node_id]['name'] = name
elif node.type == 'class_definition':
name = node.child_by_field_name('name').text.decode()
graph.nodes[node_id]['entity'] = 'Class'
graph.nodes[node_id]['name'] = name
elif node.type == 'call':
callee = node.child_by_field_name('function').text.decode()
graph.nodes[node_id]['entity'] = 'Call'
graph.nodes[node_id]['callee'] = callee
# Link to potential callee Function (symbol resolution simplified)
for func in nx.ancestors(graph, node_id):
if graph.nodes[func].get('entity') == 'Function' and callee in graph.nodes[func].get('name', ''):
graph.add_edge(func, node_id, type='calls')
# Imports, variables, etc. similarly...
for child in node.children:
extract_ast(graph, child, node_id, file_id, depth + 1)
graph_utils.py
python
import networkx as nx
def find_pattern(graph: nx.MultiDiGraph, pattern: dict) -> list[dict]:
"""
Match Cypher-like patterns on graph.
Example pattern: {'Function': {'name': 'db_query'}, '->calls->': 'Call'}
Returns matching node sets.
"""
matches = []
start_type = list(pattern.keys())[0]
start_nodes = [n for n, d in graph.nodes(data=True) if d.get('entity') == start_type]
for start in start_nodes:
if props_match(graph.nodes[start], pattern[start_type]):
path = traverse_pattern(graph, start, pattern)
if path:
matches.append({'nodes': path, 'edges': list(graph.in_edges(path))})
return matches
def props_match(node_data: dict, props: dict) -> bool:
return all(node_data.get(k) == v for k, v in props.items())
def traverse_pattern(graph: nx.MultiDiGraph, start: str, pattern: dict, current_path: list = None) -> list:
if current_path is None:
current_path = [start]
if len(pattern) == 1:
return current_path
# Extract next edge type and target
edge_key = next(k for k in pattern if '->' in k)
target_type = list(pattern.keys())[-1] if edge_key == list(pattern)[-2] else None
edge_type = edge_key.replace('->', '').strip()
neighbors = [n for _, n, edata in graph.out_edges(start, data=True) if edata.get('type') == edge_type]
for neigh in neighbors:
if target_type and graph.nodes[neigh].get('entity') == target_type:
new_pattern = {k: v for k, v in pattern.items() if k != edge_key and k != target_type}
path = traverse_pattern(graph, neigh, new_pattern, current_path + [neigh])
if path:
return path
return None
dsl.py
python
import yaml
from pathlib import Path
from graph_utils import find_pattern, props_match
def load_rules(rules_file: str):
"""Load YAML DSL rules."""
with open(rules_file) as f:
raw_rules = yaml.safe_load(f)['rules']
rules = []
for r in raw_rules:
rule = {
'name': r['name'],
'severity': r.get('severity', 'error'),
'pattern': r['pattern'], # e.g., {'Service': {}, '->calls->': 'Function', 'Function': {'name': {'$regex': '^db_'}}}
'message': r['message'],
'remediation': r.get('remediation') # playbook ref
}
rules.append(rule)
return rules
checker.py
python
from dsl import load_rules
from graph_utils import find_pattern
def check_conformance(graph, rules):
violations = []
for rule in rules:
matches = find_pattern(graph, rule['pattern'])
for match in matches:
violations.append({
**rule,
'nodes': [str(n) for n in match['nodes']],
'match': match
})
return violations
remediation.py
python
import yaml
from pathlib import Path
from jinja2 import Template
import git # gitpython
def apply_remediations(root: Path, violations: list, playbooks: dict, auto_apply: bool):
repo = git.Repo(root)
for v in violations:
playbook_key = v.get('remediation')
if not playbook_key:
print(f"Manual fix needed for {v['name']}: {v['message']}")
continue
playbook = playbooks['playbooks'][playbook_key]
action = playbook['action']
if action == 'refactor':
template = Template(playbook['template'])
fixed_code = template.render(violation=v)
# Write to file (safe check if auto_apply)
if auto_apply and playbook.get('safe', False):
file_path = v['nodes'][0].split('#')[0].replace('file://', '')
Path(file_path).write_text(fixed_code)
repo.index.add([file_path])
repo.index.commit(f"Auto-fix: {v['name']}")
print(f"Applied auto-fix to {file_path}")
else:
print(f"Template fix for {v['name']}: {fixed_code}")
elif action == 'delete':
if auto_apply:
node_file = v['nodes'][0].split('#')[0].replace('file://', '')
Path(node_file).unlink()
print(f"Deleted violating node: {node_file}")