aedile 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
aedile/__init__.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "1.0.0"
aedile/__main__.py ADDED
@@ -0,0 +1,114 @@
1
+ import argparse
2
+ import os
3
+ import sys
4
+ from collections.abc import Sequence
5
+
6
+ from aedile.mcp.server import AedileMcpServer
7
+ from aedile.shared.config import Config
8
+
9
+
10
+ def compile_agent_rules(project_root: str) -> None:
11
+ """Compiles Aedile's strict engineering thinking ladder and layer guidelines
12
+
13
+ into .cursorrules and .claudeprompt system files.
14
+ """
15
+ config_path = os.path.join(project_root, "aedile.toml")
16
+ config = Config()
17
+ if os.path.exists(config_path):
18
+ try:
19
+ config = Config.load_from_file(config_path)
20
+ except Exception:
21
+ pass
22
+
23
+ # Build the rules template
24
+ layers_str = (
25
+ " -> ".join(config.layer_order)
26
+ if config.layer_order
27
+ else "None (No strict layers declared)"
28
+ )
29
+ src_dirs_str = ", ".join(config.src_dirs)
30
+
31
+ rules_content = f"""# AEDILE ENGINEERING INTELLIGENCE LAYER GUIDELINES
32
+ # Maintains architectural integrity & optimizes reasoning token efficiency.
33
+
34
+ You are pair programming with Aedile active. You MUST run all plans through Aedile's Engineering Ladder BEFORE generating code:
35
+
36
+ ---
37
+
38
+ ## 📐 AEDILE DECISION LADDER
39
+
40
+ 1. **Necessity**: Does this feature/logic actually need to exist? If not, delete it.
41
+ 2. **Reuse**: Does the codebase already contain this? Search first. **NEVER duplicate code.**
42
+ 3. **Standard Library**: Can the standard library (e.g. pathlib, re, json, datetime) solve it? Prefer it.
43
+ 4. **Existing Dependencies**: Can an existing project dependency solve it? Check pyproject.toml/requirements.txt.
44
+ 5. **Existing Abstractions**: Reuse existing project classes/functions instead of writing new wrappers.
45
+ 6. **Architecture Layering**: Respect our declared downward import flow rules.
46
+ 7. **Dependency Cycles**: Circular module imports are strictly prohibited.
47
+ 8. **Token Efficiency**: Plan to accomplish the task with minimal reasoning steps, files, and lines of code.
48
+
49
+ ---
50
+
51
+ ## 🏛️ REPOSITORY ARCHITECTURE SCHEMATICS
52
+
53
+ - **Project Name**: {config.project_name}
54
+ - **Source Folders**: {src_dirs_str}
55
+ - **Layer Flow Hierarchy (Downward Only)**: {layers_str}
56
+ - **Module Boundaries**: Symbols starting with private prefixes (e.g., '_') are private to their module.
57
+
58
+ ---
59
+
60
+ ## 🛠️ VERIFICATION
61
+
62
+ Before completing your implementation task, you MUST invoke the `aedile_verify_architecture` tool on your proposed file and import list to ensure you have not introduced dependency cycles or layer violations.
63
+ """
64
+
65
+ cursorrules_path = os.path.join(project_root, ".cursorrules")
66
+ claudeprompt_path = os.path.join(project_root, ".claudeprompt")
67
+
68
+ try:
69
+ with open(cursorrules_path, "w", encoding="utf-8") as f:
70
+ f.write(rules_content)
71
+ with open(claudeprompt_path, "w", encoding="utf-8") as f:
72
+ f.write(rules_content)
73
+ sys.stderr.write("[Aedile] Successfully compiled rules to .cursorrules and .claudeprompt\n")
74
+ except Exception as e:
75
+ sys.stderr.write(f"[Aedile] Error compiling rules: {e}\n")
76
+
77
+
78
+ def main(argv: Sequence[str] | None = None) -> int:
79
+ parser = argparse.ArgumentParser(
80
+ prog="aedile",
81
+ description="Aedile: Engineering Intelligence Layer & MCP Server for AI Coding Agents.",
82
+ )
83
+ subparsers = parser.add_subparsers(dest="command")
84
+
85
+ # compile-rules subcommand
86
+ subparsers.add_parser(
87
+ "compile-rules",
88
+ help="Compile Aedile's thinking ladder and project layers into .cursorrules / .claudeprompt templates.",
89
+ )
90
+
91
+ args = parser.parse_args(argv)
92
+
93
+ project_root = os.getcwd()
94
+
95
+ if args.command == "compile-rules":
96
+ compile_agent_rules(project_root)
97
+ return 0
98
+ else:
99
+ # Default behavior: Start MCP Server
100
+ sys.stderr.write("[Aedile] Launching Stdio MCP Server...\n")
101
+ server = AedileMcpServer(project_root)
102
+ try:
103
+ server.run()
104
+ except KeyboardInterrupt:
105
+ sys.stderr.write("[Aedile] Server stopped by user.\n")
106
+ return 0
107
+ except Exception as e:
108
+ sys.stderr.write(f"[Aedile] Server Error: {e}\n")
109
+ return 1
110
+ return 0
111
+
112
+
113
+ if __name__ == "__main__":
114
+ sys.exit(main())
aedile/core/graph.py ADDED
@@ -0,0 +1,228 @@
1
+ import math
2
+
3
+
4
+ class ArchitectureGraph:
5
+ def __init__(self) -> None:
6
+ self.nodes: set[str] = set()
7
+ # adjacency list for directed graph: node -> set of target nodes
8
+ self.edges: dict[str, set[str]] = {}
9
+ # reverse adjacency list for tracking incoming edges
10
+ self.incoming_edges: dict[str, set[str]] = {}
11
+ # metadata mapping from module name to file path
12
+ self.module_to_file: dict[str, str] = {}
13
+
14
+ def add_node(self, module: str, filepath: str = "") -> None:
15
+ self.nodes.add(module)
16
+ if module not in self.edges:
17
+ self.edges[module] = set()
18
+ if module not in self.incoming_edges:
19
+ self.incoming_edges[module] = set()
20
+ if filepath:
21
+ self.module_to_file[module] = filepath
22
+
23
+ def add_edge(self, from_module: str, to_module: str) -> None:
24
+ if from_module not in self.nodes:
25
+ self.add_node(from_module)
26
+ if to_module not in self.nodes:
27
+ self.add_node(to_module)
28
+
29
+ self.edges[from_module].add(to_module)
30
+ self.incoming_edges[to_module].add(from_module)
31
+
32
+ def remove_edge(self, from_module: str, to_module: str) -> None:
33
+ if from_module in self.edges:
34
+ self.edges[from_module].discard(to_module)
35
+ if to_module in self.incoming_edges:
36
+ self.incoming_edges[to_module].discard(from_module)
37
+
38
+ def get_dependencies(self, module: str) -> set[str]:
39
+ return self.edges.get(module, set())
40
+
41
+ def get_dependents(self, module: str) -> set[str]:
42
+ return self.incoming_edges.get(module, set())
43
+
44
+ def find_all_cycles(self) -> list[list[str]]:
45
+ """Finds all dependency cycles in the graph using Tarjan's Strongly Connected Components.
46
+ Returns a list of cycles, where each cycle is a list of modules forming a loop.
47
+ """
48
+ index = 0
49
+ indices: dict[str, int] = {}
50
+ lowlink: dict[str, int] = {}
51
+ on_stack: set[str] = set()
52
+ stack: list[str] = []
53
+ sccs: list[list[str]] = []
54
+
55
+ def strongconnect(node: str) -> None:
56
+ nonlocal index
57
+ indices[node] = index
58
+ lowlink[node] = index
59
+ index += 1
60
+ stack.append(node)
61
+ on_stack.add(node)
62
+
63
+ # Traverse neighbors
64
+ for neighbor in sorted(self.edges.get(node, set())):
65
+ if neighbor not in indices:
66
+ strongconnect(neighbor)
67
+ lowlink[node] = min(lowlink[node], lowlink[neighbor])
68
+ elif neighbor in on_stack:
69
+ lowlink[node] = min(lowlink[node], indices[neighbor])
70
+
71
+ # If node is a root node, pop the stack and generate an SCC
72
+ if lowlink[node] == indices[node]:
73
+ scc = []
74
+ while True:
75
+ w = stack.pop()
76
+ on_stack.remove(w)
77
+ scc.append(w)
78
+ if w == node:
79
+ break
80
+ # Only keep SCCs that are actual cycles
81
+ # An SCC is a cycle if its length > 1, or if it is length 1 and has a self-loop
82
+ if len(scc) > 1:
83
+ sccs.append(scc)
84
+ elif len(scc) == 1:
85
+ if scc[0] in self.edges.get(scc[0], set()):
86
+ sccs.append(scc)
87
+
88
+ for node in sorted(self.nodes):
89
+ if node not in indices:
90
+ strongconnect(node)
91
+
92
+ # Normalize order of each cycle to match execution path
93
+ normalized_cycles = []
94
+ for scc in sccs:
95
+ # Reconstruct path order using simple path-finding inside the SCC
96
+ normalized_cycles.append(self._order_cycle(scc))
97
+
98
+ return normalized_cycles
99
+
100
+ def _order_cycle(self, scc: list[str]) -> list[str]:
101
+ """Arranges the nodes in the SCC into a sequence representing the cycle order."""
102
+ scc_set = set(scc)
103
+ if not scc:
104
+ return []
105
+
106
+ start = sorted(scc)[0]
107
+ ordered = [start]
108
+ visited = {start}
109
+
110
+ curr = start
111
+ while len(ordered) < len(scc):
112
+ next_node = None
113
+ for neighbor in sorted(self.edges.get(curr, set())):
114
+ if neighbor in scc_set and neighbor not in visited:
115
+ next_node = neighbor
116
+ break
117
+ if next_node:
118
+ ordered.append(next_node)
119
+ visited.add(next_node)
120
+ curr = next_node
121
+ else:
122
+ break
123
+ return ordered
124
+
125
+ def find_shortest_path(self, start: str, end: str) -> list[str] | None:
126
+ """Finds the shortest path between start and end modules using BFS."""
127
+ if start not in self.nodes or end not in self.nodes:
128
+ return None
129
+ if start == end:
130
+ return [start]
131
+
132
+ queue: list[list[str]] = [[start]]
133
+ visited: set[str] = {start}
134
+
135
+ while queue:
136
+ path = queue.pop(0)
137
+ node = path[-1]
138
+
139
+ for neighbor in self.edges.get(node, set()):
140
+ if neighbor == end:
141
+ return path + [end]
142
+ if neighbor not in visited:
143
+ visited.add(neighbor)
144
+ queue.append(path + [neighbor])
145
+ return None
146
+
147
+ def export_mermaid(self) -> str:
148
+ """Generates a Mermaid class/dependency diagram representation of the graph."""
149
+ lines = ["graph TD"]
150
+ # Declare nodes to style them
151
+ for node in sorted(self.nodes):
152
+ safe_id = node.replace(".", "_")
153
+ lines.append(f' {safe_id}["{node}"]')
154
+
155
+ # Declare edges
156
+ for from_node in sorted(self.edges.keys()):
157
+ from_id = from_node.replace(".", "_")
158
+ for to_node in sorted(self.edges[from_node]):
159
+ to_id = to_node.replace(".", "_")
160
+ lines.append(f" {from_id} --> {to_id}")
161
+
162
+ return "\n".join(lines)
163
+
164
+ def export_svg(self) -> str:
165
+ """Generates a beautiful SVG of the dependency graph using a circular layout."""
166
+ if not self.nodes:
167
+ return '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200"><text x="20" y="100">Empty Graph</text></svg>'
168
+
169
+ # Circular layout calculation
170
+ nodes_list = sorted(list(self.nodes))
171
+ num_nodes = len(nodes_list)
172
+ radius = min(400, 50 * num_nodes)
173
+ center_x = radius + 150
174
+ center_y = radius + 150
175
+ svg_width = center_x * 2
176
+ svg_height = center_y * 2
177
+
178
+ node_positions: dict[str, tuple[float, float]] = {}
179
+ for i, node in enumerate(nodes_list):
180
+ angle = (2 * math.pi * i) / num_nodes
181
+ x = center_x + radius * math.cos(angle)
182
+ y = center_y + radius * math.sin(angle)
183
+ node_positions[node] = (x, y)
184
+
185
+ svg_lines = [
186
+ f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {svg_width} {svg_height}" width="100%" height="100%" style="background-color: #0d1117; font-family: sans-serif;">',
187
+ " <defs>",
188
+ ' <marker id="arrow" viewBox="0 0 10 10" refX="24" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse">',
189
+ ' <path d="M 0 0 L 10 5 L 0 10 z" fill="#58a6ff" />',
190
+ " </marker>",
191
+ " </defs>",
192
+ ' <rect width="100%" height="100%" fill="#0d1117" />',
193
+ ]
194
+
195
+ # Draw edges
196
+ for from_node, targets in self.edges.items():
197
+ fx, fy = node_positions[from_node]
198
+ for to_node in targets:
199
+ tx, ty = node_positions[to_node]
200
+ # Draw edge lines
201
+ svg_lines.append(
202
+ f' <line x1="{fx:.1f}" y1="{fy:.1f}" x2="{tx:.1f}" y2="{ty:.1f}" '
203
+ f'stroke="#30363d" stroke-width="1.5" marker-end="url(#arrow)" />'
204
+ )
205
+
206
+ # Draw nodes
207
+ for node, (x, y) in node_positions.items():
208
+ # Styling nodes based on common levels (e.g. shared vs core)
209
+ fill_color = "#1f6feb"
210
+ if "shared" in node:
211
+ fill_color = "#238636"
212
+ elif "cli" in node:
213
+ fill_color = "#8957e5"
214
+ elif "rules" in node:
215
+ fill_color = "#da3633"
216
+
217
+ svg_lines.append(
218
+ f' <circle cx="{x:.1f}" cy="{y:.1f}" r="12" fill="{fill_color}" '
219
+ f'stroke="#c9d1d9" stroke-width="1.5" />'
220
+ )
221
+ # Add labels offset
222
+ svg_lines.append(
223
+ f' <text x="{x:.1f}" y="{y - 18:.1f}" font-size="12" fill="#c9d1d9" '
224
+ f'text-anchor="middle" font-weight="bold">{node}</text>'
225
+ )
226
+
227
+ svg_lines.append("</svg>")
228
+ return "\n".join(svg_lines)
aedile/core/models.py ADDED
@@ -0,0 +1,86 @@
1
+ from dataclasses import dataclass, field
2
+ from typing import Any
3
+
4
+
5
+ @dataclass
6
+ class Import:
7
+ module: str # The fully-qualified module imported (e.g. 'aedile.core.scanner')
8
+ names: list[
9
+ str
10
+ ] # Specific symbols imported (e.g. ['Scanner']) or empty for full module imports
11
+ line: int # Line number of the import statement
12
+ alias: str | None = None # Alias if imported as (e.g. 'import x as y')
13
+ is_relative: bool = False # Whether it's a relative import
14
+
15
+
16
+ @dataclass
17
+ class Symbol:
18
+ name: str # Symbol name (e.g. 'Scanner')
19
+ kind: str # 'class', 'function', 'variable', 'method'
20
+ line: int # Starting line number
21
+ end_line: int # Ending line number
22
+ docstring: str | None = None
23
+ is_private: bool = False # Derived from name prefix (e.g. starts with '_')
24
+
25
+
26
+ @dataclass
27
+ class SourceFile:
28
+ filepath: str # Absolute file path
29
+ relative_path: str # Path relative to project root
30
+ file_hash: str # SHA256 of contents (for incremental scanning)
31
+ file_size: int # Size in bytes
32
+ language: str # 'python', 'javascript', etc.
33
+ imports: list[Import] = field(default_factory=list)
34
+ symbols: list[Symbol] = field(default_factory=list)
35
+
36
+
37
+ @dataclass
38
+ class Violation:
39
+ rule_name: str # Unique name of the violated rule
40
+ filepath: str # File where the violation occurred
41
+ relative_path: str # Relative file path
42
+ line: int # Line number of the violation
43
+ message: str # Description of the violation
44
+ offending_symbol: str | None = None
45
+ confidence: float = 1.0 # Confidence score (0.0 to 1.0)
46
+ severity: str = "error" # "error" or "warning"
47
+
48
+ def to_dict(self) -> dict[str, Any]:
49
+ return {
50
+ "rule_name": self.rule_name,
51
+ "filepath": self.filepath,
52
+ "relative_path": self.relative_path,
53
+ "line": self.line,
54
+ "message": self.message,
55
+ "offending_symbol": self.offending_symbol,
56
+ "confidence": self.confidence,
57
+ "severity": self.severity,
58
+ }
59
+
60
+
61
+ @dataclass
62
+ class DuplicateGroup:
63
+ similarity: float
64
+ files: list[str] # Paths to similar files
65
+ common_patterns: list[str]
66
+
67
+
68
+ @dataclass
69
+ class ProjectMetrics:
70
+ total_files: int = 0
71
+ total_loc: int = 0
72
+ total_violations: int = 0
73
+ risk_score: float = 0.0 # Weighted architecture risk score (0 to 100)
74
+ dependency_cycles: int = 0
75
+ layer_violations: int = 0
76
+ dead_symbols: int = 0
77
+ duplicate_groups: int = 0
78
+
79
+
80
+ @dataclass
81
+ class Report:
82
+ project_name: str
83
+ violations: list[Violation]
84
+ metrics: ProjectMetrics
85
+ generated_at: str
86
+ scan_time_seconds: float
@@ -0,0 +1,90 @@
1
+ from typing import Any
2
+
3
+ from aedile.shared.config import Config
4
+
5
+
6
+ class ReasoningOptimizer:
7
+ def __init__(self, config: Config) -> None:
8
+ self.config = config
9
+
10
+ def optimize_plan(
11
+ self,
12
+ query: str,
13
+ similar_symbols: list[dict[str, Any]],
14
+ stdlib_recs: list[dict[str, Any]],
15
+ dep_recs: list[str],
16
+ ) -> str:
17
+ """Analyzes the proposed feature request against codebase intelligence and returns
18
+
19
+ a formatted engineering guidance review block for the AI agent.
20
+ """
21
+ sections = []
22
+ sections.append("### 🛡️ AEDILE ENGINEERING INTELLIGENCE REVIEW")
23
+ sections.append(
24
+ "Before writing any code, optimize your implementation plan using this guidance:"
25
+ )
26
+
27
+ has_redundancy = False
28
+
29
+ # 1. Existing Codebase Abstractions
30
+ if similar_symbols:
31
+ has_redundancy = True
32
+ sections.append("\n#### 🔍 Codebase Reuse Opportunities")
33
+ sections.append(
34
+ "The repository already contains similar functionalities. **Do NOT duplicate them**:"
35
+ )
36
+ for sym in similar_symbols:
37
+ sections.append(
38
+ f"- **{sym['name']}** ({sym['kind']}) in [{sym['relative_path']}](file:///{sym['relative_path']}) on line {sym['line']} (Confidence: {sym['score']})"
39
+ )
40
+ sections.append(
41
+ "👉 *Recommendation*: Import and reuse these existing functions/classes instead of creating new ones."
42
+ )
43
+
44
+ # 2. Standard Library Matches
45
+ if stdlib_recs:
46
+ has_redundancy = True
47
+ sections.append("\n#### 📦 Python Standard Library Solutions")
48
+ sections.append(
49
+ "You can solve this using built-in capabilities without extra dependencies:"
50
+ )
51
+ for rec in stdlib_recs:
52
+ sections.append(f"- **{rec['module']}**: {rec['description']}")
53
+ sections.append("👉 *Recommendation*: Use the standard library imports shown above.")
54
+
55
+ # 3. Third-party Dependency Reuse
56
+ if dep_recs:
57
+ has_redundancy = True
58
+ sections.append("\n#### 🔌 Active Project Dependencies")
59
+ sections.append(
60
+ "The project already declares these third-party dependencies. Reuse them:"
61
+ )
62
+ for dep in dep_recs:
63
+ sections.append(f"- **{dep}** (found in project configurations)")
64
+ sections.append(
65
+ "👉 *Recommendation*: Reuse these pre-installed packages; do not install alternatives or write custom mock implementations."
66
+ )
67
+
68
+ # 4. Token & Architecture Efficiency Guidelines
69
+ sections.append("\n#### ⚙️ Reasoning & Context Optimization")
70
+ sections.append(
71
+ "To minimize token usage and architectural entropy, structure your implementation plan as follows:"
72
+ )
73
+
74
+ if has_redundancy:
75
+ sections.append(
76
+ "- [ ] **Zero Code Generation**: Check if you can complete this task by writing 0 lines of new logic and simply linking/exposing the existing modules."
77
+ )
78
+ else:
79
+ sections.append(
80
+ "- [ ] **Simplicity First**: Implement the minimum necessary logic. Choose a single-module implementation over multi-file setups where possible."
81
+ )
82
+
83
+ sections.append(
84
+ "- [ ] **Fewer Tool Calls**: Plan to accomplish this modification in at most 1 to 2 tool calls. Minimize intermediate file writes."
85
+ )
86
+ sections.append(
87
+ "- [ ] **Architectural Integrity**: Ensure any new imports respect the project's layer order constraints."
88
+ )
89
+
90
+ return "\n".join(sections)