adre-cli 0.1.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.
Files changed (48) hide show
  1. adre/__init__.py +5 -0
  2. adre/analyzers/__init__.py +1 -0
  3. adre/analyzers/architecture.py +253 -0
  4. adre/analyzers/findings.py +457 -0
  5. adre/analyzers/inference.py +163 -0
  6. adre/cli.py +923 -0
  7. adre/core/__init__.py +1 -0
  8. adre/core/accepted.py +225 -0
  9. adre/core/adaptive.py +221 -0
  10. adre/core/baseline.py +1165 -0
  11. adre/core/config.py +60 -0
  12. adre/core/decision_engine.py +361 -0
  13. adre/core/declared.py +313 -0
  14. adre/core/evolution_intelligence.py +390 -0
  15. adre/core/explainer.py +413 -0
  16. adre/core/git_intelligence.py +392 -0
  17. adre/core/github_check.py +212 -0
  18. adre/core/incremental.py +288 -0
  19. adre/core/layers.py +306 -0
  20. adre/core/pr_intelligence.py +261 -0
  21. adre/core/pr_review.py +454 -0
  22. adre/core/prioritization.py +196 -0
  23. adre/core/project.py +41 -0
  24. adre/core/refactor_intelligence.py +201 -0
  25. adre/core/repositories.py +312 -0
  26. adre/core/review.py +96 -0
  27. adre/core/rules_shared.py +75 -0
  28. adre/core/sarif.py +141 -0
  29. adre/core/scope.py +141 -0
  30. adre/core/snapshots.py +242 -0
  31. adre/core/stability_intelligence.py +361 -0
  32. adre/graph/__init__.py +0 -0
  33. adre/graph/dependencies.py +379 -0
  34. adre/parsers/__init__.py +87 -0
  35. adre/parsers/go.py +140 -0
  36. adre/parsers/javascript.py +364 -0
  37. adre/parsers/jvm.py +127 -0
  38. adre/parsers/python.py +153 -0
  39. adre/reports/__init__.py +1 -0
  40. adre/reports/architecture.py +349 -0
  41. adre/rules.py +12 -0
  42. adre/web.py +3731 -0
  43. adre_cli-0.1.0.dist-info/METADATA +343 -0
  44. adre_cli-0.1.0.dist-info/RECORD +48 -0
  45. adre_cli-0.1.0.dist-info/WHEEL +5 -0
  46. adre_cli-0.1.0.dist-info/entry_points.txt +2 -0
  47. adre_cli-0.1.0.dist-info/licenses/LICENSE +202 -0
  48. adre_cli-0.1.0.dist-info/top_level.txt +1 -0
