repodna-engine 1.0.1__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.
- repodna/__init__.py +3 -0
- repodna/__main__.py +10 -0
- repodna/advisor/__init__.py +17 -0
- repodna/advisor/engine.py +502 -0
- repodna/advisor/models.py +101 -0
- repodna/agent/__init__.py +87 -0
- repodna/agent/context.py +558 -0
- repodna/agent/deltas.py +198 -0
- repodna/agent/evidence.py +134 -0
- repodna/agent/expansion.py +447 -0
- repodna/agent/localization.py +518 -0
- repodna/agent/models.py +695 -0
- repodna/agent/patch.py +378 -0
- repodna/agent/postflight.py +278 -0
- repodna/agent/preflight.py +336 -0
- repodna/agent/ranking.py +318 -0
- repodna/agent/repo_map.py +392 -0
- repodna/agent/safety.py +111 -0
- repodna/agent/service.py +574 -0
- repodna/agent/sessions.py +264 -0
- repodna/agent/task.py +660 -0
- repodna/agent/telemetry.py +101 -0
- repodna/agent/token_budget.py +231 -0
- repodna/api/__init__.py +1 -0
- repodna/api/agent_routes.py +248 -0
- repodna/api/app.py +2904 -0
- repodna/benchmarks/__init__.py +29 -0
- repodna/benchmarks/baselines.py +126 -0
- repodna/benchmarks/budget_bench.py +162 -0
- repodna/benchmarks/engine.py +418 -0
- repodna/benchmarks/evaluator.py +310 -0
- repodna/benchmarks/metrics.py +206 -0
- repodna/benchmarks/models.py +194 -0
- repodna/benchmarks/scalability.py +166 -0
- repodna/brain/__init__.py +46 -0
- repodna/brain/evidence.py +276 -0
- repodna/brain/extractor.py +1207 -0
- repodna/brain/indexer.py +766 -0
- repodna/brain/models.py +275 -0
- repodna/brain/multilang_extractors.py +889 -0
- repodna/brain/retrieval.py +469 -0
- repodna/brain/tracer.py +203 -0
- repodna/cli/__init__.py +1 -0
- repodna/cli/__main__.py +10 -0
- repodna/cli/agent_cmd.py +228 -0
- repodna/cli/installer.py +590 -0
- repodna/cli/main.py +2173 -0
- repodna/cli/plugin_cmd.py +130 -0
- repodna/cli/workspace_cmd.py +211 -0
- repodna/context/__init__.py +9 -0
- repodna/context/builder.py +379 -0
- repodna/context/models.py +133 -0
- repodna/contract/__init__.py +39 -0
- repodna/contract/evaluator.py +318 -0
- repodna/contract/loader.py +260 -0
- repodna/contract/models.py +185 -0
- repodna/core/__init__.py +1 -0
- repodna/core/analyzer.py +1424 -0
- repodna/diff/__init__.py +35 -0
- repodna/diff/engine.py +332 -0
- repodna/diff/models.py +117 -0
- repodna/diff/snapshot.py +248 -0
- repodna/ecosystem/__init__.py +27 -0
- repodna/ecosystem/contracts.py +129 -0
- repodna/ecosystem/doctor.py +253 -0
- repodna/git_insights/__init__.py +1 -0
- repodna/git_insights/analyzer.py +273 -0
- repodna/graph/__init__.py +1 -0
- repodna/graph/engine.py +562 -0
- repodna/guardian/__init__.py +17 -0
- repodna/guardian/engine.py +369 -0
- repodna/guardian/models.py +104 -0
- repodna/history/__init__.py +40 -0
- repodna/history/cache.py +240 -0
- repodna/history/diff.py +394 -0
- repodna/history/engine.py +557 -0
- repodna/history/evidence.py +160 -0
- repodna/history/models.py +258 -0
- repodna/history/timeline.py +164 -0
- repodna/intelligence/__init__.py +33 -0
- repodna/intelligence/models.py +165 -0
- repodna/intelligence/service.py +570 -0
- repodna/live/__init__.py +94 -0
- repodna/live/alerts.py +443 -0
- repodna/live/coordinator.py +351 -0
- repodna/live/diff.py +444 -0
- repodna/live/events.py +471 -0
- repodna/live/filtering.py +329 -0
- repodna/live/history.py +637 -0
- repodna/live/models.py +505 -0
- repodna/live/observer.py +653 -0
- repodna/live/reconciliation.py +253 -0
- repodna/live/session.py +1547 -0
- repodna/mcp/__init__.py +5 -0
- repodna/mcp/__main__.py +6 -0
- repodna/mcp/agent_tools.py +258 -0
- repodna/mcp/server.py +3283 -0
- repodna/mcp/workspace_tools.py +200 -0
- repodna/parsers/__init__.py +13 -0
- repodna/parsers/base.py +126 -0
- repodna/parsers/capabilities.py +361 -0
- repodna/parsers/project_metadata.py +232 -0
- repodna/parsers/resolver.py +621 -0
- repodna/parsers/treesitter_parser.py +830 -0
- repodna/passport/__init__.py +64 -0
- repodna/passport/generator.py +546 -0
- repodna/passport/migrator.py +139 -0
- repodna/passport/models.py +224 -0
- repodna/passport/validator.py +143 -0
- repodna/performance/__init__.py +89 -0
- repodna/performance/cache.py +1584 -0
- repodna/performance/identity.py +341 -0
- repodna/performance/incremental.py +317 -0
- repodna/performance/models.py +157 -0
- repodna/performance/parallel.py +291 -0
- repodna/plugins/__init__.py +47 -0
- repodna/plugins/evaluator.py +334 -0
- repodna/plugins/models.py +113 -0
- repodna/plugins/validator.py +256 -0
- repodna/quality/__init__.py +91 -0
- repodna/quality/complexity.py +352 -0
- repodna/quality/config.py +159 -0
- repodna/quality/debt.py +73 -0
- repodna/quality/duplicates.py +330 -0
- repodna/quality/engine.py +282 -0
- repodna/quality/impact.py +198 -0
- repodna/quality/models.py +427 -0
- repodna/quality/rules.py +364 -0
- repodna/quality/sarif.py +107 -0
- repodna/quality/security_signals.py +278 -0
- repodna/quality/test_mapping.py +271 -0
- repodna/quality/unused.py +201 -0
- repodna/reports/__init__.py +1 -0
- repodna/reports/exporter.py +374 -0
- repodna/rules/__init__.py +1 -0
- repodna/rules/health.py +436 -0
- repodna/schemas/__init__.py +1 -0
- repodna/schemas/models.py +348 -0
- repodna/security/__init__.py +1 -0
- repodna/security/safe_yaml.py +81 -0
- repodna/security/validators.py +583 -0
- repodna/skills/__init__.py +0 -0
- repodna/skills/repodna/SKILL.md +59 -0
- repodna/skills/repodna/__init__.py +0 -0
- repodna/skills/repodna/examples/workflows.md +85 -0
- repodna/skills/repodna/references/architecture-rules.md +26 -0
- repodna/storage/__init__.py +1 -0
- repodna/storage/workspace.py +199 -0
- repodna/webui/__init__.py +1 -0
- repodna/webui/assets/DependencyGraph-km_Qo-nG.js +43 -0
- repodna/webui/assets/HealthReportView-WVL39aNO.js +1 -0
- repodna/webui/assets/index-ByZ5e5pe.js +506 -0
- repodna/webui/assets/index-CDj3e8hw.css +1 -0
- repodna/webui/index.html +21 -0
- repodna/workspace/__init__.py +131 -0
- repodna/workspace/compatibility.py +317 -0
- repodna/workspace/context.py +175 -0
- repodna/workspace/contracts.py +369 -0
- repodna/workspace/federation.py +411 -0
- repodna/workspace/identity.py +202 -0
- repodna/workspace/impact.py +111 -0
- repodna/workspace/manifest.py +266 -0
- repodna/workspace/models.py +461 -0
- repodna/workspace/packages.py +494 -0
- repodna/workspace/policies.py +142 -0
- repodna/workspace/services.py +238 -0
- repodna/workspace/topology.py +316 -0
- repodna_engine-1.0.1.dist-info/METADATA +129 -0
- repodna_engine-1.0.1.dist-info/RECORD +173 -0
- repodna_engine-1.0.1.dist-info/WHEEL +5 -0
- repodna_engine-1.0.1.dist-info/entry_points.txt +2 -0
- repodna_engine-1.0.1.dist-info/licenses/LICENSE +21 -0
- repodna_engine-1.0.1.dist-info/top_level.txt +1 -0
repodna/__init__.py
ADDED
repodna/__main__.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""RepoDNA Refactoring Advisor package."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from repodna.advisor.engine import RefactoringAdvisorEngine
|
|
6
|
+
from repodna.advisor.models import (
|
|
7
|
+
AdvisorCategory,
|
|
8
|
+
RefactoringAdvisorReport,
|
|
9
|
+
RefactoringRecommendation,
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
__all__ = [
|
|
13
|
+
"AdvisorCategory",
|
|
14
|
+
"RefactoringAdvisorEngine",
|
|
15
|
+
"RefactoringAdvisorReport",
|
|
16
|
+
"RefactoringRecommendation",
|
|
17
|
+
]
|
|
@@ -0,0 +1,502 @@
|
|
|
1
|
+
"""Refactoring Advisor Engine for RepoDNA.
|
|
2
|
+
|
|
3
|
+
Produces deterministic, evidence-based architectural refactoring advice across four categories:
|
|
4
|
+
1. Circular dependency reduction
|
|
5
|
+
2. High coupling module review
|
|
6
|
+
3. Layer boundary improvement
|
|
7
|
+
4. Oversized architectural hub review
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import hashlib
|
|
13
|
+
from typing import TYPE_CHECKING
|
|
14
|
+
|
|
15
|
+
from repodna.advisor.models import (
|
|
16
|
+
AdvisorCategory,
|
|
17
|
+
RefactoringAdvisorReport,
|
|
18
|
+
RefactoringRecommendation,
|
|
19
|
+
)
|
|
20
|
+
from repodna.schemas.models import AnalysisResult, DependencyEdge, FileNode
|
|
21
|
+
|
|
22
|
+
if TYPE_CHECKING:
|
|
23
|
+
from repodna.contract.models import ArchitectureContract
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class RefactoringAdvisorEngine:
|
|
27
|
+
"""Deterministic, evidence-grounded architectural refactoring advisor."""
|
|
28
|
+
|
|
29
|
+
def __init__(
|
|
30
|
+
self,
|
|
31
|
+
analysis: AnalysisResult,
|
|
32
|
+
contract: ArchitectureContract | None = None,
|
|
33
|
+
) -> None:
|
|
34
|
+
self.analysis = analysis
|
|
35
|
+
self.contract = contract
|
|
36
|
+
self.file_map: dict[str, FileNode] = {f.id: f for f in analysis.files}
|
|
37
|
+
self.edge_map: dict[tuple[str, str], list[DependencyEdge]] = {}
|
|
38
|
+
for edge in analysis.edges:
|
|
39
|
+
pair = (edge.source, edge.target)
|
|
40
|
+
self.edge_map.setdefault(pair, []).append(edge)
|
|
41
|
+
|
|
42
|
+
def generate_report(
|
|
43
|
+
self,
|
|
44
|
+
category_filter: AdvisorCategory | None = None,
|
|
45
|
+
min_severity: str | None = None,
|
|
46
|
+
) -> RefactoringAdvisorReport:
|
|
47
|
+
"""Generates comprehensive, deduplicated refactoring advice."""
|
|
48
|
+
recommendations: list[RefactoringRecommendation] = []
|
|
49
|
+
|
|
50
|
+
# 1. Circular dependency reduction
|
|
51
|
+
recs_cycle = self._analyze_circular_dependencies()
|
|
52
|
+
recommendations.extend(recs_cycle)
|
|
53
|
+
|
|
54
|
+
# 2. High coupling module review
|
|
55
|
+
recs_coupling = self._analyze_high_coupling()
|
|
56
|
+
recommendations.extend(recs_coupling)
|
|
57
|
+
|
|
58
|
+
# 3. Layer boundary improvement
|
|
59
|
+
recs_layer = self._analyze_layer_boundaries()
|
|
60
|
+
recommendations.extend(recs_layer)
|
|
61
|
+
|
|
62
|
+
# 4. Oversized architectural hub review
|
|
63
|
+
recs_hub = self._analyze_oversized_hubs()
|
|
64
|
+
recommendations.extend(recs_hub)
|
|
65
|
+
|
|
66
|
+
# Deduplicate
|
|
67
|
+
deduped = self._deduplicate_recommendations(recommendations)
|
|
68
|
+
|
|
69
|
+
# Filter
|
|
70
|
+
filtered = self._apply_filters(deduped, category_filter, min_severity)
|
|
71
|
+
|
|
72
|
+
# Sort: critical -> high -> medium -> low
|
|
73
|
+
severity_order = {"critical": 0, "high": 1, "medium": 2, "low": 3}
|
|
74
|
+
filtered.sort(
|
|
75
|
+
key=lambda r: (
|
|
76
|
+
severity_order.get(r.severity, 4),
|
|
77
|
+
r.category.value,
|
|
78
|
+
r.target_module,
|
|
79
|
+
)
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
by_cat: dict[str, int] = {cat.value: 0 for cat in AdvisorCategory}
|
|
83
|
+
by_sev: dict[str, int] = {"critical": 0, "high": 0, "medium": 0, "low": 0}
|
|
84
|
+
|
|
85
|
+
for r in filtered:
|
|
86
|
+
by_cat[r.category.value] = by_cat.get(r.category.value, 0) + 1
|
|
87
|
+
by_sev[r.severity] = by_sev.get(r.severity, 0) + 1
|
|
88
|
+
|
|
89
|
+
summary = self._format_summary(filtered, by_cat, by_sev)
|
|
90
|
+
|
|
91
|
+
repo_ident = (
|
|
92
|
+
self.analysis.git_insights.snapshot_identity
|
|
93
|
+
if self.analysis.git_insights and self.analysis.git_insights.snapshot_identity
|
|
94
|
+
else self.analysis.target_display
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
return RefactoringAdvisorReport(
|
|
98
|
+
schema_version="1.0.0",
|
|
99
|
+
repo_identity=repo_ident,
|
|
100
|
+
total_recommendations=len(filtered),
|
|
101
|
+
total_modules_analyzed=len(self.analysis.files),
|
|
102
|
+
by_category=by_cat,
|
|
103
|
+
by_severity=by_sev,
|
|
104
|
+
recommendations=filtered,
|
|
105
|
+
summary_text=summary,
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
# -------------------------------------------------------------------------
|
|
109
|
+
# Category 1: Circular Dependency Reduction
|
|
110
|
+
# -------------------------------------------------------------------------
|
|
111
|
+
def _analyze_circular_dependencies(self) -> list[RefactoringRecommendation]:
|
|
112
|
+
recs: list[RefactoringRecommendation] = []
|
|
113
|
+
revision = (
|
|
114
|
+
self.analysis.git_insights.commit_sha
|
|
115
|
+
if self.analysis.git_insights and self.analysis.git_insights.commit_sha
|
|
116
|
+
else "WORKING_TREE"
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
for cycle in self.analysis.cycles:
|
|
120
|
+
nodes = cycle.nodes
|
|
121
|
+
if not nodes:
|
|
122
|
+
continue
|
|
123
|
+
|
|
124
|
+
unique_nodes: list[str] = []
|
|
125
|
+
for n in nodes:
|
|
126
|
+
if n not in unique_nodes:
|
|
127
|
+
unique_nodes.append(n)
|
|
128
|
+
|
|
129
|
+
if len(unique_nodes) < 2:
|
|
130
|
+
continue
|
|
131
|
+
|
|
132
|
+
# Identify candidate edge to break: find the edge with highest instability or lowest symbol count
|
|
133
|
+
best_break_source = unique_nodes[0]
|
|
134
|
+
best_break_target = unique_nodes[1]
|
|
135
|
+
min_weight = 999999
|
|
136
|
+
|
|
137
|
+
for i in range(len(unique_nodes)):
|
|
138
|
+
src = unique_nodes[i]
|
|
139
|
+
tgt = unique_nodes[(i + 1) % len(unique_nodes)]
|
|
140
|
+
edges = self.edge_map.get((src, tgt), [])
|
|
141
|
+
import_count = sum(len(e.import_names) for e in edges) if edges else 1
|
|
142
|
+
src_node = self.file_map.get(src)
|
|
143
|
+
tgt_node = self.file_map.get(tgt)
|
|
144
|
+
|
|
145
|
+
# Prioritize edges where target is unstable or import surface is small
|
|
146
|
+
weight = import_count * 10
|
|
147
|
+
if tgt_node:
|
|
148
|
+
weight -= int(tgt_node.instability * 5)
|
|
149
|
+
if src_node and src_node.is_hub:
|
|
150
|
+
weight += 20 # Don't break at the hub if possible
|
|
151
|
+
|
|
152
|
+
if weight < min_weight:
|
|
153
|
+
min_weight = weight
|
|
154
|
+
best_break_source = src
|
|
155
|
+
best_break_target = tgt
|
|
156
|
+
|
|
157
|
+
# Extract evidence
|
|
158
|
+
edges = self.edge_map.get((best_break_source, best_break_target), [])
|
|
159
|
+
snippets: list[str] = []
|
|
160
|
+
for e in edges:
|
|
161
|
+
import_str = (
|
|
162
|
+
f"import {{{', '.join(e.import_names)}}}"
|
|
163
|
+
if e.import_names
|
|
164
|
+
else "import ..."
|
|
165
|
+
)
|
|
166
|
+
snippets.append(
|
|
167
|
+
f"{e.source}:{e.line} -> {import_str} from '{e.target}'"
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
# Affected modules = nodes in cycle + modules that import the cycle nodes
|
|
171
|
+
affected: set[str] = set(unique_nodes)
|
|
172
|
+
for n in unique_nodes:
|
|
173
|
+
fn = self.file_map.get(n)
|
|
174
|
+
if fn:
|
|
175
|
+
affected.update(fn.imported_by)
|
|
176
|
+
affected.discard(best_break_source)
|
|
177
|
+
|
|
178
|
+
hash_src = f"cycle:{':'.join(sorted(unique_nodes))}"
|
|
179
|
+
rec_id = f"ref_cycle_{hashlib.sha256(hash_src.encode()).hexdigest()[:12]}"
|
|
180
|
+
|
|
181
|
+
recs.append(
|
|
182
|
+
RefactoringRecommendation(
|
|
183
|
+
recommendation_id=rec_id,
|
|
184
|
+
target_module=best_break_source,
|
|
185
|
+
category=AdvisorCategory.CIRCULAR_DEPENDENCY,
|
|
186
|
+
severity="critical" if len(unique_nodes) <= 3 else "high",
|
|
187
|
+
title=f"Break circular dependency cycle ({len(unique_nodes)} modules)",
|
|
188
|
+
description=(
|
|
189
|
+
f"A circular dependency loop exists between {len(unique_nodes)} modules: "
|
|
190
|
+
f"{' -> '.join(unique_nodes)} -> {unique_nodes[0]}. "
|
|
191
|
+
f"Severing the link from '{best_break_source}' to '{best_break_target}' "
|
|
192
|
+
f"will eliminate this cycle and restore an acyclic DAG."
|
|
193
|
+
),
|
|
194
|
+
evidence_id=f"ev_cycle_{rec_id}",
|
|
195
|
+
evidence_snippets=snippets,
|
|
196
|
+
revision_source=revision,
|
|
197
|
+
affected_modules=sorted(list(affected))[:10],
|
|
198
|
+
expected_architectural_benefit=(
|
|
199
|
+
f"Eliminates 1 circular dependency chain of length {len(unique_nodes)}. "
|
|
200
|
+
f"Restores strict topological compilation order and eliminates runtime import deadlocks."
|
|
201
|
+
),
|
|
202
|
+
suggested_action_steps=[
|
|
203
|
+
f"1. Inspect imports from '{best_break_target}' in '{best_break_source}'.",
|
|
204
|
+
"2. Extract shared data models or interface signatures into a neutral shared module (e.g. 'models.py' or 'types.ts').",
|
|
205
|
+
f"3. Invert the dependency so '{best_break_source}' depends on the shared abstraction rather than concrete '{best_break_target}'.",
|
|
206
|
+
f"4. Re-run RepoDNA analysis to verify that cycle {cycle.id} is resolved.",
|
|
207
|
+
],
|
|
208
|
+
risks_and_limitations=(
|
|
209
|
+
"Extracting shared types may touch multiple import statements across dependent modules. "
|
|
210
|
+
"Keep backward-compatible re-exports during transition if necessary."
|
|
211
|
+
),
|
|
212
|
+
support_level="verified",
|
|
213
|
+
metric_delta_preview={
|
|
214
|
+
"cycle_length": len(unique_nodes),
|
|
215
|
+
"cycle_id": cycle.id,
|
|
216
|
+
"cycle_reduction": 1,
|
|
217
|
+
"breaking_edge": f"{best_break_source} -> {best_break_target}",
|
|
218
|
+
},
|
|
219
|
+
)
|
|
220
|
+
)
|
|
221
|
+
|
|
222
|
+
return recs
|
|
223
|
+
|
|
224
|
+
# -------------------------------------------------------------------------
|
|
225
|
+
# Category 2: High Coupling Module Review
|
|
226
|
+
# -------------------------------------------------------------------------
|
|
227
|
+
def _analyze_high_coupling(self) -> list[RefactoringRecommendation]:
|
|
228
|
+
recs: list[RefactoringRecommendation] = []
|
|
229
|
+
revision = (
|
|
230
|
+
self.analysis.git_insights.commit_sha
|
|
231
|
+
if self.analysis.git_insights and self.analysis.git_insights.commit_sha
|
|
232
|
+
else "WORKING_TREE"
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
for f in self.analysis.files:
|
|
236
|
+
# Skip test files and third-party files
|
|
237
|
+
if any(part in f.id for part in ("tests/", "test_", "__tests__", "spec.")):
|
|
238
|
+
continue
|
|
239
|
+
|
|
240
|
+
instability = (
|
|
241
|
+
f.fan_out / (f.fan_in + f.fan_out)
|
|
242
|
+
if (f.fan_in + f.fan_out) > 0
|
|
243
|
+
else f.instability
|
|
244
|
+
)
|
|
245
|
+
|
|
246
|
+
# Flag if fan_out >= 7 or (instability > 0.8 and fan_in + fan_out >= 8)
|
|
247
|
+
if f.fan_out >= 7 or (instability >= 0.8 and (f.fan_in + f.fan_out) >= 8):
|
|
248
|
+
rec_id = f"ref_coupling_{hashlib.sha256(f.id.encode()).hexdigest()[:12]}"
|
|
249
|
+
severity = "high" if f.fan_out >= 10 else "medium"
|
|
250
|
+
|
|
251
|
+
recs.append(
|
|
252
|
+
RefactoringRecommendation(
|
|
253
|
+
recommendation_id=rec_id,
|
|
254
|
+
target_module=f.id,
|
|
255
|
+
category=AdvisorCategory.HIGH_COUPLING,
|
|
256
|
+
severity=severity,
|
|
257
|
+
title=f"Decouple high efferent coupling in {f.name} (fan-out: {f.fan_out})",
|
|
258
|
+
description=(
|
|
259
|
+
f"Module '{f.id}' directly imports {f.fan_out} internal modules "
|
|
260
|
+
f"(Instability metric I = {instability:.2f}). "
|
|
261
|
+
f"High efferent coupling makes this module sensitive to changes in any of its dependencies."
|
|
262
|
+
),
|
|
263
|
+
evidence_id=f"ev_coupling_{rec_id}",
|
|
264
|
+
evidence_snippets=[
|
|
265
|
+
f"Imports {len(f.imports_internal)} internal dependencies: {', '.join(f.imports_internal[:6])}{'...' if len(f.imports_internal) > 6 else ''}"
|
|
266
|
+
],
|
|
267
|
+
revision_source=revision,
|
|
268
|
+
affected_modules=f.imported_by[:10],
|
|
269
|
+
expected_architectural_benefit=(
|
|
270
|
+
f"Reduces efferent coupling from {f.fan_out} to < 5. "
|
|
271
|
+
f"Lowers instability metric and limits ripple effects during dependency refactoring."
|
|
272
|
+
),
|
|
273
|
+
suggested_action_steps=[
|
|
274
|
+
f"1. Audit the {f.fan_out} outgoing imports in '{f.id}'. Group them by cohesive domain capability.",
|
|
275
|
+
"2. Introduce a Facade or Gateway module to consolidate low-level subsystem dependencies.",
|
|
276
|
+
"3. Pass dependencies via constructor or dependency injection rather than direct concrete imports.",
|
|
277
|
+
"4. Move utility or transformation functions into separate pure modules.",
|
|
278
|
+
],
|
|
279
|
+
risks_and_limitations=(
|
|
280
|
+
"Introducing facades adds an extra layer of indirection. Ensure interfaces remain cohesive."
|
|
281
|
+
),
|
|
282
|
+
support_level="verified",
|
|
283
|
+
metric_delta_preview={
|
|
284
|
+
"current_fan_out": f.fan_out,
|
|
285
|
+
"current_instability": round(instability, 3),
|
|
286
|
+
"target_fan_out": max(3, f.fan_out // 2),
|
|
287
|
+
},
|
|
288
|
+
)
|
|
289
|
+
)
|
|
290
|
+
|
|
291
|
+
return recs
|
|
292
|
+
|
|
293
|
+
# -------------------------------------------------------------------------
|
|
294
|
+
# Category 3: Layer Boundary Improvement
|
|
295
|
+
# -------------------------------------------------------------------------
|
|
296
|
+
def _analyze_layer_boundaries(self) -> list[RefactoringRecommendation]:
|
|
297
|
+
recs: list[RefactoringRecommendation] = []
|
|
298
|
+
revision = (
|
|
299
|
+
self.analysis.git_insights.commit_sha
|
|
300
|
+
if self.analysis.git_insights and self.analysis.git_insights.commit_sha
|
|
301
|
+
else "WORKING_TREE"
|
|
302
|
+
)
|
|
303
|
+
|
|
304
|
+
def get_layer(path: str) -> tuple[int, str]:
|
|
305
|
+
low = path.lower()
|
|
306
|
+
if any(k in low for k in ("models", "types", "schemas", "interfaces", "entities")):
|
|
307
|
+
return (0, "Core Types/Domain")
|
|
308
|
+
if any(k in low for k in ("utils", "common", "core", "storage", "parsers", "graph")):
|
|
309
|
+
return (1, "Infrastructure/Core")
|
|
310
|
+
if any(k in low for k in ("services", "brain", "history", "guardian", "rules")):
|
|
311
|
+
return (2, "Business Logic/Services")
|
|
312
|
+
if any(k in low for k in ("api", "cli", "mcp", "views", "components", "pages")):
|
|
313
|
+
return (3, "Presentation/Interface")
|
|
314
|
+
return (1, "Infrastructure/Core")
|
|
315
|
+
|
|
316
|
+
for edge in self.analysis.edges:
|
|
317
|
+
src_tier, src_layer = get_layer(edge.source)
|
|
318
|
+
tgt_tier, tgt_layer = get_layer(edge.target)
|
|
319
|
+
|
|
320
|
+
# Inversion: Lower tier importing higher tier
|
|
321
|
+
if src_tier < tgt_tier and (tgt_tier - src_tier) >= 2:
|
|
322
|
+
rec_id = f"ref_layer_{hashlib.sha256(f'{edge.source}->{edge.target}'.encode()).hexdigest()[:12]}"
|
|
323
|
+
recs.append(
|
|
324
|
+
RefactoringRecommendation(
|
|
325
|
+
recommendation_id=rec_id,
|
|
326
|
+
target_module=edge.source,
|
|
327
|
+
category=AdvisorCategory.LAYER_BOUNDARY,
|
|
328
|
+
severity="high" if src_tier == 0 else "medium",
|
|
329
|
+
title=f"Resolve layer boundary inversion in {edge.source}",
|
|
330
|
+
description=(
|
|
331
|
+
f"Lower architectural layer '{src_layer}' ({edge.source}) imports from "
|
|
332
|
+
f"higher layer '{tgt_layer}' ({edge.target}). "
|
|
333
|
+
f"Architectural clean layers require dependencies to flow toward the core/domain."
|
|
334
|
+
),
|
|
335
|
+
evidence_id=f"ev_layer_{rec_id}",
|
|
336
|
+
evidence_snippets=[
|
|
337
|
+
f"{edge.source}:{edge.line} -> imports '{edge.target}'"
|
|
338
|
+
],
|
|
339
|
+
revision_source=revision,
|
|
340
|
+
affected_modules=[edge.target],
|
|
341
|
+
expected_architectural_benefit=(
|
|
342
|
+
"Enforces clean unidirectional dependency flow and preserves layer modularity."
|
|
343
|
+
),
|
|
344
|
+
suggested_action_steps=[
|
|
345
|
+
f"1. Remove direct import of '{edge.target}' from '{edge.source}'.",
|
|
346
|
+
"2. Define an interface or abstract base class within the lower layer.",
|
|
347
|
+
f"3. Invert dependency: have '{edge.target}' implement or satisfy the contract defined in '{src_layer}'.",
|
|
348
|
+
"4. Wire the concrete instance at application bootstrap / composition root.",
|
|
349
|
+
],
|
|
350
|
+
risks_and_limitations=(
|
|
351
|
+
"Requires dependency injection or event dispatching to avoid direct coupling."
|
|
352
|
+
),
|
|
353
|
+
support_level="verified",
|
|
354
|
+
metric_delta_preview={
|
|
355
|
+
"source_layer": src_layer,
|
|
356
|
+
"target_layer": tgt_layer,
|
|
357
|
+
"violating_edge": f"{edge.source} -> {edge.target}",
|
|
358
|
+
},
|
|
359
|
+
)
|
|
360
|
+
)
|
|
361
|
+
|
|
362
|
+
return recs
|
|
363
|
+
|
|
364
|
+
# -------------------------------------------------------------------------
|
|
365
|
+
# Category 4: Oversized Architectural Hub Review
|
|
366
|
+
# -------------------------------------------------------------------------
|
|
367
|
+
def _analyze_oversized_hubs(self) -> list[RefactoringRecommendation]:
|
|
368
|
+
recs: list[RefactoringRecommendation] = []
|
|
369
|
+
revision = (
|
|
370
|
+
self.analysis.git_insights.commit_sha
|
|
371
|
+
if self.analysis.git_insights and self.analysis.git_insights.commit_sha
|
|
372
|
+
else "WORKING_TREE"
|
|
373
|
+
)
|
|
374
|
+
|
|
375
|
+
for f in self.analysis.files:
|
|
376
|
+
# Skip test files
|
|
377
|
+
if any(part in f.id for part in ("tests/", "test_", "__tests__", "spec.")):
|
|
378
|
+
continue
|
|
379
|
+
|
|
380
|
+
is_hub_condition = (
|
|
381
|
+
f.is_hub
|
|
382
|
+
or (f.fan_in >= 8 and f.fan_out >= 6)
|
|
383
|
+
or ((f.fan_in + f.fan_out) >= 14 and f.lines_code >= 250)
|
|
384
|
+
)
|
|
385
|
+
|
|
386
|
+
if is_hub_condition:
|
|
387
|
+
rec_id = f"ref_hub_{hashlib.sha256(f.id.encode()).hexdigest()[:12]}"
|
|
388
|
+
if f.lines_code >= 500 or (f.fan_in + f.fan_out) >= 20:
|
|
389
|
+
severity = "critical"
|
|
390
|
+
elif f.lines_code >= 300 or (f.fan_in + f.fan_out) >= 14 or f.is_hub:
|
|
391
|
+
severity = "high"
|
|
392
|
+
else:
|
|
393
|
+
severity = "medium"
|
|
394
|
+
|
|
395
|
+
recs.append(
|
|
396
|
+
RefactoringRecommendation(
|
|
397
|
+
recommendation_id=rec_id,
|
|
398
|
+
target_module=f.id,
|
|
399
|
+
category=AdvisorCategory.OVERSIZED_HUB,
|
|
400
|
+
severity=severity,
|
|
401
|
+
title=f"Decompose oversized architectural hub {f.name}",
|
|
402
|
+
description=(
|
|
403
|
+
f"Module '{f.id}' acts as a central hub with {f.fan_in} incoming and "
|
|
404
|
+
f"{f.fan_out} outgoing dependencies ({f.lines_code} LOC). "
|
|
405
|
+
f"High degree centrality creates a Single Point of Failure (SPOF) and merge conflict hot spot."
|
|
406
|
+
),
|
|
407
|
+
evidence_id=f"ev_hub_{rec_id}",
|
|
408
|
+
evidence_snippets=[
|
|
409
|
+
f"Fan-in: {f.fan_in} callers | Fan-out: {f.fan_out} callees | LOC: {f.lines_code}"
|
|
410
|
+
],
|
|
411
|
+
revision_source=revision,
|
|
412
|
+
affected_modules=f.imported_by[:10],
|
|
413
|
+
expected_architectural_benefit=(
|
|
414
|
+
"Decomposes monolithic hub into cohesive domain modules, reducing blast radius and merge conflict frequency."
|
|
415
|
+
),
|
|
416
|
+
suggested_action_steps=[
|
|
417
|
+
f"1. Audit responsibilities inside '{f.name}' ({f.lines_code} LOC, {f.fan_in} consumers).",
|
|
418
|
+
"2. Extract self-contained domain functions or classes into cohesive sibling modules.",
|
|
419
|
+
f"3. Retain '{f.id}' as a slim re-export facade during transition to preserve consumer compatibility.",
|
|
420
|
+
"4. Deprecate unused re-exports over time.",
|
|
421
|
+
],
|
|
422
|
+
risks_and_limitations=(
|
|
423
|
+
f"Refactoring a central hub affects {f.fan_in} incoming consumers. "
|
|
424
|
+
f"Coordinate migration across dependent sub-packages."
|
|
425
|
+
),
|
|
426
|
+
support_level="verified",
|
|
427
|
+
metric_delta_preview={
|
|
428
|
+
"current_degree": f.fan_in + f.fan_out,
|
|
429
|
+
"fan_in": f.fan_in,
|
|
430
|
+
"fan_out": f.fan_out,
|
|
431
|
+
"lines_code": f.lines_code,
|
|
432
|
+
},
|
|
433
|
+
)
|
|
434
|
+
)
|
|
435
|
+
|
|
436
|
+
return recs
|
|
437
|
+
|
|
438
|
+
# -------------------------------------------------------------------------
|
|
439
|
+
# Helper & Formatting Methods
|
|
440
|
+
# -------------------------------------------------------------------------
|
|
441
|
+
def _deduplicate_recommendations(
|
|
442
|
+
self, recs: list[RefactoringRecommendation]
|
|
443
|
+
) -> list[RefactoringRecommendation]:
|
|
444
|
+
seen_keys: set[tuple[str, str]] = set()
|
|
445
|
+
deduped: list[RefactoringRecommendation] = []
|
|
446
|
+
|
|
447
|
+
for r in recs:
|
|
448
|
+
key = (r.target_module, r.category.value)
|
|
449
|
+
if key not in seen_keys:
|
|
450
|
+
seen_keys.add(key)
|
|
451
|
+
deduped.append(r)
|
|
452
|
+
|
|
453
|
+
return deduped
|
|
454
|
+
|
|
455
|
+
def _apply_filters(
|
|
456
|
+
self,
|
|
457
|
+
recs: list[RefactoringRecommendation],
|
|
458
|
+
category_filter: AdvisorCategory | None,
|
|
459
|
+
min_severity: str | None,
|
|
460
|
+
) -> list[RefactoringRecommendation]:
|
|
461
|
+
res = recs
|
|
462
|
+
if category_filter:
|
|
463
|
+
res = [r for r in res if r.category == category_filter]
|
|
464
|
+
|
|
465
|
+
if min_severity:
|
|
466
|
+
sev_levels = {"low": 1, "medium": 2, "high": 3, "critical": 4}
|
|
467
|
+
min_val = sev_levels.get(min_severity.lower(), 1)
|
|
468
|
+
res = [r for r in res if sev_levels.get(r.severity.lower(), 1) >= min_val]
|
|
469
|
+
|
|
470
|
+
return res
|
|
471
|
+
|
|
472
|
+
def _format_summary(
|
|
473
|
+
self,
|
|
474
|
+
recs: list[RefactoringRecommendation],
|
|
475
|
+
by_cat: dict[str, int],
|
|
476
|
+
by_sev: dict[str, int],
|
|
477
|
+
) -> str:
|
|
478
|
+
lines = [
|
|
479
|
+
"=" * 78,
|
|
480
|
+
"RepoDNA Architectural Refactoring Advisor",
|
|
481
|
+
"=" * 78,
|
|
482
|
+
f"Total Recommendations : {len(recs)}",
|
|
483
|
+
f"By Severity : Critical: {by_sev.get('critical', 0)} | High: {by_sev.get('high', 0)} | Medium: {by_sev.get('medium', 0)} | Low: {by_sev.get('low', 0)}",
|
|
484
|
+
f"By Category : Circular: {by_cat.get(AdvisorCategory.CIRCULAR_DEPENDENCY.value, 0)} | Coupling: {by_cat.get(AdvisorCategory.HIGH_COUPLING.value, 0)} | Layers: {by_cat.get(AdvisorCategory.LAYER_BOUNDARY.value, 0)} | Hubs: {by_cat.get(AdvisorCategory.OVERSIZED_HUB.value, 0)}",
|
|
485
|
+
"-" * 78,
|
|
486
|
+
]
|
|
487
|
+
|
|
488
|
+
if not recs:
|
|
489
|
+
lines.append("No architectural refactoring recommendations. Clean architecture detected!")
|
|
490
|
+
else:
|
|
491
|
+
for i, r in enumerate(recs, 1):
|
|
492
|
+
sev_tag = f"[{r.severity.upper()}]"
|
|
493
|
+
cat_tag = f"({r.category.value})"
|
|
494
|
+
lines.append(f"{i}. {sev_tag} {r.title} {cat_tag}")
|
|
495
|
+
lines.append(f" Target : {r.target_module}")
|
|
496
|
+
lines.append(f" Benefit : {r.expected_architectural_benefit}")
|
|
497
|
+
if r.suggested_action_steps:
|
|
498
|
+
lines.append(f" Action : {r.suggested_action_steps[0]}")
|
|
499
|
+
lines.append("-" * 78)
|
|
500
|
+
|
|
501
|
+
lines.append("=" * 78)
|
|
502
|
+
return "\n".join(lines)
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""Data models for RepoDNA Refactoring Advisor.
|
|
2
|
+
|
|
3
|
+
Provides deterministic, evidence-based architectural refactoring recommendations.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from enum import StrEnum
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from pydantic import BaseModel, Field
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class AdvisorCategory(StrEnum):
|
|
15
|
+
"""The four core architectural refactoring recommendation categories."""
|
|
16
|
+
|
|
17
|
+
CIRCULAR_DEPENDENCY = "circular_dependency_reduction"
|
|
18
|
+
HIGH_COUPLING = "high_coupling_module_review"
|
|
19
|
+
LAYER_BOUNDARY = "layer_boundary_improvement"
|
|
20
|
+
OVERSIZED_HUB = "oversized_architectural_hub_review"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class RefactoringRecommendation(BaseModel):
|
|
24
|
+
"""A deterministic, evidence-grounded architectural refactoring recommendation."""
|
|
25
|
+
|
|
26
|
+
recommendation_id: str = Field(
|
|
27
|
+
description="Deterministic unique ID, e.g. ref_cycle_<hash>"
|
|
28
|
+
)
|
|
29
|
+
target_module: str = Field(
|
|
30
|
+
description="Normalized POSIX relative file path of primary target module"
|
|
31
|
+
)
|
|
32
|
+
category: AdvisorCategory
|
|
33
|
+
severity: str = Field(description="critical, high, medium, low")
|
|
34
|
+
title: str
|
|
35
|
+
description: str
|
|
36
|
+
evidence_id: str | None = None
|
|
37
|
+
evidence_snippets: list[str] = Field(default_factory=list)
|
|
38
|
+
revision_source: str = "WORKING_TREE"
|
|
39
|
+
affected_modules: list[str] = Field(
|
|
40
|
+
default_factory=list, description="Downstream / dependent modules"
|
|
41
|
+
)
|
|
42
|
+
expected_architectural_benefit: str
|
|
43
|
+
suggested_action_steps: list[str] = Field(default_factory=list)
|
|
44
|
+
risks_and_limitations: str
|
|
45
|
+
support_level: str = Field(
|
|
46
|
+
default="verified", description="verified or candidate"
|
|
47
|
+
)
|
|
48
|
+
metric_delta_preview: dict[str, Any] = Field(default_factory=dict)
|
|
49
|
+
|
|
50
|
+
@property
|
|
51
|
+
def target_modules(self) -> list[str]:
|
|
52
|
+
return [self.target_module, *[m for m in self.affected_modules if m != self.target_module]]
|
|
53
|
+
|
|
54
|
+
@property
|
|
55
|
+
def action_steps(self) -> list[str]:
|
|
56
|
+
return self.suggested_action_steps
|
|
57
|
+
|
|
58
|
+
@property
|
|
59
|
+
def expected_benefit(self) -> str:
|
|
60
|
+
return self.expected_architectural_benefit
|
|
61
|
+
|
|
62
|
+
@property
|
|
63
|
+
def impact_description(self) -> str:
|
|
64
|
+
return self.description
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class RefactoringAdvisorReport(BaseModel):
|
|
68
|
+
"""Aggregated architectural refactoring report for a repository analysis."""
|
|
69
|
+
|
|
70
|
+
schema_version: str = "1.0.0"
|
|
71
|
+
repo_identity: str
|
|
72
|
+
total_recommendations: int
|
|
73
|
+
total_modules_analyzed: int = 0
|
|
74
|
+
by_category: dict[str, int]
|
|
75
|
+
by_severity: dict[str, int]
|
|
76
|
+
recommendations: list[RefactoringRecommendation]
|
|
77
|
+
summary_text: str
|
|
78
|
+
|
|
79
|
+
@property
|
|
80
|
+
def repo_name(self) -> str:
|
|
81
|
+
return self.repo_identity
|
|
82
|
+
|
|
83
|
+
@property
|
|
84
|
+
def summary(self) -> str:
|
|
85
|
+
return self.summary_text
|
|
86
|
+
|
|
87
|
+
@property
|
|
88
|
+
def critical_cycles_detected(self) -> int:
|
|
89
|
+
return self.by_category.get(AdvisorCategory.CIRCULAR_DEPENDENCY.value, 0)
|
|
90
|
+
|
|
91
|
+
@property
|
|
92
|
+
def high_coupling_modules(self) -> int:
|
|
93
|
+
return self.by_category.get(AdvisorCategory.HIGH_COUPLING.value, 0)
|
|
94
|
+
|
|
95
|
+
@property
|
|
96
|
+
def layer_boundary_violations(self) -> int:
|
|
97
|
+
return self.by_category.get(AdvisorCategory.LAYER_BOUNDARY.value, 0)
|
|
98
|
+
|
|
99
|
+
@property
|
|
100
|
+
def oversized_hubs(self) -> int:
|
|
101
|
+
return self.by_category.get(AdvisorCategory.OVERSIZED_HUB.value, 0)
|