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
@@ -0,0 +1,201 @@
1
+ from adre.core.prioritization import build_file_risk_ranking, rank_architecture_issues
2
+
3
+
4
+ LEVEL_ORDER = {
5
+ "low": 1,
6
+ "medium": 2,
7
+ "high": 3,
8
+ }
9
+
10
+
11
+ def clean_files(files):
12
+ result = []
13
+ for file in files:
14
+ if file and file != "multiple" and file not in result:
15
+ result.append(file)
16
+ return result
17
+
18
+
19
+ def impact_level(score):
20
+ if score >= 75:
21
+ return "high"
22
+ if score >= 40:
23
+ return "medium"
24
+ return "low"
25
+
26
+
27
+ def strongest_level(levels):
28
+ return max(levels, key=lambda level: LEVEL_ORDER[level])
29
+
30
+
31
+ def estimate_refactor_impact(recommendation):
32
+ category = recommendation.get("category")
33
+ priority_score = recommendation.get("priority_score", 0)
34
+
35
+ if category == "cycle":
36
+ return {
37
+ "risk_reduction": "high",
38
+ "cycle_reduction": "high",
39
+ "coupling_reduction": "medium",
40
+ "maintainability_improvement": "high",
41
+ }
42
+
43
+ if category == "hotspot":
44
+ level = impact_level(priority_score)
45
+ return {
46
+ "risk_reduction": level,
47
+ "cycle_reduction": "low",
48
+ "coupling_reduction": "high" if level == "high" else "medium",
49
+ "maintainability_improvement": level,
50
+ }
51
+
52
+ if category == "layer_violation":
53
+ level = impact_level(priority_score)
54
+ return {
55
+ "risk_reduction": level,
56
+ "cycle_reduction": "low",
57
+ "coupling_reduction": "medium",
58
+ "maintainability_improvement": level,
59
+ }
60
+
61
+ return {
62
+ "risk_reduction": "medium",
63
+ "cycle_reduction": "low",
64
+ "coupling_reduction": "medium",
65
+ "maintainability_improvement": "medium",
66
+ }
67
+
68
+
69
+ def recommendation_overall_impact(impact):
70
+ return strongest_level([
71
+ impact["risk_reduction"],
72
+ impact["cycle_reduction"],
73
+ impact["coupling_reduction"],
74
+ impact["maintainability_improvement"],
75
+ ])
76
+
77
+
78
+ def cycle_recommendations(analysis):
79
+ recommendations = []
80
+ for cycle in analysis.get("cycles", []):
81
+ files = clean_files(cycle)
82
+ if len(files) < 2:
83
+ continue
84
+ recommendation = {
85
+ "title": "Break circular dependency",
86
+ "category": "cycle",
87
+ "affected_files": files,
88
+ "rationale": (
89
+ "These files depend on each other in a cycle, which makes import order fragile "
90
+ "and blurs ownership boundaries."
91
+ ),
92
+ "recommended_action": (
93
+ "Extract the shared contract, DTO, or helper behavior into a neutral lower-level module, "
94
+ "then update the cycle participants to depend on that module instead of each other."
95
+ ),
96
+ "expected_benefit": (
97
+ "Removes circular dependency pressure and restores clearer module responsibility."
98
+ ),
99
+ "priority_score": 100,
100
+ }
101
+ recommendation["impact_estimate"] = estimate_refactor_impact(recommendation)
102
+ recommendation["impact"] = recommendation_overall_impact(recommendation["impact_estimate"])
103
+ recommendations.append(recommendation)
104
+ return recommendations
105
+
106
+
107
+ def layer_recommendation(issue):
108
+ file = issue.get("file")
109
+ imported = issue.get("imported")
110
+ source_layer = issue.get("layer", "unknown")
111
+ imported_layer = issue.get("imported_layer", "unknown")
112
+ affected_files = clean_files([file, imported if imported and imported.endswith(".py") else None])
113
+
114
+ recommendation = {
115
+ "title": f"Restore {source_layer} to {imported_layer} boundary",
116
+ "category": "layer_violation",
117
+ "affected_files": affected_files or clean_files([file]),
118
+ "rationale": (
119
+ f"{file} crosses from {source_layer} into {imported_layer}. "
120
+ "That dependency direction increases coupling and makes the layer boundary harder to enforce."
121
+ ),
122
+ "recommended_action": (
123
+ "Move the depended-on behavior behind an allowed layer boundary. Keep orchestration in services, "
124
+ "keep route handlers thin, and place shared contracts in a neutral module used by both sides."
125
+ ),
126
+ "expected_benefit": (
127
+ "Reduces cross-layer coupling and makes future changes easier to isolate."
128
+ ),
129
+ "priority_score": issue.get("priority_score", 0),
130
+ }
131
+ recommendation["impact_estimate"] = estimate_refactor_impact(recommendation)
132
+ recommendation["impact"] = recommendation_overall_impact(recommendation["impact_estimate"])
133
+ return recommendation
134
+
135
+
136
+ def hotspot_recommendation(file_risk):
137
+ file = file_risk["file"]
138
+ recommendation = {
139
+ "title": f"Reduce hotspot pressure in {file}",
140
+ "category": "hotspot",
141
+ "affected_files": [file],
142
+ "rationale": (
143
+ f"{file} is accumulating architectural pressure: {', '.join(file_risk.get('reasons', []))}."
144
+ ),
145
+ "recommended_action": (
146
+ "Split stable contracts from volatile implementation details. Move broadly reused types or helpers "
147
+ "into a smaller interface module and keep feature-specific behavior close to its owning layer."
148
+ ),
149
+ "expected_benefit": (
150
+ "Reduces coupling concentration and lowers the blast radius of future changes."
151
+ ),
152
+ "priority_score": file_risk.get("risk_score", 0),
153
+ }
154
+ recommendation["impact_estimate"] = estimate_refactor_impact(recommendation)
155
+ recommendation["impact"] = recommendation_overall_impact(recommendation["impact_estimate"])
156
+ return recommendation
157
+
158
+
159
+ def recommendation_key(recommendation):
160
+ return (
161
+ recommendation.get("category"),
162
+ recommendation.get("title"),
163
+ tuple(recommendation.get("affected_files", [])),
164
+ )
165
+
166
+
167
+ def generate_refactor_recommendations(analysis):
168
+ recommendations = []
169
+ seen = set()
170
+
171
+ for recommendation in cycle_recommendations(analysis):
172
+ key = recommendation_key(recommendation)
173
+ if key not in seen:
174
+ seen.add(key)
175
+ recommendations.append(recommendation)
176
+
177
+ for issue in rank_architecture_issues(analysis):
178
+ if issue.get("issue_type") == "cycle":
179
+ continue
180
+ if issue.get("priority_level") not in {"critical", "high"}:
181
+ continue
182
+ recommendation = layer_recommendation(issue)
183
+ key = recommendation_key(recommendation)
184
+ if key not in seen:
185
+ seen.add(key)
186
+ recommendations.append(recommendation)
187
+
188
+ for file_risk in build_file_risk_ranking(analysis):
189
+ reasons = set(file_risk.get("reasons", []))
190
+ if "hotspot" not in reasons:
191
+ continue
192
+ recommendation = hotspot_recommendation(file_risk)
193
+ key = recommendation_key(recommendation)
194
+ if key not in seen:
195
+ seen.add(key)
196
+ recommendations.append(recommendation)
197
+
198
+ return sorted(
199
+ recommendations,
200
+ key=lambda item: (-item.get("priority_score", 0), item.get("title", "")),
201
+ )
@@ -0,0 +1,312 @@
1
+ import hashlib
2
+ import json
3
+ import os
4
+ import re
5
+ import shutil
6
+ import subprocess
7
+ from datetime import datetime, timezone
8
+
9
+ from adre.core.config import SOURCE_WALK_LIMIT
10
+ from adre.core.git_intelligence import run_git_command
11
+
12
+
13
+ REGISTRY_FILE = os.path.realpath(os.path.join(os.getcwd(), ".adre_repositories.json"))
14
+ TEMP_REPOSITORY_ROOT = os.path.realpath(os.path.join(os.getcwd(), ".adre_repositories"))
15
+ SOURCE_EXTENSIONS = {
16
+ ".py", ".js", ".jsx", ".ts", ".tsx", ".java", ".go", ".rs", ".rb", ".php",
17
+ ".cs", ".cpp", ".c", ".h", ".hpp", ".swift", ".kt", ".kts", ".scala",
18
+ }
19
+ GITHUB_REPOSITORY_PATTERN = re.compile(r"^https://github\.com/([A-Za-z0-9_.-]+)/([A-Za-z0-9_.-]+?)(?:\.git)?/?$")
20
+
21
+
22
+ def utc_now():
23
+ return datetime.now(timezone.utc).isoformat(timespec="seconds")
24
+
25
+
26
+ def load_repository_registry():
27
+ try:
28
+ with open(REGISTRY_FILE, "r", encoding="utf-8") as registry:
29
+ data = json.load(registry)
30
+ except (OSError, json.JSONDecodeError):
31
+ data = {"repositories": []}
32
+ data.setdefault("repositories", [])
33
+ return data
34
+
35
+
36
+ def save_repository_registry(data):
37
+ with open(REGISTRY_FILE, "w", encoding="utf-8") as registry:
38
+ json.dump(data, registry, indent=2, sort_keys=True)
39
+
40
+
41
+ def repository_name_from_path(path):
42
+ return os.path.basename(os.path.realpath(path)) or os.path.realpath(path)
43
+
44
+
45
+ def repository_name_from_github_url(url):
46
+ match = GITHUB_REPOSITORY_PATTERN.match(url.strip())
47
+ if not match:
48
+ return None
49
+ return f"{match.group(1)}/{match.group(2)}"
50
+
51
+
52
+ def has_source_files(path):
53
+ walked = 0
54
+ for root, dirs, files in os.walk(path):
55
+ dirs[:] = [
56
+ directory for directory in dirs
57
+ if directory not in {
58
+ ".git", "node_modules", ".venv", "venv", "__pycache__", "dist", "build",
59
+ ".adre_repositories", "coverage",
60
+ } and not directory.startswith(".")
61
+ ]
62
+ for file_name in files:
63
+ walked += 1
64
+ if os.path.splitext(file_name)[1].lower() in SOURCE_EXTENSIONS:
65
+ return True
66
+ if walked >= SOURCE_WALK_LIMIT:
67
+ return False
68
+ return False
69
+
70
+
71
+ def normalize_local_path(path):
72
+ expanded = os.path.expanduser(path.strip())
73
+ if not expanded:
74
+ raise ValueError("Enter a local repository path.")
75
+ if os.path.isabs(expanded):
76
+ candidate = expanded
77
+ else:
78
+ candidate = os.path.join(os.getcwd(), expanded)
79
+ return os.path.realpath(candidate)
80
+
81
+
82
+ def validate_local_repository(path):
83
+ absolute_path = normalize_local_path(path)
84
+ if not os.path.isdir(absolute_path):
85
+ raise ValueError("Local repository directory does not exist.")
86
+ if not os.access(absolute_path, os.R_OK):
87
+ raise ValueError("Local repository directory is not readable.")
88
+ if not has_source_files(absolute_path):
89
+ raise ValueError("Local repository does not contain recognized source files.")
90
+ return absolute_path
91
+
92
+
93
+ def validate_github_url(url):
94
+ normalized_url = url.strip()
95
+ match = GITHUB_REPOSITORY_PATTERN.match(normalized_url)
96
+ if not match:
97
+ raise ValueError("Enter a valid GitHub repository URL such as https://github.com/user/repo.")
98
+ owner, repository = match.groups()
99
+ return f"https://github.com/{owner}/{repository}.git"
100
+
101
+
102
+ def clone_directory_for_url(url):
103
+ digest = hashlib.sha256(url.encode("utf-8")).hexdigest()[:16]
104
+ name = repository_name_from_github_url(url.replace(".git", "")) or digest
105
+ safe_name = re.sub(r"[^A-Za-z0-9_.-]+", "-", name)
106
+ return os.path.join(TEMP_REPOSITORY_ROOT, f"{safe_name}-{digest}")
107
+
108
+
109
+ def cleanup_old_temporary_repositories(active_paths):
110
+ os.makedirs(TEMP_REPOSITORY_ROOT, exist_ok=True)
111
+ active = {os.path.realpath(path) for path in active_paths}
112
+ for entry in os.listdir(TEMP_REPOSITORY_ROOT):
113
+ candidate = os.path.realpath(os.path.join(TEMP_REPOSITORY_ROOT, entry))
114
+ if not candidate.startswith(TEMP_REPOSITORY_ROOT + os.sep):
115
+ continue
116
+ if candidate not in active and os.path.isdir(candidate):
117
+ shutil.rmtree(candidate, ignore_errors=True)
118
+
119
+
120
+ def clone_or_reuse_github_repository(url):
121
+ clone_url = validate_github_url(url)
122
+ clone_path = os.path.realpath(clone_directory_for_url(clone_url))
123
+ if clone_path != TEMP_REPOSITORY_ROOT and not clone_path.startswith(TEMP_REPOSITORY_ROOT + os.sep):
124
+ raise ValueError("Unsafe clone destination was rejected.")
125
+
126
+ os.makedirs(TEMP_REPOSITORY_ROOT, exist_ok=True)
127
+ if os.path.isdir(os.path.join(clone_path, ".git")) and has_source_files(clone_path):
128
+ return clone_path, clone_url
129
+
130
+ if os.path.isdir(clone_path):
131
+ shutil.rmtree(clone_path)
132
+
133
+ try:
134
+ run_git_command(
135
+ None,
136
+ ["clone", "--depth", "1", "--template=", clone_url, clone_path],
137
+ timeout=120,
138
+ )
139
+ except FileNotFoundError as exc:
140
+ raise RuntimeError("Git CLI is not available on this machine.") from exc
141
+ except subprocess.TimeoutExpired as exc:
142
+ raise RuntimeError("GitHub clone timed out. Try again or clone the repository locally.") from exc
143
+ except subprocess.CalledProcessError as exc:
144
+ details = (exc.stderr or exc.stdout or "").strip()
145
+ raise RuntimeError(details or "GitHub clone failed.") from exc
146
+
147
+ if not has_source_files(clone_path):
148
+ raise ValueError("Cloned GitHub repository does not contain recognized source files.")
149
+ return clone_path, clone_url
150
+
151
+
152
+ def upsert_repository(name, source_type, path, source_url=None):
153
+ registry = load_repository_registry()
154
+ absolute_path = os.path.realpath(path)
155
+ now = utc_now()
156
+ entry = {
157
+ "name": name,
158
+ "source_type": source_type,
159
+ "path": absolute_path,
160
+ "source_url": source_url or "",
161
+ "last_analyzed": now,
162
+ }
163
+
164
+ repositories = [
165
+ item for item in registry["repositories"]
166
+ if os.path.realpath(item.get("path", "")) != absolute_path
167
+ ]
168
+ repositories.insert(0, entry)
169
+ registry["repositories"] = repositories[:20]
170
+ save_repository_registry(registry)
171
+
172
+ active_github_paths = [
173
+ item["path"] for item in registry["repositories"]
174
+ if item.get("source_type") == "github"
175
+ ]
176
+ cleanup_old_temporary_repositories(active_github_paths)
177
+ return entry
178
+
179
+
180
+ def register_local_repository(path):
181
+ absolute_path = validate_local_repository(path)
182
+ return upsert_repository(repository_name_from_path(absolute_path), "local", absolute_path)
183
+
184
+
185
+ def register_github_repository(url):
186
+ clone_path, clone_url = clone_or_reuse_github_repository(url)
187
+ name = repository_name_from_github_url(clone_url.replace(".git", "")) or repository_name_from_path(clone_path)
188
+ return upsert_repository(name, "github", clone_path, source_url=clone_url)
189
+
190
+
191
+ def get_recent_repositories(limit=8):
192
+ registry = load_repository_registry()
193
+ return registry.get("repositories", [])[:limit]
194
+
195
+
196
+ def get_pinned_repositories():
197
+ return [item for item in load_repository_registry().get("repositories", []) if item.get("pinned")]
198
+
199
+
200
+ def toggle_repository_pin(path):
201
+ absolute_path = os.path.realpath(path)
202
+ registry = load_repository_registry()
203
+ updated = None
204
+ for item in registry.get("repositories", []):
205
+ if os.path.realpath(item.get("path", "")) == absolute_path:
206
+ item["pinned"] = not item.get("pinned", False)
207
+ updated = item
208
+ break
209
+ if updated:
210
+ save_repository_registry(registry)
211
+ return updated
212
+
213
+
214
+ def list_browsable_directories(parent_path=None, limit=80):
215
+ if parent_path in (None, "", "~", "home"):
216
+ shortcuts = [
217
+ os.path.expanduser("~"),
218
+ os.path.join(os.path.expanduser("~"), "Projects"),
219
+ os.path.join(os.path.expanduser("~"), "Developer"),
220
+ os.path.join(os.path.expanduser("~"), "repos"),
221
+ os.getcwd(),
222
+ ]
223
+ seen = set()
224
+ directories = []
225
+ for candidate in shortcuts:
226
+ real_path = os.path.realpath(candidate)
227
+ if real_path in seen or not os.path.isdir(real_path) or not os.access(real_path, os.R_OK):
228
+ continue
229
+ seen.add(real_path)
230
+ directories.append({
231
+ "name": os.path.basename(real_path) or real_path,
232
+ "path": real_path,
233
+ "has_source_files": has_source_files(real_path),
234
+ })
235
+ return {
236
+ "parent": "",
237
+ "parent_up": "",
238
+ "can_go_up": False,
239
+ "directories": directories,
240
+ }
241
+
242
+ absolute_path = normalize_local_path(parent_path)
243
+ if not os.path.isdir(absolute_path):
244
+ raise ValueError("Directory does not exist.")
245
+ if not os.access(absolute_path, os.R_OK):
246
+ raise ValueError("Directory is not readable.")
247
+
248
+ directories = []
249
+ try:
250
+ for entry_name in sorted(os.listdir(absolute_path))[:limit]:
251
+ if entry_name.startswith("."):
252
+ continue
253
+ entry_path = os.path.realpath(os.path.join(absolute_path, entry_name))
254
+ if os.path.isdir(entry_path) and os.access(entry_path, os.R_OK):
255
+ directories.append({
256
+ "name": entry_name,
257
+ "path": entry_path,
258
+ "has_source_files": has_source_files(entry_path),
259
+ })
260
+ except OSError as exc:
261
+ raise ValueError("Could not list directory contents.") from exc
262
+
263
+ parent_up = os.path.dirname(absolute_path)
264
+ can_go_up = parent_up != absolute_path and os.access(parent_up, os.R_OK)
265
+ return {
266
+ "parent": absolute_path,
267
+ "parent_up": parent_up if can_go_up else "",
268
+ "can_go_up": can_go_up,
269
+ "directories": directories,
270
+ }
271
+
272
+
273
+ def ensure_repository_context(path):
274
+ absolute_path = normalize_local_path(path)
275
+ entry = find_repository_for_path(absolute_path)
276
+ if entry:
277
+ return entry
278
+ if os.path.isdir(absolute_path) and has_source_files(absolute_path):
279
+ return upsert_repository(repository_name_from_path(absolute_path), "local", absolute_path)
280
+ return repository_display_context(absolute_path)
281
+
282
+
283
+ def find_repository_for_path(path):
284
+ absolute_path = os.path.realpath(path)
285
+ for item in load_repository_registry().get("repositories", []):
286
+ item_path = os.path.realpath(item.get("path", ""))
287
+ if absolute_path == item_path or absolute_path.startswith(item_path + os.sep):
288
+ return item
289
+ return None
290
+
291
+
292
+ def repository_display_context(path):
293
+ entry = find_repository_for_path(path)
294
+ if entry:
295
+ return entry
296
+ absolute_path = os.path.realpath(path)
297
+ return {
298
+ "name": repository_name_from_path(absolute_path),
299
+ "source_type": "local",
300
+ "path": absolute_path,
301
+ "source_url": "",
302
+ "last_analyzed": "",
303
+ }
304
+
305
+
306
+ def allowed_source_roots():
307
+ roots = {os.path.realpath(os.getcwd())}
308
+ for item in load_repository_registry().get("repositories", []):
309
+ path = item.get("path")
310
+ if path:
311
+ roots.add(os.path.realpath(path))
312
+ return roots
adre/core/review.py ADDED
@@ -0,0 +1,96 @@
1
+ """Working-tree review shared by `adre review` and the web UI.
2
+
3
+ Both interfaces must give the same answer: compare the current tree with the
4
+ saved baseline, apply the declared architecture (`.adre/architecture.json`),
5
+ move findings covered by `.adre/accepted.json` aside, and list stale accepted
6
+ entries.
7
+ """
8
+ import json
9
+ import os
10
+
11
+ from adre.analyzers.architecture import analyze_project_architecture
12
+ from adre.core.accepted import (
13
+ accepted_fail_on_stale,
14
+ apply_accepted,
15
+ load_accepted,
16
+ stale_accepted_rules,
17
+ )
18
+ from adre.core.baseline import compare_to_baseline, load_architecture_baseline, resolve_baseline_path
19
+ from adre.core.declared import load_declared
20
+
21
+
22
+ OK = "ok"
23
+ NO_BASELINE = "no_baseline"
24
+ INVALID = "invalid"
25
+
26
+ RULES_ONLY_BASELINE = {"enough_structure": False, "layers": [], "scope": {}, "dependencies": [], "cycles": []}
27
+
28
+
29
+ def review_working_tree(project_path, baseline_path=None, selected_paths=None, expand_related=True, analysis=None):
30
+ """Review the current tree. Returns a dict with:
31
+
32
+ status: "ok", "no_baseline" (no baseline and no declared rules) or
33
+ "invalid" (baseline, architecture.json or accepted.json unreadable)
34
+ error: message for "invalid"
35
+ comparison: compare_to_baseline result plus accepted_drift,
36
+ stale_accepted, fail_on_stale and rules_only
37
+ analysis: the current analysis
38
+ baseline_path: the baseline file used (or that would be used)
39
+ exit_code: 0 clean, 2 drift (or stale entries with fail_on_stale), 1 error
40
+ """
41
+ explicit = baseline_path
42
+ baseline_path = resolve_baseline_path(project_path, explicit)
43
+ result = {
44
+ "status": OK,
45
+ "error": "",
46
+ "comparison": None,
47
+ "analysis": analysis,
48
+ "baseline_path": baseline_path,
49
+ "exit_code": 0,
50
+ }
51
+ try:
52
+ declared = load_declared(project_path)
53
+ accepted_rules = load_accepted(project_path)
54
+ except ValueError as exc:
55
+ result.update(status=INVALID, error=str(exc), exit_code=1)
56
+ return result
57
+
58
+ rules_only = False
59
+ if os.path.isfile(baseline_path):
60
+ try:
61
+ baseline = load_architecture_baseline(baseline_path)
62
+ except (OSError, ValueError, json.JSONDecodeError) as exc:
63
+ result.update(status=INVALID, error="could not load baseline {0}: {1}".format(baseline_path, exc), exit_code=1)
64
+ return result
65
+ elif declared is not None and not explicit:
66
+ # Rules-only mode: every current dependency is checked against the
67
+ # declared architecture.
68
+ baseline = dict(RULES_ONLY_BASELINE)
69
+ rules_only = True
70
+ else:
71
+ result.update(
72
+ status=NO_BASELINE if not explicit else INVALID,
73
+ error="no baseline at {0}".format(baseline_path),
74
+ exit_code=1,
75
+ )
76
+ return result
77
+
78
+ if analysis is None:
79
+ analysis = analyze_project_architecture(
80
+ project_path,
81
+ selected_paths=selected_paths,
82
+ expand_related=expand_related,
83
+ )
84
+ comparison = compare_to_baseline(baseline, analysis, declared=declared)
85
+ comparison["drift"], comparison["accepted_drift"] = apply_accepted(comparison.get("drift"), accepted_rules)
86
+ comparison["stale_accepted"] = stale_accepted_rules(accepted_rules, analysis)
87
+ comparison["fail_on_stale"] = accepted_fail_on_stale(project_path)
88
+ comparison["rules_only"] = rules_only
89
+ comparison["baseline_path"] = baseline_path
90
+ comparison["incremental"] = analysis.get("incremental") or (analysis.get("scope") or {}).get("incremental")
91
+
92
+ exit_code = 0
93
+ if comparison["drift"] or (comparison["stale_accepted"] and comparison["fail_on_stale"]):
94
+ exit_code = 2
95
+ result.update(comparison=comparison, analysis=analysis, exit_code=exit_code)
96
+ return result
@@ -0,0 +1,75 @@
1
+ SEVERITY_ORDER = {
2
+ "critical": 0,
3
+ "high": 1,
4
+ "medium": 2,
5
+ "low": 3,
6
+ }
7
+
8
+
9
+ def layer_violation_weight(issue):
10
+ severity = issue.get("severity", "low")
11
+ if severity == "critical":
12
+ return 18
13
+ if severity == "high":
14
+ return 14
15
+ if severity == "medium":
16
+ return 9
17
+ return 4
18
+
19
+
20
+ def hotspot_growth_score(dependency_growth_per_file):
21
+ score = 0
22
+ for growth in dependency_growth_per_file:
23
+ inbound_delta = growth.get("inbound_dependency_delta", 0)
24
+ if inbound_delta > 0:
25
+ score += min(20, inbound_delta * 5)
26
+ return score
27
+
28
+
29
+ def calculate_structural_drift_score(
30
+ added_edges,
31
+ removed_edges,
32
+ new_cycles,
33
+ resolved_cycles,
34
+ new_issues,
35
+ fixed_issues,
36
+ dependency_growth_per_file,
37
+ ):
38
+ raw_score = (
39
+ min(12, len(added_edges) * 2)
40
+ + min(70, len(new_cycles) * 35)
41
+ + min(45, sum(layer_violation_weight(issue) for issue in new_issues))
42
+ + min(35, hotspot_growth_score(dependency_growth_per_file))
43
+ - min(10, len(removed_edges) * 2)
44
+ - min(50, len(resolved_cycles) * 25)
45
+ - min(30, sum(layer_violation_weight(issue) for issue in fixed_issues) // 2)
46
+ )
47
+ return max(0, min(100, raw_score))
48
+
49
+
50
+ def classify_architecture_change(
51
+ score_delta=0,
52
+ new_cycle_count=0,
53
+ coupling_growth=0,
54
+ layer_violation_delta=0,
55
+ hotspot_growth=0,
56
+ ):
57
+ if new_cycle_count > 0:
58
+ return "critical"
59
+ if score_delta <= -20:
60
+ return "critical"
61
+ if score_delta < -10:
62
+ return "high"
63
+ if coupling_growth >= 8 or hotspot_growth >= 5 or layer_violation_delta >= 2:
64
+ return "high"
65
+ if score_delta < 0 or coupling_growth >= 4 or hotspot_growth >= 3 or layer_violation_delta >= 1:
66
+ return "medium"
67
+ return "low"
68
+
69
+
70
+ def recommendation_from_risk(risk_level):
71
+ if risk_level == "critical":
72
+ return "block"
73
+ if risk_level in {"high", "medium"}:
74
+ return "warn"
75
+ return "allow"