adre/core/__init__.py ADDED
@@ -0,0 +1 @@
1
+
adre/core/accepted.py ADDED
@@ -0,0 +1,225 @@
1
+ """Accepted architecture exceptions: `.adre/accepted.json`.
2
+
3
+ Lets a team record an intentional boundary crossing, with a reason, instead
4
+ of re-saving the whole baseline. The file lives in the repository, so adding
5
+ an entry in a pull request is visible in that PR's diff, and the review
6
+ output lists every finding that an entry accepted.
7
+
8
+ Format:
9
+
10
+ {
11
+ "accepted": [
12
+ {
13
+ "from": "controllers/admin_controller.py",
14
+ "to": "repositories/*",
15
+ "type": "layer_skip",
16
+ "reason": "Admin bulk export reads repositories directly (ARCH-12)."
17
+ }
18
+ ]
19
+ }
20
+
21
+ `from` and `to` are glob patterns (fnmatch, `*` also matches `/`) over
22
+ project-relative paths. `to` defaults to `*`. For `repository_bypass`, `to`
23
+ matches the database module (e.g. `sqlite3`). For `cycle`, `from` matches a
24
+ file that joined the cycle group and `to` matches any file in the group.
25
+ `type` is optional: one issue type or a list of them. `reason` is required.
26
+ """
27
+ import json
28
+ import os
29
+ from fnmatch import fnmatchcase
30
+
31
+ from adre.core.config import BASELINE_DIRNAME
32
+
33
+
34
+ ACCEPTED_FILENAME = "accepted.json"
35
+ ISSUE_TYPES = {
36
+ "declared_violation",
37
+ "indirect_violation",
38
+ "layer_skip",
39
+ "layer_violation",
40
+ "unexpected_dependency",
41
+ "repository_bypass",
42
+ "cycle",
43
+ }
44
+
45
+
46
+ def accepted_path(project_root):
47
+ return os.path.join(os.path.realpath(project_root), BASELINE_DIRNAME, ACCEPTED_FILENAME)
48
+
49
+
50
+ def accepted_rel_path():
51
+ return "{0}/{1}".format(BASELINE_DIRNAME, ACCEPTED_FILENAME)
52
+
53
+
54
+ def parse_accepted(data, source=ACCEPTED_FILENAME):
55
+ if not isinstance(data, dict) or not isinstance(data.get("accepted"), list):
56
+ raise ValueError('{0} must be an object with an "accepted" list.'.format(source))
57
+ if not isinstance(data.get("fail_on_stale", False), bool):
58
+ raise ValueError('{0}: "fail_on_stale" must be true or false.'.format(source))
59
+ rules = []
60
+ for index, entry in enumerate(data["accepted"], start=1):
61
+ where = "{0} entry {1}".format(source, index)
62
+ if not isinstance(entry, dict):
63
+ raise ValueError("{0} must be an object.".format(where))
64
+ source_pattern = entry.get("from")
65
+ if not isinstance(source_pattern, str) or not source_pattern.strip():
66
+ raise ValueError('{0} needs a "from" pattern.'.format(where))
67
+ target_pattern = entry.get("to", "*")
68
+ if not isinstance(target_pattern, str) or not target_pattern.strip():
69
+ raise ValueError('{0} has an invalid "to" pattern.'.format(where))
70
+ reason = entry.get("reason")
71
+ if not isinstance(reason, str) or not reason.strip():
72
+ raise ValueError('{0} needs a "reason" explaining why the crossing is accepted.'.format(where))
73
+ types = entry.get("type")
74
+ if types is None:
75
+ types = []
76
+ elif isinstance(types, str):
77
+ types = [types]
78
+ if not isinstance(types, list) or any(item not in ISSUE_TYPES for item in types):
79
+ raise ValueError(
80
+ '{0} has an unknown "type"; use one of: {1}.'.format(where, ", ".join(sorted(ISSUE_TYPES)))
81
+ )
82
+ rules.append({
83
+ "from": source_pattern.strip().replace("\\", "/"),
84
+ "to": target_pattern.strip().replace("\\", "/"),
85
+ "type": list(types),
86
+ "reason": reason.strip(),
87
+ "index": index,
88
+ })
89
+ return rules
90
+
91
+
92
+ def load_accepted(project_root):
93
+ """Return the accepted rules, [] when the file is absent.
94
+
95
+ Raises ValueError when the file exists but is invalid, so a typo can
96
+ never silently accept or reject findings.
97
+ """
98
+ path = accepted_path(project_root)
99
+ if not os.path.exists(path):
100
+ return []
101
+ if os.path.islink(path):
102
+ raise ValueError("{0} must not be a symlink.".format(accepted_rel_path()))
103
+ try:
104
+ with open(path, "r", encoding="utf-8") as handle:
105
+ data = json.load(handle)
106
+ except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc:
107
+ raise ValueError("{0} could not be read: {1}".format(accepted_rel_path(), exc))
108
+ return parse_accepted(data, source=accepted_rel_path())
109
+
110
+
111
+ def _norm(value):
112
+ return (value or "").replace("\\", "/")
113
+
114
+
115
+ def _targets_for(finding):
116
+ issue_type = finding.get("issue_type")
117
+ if issue_type == "cycle":
118
+ return finding.get("cycle_group") or finding.get("affected_files") or []
119
+ if issue_type == "indirect_violation":
120
+ return [finding.get("imported"), finding.get("chain_to")]
121
+ return [finding.get("imported")]
122
+
123
+
124
+ def _sources_for(finding):
125
+ if finding.get("issue_type") == "cycle":
126
+ return finding.get("joined_files") or [finding.get("file")]
127
+ if finding.get("issue_type") == "indirect_violation":
128
+ return [finding.get("file"), finding.get("chain_from")]
129
+ return [finding.get("file")]
130
+
131
+
132
+ def rule_matches(rule, finding):
133
+ if rule["type"] and finding.get("issue_type") not in rule["type"]:
134
+ return False
135
+ sources = [_norm(item) for item in _sources_for(finding) if item]
136
+ targets = [_norm(item) for item in _targets_for(finding) if item]
137
+ if not sources:
138
+ return False
139
+ if finding.get("issue_type") == "cycle":
140
+ # Every file that joined the group must be covered.
141
+ if not all(fnmatchcase(item, rule["from"]) for item in sources):
142
+ return False
143
+ elif not any(fnmatchcase(item, rule["from"]) for item in sources):
144
+ return False
145
+ if rule["to"] == "*":
146
+ return True
147
+ return any(fnmatchcase(item, rule["to"]) for item in targets)
148
+
149
+
150
+ def apply_accepted(drift, rules):
151
+ """Split findings into (still_drift, accepted). Accepted items carry the rule."""
152
+ remaining = []
153
+ accepted = []
154
+ for finding in drift or []:
155
+ rule = next((rule for rule in rules or [] if rule_matches(rule, finding)), None)
156
+ if rule is None:
157
+ remaining.append(finding)
158
+ continue
159
+ item = dict(finding)
160
+ item["accepted_by"] = {
161
+ "from": rule["from"],
162
+ "to": rule["to"],
163
+ "type": rule["type"],
164
+ "reason": rule["reason"],
165
+ "entry": rule["index"],
166
+ }
167
+ accepted.append(item)
168
+ return remaining, accepted
169
+
170
+
171
+ EDGE_TYPES = {
172
+ "declared_violation", "indirect_violation", "layer_skip", "layer_violation", "unexpected_dependency",
173
+ }
174
+
175
+
176
+ def accepted_fail_on_stale(project_root):
177
+ """True when accepted.json sets "fail_on_stale": true."""
178
+ path = accepted_path(project_root)
179
+ if not os.path.isfile(path) or os.path.islink(path):
180
+ return False
181
+ try:
182
+ with open(path, "r", encoding="utf-8") as handle:
183
+ data = json.load(handle)
184
+ except (OSError, UnicodeDecodeError, json.JSONDecodeError):
185
+ return False
186
+ return isinstance(data, dict) and data.get("fail_on_stale") is True
187
+
188
+
189
+ def _rule_still_applies(rule, analysis):
190
+ types = set(rule["type"]) or (EDGE_TYPES | {"repository_bypass", "cycle"})
191
+ if types & EDGE_TYPES:
192
+ for source, targets in (analysis.get("resolved_graph") or {}).items():
193
+ if not fnmatchcase(_norm(source), rule["from"]):
194
+ continue
195
+ if any(rule["to"] == "*" or fnmatchcase(_norm(target), rule["to"]) for target in targets):
196
+ return True
197
+ architecture = analysis.get("architecture") or {}
198
+ if "repository_bypass" in types:
199
+ for item in architecture.get("persistence_access") or []:
200
+ if fnmatchcase(_norm(item.get("file")), rule["from"]) and (
201
+ rule["to"] == "*" or fnmatchcase(item.get("module") or "", rule["to"])
202
+ ):
203
+ return True
204
+ if "cycle" in types:
205
+ for group in architecture.get("cycle_groups") or analysis.get("cycle_groups") or []:
206
+ members = [_norm(item) for item in group]
207
+ if any(fnmatchcase(item, rule["from"]) for item in members) and (
208
+ rule["to"] == "*" or any(fnmatchcase(item, rule["to"]) for item in members)
209
+ ):
210
+ return True
211
+ return False
212
+
213
+
214
+ def stale_accepted_rules(rules, analysis):
215
+ """Accepted entries that match nothing in the current code.
216
+
217
+ An entry is stale when no current dependency, database import or cycle
218
+ group it could apply to exists any more, i.e. the crossing it excused was
219
+ removed and the entry only hides a future regression.
220
+ """
221
+ return [
222
+ {key: rule[key] for key in ("index", "from", "to", "type", "reason")}
223
+ for rule in rules or []
224
+ if not _rule_still_applies(rule, analysis)
225
+ ]
adre/core/adaptive.py ADDED
@@ -0,0 +1,221 @@
1
+ """Legacy folder-name architecture classification.
2
+
3
+ This module is not the architecture source of truth. ArchitectureBaseline
4
+ records observed layers, directions, and patterns. Folder names remain
5
+ evidence during baseline inference via core.layers, not a competing model.
6
+ """
7
+ import os
8
+ from collections import Counter, defaultdict
9
+
10
+ from adre.core.config import SKIP_DIRS
11
+
12
+
13
+ ARCHITECTURE_TYPES = {
14
+ "fastapi_like",
15
+ "clean_architecture",
16
+ "layered_backend",
17
+ "frontend_react_like",
18
+ "generic_python_project",
19
+ }
20
+
21
+
22
+ LAYER_ALIASES = {
23
+ "routes": {"routes", "routers", "api", "endpoints", "views", "controllers"},
24
+ "services": {"services", "service", "business", "use_cases", "usecases"},
25
+ "models": {"models", "model", "schemas", "entities", "domain"},
26
+ "interface": {"interface", "interfaces", "presentation", "presenters", "controllers", "routes", "api", "views"},
27
+ "application": {"application", "app", "use_cases", "usecases", "services", "commands", "queries"},
28
+ "domain": {"domain", "entities", "entity", "value_objects", "models"},
29
+ "infrastructure": {"infrastructure", "infra", "repositories", "repository", "persistence", "database", "db", "external"},
30
+ "components": {"components", "component", "pages", "views", "screens"},
31
+ "hooks": {"hooks", "hook"},
32
+ "frontend_services": {"services", "api", "client", "clients", "lib"},
33
+ "scripts": {"scripts", "tools", "jobs", "tasks", "cli"},
34
+ "core": {"core", "common", "shared", "utils", "helpers", "lib"},
35
+ }
36
+
37
+
38
+ def _iter_project_files(project_root):
39
+ for root, dirs, filenames in os.walk(project_root):
40
+ dirs[:] = [d for d in dirs if d not in SKIP_DIRS and not d.startswith(".")]
41
+ for filename in filenames:
42
+ path = os.path.join(root, filename)
43
+ rel_path = os.path.relpath(path, project_root)
44
+ yield path, rel_path
45
+
46
+
47
+ def _read_text(path, limit=20000):
48
+ try:
49
+ with open(path, "r", encoding="utf-8") as f:
50
+ return f.read(limit)
51
+ except (OSError, UnicodeDecodeError):
52
+ return ""
53
+
54
+
55
+ def _folder_tokens(rel_path):
56
+ parts = rel_path.split(os.sep)
57
+ return [part.lower().replace("-", "_") for part in parts[:-1]]
58
+
59
+
60
+ def _has_any_folder(folder_counts, names):
61
+ return any(folder_counts.get(name, 0) for name in names)
62
+
63
+
64
+ def detect_project_architecture_type(project_root):
65
+ folder_counts = Counter()
66
+ file_ext_counts = Counter()
67
+ import_hits = Counter()
68
+ detected_layers = set()
69
+
70
+ for path, rel_path in _iter_project_files(project_root):
71
+ _, ext = os.path.splitext(rel_path)
72
+ file_ext_counts[ext.lower()] += 1
73
+ for folder in _folder_tokens(rel_path):
74
+ folder_counts[folder] += 1
75
+ for layer, aliases in LAYER_ALIASES.items():
76
+ if folder in aliases:
77
+ detected_layers.add(layer)
78
+
79
+ text = _read_text(path)
80
+ lowered = text.lower()
81
+ if "fastapi" in lowered or "apirouter" in lowered:
82
+ import_hits["fastapi_like"] += 2
83
+ if "pydantic" in lowered:
84
+ import_hits["fastapi_like"] += 1
85
+ if "react" in lowered or "usestate" in lowered or "useeffect" in lowered:
86
+ import_hits["frontend_react_like"] += 2
87
+ if "from domain" in lowered or "import domain" in lowered:
88
+ import_hits["clean_architecture"] += 1
89
+ if "from application" in lowered or "import application" in lowered:
90
+ import_hits["clean_architecture"] += 1
91
+
92
+ scores = defaultdict(int)
93
+
94
+ if _has_any_folder(folder_counts, {"routes", "routers", "api", "endpoints"}) and _has_any_folder(folder_counts, {"services", "service"}) and _has_any_folder(folder_counts, {"models", "schemas"}):
95
+ scores["fastapi_like"] += 6
96
+ scores["fastapi_like"] += import_hits["fastapi_like"]
97
+
98
+ canonical_clean_folders = {"interface", "interfaces", "application", "domain", "infrastructure", "infra"}
99
+ clean_layer_count = sum(1 for folder in canonical_clean_folders if folder_counts.get(folder, 0))
100
+ if clean_layer_count >= 3:
101
+ scores["clean_architecture"] += clean_layer_count * 2
102
+ scores["clean_architecture"] += import_hits["clean_architecture"]
103
+
104
+ layered_count = sum(1 for layer in ["routes", "services", "models"] if layer in detected_layers)
105
+ if layered_count >= 2:
106
+ scores["layered_backend"] += layered_count * 2
107
+ if _has_any_folder(folder_counts, {"routes", "routers", "api", "endpoints", "controllers"}) and _has_any_folder(folder_counts, {"services", "service"}) and _has_any_folder(folder_counts, {"models", "schemas", "repositories", "repository"}):
108
+ scores["layered_backend"] += 6
109
+
110
+ frontend_exts = file_ext_counts[".tsx"] + file_ext_counts[".jsx"]
111
+ if frontend_exts:
112
+ scores["frontend_react_like"] += min(5, frontend_exts)
113
+ if _has_any_folder(folder_counts, {"components", "hooks", "pages", "screens"}):
114
+ scores["frontend_react_like"] += 4
115
+ scores["frontend_react_like"] += import_hits["frontend_react_like"]
116
+
117
+ python_files = file_ext_counts[".py"]
118
+ if python_files:
119
+ scores["generic_python_project"] += 1
120
+
121
+ priority = {
122
+ "fastapi_like": 5,
123
+ "clean_architecture": 4,
124
+ "frontend_react_like": 3,
125
+ "layered_backend": 2,
126
+ "generic_python_project": 1,
127
+ }
128
+ architecture_type = max(ARCHITECTURE_TYPES, key=lambda name: (scores[name], priority[name]))
129
+ if architecture_type == "fastapi_like" and import_hits["fastapi_like"] == 0:
130
+ architecture_type = "layered_backend"
131
+ if scores[architecture_type] <= 1:
132
+ architecture_type = "generic_python_project"
133
+
134
+ confidence = _confidence_for_type(architecture_type, scores, detected_layers, python_files, frontend_exts)
135
+ return {
136
+ "architecture_type": architecture_type,
137
+ "confidence": confidence,
138
+ "detected_layers": sorted(_layers_for_architecture(architecture_type, detected_layers)),
139
+ }
140
+
141
+
142
+ def _confidence_for_type(architecture_type, scores, detected_layers, python_files, frontend_exts):
143
+ if architecture_type == "generic_python_project":
144
+ return 0.45 if python_files else 0.35
145
+
146
+ expected_layers = _expected_layers(architecture_type)
147
+ layer_match = len(set(expected_layers) & detected_layers) / max(1, len(expected_layers))
148
+ score_strength = min(1.0, scores[architecture_type] / 8)
149
+ file_signal = 1.0 if (python_files or frontend_exts or architecture_type == "layered_backend") else 0.4
150
+ return round(max(0.0, min(1.0, (layer_match * 0.55) + (score_strength * 0.35) + (file_signal * 0.10))), 2)
151
+
152
+
153
+ def _expected_layers(architecture_type):
154
+ return {
155
+ "fastapi_like": ["routes", "services", "models"],
156
+ "clean_architecture": ["interface", "application", "domain", "infrastructure"],
157
+ "layered_backend": ["routes", "services", "models"],
158
+ "frontend_react_like": ["components", "hooks", "frontend_services"],
159
+ "generic_python_project": ["scripts", "core"],
160
+ }.get(architecture_type, ["scripts", "core"])
161
+
162
+
163
+ def _layers_for_architecture(architecture_type, detected_layers):
164
+ expected = set(_expected_layers(architecture_type))
165
+ present_expected = expected & detected_layers
166
+ return present_expected or expected
167
+
168
+
169
+ def generate_rules_from_architecture(detected_type):
170
+ if isinstance(detected_type, dict):
171
+ architecture_type = detected_type.get("architecture_type", "generic_python_project")
172
+ else:
173
+ architecture_type = detected_type
174
+
175
+ if architecture_type == "fastapi_like":
176
+ layer_rules = {
177
+ "routes": ["services"],
178
+ "services": ["models"],
179
+ "models": [],
180
+ "root": ["routes", "services", "models"],
181
+ }
182
+ elif architecture_type == "clean_architecture":
183
+ layer_rules = {
184
+ "interface": ["application"],
185
+ "application": ["domain"],
186
+ "infrastructure": ["application", "domain"],
187
+ "domain": [],
188
+ "root": ["interface", "application", "domain", "infrastructure"],
189
+ }
190
+ elif architecture_type == "layered_backend":
191
+ layer_rules = {
192
+ "routes": ["services"],
193
+ "services": ["models"],
194
+ "models": [],
195
+ "root": ["routes", "services", "models"],
196
+ }
197
+ elif architecture_type == "frontend_react_like":
198
+ layer_rules = {
199
+ "components": ["hooks"],
200
+ "hooks": ["frontend_services"],
201
+ "frontend_services": [],
202
+ "root": ["components", "hooks", "frontend_services"],
203
+ }
204
+ else:
205
+ layer_rules = {
206
+ "scripts": ["core"],
207
+ "core": [],
208
+ "root": ["scripts", "core"],
209
+ }
210
+
211
+ layer_aliases = {
212
+ layer: sorted(LAYER_ALIASES.get(layer, {layer}))
213
+ for layer in layer_rules
214
+ if layer != "root"
215
+ }
216
+
217
+ return {
218
+ "architecture_type": architecture_type,
219
+ "layer_rules": layer_rules,
220
+ "layer_aliases": layer_aliases,
221
+ }