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.
- adre/__init__.py +5 -0
- adre/analyzers/__init__.py +1 -0
- adre/analyzers/architecture.py +253 -0
- adre/analyzers/findings.py +457 -0
- adre/analyzers/inference.py +163 -0
- adre/cli.py +923 -0
- adre/core/__init__.py +1 -0
- adre/core/accepted.py +225 -0
- adre/core/adaptive.py +221 -0
- adre/core/baseline.py +1165 -0
- adre/core/config.py +60 -0
- adre/core/decision_engine.py +361 -0
- adre/core/declared.py +313 -0
- adre/core/evolution_intelligence.py +390 -0
- adre/core/explainer.py +413 -0
- adre/core/git_intelligence.py +392 -0
- adre/core/github_check.py +212 -0
- adre/core/incremental.py +288 -0
- adre/core/layers.py +306 -0
- adre/core/pr_intelligence.py +261 -0
- adre/core/pr_review.py +454 -0
- adre/core/prioritization.py +196 -0
- adre/core/project.py +41 -0
- adre/core/refactor_intelligence.py +201 -0
- adre/core/repositories.py +312 -0
- adre/core/review.py +96 -0
- adre/core/rules_shared.py +75 -0
- adre/core/sarif.py +141 -0
- adre/core/scope.py +141 -0
- adre/core/snapshots.py +242 -0
- adre/core/stability_intelligence.py +361 -0
- adre/graph/__init__.py +0 -0
- adre/graph/dependencies.py +379 -0
- adre/parsers/__init__.py +87 -0
- adre/parsers/go.py +140 -0
- adre/parsers/javascript.py +364 -0
- adre/parsers/jvm.py +127 -0
- adre/parsers/python.py +153 -0
- adre/reports/__init__.py +1 -0
- adre/reports/architecture.py +349 -0
- adre/rules.py +12 -0
- adre/web.py +3731 -0
- adre_cli-0.1.0.dist-info/METADATA +343 -0
- adre_cli-0.1.0.dist-info/RECORD +48 -0
- adre_cli-0.1.0.dist-info/WHEEL +5 -0
- adre_cli-0.1.0.dist-info/entry_points.txt +2 -0
- adre_cli-0.1.0.dist-info/licenses/LICENSE +202 -0
- adre_cli-0.1.0.dist-info/top_level.txt +1 -0
adre/core/baseline.py
ADDED
|
@@ -0,0 +1,1165 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import os
|
|
3
|
+
from collections import Counter, defaultdict
|
|
4
|
+
from datetime import datetime, timezone
|
|
5
|
+
|
|
6
|
+
from adre.analyzers.findings import import_line_for_file, peer_follow_counts, relationship_confidence
|
|
7
|
+
from adre.core.config import (
|
|
8
|
+
ANALYZER_VERSION,
|
|
9
|
+
BASELINE_DIRNAME,
|
|
10
|
+
BASELINE_FILENAME,
|
|
11
|
+
BASELINE_SCHEMA_VERSION,
|
|
12
|
+
SKIP_DIRS,
|
|
13
|
+
)
|
|
14
|
+
from adre.core.declared import check_declared
|
|
15
|
+
from adre.core.incremental import hash_source_file
|
|
16
|
+
from adre.graph.dependencies import shortest_cycle_through
|
|
17
|
+
from adre.core.layers import GENERIC_CLUSTER_NAMES, persistence_import_hits, role_from_filename, role_for_token
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def architecture_type_from_baseline(baseline):
|
|
21
|
+
baseline = baseline or {}
|
|
22
|
+
if not baseline.get("enough_structure"):
|
|
23
|
+
return "insufficient"
|
|
24
|
+
names = {pattern.get("name") for pattern in baseline.get("patterns") or []}
|
|
25
|
+
if "service_layer" in names and "repository_pattern" in names:
|
|
26
|
+
return "layered"
|
|
27
|
+
if "repository_pattern" in names:
|
|
28
|
+
return "repository"
|
|
29
|
+
if "service_layer" in names:
|
|
30
|
+
return "service_layer"
|
|
31
|
+
if baseline.get("summary_path"):
|
|
32
|
+
return "layered"
|
|
33
|
+
return "observed"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _drift_item(**kwargs):
|
|
37
|
+
changed = kwargs.get("changed") or ""
|
|
38
|
+
established = kwargs.get("established") or kwargs.get("established_pattern") or ""
|
|
39
|
+
reason = kwargs.get("reason") or kwargs.get("why_it_matters") or ""
|
|
40
|
+
kwargs.setdefault("title", "Architectural drift")
|
|
41
|
+
kwargs["changed"] = changed
|
|
42
|
+
kwargs["established"] = established
|
|
43
|
+
kwargs["established_pattern"] = kwargs.get("established_pattern") or established
|
|
44
|
+
kwargs["reason"] = reason
|
|
45
|
+
if not kwargs.get("problem") and changed and established:
|
|
46
|
+
kwargs["problem"] = "{0} violates established {1}.".format(changed, established)
|
|
47
|
+
return kwargs
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
ARCHITECTURAL_ROLES = {"application", "domain", "data"}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def utc_now():
|
|
54
|
+
return datetime.now(timezone.utc).isoformat(timespec="seconds")
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def default_baseline_path(project_root):
|
|
58
|
+
return os.path.join(os.path.realpath(project_root), BASELINE_DIRNAME, BASELINE_FILENAME)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def evidence_item(signal, detail, classification="inferred"):
|
|
62
|
+
return {
|
|
63
|
+
"signal": signal,
|
|
64
|
+
"detail": detail,
|
|
65
|
+
"classification": classification,
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def evidence_lines(items):
|
|
70
|
+
lines = []
|
|
71
|
+
for item in items or []:
|
|
72
|
+
if isinstance(item, dict):
|
|
73
|
+
detail = item.get("detail") or item.get("signal") or ""
|
|
74
|
+
if detail:
|
|
75
|
+
lines.append(detail)
|
|
76
|
+
elif item:
|
|
77
|
+
lines.append(str(item))
|
|
78
|
+
return lines
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _persistence_imports(record):
|
|
82
|
+
return persistence_import_hits(record)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _file_hash(project_root, rel_path):
|
|
86
|
+
absolute = os.path.join(project_root, rel_path)
|
|
87
|
+
return hash_source_file(absolute, project_root=project_root)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _cluster_edge_counts(dependency_graph, resolved_graph):
|
|
91
|
+
counts = Counter()
|
|
92
|
+
examples = defaultdict(list)
|
|
93
|
+
for source, targets in resolved_graph.items():
|
|
94
|
+
source_meta = dependency_graph.get(source) or {}
|
|
95
|
+
src_cluster = source_meta.get("cluster") or "root"
|
|
96
|
+
for target in targets:
|
|
97
|
+
target_meta = dependency_graph.get(target) or {}
|
|
98
|
+
dst_cluster = target_meta.get("cluster") or "root"
|
|
99
|
+
if src_cluster == dst_cluster:
|
|
100
|
+
continue
|
|
101
|
+
counts[(src_cluster, dst_cluster)] += 1
|
|
102
|
+
pair = "{0} -> {1}".format(source, target)
|
|
103
|
+
if pair not in examples[(src_cluster, dst_cluster)]:
|
|
104
|
+
examples[(src_cluster, dst_cluster)].append(pair)
|
|
105
|
+
return counts, examples
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _build_layers(dependency_graph, cluster_edges, edge_examples):
|
|
109
|
+
files_by_cluster = defaultdict(list)
|
|
110
|
+
for file_path, record in dependency_graph.items():
|
|
111
|
+
files_by_cluster[record.get("cluster") or "root"].append(file_path)
|
|
112
|
+
|
|
113
|
+
layers = []
|
|
114
|
+
for cluster, files in sorted(files_by_cluster.items()):
|
|
115
|
+
role_votes = Counter()
|
|
116
|
+
evidence = []
|
|
117
|
+
directory_role = role_for_token(cluster)
|
|
118
|
+
if directory_role:
|
|
119
|
+
role_votes[directory_role] += 2
|
|
120
|
+
evidence.append(evidence_item(
|
|
121
|
+
"directory_name",
|
|
122
|
+
"{0} file(s) live under a {1}/ directory, which is commonly used as a {2} boundary.".format(
|
|
123
|
+
len(files), cluster, directory_role
|
|
124
|
+
),
|
|
125
|
+
"inferred",
|
|
126
|
+
))
|
|
127
|
+
|
|
128
|
+
suffix_hits = 0
|
|
129
|
+
persistence_files = 0
|
|
130
|
+
for file_path in files:
|
|
131
|
+
record = dependency_graph.get(file_path) or {}
|
|
132
|
+
suffix_role = role_from_filename(os.path.basename(file_path))
|
|
133
|
+
if suffix_role:
|
|
134
|
+
suffix_hits += 1
|
|
135
|
+
role_votes[suffix_role] += 1
|
|
136
|
+
if _persistence_imports(record):
|
|
137
|
+
persistence_files += 1
|
|
138
|
+
role_votes["data"] += 1
|
|
139
|
+
|
|
140
|
+
split_files = [
|
|
141
|
+
file_path for file_path in files
|
|
142
|
+
if (dependency_graph.get(file_path) or {}).get("relationship_split")
|
|
143
|
+
]
|
|
144
|
+
if split_files:
|
|
145
|
+
physical = (dependency_graph.get(split_files[0]) or {}).get("physical_cluster") or cluster
|
|
146
|
+
split_role = (dependency_graph.get(split_files[0]) or {}).get("role")
|
|
147
|
+
if split_role:
|
|
148
|
+
role_votes[split_role] += 2
|
|
149
|
+
evidence.append(evidence_item(
|
|
150
|
+
"internal_relationship",
|
|
151
|
+
"{0} file(s) in {1}/ were separated from physical {2}/ because they participate in a proven service/port dependency.".format(
|
|
152
|
+
len(split_files), cluster, physical
|
|
153
|
+
),
|
|
154
|
+
"proven",
|
|
155
|
+
))
|
|
156
|
+
|
|
157
|
+
if suffix_hits:
|
|
158
|
+
evidence.append(evidence_item(
|
|
159
|
+
"filename_suffix",
|
|
160
|
+
"{0} file name(s) in {1}/ use a role suffix such as Controller, Service, or Repository.".format(
|
|
161
|
+
suffix_hits, cluster
|
|
162
|
+
),
|
|
163
|
+
"inferred",
|
|
164
|
+
))
|
|
165
|
+
if persistence_files:
|
|
166
|
+
evidence.append(evidence_item(
|
|
167
|
+
"persistence_import",
|
|
168
|
+
"{0} file(s) in {1}/ import a database driver or ORM.".format(persistence_files, cluster),
|
|
169
|
+
"proven",
|
|
170
|
+
))
|
|
171
|
+
|
|
172
|
+
outgoing = []
|
|
173
|
+
incoming = 0
|
|
174
|
+
for (source, target), count in cluster_edges.items():
|
|
175
|
+
if source == cluster:
|
|
176
|
+
outgoing.append((target, count))
|
|
177
|
+
if target == cluster:
|
|
178
|
+
incoming += count
|
|
179
|
+
if outgoing:
|
|
180
|
+
outgoing.sort(key=lambda item: (-item[1], item[0]))
|
|
181
|
+
top_target, top_count = outgoing[0]
|
|
182
|
+
evidence.append(evidence_item(
|
|
183
|
+
"dependency_direction",
|
|
184
|
+
"{0} resolved import(s) leave {1}/ toward {2}/.".format(top_count, cluster, top_target),
|
|
185
|
+
"proven",
|
|
186
|
+
))
|
|
187
|
+
|
|
188
|
+
if role_votes:
|
|
189
|
+
role, vote_score = role_votes.most_common(1)[0]
|
|
190
|
+
else:
|
|
191
|
+
role, vote_score = "unknown", 0
|
|
192
|
+
|
|
193
|
+
signal_count = len(evidence)
|
|
194
|
+
if vote_score >= 4 and signal_count >= 2:
|
|
195
|
+
confidence = 0.9
|
|
196
|
+
elif vote_score >= 2 and signal_count >= 2:
|
|
197
|
+
confidence = 0.78
|
|
198
|
+
elif signal_count >= 2:
|
|
199
|
+
confidence = 0.64
|
|
200
|
+
elif signal_count == 1:
|
|
201
|
+
confidence = 0.48
|
|
202
|
+
else:
|
|
203
|
+
confidence = 0.2
|
|
204
|
+
role = "unknown"
|
|
205
|
+
|
|
206
|
+
if cluster in GENERIC_CLUSTER_NAMES and not directory_role and suffix_hits == 0:
|
|
207
|
+
role = "unknown"
|
|
208
|
+
confidence = min(confidence, 0.4)
|
|
209
|
+
classification = "insufficient"
|
|
210
|
+
elif role == "unknown":
|
|
211
|
+
classification = "insufficient"
|
|
212
|
+
elif confidence >= 0.85 and any(item["classification"] == "proven" for item in evidence):
|
|
213
|
+
classification = "inferred"
|
|
214
|
+
else:
|
|
215
|
+
classification = "inferred"
|
|
216
|
+
|
|
217
|
+
layers.append({
|
|
218
|
+
"name": cluster,
|
|
219
|
+
"role": role,
|
|
220
|
+
"confidence": round(confidence, 2),
|
|
221
|
+
"classification": classification,
|
|
222
|
+
"file_count": len(files),
|
|
223
|
+
"files": sorted(files),
|
|
224
|
+
"evidence": evidence,
|
|
225
|
+
})
|
|
226
|
+
return layers
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _build_directions(cluster_edges, edge_examples, layers, cycles, resolved_graph):
|
|
230
|
+
del cycles, resolved_graph
|
|
231
|
+
role_by_cluster = {layer["name"]: layer["role"] for layer in layers}
|
|
232
|
+
|
|
233
|
+
outgoing_totals = Counter()
|
|
234
|
+
architectural_outgoing = Counter()
|
|
235
|
+
for (source, target), count in cluster_edges.items():
|
|
236
|
+
outgoing_totals[source] += count
|
|
237
|
+
if role_by_cluster.get(target, "unknown") in ARCHITECTURAL_ROLES:
|
|
238
|
+
architectural_outgoing[source] += count
|
|
239
|
+
|
|
240
|
+
directions = []
|
|
241
|
+
for (source, target), count in sorted(cluster_edges.items(), key=lambda item: (-item[1], item[0])):
|
|
242
|
+
source_role = role_by_cluster.get(source, "unknown")
|
|
243
|
+
target_role = role_by_cluster.get(target, "unknown")
|
|
244
|
+
total = outgoing_totals.get(source) or 1
|
|
245
|
+
share = count / float(total)
|
|
246
|
+
examples = edge_examples.get((source, target), [])[:5]
|
|
247
|
+
if source_role == "presentation" and target_role in {"application", "data"}:
|
|
248
|
+
depth_roles = {"application", "data"}
|
|
249
|
+
depth_total = sum(
|
|
250
|
+
other_count
|
|
251
|
+
for (src, dst), other_count in cluster_edges.items()
|
|
252
|
+
if src == source and role_by_cluster.get(dst, "unknown") in depth_roles
|
|
253
|
+
)
|
|
254
|
+
decision_share = count / float(depth_total or 1)
|
|
255
|
+
competing = [
|
|
256
|
+
other_count
|
|
257
|
+
for (src, dst), other_count in cluster_edges.items()
|
|
258
|
+
if src == source and dst != target
|
|
259
|
+
and role_by_cluster.get(dst, "unknown") in depth_roles
|
|
260
|
+
]
|
|
261
|
+
elif target_role in ARCHITECTURAL_ROLES and architectural_outgoing.get(source):
|
|
262
|
+
decision_share = count / float(architectural_outgoing[source])
|
|
263
|
+
competing = [
|
|
264
|
+
other_count
|
|
265
|
+
for (src, dst), other_count in cluster_edges.items()
|
|
266
|
+
if src == source and dst != target
|
|
267
|
+
and role_by_cluster.get(dst, "unknown") in ARCHITECTURAL_ROLES
|
|
268
|
+
]
|
|
269
|
+
else:
|
|
270
|
+
decision_share = share
|
|
271
|
+
competing = [
|
|
272
|
+
other_count
|
|
273
|
+
for (src, dst), other_count in cluster_edges.items()
|
|
274
|
+
if src == source and dst != target
|
|
275
|
+
]
|
|
276
|
+
|
|
277
|
+
# Unknown/generic clusters (src, modules, dto files) must not drown a
|
|
278
|
+
# real role→role plurality such as controller → service.
|
|
279
|
+
established = decision_share > 0.5 or (decision_share >= 0.5 and count >= 1)
|
|
280
|
+
if competing and count < max(competing):
|
|
281
|
+
established = False
|
|
282
|
+
|
|
283
|
+
directions.append({
|
|
284
|
+
"source": source,
|
|
285
|
+
"target": target,
|
|
286
|
+
"source_role": source_role,
|
|
287
|
+
"target_role": target_role,
|
|
288
|
+
"count": count,
|
|
289
|
+
"share": round(share, 2),
|
|
290
|
+
"architectural_share": round(decision_share, 2),
|
|
291
|
+
"established": bool(established and count >= 1),
|
|
292
|
+
"classification": "proven",
|
|
293
|
+
"confidence": round(min(0.99, 0.55 + decision_share * 0.4 + min(count, 4) * 0.05), 2),
|
|
294
|
+
"evidence": [
|
|
295
|
+
evidence_item("resolved_import", example, "proven")
|
|
296
|
+
for example in examples
|
|
297
|
+
],
|
|
298
|
+
})
|
|
299
|
+
return directions
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def _observed_skip_paths(directions):
|
|
303
|
+
by_source = defaultdict(list)
|
|
304
|
+
data_counts = Counter()
|
|
305
|
+
for direction in directions:
|
|
306
|
+
by_source[direction["source"]].append(direction)
|
|
307
|
+
if direction.get("target_role") == "data":
|
|
308
|
+
data_counts[direction["source"]] += direction.get("count") or 0
|
|
309
|
+
|
|
310
|
+
paths = []
|
|
311
|
+
for first in directions:
|
|
312
|
+
if first["source_role"] == "unknown" or first["target_role"] == "unknown":
|
|
313
|
+
continue
|
|
314
|
+
if not first.get("established"):
|
|
315
|
+
continue
|
|
316
|
+
if first["source_role"] != "presentation":
|
|
317
|
+
continue
|
|
318
|
+
if first["target_role"] not in {"application", "domain"}:
|
|
319
|
+
continue
|
|
320
|
+
# A minority helper (1/10 controllers → services) is not a skip path
|
|
321
|
+
# when most peers already go straight to data.
|
|
322
|
+
if (first.get("count") or 0) < (data_counts.get(first["source"]) or 0):
|
|
323
|
+
continue
|
|
324
|
+
for second in by_source.get(first["target"], []):
|
|
325
|
+
if second["target"] == first["source"]:
|
|
326
|
+
continue
|
|
327
|
+
if not second.get("established"):
|
|
328
|
+
continue
|
|
329
|
+
if second["target_role"] != "data":
|
|
330
|
+
continue
|
|
331
|
+
paths.append({
|
|
332
|
+
"source": first["source"],
|
|
333
|
+
"intermediate": first["target"],
|
|
334
|
+
"target": second["target"],
|
|
335
|
+
"path": "{0} -> {1} -> {2}".format(first["source"], first["target"], second["target"]),
|
|
336
|
+
"classification": "inferred",
|
|
337
|
+
})
|
|
338
|
+
return paths
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def _build_patterns(layers, directions, skip_paths, dependency_graph, resolved_graph):
|
|
342
|
+
patterns = []
|
|
343
|
+
role_clusters = defaultdict(list)
|
|
344
|
+
for layer in layers:
|
|
345
|
+
if layer["role"] != "unknown" and layer["confidence"] >= 0.6:
|
|
346
|
+
role_clusters[layer["role"]].append(layer)
|
|
347
|
+
|
|
348
|
+
established_presentation_to_application = any(
|
|
349
|
+
direction.get("established")
|
|
350
|
+
and direction.get("source_role") == "presentation"
|
|
351
|
+
and direction.get("target_role") == "application"
|
|
352
|
+
for direction in directions
|
|
353
|
+
)
|
|
354
|
+
if role_clusters.get("presentation") and role_clusters.get("application") and established_presentation_to_application:
|
|
355
|
+
path = " -> ".join(
|
|
356
|
+
layer["name"]
|
|
357
|
+
for role in ("presentation", "application", "domain", "data")
|
|
358
|
+
for layer in role_clusters.get(role, [])[:1]
|
|
359
|
+
)
|
|
360
|
+
evidence = []
|
|
361
|
+
for role in ("presentation", "application"):
|
|
362
|
+
layer = role_clusters[role][0]
|
|
363
|
+
evidence.extend(layer["evidence"][:2])
|
|
364
|
+
for direction in directions:
|
|
365
|
+
if (
|
|
366
|
+
direction.get("established")
|
|
367
|
+
and direction["source_role"] == "presentation"
|
|
368
|
+
and direction["target_role"] == "application"
|
|
369
|
+
):
|
|
370
|
+
evidence.append(evidence_item(
|
|
371
|
+
"dependency_direction",
|
|
372
|
+
"{0} -> {1} is observed {2} time(s).".format(
|
|
373
|
+
direction["source"], direction["target"], direction["count"]
|
|
374
|
+
),
|
|
375
|
+
"proven",
|
|
376
|
+
))
|
|
377
|
+
break
|
|
378
|
+
patterns.append({
|
|
379
|
+
"name": "service_layer",
|
|
380
|
+
"classification": "inferred",
|
|
381
|
+
"confidence": round(min(layer["confidence"] for layer in (
|
|
382
|
+
role_clusters["presentation"][0],
|
|
383
|
+
role_clusters["application"][0],
|
|
384
|
+
)), 2),
|
|
385
|
+
"affected_files": role_clusters["presentation"][0]["files"][:8] + role_clusters["application"][0]["files"][:8],
|
|
386
|
+
"summary": path,
|
|
387
|
+
"evidence": evidence[:6],
|
|
388
|
+
})
|
|
389
|
+
|
|
390
|
+
named_data_layers = []
|
|
391
|
+
for layer in role_clusters.get("data") or []:
|
|
392
|
+
if role_for_token(layer["name"]) == "data":
|
|
393
|
+
named_data_layers.append(layer)
|
|
394
|
+
continue
|
|
395
|
+
if any(role_from_filename(os.path.basename(path)) == "data" for path in layer.get("files") or []):
|
|
396
|
+
named_data_layers.append(layer)
|
|
397
|
+
data_layers = named_data_layers
|
|
398
|
+
if data_layers:
|
|
399
|
+
data_files = []
|
|
400
|
+
for layer in data_layers:
|
|
401
|
+
data_files.extend(layer["files"])
|
|
402
|
+
dependents = []
|
|
403
|
+
db_files = []
|
|
404
|
+
for file_path in data_files:
|
|
405
|
+
record = dependency_graph.get(file_path) or {}
|
|
406
|
+
if _persistence_imports(record):
|
|
407
|
+
db_files.append(file_path)
|
|
408
|
+
for source, targets in resolved_graph.items():
|
|
409
|
+
if file_path in targets and source not in data_files:
|
|
410
|
+
dependents.append("{0} -> {1}".format(source, file_path))
|
|
411
|
+
if dependents:
|
|
412
|
+
evidence = [
|
|
413
|
+
evidence_item(
|
|
414
|
+
"inbound_dependency",
|
|
415
|
+
"{0} module(s) depend on {1} data/persistence module(s).".format(
|
|
416
|
+
len(set(item.split(" -> ")[0] for item in dependents)),
|
|
417
|
+
len(data_files),
|
|
418
|
+
),
|
|
419
|
+
"proven",
|
|
420
|
+
)
|
|
421
|
+
]
|
|
422
|
+
if db_files:
|
|
423
|
+
evidence.append(evidence_item(
|
|
424
|
+
"persistence_import",
|
|
425
|
+
"Database access is contained in: {0}.".format(", ".join(db_files[:5])),
|
|
426
|
+
"proven",
|
|
427
|
+
))
|
|
428
|
+
evidence.append(evidence_item(
|
|
429
|
+
"directory_name",
|
|
430
|
+
"Data-layer directories: {0}.".format(", ".join(layer["name"] for layer in data_layers)),
|
|
431
|
+
"inferred",
|
|
432
|
+
))
|
|
433
|
+
patterns.append({
|
|
434
|
+
"name": "repository_pattern",
|
|
435
|
+
"classification": "inferred",
|
|
436
|
+
"confidence": 0.86 if db_files and len(dependents) >= 1 else 0.7,
|
|
437
|
+
"affected_files": data_files[:12],
|
|
438
|
+
"summary": "{0} used as persistence boundary".format(data_layers[0]["name"]),
|
|
439
|
+
"evidence": evidence,
|
|
440
|
+
})
|
|
441
|
+
|
|
442
|
+
if skip_paths:
|
|
443
|
+
patterns.append({
|
|
444
|
+
"name": "layered_dependency_direction",
|
|
445
|
+
"classification": "inferred",
|
|
446
|
+
"confidence": 0.84,
|
|
447
|
+
"affected_files": [],
|
|
448
|
+
"summary": skip_paths[0]["path"],
|
|
449
|
+
"evidence": [
|
|
450
|
+
evidence_item("observed_path", item["path"], "proven")
|
|
451
|
+
for item in skip_paths[:4]
|
|
452
|
+
],
|
|
453
|
+
})
|
|
454
|
+
return patterns
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
def _enough_structure(layers, directions, patterns):
|
|
458
|
+
known_layers = [layer for layer in layers if layer["role"] != "unknown" and layer["confidence"] >= 0.6]
|
|
459
|
+
proven_directions = [item for item in directions if item["count"] >= 1]
|
|
460
|
+
if len(known_layers) < 2 or not proven_directions:
|
|
461
|
+
return False
|
|
462
|
+
if any(pattern["name"] in {"service_layer", "repository_pattern", "layered_dependency_direction"} for pattern in patterns):
|
|
463
|
+
return True
|
|
464
|
+
established_role_dirs = [
|
|
465
|
+
item for item in directions
|
|
466
|
+
if item.get("established")
|
|
467
|
+
and item.get("source_role") not in {None, "unknown"}
|
|
468
|
+
and item.get("target_role") not in {None, "unknown"}
|
|
469
|
+
and item.get("source_role") != item.get("target_role")
|
|
470
|
+
]
|
|
471
|
+
return len(known_layers) >= 3 and len(established_role_dirs) >= 2
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
def _summary_path(layers, skip_paths, patterns):
|
|
475
|
+
del layers
|
|
476
|
+
if skip_paths:
|
|
477
|
+
return skip_paths[0]["path"]
|
|
478
|
+
for name in ("layered_dependency_direction", "service_layer", "repository_pattern"):
|
|
479
|
+
for pattern in patterns:
|
|
480
|
+
if pattern.get("name") == name and pattern.get("summary"):
|
|
481
|
+
return pattern["summary"]
|
|
482
|
+
return ""
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
def _persistence_access(dependency_graph):
|
|
486
|
+
access = []
|
|
487
|
+
for file_path, record in sorted(dependency_graph.items()):
|
|
488
|
+
for hit in _persistence_imports(record or {}):
|
|
489
|
+
access.append({
|
|
490
|
+
"file": file_path,
|
|
491
|
+
"module": hit.get("module"),
|
|
492
|
+
"line": hit.get("line"),
|
|
493
|
+
"classification": "proven",
|
|
494
|
+
})
|
|
495
|
+
return access
|
|
496
|
+
|
|
497
|
+
|
|
498
|
+
def _file_entries(project_root, dependency_graph, resolved_graph):
|
|
499
|
+
entries = []
|
|
500
|
+
inbound = Counter()
|
|
501
|
+
for source, targets in resolved_graph.items():
|
|
502
|
+
for target in targets:
|
|
503
|
+
inbound[target] += 1
|
|
504
|
+
for file_path, record in sorted(dependency_graph.items()):
|
|
505
|
+
entries.append({
|
|
506
|
+
"path": file_path,
|
|
507
|
+
"cluster": record.get("cluster") or "root",
|
|
508
|
+
"role": record.get("role") or "unknown",
|
|
509
|
+
"language": record.get("language"),
|
|
510
|
+
"symbols": [symbol.get("name") for symbol in (record.get("symbols") or []) if symbol.get("name")][:12],
|
|
511
|
+
"depends_on": sorted(resolved_graph.get(file_path, [])),
|
|
512
|
+
"depended_on_by_count": inbound.get(file_path, 0),
|
|
513
|
+
"hash": _file_hash(project_root, file_path),
|
|
514
|
+
})
|
|
515
|
+
return entries
|
|
516
|
+
|
|
517
|
+
|
|
518
|
+
def build_architecture_baseline(
|
|
519
|
+
project_root,
|
|
520
|
+
scope,
|
|
521
|
+
dependency_graph,
|
|
522
|
+
resolved_graph,
|
|
523
|
+
inferred=None,
|
|
524
|
+
cycles=None,
|
|
525
|
+
architecture_detection=None,
|
|
526
|
+
cycle_groups=None,
|
|
527
|
+
runtime_graph=None,
|
|
528
|
+
):
|
|
529
|
+
del runtime_graph
|
|
530
|
+
inferred = inferred or {}
|
|
531
|
+
cycles = cycles or []
|
|
532
|
+
cycle_groups = _groups_from_cycles(cycles) if cycle_groups is None else [list(group) for group in cycle_groups]
|
|
533
|
+
del architecture_detection
|
|
534
|
+
cluster_edges, edge_examples = _cluster_edge_counts(dependency_graph, resolved_graph)
|
|
535
|
+
layers = _build_layers(dependency_graph, cluster_edges, edge_examples)
|
|
536
|
+
directions = _build_directions(cluster_edges, edge_examples, layers, cycles, resolved_graph)
|
|
537
|
+
skip_paths = _observed_skip_paths(directions)
|
|
538
|
+
skip_hops = {
|
|
539
|
+
(item["source"], item["intermediate"]) for item in skip_paths
|
|
540
|
+
} | {
|
|
541
|
+
(item["intermediate"], item["target"]) for item in skip_paths
|
|
542
|
+
}
|
|
543
|
+
for direction in directions:
|
|
544
|
+
if (direction["source"], direction["target"]) in skip_hops:
|
|
545
|
+
direction["established"] = True
|
|
546
|
+
patterns = _build_patterns(layers, directions, skip_paths, dependency_graph, resolved_graph)
|
|
547
|
+
enough = _enough_structure(layers, directions, patterns)
|
|
548
|
+
known_layers = [layer for layer in layers if layer["role"] != "unknown"]
|
|
549
|
+
if enough and known_layers:
|
|
550
|
+
confidence = round(sum(layer["confidence"] for layer in known_layers) / float(len(known_layers)), 2)
|
|
551
|
+
classification = "inferred"
|
|
552
|
+
elif known_layers:
|
|
553
|
+
confidence = round(min(0.49, sum(layer["confidence"] for layer in known_layers) / float(len(known_layers))), 2)
|
|
554
|
+
classification = "insufficient"
|
|
555
|
+
enough = False
|
|
556
|
+
else:
|
|
557
|
+
confidence = 0.2
|
|
558
|
+
classification = "insufficient"
|
|
559
|
+
enough = False
|
|
560
|
+
|
|
561
|
+
scope_payload = dict(scope or {})
|
|
562
|
+
scope_payload.setdefault("excluded_directories", sorted(SKIP_DIRS))
|
|
563
|
+
|
|
564
|
+
dependencies = []
|
|
565
|
+
for source, targets in sorted(resolved_graph.items()):
|
|
566
|
+
for target in sorted(targets):
|
|
567
|
+
dependencies.append({
|
|
568
|
+
"source": source,
|
|
569
|
+
"target": target,
|
|
570
|
+
"classification": "proven",
|
|
571
|
+
})
|
|
572
|
+
|
|
573
|
+
return {
|
|
574
|
+
"schema_version": BASELINE_SCHEMA_VERSION,
|
|
575
|
+
"analyzer_version": ANALYZER_VERSION,
|
|
576
|
+
"created_at": utc_now(),
|
|
577
|
+
"project_root": project_root,
|
|
578
|
+
"repository": os.path.basename(os.path.realpath(project_root)),
|
|
579
|
+
"scope": scope_payload,
|
|
580
|
+
"classification": classification,
|
|
581
|
+
"confidence": confidence,
|
|
582
|
+
"enough_structure": enough,
|
|
583
|
+
"summary_path": _summary_path(layers, skip_paths, patterns) if enough else "",
|
|
584
|
+
"architecture_type": architecture_type_from_baseline({
|
|
585
|
+
"enough_structure": enough,
|
|
586
|
+
"patterns": patterns,
|
|
587
|
+
"summary_path": _summary_path(layers, skip_paths, patterns) if enough else "",
|
|
588
|
+
}),
|
|
589
|
+
"layers": layers,
|
|
590
|
+
"directions": directions,
|
|
591
|
+
"skip_paths": skip_paths,
|
|
592
|
+
"patterns": patterns,
|
|
593
|
+
"boundaries": [
|
|
594
|
+
{
|
|
595
|
+
"from": direction["source"],
|
|
596
|
+
"to": direction["target"],
|
|
597
|
+
"established": direction["established"],
|
|
598
|
+
}
|
|
599
|
+
for direction in directions
|
|
600
|
+
if direction["established"]
|
|
601
|
+
],
|
|
602
|
+
"dependencies": dependencies,
|
|
603
|
+
"persistence_access": _persistence_access(dependency_graph),
|
|
604
|
+
"cycles": cycles,
|
|
605
|
+
"cycle_groups": cycle_groups,
|
|
606
|
+
"files": _file_entries(project_root, dependency_graph, resolved_graph),
|
|
607
|
+
"notes": [] if enough else [
|
|
608
|
+
"Not enough repeated structure to treat this as an established architecture. Findings are limited to proven graph facts such as cycles."
|
|
609
|
+
],
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
|
|
613
|
+
def save_architecture_baseline(baseline, destination=None):
|
|
614
|
+
project_root = os.path.realpath(baseline.get("project_root") or os.getcwd())
|
|
615
|
+
if destination:
|
|
616
|
+
raw = destination
|
|
617
|
+
path = destination if os.path.isabs(destination) else os.path.join(project_root, destination)
|
|
618
|
+
path = os.path.realpath(path)
|
|
619
|
+
if not os.path.isabs(raw) and path != project_root and not path.startswith(project_root + os.sep):
|
|
620
|
+
raise ValueError("Baseline destination must stay inside the project.")
|
|
621
|
+
else:
|
|
622
|
+
path = default_baseline_path(project_root)
|
|
623
|
+
directory = os.path.dirname(path)
|
|
624
|
+
os.makedirs(directory, exist_ok=True)
|
|
625
|
+
payload = dict(baseline)
|
|
626
|
+
payload["saved_at"] = utc_now()
|
|
627
|
+
with open(path, "w", encoding="utf-8") as handle:
|
|
628
|
+
json.dump(payload, handle, indent=2, sort_keys=True)
|
|
629
|
+
return path
|
|
630
|
+
|
|
631
|
+
|
|
632
|
+
def validate_architecture_baseline(data, source="baseline"):
|
|
633
|
+
if not isinstance(data, dict) or "layers" not in data or "scope" not in data:
|
|
634
|
+
raise ValueError("{0} is not an architecture baseline.".format(source))
|
|
635
|
+
schema = data.get("schema_version") or 1
|
|
636
|
+
try:
|
|
637
|
+
schema = int(schema)
|
|
638
|
+
except (TypeError, ValueError):
|
|
639
|
+
raise ValueError("{0} has an invalid schema version.".format(source))
|
|
640
|
+
if schema < 1:
|
|
641
|
+
raise ValueError("{0} has an unsupported schema version.".format(source))
|
|
642
|
+
if schema > BASELINE_SCHEMA_VERSION:
|
|
643
|
+
raise ValueError(
|
|
644
|
+
"Baseline schema {0} is newer than analyzer schema {1}.".format(
|
|
645
|
+
schema, BASELINE_SCHEMA_VERSION
|
|
646
|
+
)
|
|
647
|
+
)
|
|
648
|
+
return data
|
|
649
|
+
|
|
650
|
+
|
|
651
|
+
def load_architecture_baseline(path):
|
|
652
|
+
with open(path, "r", encoding="utf-8") as handle:
|
|
653
|
+
data = json.load(handle)
|
|
654
|
+
return validate_architecture_baseline(data, source=path)
|
|
655
|
+
|
|
656
|
+
|
|
657
|
+
|
|
658
|
+
def resolve_baseline_path(project_root, explicit_path=None):
|
|
659
|
+
if explicit_path:
|
|
660
|
+
if os.path.isabs(explicit_path):
|
|
661
|
+
return os.path.realpath(explicit_path)
|
|
662
|
+
cwd_candidate = os.path.realpath(explicit_path)
|
|
663
|
+
if os.path.isfile(cwd_candidate):
|
|
664
|
+
return cwd_candidate
|
|
665
|
+
return os.path.realpath(os.path.join(project_root, explicit_path))
|
|
666
|
+
return default_baseline_path(project_root)
|
|
667
|
+
|
|
668
|
+
|
|
669
|
+
def _edge_set(baseline):
|
|
670
|
+
return {
|
|
671
|
+
(item["source"], item["target"])
|
|
672
|
+
for item in baseline.get("dependencies") or []
|
|
673
|
+
if item.get("source") and item.get("target")
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
|
|
677
|
+
def _groups_from_cycles(cycles):
|
|
678
|
+
"""Merge cycles that share files into cycle groups (for old baselines)."""
|
|
679
|
+
parent = {}
|
|
680
|
+
|
|
681
|
+
def find(item):
|
|
682
|
+
while parent[item] != item:
|
|
683
|
+
parent[item] = parent[parent[item]]
|
|
684
|
+
item = parent[item]
|
|
685
|
+
return item
|
|
686
|
+
|
|
687
|
+
for cycle in cycles or []:
|
|
688
|
+
members = [item for item in cycle if item]
|
|
689
|
+
for item in members:
|
|
690
|
+
parent.setdefault(item, item)
|
|
691
|
+
for item in members[1:]:
|
|
692
|
+
root_a, root_b = find(members[0]), find(item)
|
|
693
|
+
if root_a != root_b:
|
|
694
|
+
parent[root_b] = root_a
|
|
695
|
+
groups = defaultdict(set)
|
|
696
|
+
for item in parent:
|
|
697
|
+
groups[find(item)].add(item)
|
|
698
|
+
return [sorted(group) for group in groups.values() if len(group) > 1]
|
|
699
|
+
|
|
700
|
+
|
|
701
|
+
def _cycle_groups(container, renames=None):
|
|
702
|
+
"""Cycle groups (strongly connected files) from a baseline or architecture dict."""
|
|
703
|
+
renames = renames or {}
|
|
704
|
+
container = container or {}
|
|
705
|
+
groups = container.get("cycle_groups")
|
|
706
|
+
if groups is None:
|
|
707
|
+
groups = _groups_from_cycles(container.get("cycles"))
|
|
708
|
+
mapped = []
|
|
709
|
+
for group in groups or []:
|
|
710
|
+
members = sorted({renames.get(item, item) for item in group if item})
|
|
711
|
+
if len(members) > 1:
|
|
712
|
+
mapped.append(members)
|
|
713
|
+
return sorted(mapped, key=lambda group: (-len(group), group))
|
|
714
|
+
|
|
715
|
+
|
|
716
|
+
def _analysis_cycle_groups(analysis, renames=None):
|
|
717
|
+
current = analysis.get("architecture") or {}
|
|
718
|
+
if current.get("cycle_groups") is not None or current.get("cycles") is not None:
|
|
719
|
+
return _cycle_groups(current, renames)
|
|
720
|
+
return _cycle_groups(analysis, renames)
|
|
721
|
+
|
|
722
|
+
|
|
723
|
+
def _new_cycle_groups(current_groups, prior_groups, runtime_graph):
|
|
724
|
+
"""Current cycle groups that are not contained in a single prior group.
|
|
725
|
+
|
|
726
|
+
A group that only lost files, or gained edges among the same files, is not
|
|
727
|
+
new. A group that gained files (or merged two groups) is new, and the
|
|
728
|
+
files that joined are named so the finding points at the change.
|
|
729
|
+
"""
|
|
730
|
+
prior_sets = [set(group) for group in prior_groups]
|
|
731
|
+
new_groups = []
|
|
732
|
+
for group in current_groups:
|
|
733
|
+
members = set(group)
|
|
734
|
+
if any(members <= prior for prior in prior_sets):
|
|
735
|
+
continue
|
|
736
|
+
overlap = max(prior_sets, key=lambda prior: (len(members & prior), sorted(prior)), default=set())
|
|
737
|
+
joined = sorted(members - overlap) if members & overlap else sorted(members)
|
|
738
|
+
cycle = None
|
|
739
|
+
if runtime_graph:
|
|
740
|
+
cycle = shortest_cycle_through(runtime_graph, joined[0], members)
|
|
741
|
+
if not cycle:
|
|
742
|
+
cycle = list(group) + [group[0]]
|
|
743
|
+
new_groups.append({
|
|
744
|
+
"members": sorted(members),
|
|
745
|
+
"joined": joined,
|
|
746
|
+
"previous_members": sorted(members & overlap),
|
|
747
|
+
"cycle": cycle,
|
|
748
|
+
})
|
|
749
|
+
return new_groups
|
|
750
|
+
|
|
751
|
+
|
|
752
|
+
def _resolved_cycle_groups(current_groups, prior_groups):
|
|
753
|
+
current_sets = [set(group) for group in current_groups]
|
|
754
|
+
resolved = []
|
|
755
|
+
for group in prior_groups:
|
|
756
|
+
if not any(set(group) <= current for current in current_sets):
|
|
757
|
+
resolved.append(list(group))
|
|
758
|
+
return resolved
|
|
759
|
+
|
|
760
|
+
|
|
761
|
+
def _cycle_drift_item(item, cluster_of=None):
|
|
762
|
+
cycle = item["cycle"]
|
|
763
|
+
path = " -> ".join(cycle)
|
|
764
|
+
joined = item["joined"]
|
|
765
|
+
previous = item["previous_members"]
|
|
766
|
+
if previous:
|
|
767
|
+
reason = "{0} joined a group of {1} file(s) that import each other at load time.".format(
|
|
768
|
+
", ".join(joined), len(previous)
|
|
769
|
+
)
|
|
770
|
+
else:
|
|
771
|
+
reason = "{0} files now import each other at load time; this cycle did not exist before.".format(
|
|
772
|
+
len(item["members"])
|
|
773
|
+
)
|
|
774
|
+
evidence = [path]
|
|
775
|
+
if len(item["members"]) > len(cycle) - 1:
|
|
776
|
+
evidence.append("Cycle group ({0} files): {1}".format(
|
|
777
|
+
len(item["members"]), ", ".join(item["members"][:12])
|
|
778
|
+
))
|
|
779
|
+
first = joined[0] if joined else (cycle[0] if cycle else "")
|
|
780
|
+
return _drift_item(
|
|
781
|
+
issue_type="cycle",
|
|
782
|
+
severity="critical",
|
|
783
|
+
kind="deterministic",
|
|
784
|
+
confidence=1.0,
|
|
785
|
+
title="Architectural drift",
|
|
786
|
+
changed=path,
|
|
787
|
+
established="acyclic module dependencies",
|
|
788
|
+
reason=reason,
|
|
789
|
+
problem="{0} is a new circular dependency compared with the baseline.".format(path),
|
|
790
|
+
evidence=evidence,
|
|
791
|
+
established_pattern="acyclic module dependencies",
|
|
792
|
+
affected_files=list(item["members"]),
|
|
793
|
+
why_it_matters="Files in an import cycle cannot be loaded, tested, or changed independently.",
|
|
794
|
+
classification="proven",
|
|
795
|
+
file=first,
|
|
796
|
+
imported=path,
|
|
797
|
+
layer=(cluster_of or {}).get(first, "unknown"),
|
|
798
|
+
imported_layer="multiple",
|
|
799
|
+
cycle_group=list(item["members"]),
|
|
800
|
+
joined_files=list(joined),
|
|
801
|
+
)
|
|
802
|
+
|
|
803
|
+
|
|
804
|
+
def _analysis_edge_set(analysis):
|
|
805
|
+
current = analysis.get("architecture") or {}
|
|
806
|
+
if current.get("dependencies"):
|
|
807
|
+
return _edge_set(current)
|
|
808
|
+
return {
|
|
809
|
+
(source, target)
|
|
810
|
+
for source, targets in (analysis.get("resolved_graph") or {}).items()
|
|
811
|
+
for target in targets
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
|
|
815
|
+
def _persistence_set(items, renames=None):
|
|
816
|
+
renames = renames or {}
|
|
817
|
+
return {
|
|
818
|
+
(renames.get(item.get("file"), item.get("file")), item.get("module"))
|
|
819
|
+
for item in items or []
|
|
820
|
+
if item.get("file") and item.get("module")
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
|
|
824
|
+
def _compare_inferred(baseline, analysis, reference=None, renames=None):
|
|
825
|
+
"""Compare the current analysis against the accepted baseline.
|
|
826
|
+
|
|
827
|
+
`baseline` supplies the accepted architecture model (layers, directions,
|
|
828
|
+
skip paths, patterns). `reference`, when given, is the analysis of the
|
|
829
|
+
base tree (e.g. the PR base commit): only edges, cycles, and persistence
|
|
830
|
+
imports that are new relative to that tree count as drift. `renames`
|
|
831
|
+
maps reference paths to their current paths so that moving a file does
|
|
832
|
+
not look like a new dependency. Without `reference`, the saved
|
|
833
|
+
baseline's own edges are used.
|
|
834
|
+
"""
|
|
835
|
+
renames = dict(renames or {})
|
|
836
|
+
current = analysis.get("architecture") or {}
|
|
837
|
+
baseline_enough = bool(baseline.get("enough_structure"))
|
|
838
|
+
current_edges = _analysis_edge_set(analysis)
|
|
839
|
+
if reference is not None:
|
|
840
|
+
prior_edges_raw = _analysis_edge_set(reference)
|
|
841
|
+
prior_groups = _analysis_cycle_groups(reference, renames)
|
|
842
|
+
prior_persistence = _persistence_set(
|
|
843
|
+
(reference.get("architecture") or {}).get("persistence_access"), renames
|
|
844
|
+
)
|
|
845
|
+
comparison_mode = "base_tree"
|
|
846
|
+
else:
|
|
847
|
+
prior_edges_raw = _edge_set(baseline)
|
|
848
|
+
prior_groups = _cycle_groups(baseline, renames)
|
|
849
|
+
prior_persistence = _persistence_set(baseline.get("persistence_access"), renames)
|
|
850
|
+
comparison_mode = "baseline_snapshot"
|
|
851
|
+
baseline_edges = {
|
|
852
|
+
(renames.get(source, source), renames.get(target, target))
|
|
853
|
+
for source, target in prior_edges_raw
|
|
854
|
+
}
|
|
855
|
+
current_groups = _analysis_cycle_groups(analysis)
|
|
856
|
+
runtime_graph = analysis.get("runtime_graph")
|
|
857
|
+
if runtime_graph is None:
|
|
858
|
+
runtime_graph = analysis.get("resolved_graph") or {}
|
|
859
|
+
added_edges = sorted(current_edges - baseline_edges)
|
|
860
|
+
removed_edges = sorted(baseline_edges - current_edges)
|
|
861
|
+
new_groups = _new_cycle_groups(current_groups, prior_groups, runtime_graph)
|
|
862
|
+
new_cycles = [item["cycle"] for item in new_groups]
|
|
863
|
+
resolved_cycles = _resolved_cycle_groups(current_groups, prior_groups)
|
|
864
|
+
|
|
865
|
+
drift = []
|
|
866
|
+
if not baseline_enough:
|
|
867
|
+
for item in new_groups:
|
|
868
|
+
drift.append(_cycle_drift_item(item))
|
|
869
|
+
if drift:
|
|
870
|
+
summary = "{0} new cycle(s); baseline has no established layered architecture.".format(len(drift))
|
|
871
|
+
else:
|
|
872
|
+
summary = "Baseline has no established architecture to drift from."
|
|
873
|
+
return {
|
|
874
|
+
"baseline_enough_structure": False,
|
|
875
|
+
"current_enough_structure": bool(current.get("enough_structure")),
|
|
876
|
+
"added_dependencies": [{"source": source, "target": target} for source, target in added_edges],
|
|
877
|
+
"removed_dependencies": [{"source": source, "target": target} for source, target in removed_edges],
|
|
878
|
+
"new_cycles": new_cycles,
|
|
879
|
+
"new_cycle_groups": new_groups,
|
|
880
|
+
"resolved_cycles": resolved_cycles,
|
|
881
|
+
"drift": drift,
|
|
882
|
+
"summary": summary,
|
|
883
|
+
"baseline_path": baseline.get("project_root"),
|
|
884
|
+
"baseline_summary_path": baseline.get("summary_path") or "",
|
|
885
|
+
"current_summary_path": current.get("summary_path") or analysis.get("established_pattern") or "",
|
|
886
|
+
"comparison_mode": comparison_mode,
|
|
887
|
+
"renamed_files": [{"from": old, "to": new} for old, new in sorted(renames.items())],
|
|
888
|
+
"baseline_analyzer_version": baseline.get("analyzer_version"),
|
|
889
|
+
"current_analyzer_version": ANALYZER_VERSION,
|
|
890
|
+
"analyzer_version_mismatch": bool(
|
|
891
|
+
baseline.get("analyzer_version") and baseline.get("analyzer_version") != ANALYZER_VERSION
|
|
892
|
+
),
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
skip_paths = baseline.get("skip_paths") or []
|
|
896
|
+
cluster_of = {}
|
|
897
|
+
for layer in baseline.get("layers") or []:
|
|
898
|
+
for file_path in layer.get("files") or []:
|
|
899
|
+
cluster_of[file_path] = layer["name"]
|
|
900
|
+
for file_path, record in (analysis.get("dependency_graph") or {}).items():
|
|
901
|
+
cluster_of.setdefault(file_path, record.get("cluster") or "root")
|
|
902
|
+
|
|
903
|
+
role_of = {layer["name"]: layer["role"] for layer in baseline.get("layers") or []}
|
|
904
|
+
for file_path, record in (analysis.get("dependency_graph") or {}).items():
|
|
905
|
+
cluster = record.get("cluster") or "root"
|
|
906
|
+
role_of.setdefault(cluster, record.get("role") or "unknown")
|
|
907
|
+
repository_established = any(pattern.get("name") == "repository_pattern" for pattern in baseline.get("patterns") or [])
|
|
908
|
+
data_clusters = {layer["name"] for layer in baseline.get("layers") or [] if layer.get("role") == "data"}
|
|
909
|
+
inferred = analysis.get("inferred_architecture") or {}
|
|
910
|
+
resolved_graph = analysis.get("resolved_graph") or {}
|
|
911
|
+
established_role_pairs = {
|
|
912
|
+
(item.get("source_role"), item.get("target_role"))
|
|
913
|
+
for item in baseline.get("directions") or []
|
|
914
|
+
if item.get("established")
|
|
915
|
+
and item.get("source_role") not in {None, "unknown"}
|
|
916
|
+
and item.get("target_role") not in {None, "unknown"}
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
def matching_skip(src_cluster, dst_cluster, source_file=None):
|
|
920
|
+
for path in skip_paths:
|
|
921
|
+
if src_cluster == path["source"] and dst_cluster == path["target"]:
|
|
922
|
+
return path
|
|
923
|
+
if (
|
|
924
|
+
role_of.get(src_cluster) == "presentation"
|
|
925
|
+
and role_of.get(dst_cluster) == "data"
|
|
926
|
+
and skip_paths
|
|
927
|
+
and source_file
|
|
928
|
+
):
|
|
929
|
+
dest = {
|
|
930
|
+
cluster_of.get(target_file)
|
|
931
|
+
for target_file in (resolved_graph.get(source_file) or [])
|
|
932
|
+
}
|
|
933
|
+
dest.discard(None)
|
|
934
|
+
for path in skip_paths:
|
|
935
|
+
if src_cluster == path["source"] and path.get("intermediate") in dest:
|
|
936
|
+
return path
|
|
937
|
+
return None
|
|
938
|
+
|
|
939
|
+
for source, target in added_edges:
|
|
940
|
+
src_cluster = cluster_of.get(source)
|
|
941
|
+
dst_cluster = cluster_of.get(target)
|
|
942
|
+
path = matching_skip(src_cluster, dst_cluster, source)
|
|
943
|
+
if path:
|
|
944
|
+
followed, considered = peer_follow_counts(
|
|
945
|
+
inferred, resolved_graph, src_cluster, path.get("intermediate"), source
|
|
946
|
+
)
|
|
947
|
+
evidence = ["{0} -> {1}".format(source, target), "Established path: {0}".format(path["path"])]
|
|
948
|
+
if considered:
|
|
949
|
+
evidence.append(
|
|
950
|
+
"{0} of {1} other {2} module(s) depend on {3}.".format(
|
|
951
|
+
followed, considered, src_cluster, path.get("intermediate")
|
|
952
|
+
)
|
|
953
|
+
)
|
|
954
|
+
drift.append(_drift_item(
|
|
955
|
+
issue_type="layer_skip",
|
|
956
|
+
severity="high",
|
|
957
|
+
kind="deterministic",
|
|
958
|
+
confidence=relationship_confidence(followed, considered),
|
|
959
|
+
title="Architectural drift",
|
|
960
|
+
changed="{0} -> {1}".format(source, target),
|
|
961
|
+
established=path["path"],
|
|
962
|
+
reason="{0} bypasses the established repository/layer path {1}.".format(source, path["path"]),
|
|
963
|
+
problem="{0} now depends on {1}, skipping {2}.".format(source, target, path["path"]),
|
|
964
|
+
evidence=evidence,
|
|
965
|
+
established_pattern=path["path"],
|
|
966
|
+
affected_files=[source, target],
|
|
967
|
+
why_it_matters="This change bypasses the established layered dependency direction recorded in the baseline.",
|
|
968
|
+
classification="proven",
|
|
969
|
+
file=source,
|
|
970
|
+
imported=target,
|
|
971
|
+
layer=src_cluster,
|
|
972
|
+
imported_layer=dst_cluster,
|
|
973
|
+
line=import_line_for_file((analysis.get("dependency_graph") or {}).get(source), target),
|
|
974
|
+
))
|
|
975
|
+
established_forward = [
|
|
976
|
+
item for item in baseline.get("directions") or []
|
|
977
|
+
if item.get("established") and item["source"] == dst_cluster and item["target"] == src_cluster
|
|
978
|
+
]
|
|
979
|
+
if established_forward:
|
|
980
|
+
drift.append(_drift_item(
|
|
981
|
+
issue_type="layer_violation",
|
|
982
|
+
severity="high",
|
|
983
|
+
kind="deterministic",
|
|
984
|
+
confidence=0.92,
|
|
985
|
+
title="Architectural drift",
|
|
986
|
+
changed="{0} -> {1}".format(source, target),
|
|
987
|
+
established="{0} -> {1}".format(dst_cluster, src_cluster),
|
|
988
|
+
reason="The saved baseline recorded the opposite dependency direction between these layers.",
|
|
989
|
+
problem="{0} now depends on {1}, reversing established {2} -> {3}.".format(
|
|
990
|
+
source, target, dst_cluster, src_cluster
|
|
991
|
+
),
|
|
992
|
+
evidence=["{0} -> {1}".format(source, target)],
|
|
993
|
+
established_pattern="{0} -> {1}".format(dst_cluster, src_cluster),
|
|
994
|
+
affected_files=[source, target],
|
|
995
|
+
why_it_matters="The baseline recorded the opposite dependency direction between these layers.",
|
|
996
|
+
classification="proven",
|
|
997
|
+
file=source,
|
|
998
|
+
imported=target,
|
|
999
|
+
layer=src_cluster,
|
|
1000
|
+
imported_layer=dst_cluster,
|
|
1001
|
+
line=import_line_for_file((analysis.get("dependency_graph") or {}).get(source), target),
|
|
1002
|
+
))
|
|
1003
|
+
baseline_pairs = {(item["source"], item["target"]) for item in baseline.get("directions") or []}
|
|
1004
|
+
src_role = role_of.get(src_cluster)
|
|
1005
|
+
dst_role = role_of.get(dst_cluster)
|
|
1006
|
+
if (
|
|
1007
|
+
src_cluster and dst_cluster and src_cluster != dst_cluster
|
|
1008
|
+
and (src_cluster, dst_cluster) not in baseline_pairs
|
|
1009
|
+
and src_role not in {None, "unknown", "shared"}
|
|
1010
|
+
and dst_role not in {None, "unknown", "shared"}
|
|
1011
|
+
and (src_role, dst_role) not in established_role_pairs
|
|
1012
|
+
):
|
|
1013
|
+
skip_match = path is not None
|
|
1014
|
+
reverse_match = bool(established_forward)
|
|
1015
|
+
if not skip_match and not reverse_match:
|
|
1016
|
+
drift.append(_drift_item(
|
|
1017
|
+
issue_type="unexpected_dependency",
|
|
1018
|
+
severity="medium",
|
|
1019
|
+
kind="inferred",
|
|
1020
|
+
confidence=0.7,
|
|
1021
|
+
title="Architectural drift",
|
|
1022
|
+
changed="{0} -> {1}".format(source, target),
|
|
1023
|
+
established=current.get("summary_path") or baseline.get("summary_path") or "",
|
|
1024
|
+
reason="{0} introduced a {1} -> {2} dependency that was not part of the saved baseline.".format(
|
|
1025
|
+
source, src_cluster, dst_cluster
|
|
1026
|
+
),
|
|
1027
|
+
problem="{0} introduced a {1} -> {2} dependency that was not part of the baseline.".format(
|
|
1028
|
+
source, src_cluster, dst_cluster
|
|
1029
|
+
),
|
|
1030
|
+
evidence=["{0} -> {1}".format(source, target)],
|
|
1031
|
+
established_pattern=current.get("summary_path") or baseline.get("summary_path") or "",
|
|
1032
|
+
affected_files=[source, target],
|
|
1033
|
+
why_it_matters="New edges between established layers can silently change the architecture.",
|
|
1034
|
+
classification="inferred",
|
|
1035
|
+
file=source,
|
|
1036
|
+
imported=target,
|
|
1037
|
+
layer=src_cluster,
|
|
1038
|
+
imported_layer=dst_cluster,
|
|
1039
|
+
line=import_line_for_file((analysis.get("dependency_graph") or {}).get(source), target),
|
|
1040
|
+
))
|
|
1041
|
+
|
|
1042
|
+
baseline_persistence = prior_persistence
|
|
1043
|
+
if repository_established:
|
|
1044
|
+
for file_path, record in (analysis.get("dependency_graph") or {}).items():
|
|
1045
|
+
cluster = record.get("cluster")
|
|
1046
|
+
if cluster in data_clusters:
|
|
1047
|
+
continue
|
|
1048
|
+
if (record.get("role") or role_of.get(cluster)) not in {"presentation", "application"}:
|
|
1049
|
+
continue
|
|
1050
|
+
hits = [
|
|
1051
|
+
hit for hit in _persistence_imports(record)
|
|
1052
|
+
if (file_path, hit.get("module")) not in baseline_persistence
|
|
1053
|
+
]
|
|
1054
|
+
if not hits:
|
|
1055
|
+
continue
|
|
1056
|
+
drift.append(_drift_item(
|
|
1057
|
+
issue_type="repository_bypass",
|
|
1058
|
+
severity="high",
|
|
1059
|
+
kind="deterministic",
|
|
1060
|
+
confidence=0.94,
|
|
1061
|
+
title="Architectural drift",
|
|
1062
|
+
changed="{0} -> {1}".format(file_path, hits[0].get("module")),
|
|
1063
|
+
established=baseline.get("summary_path") or "service -> repository -> database",
|
|
1064
|
+
reason="{0} bypasses the established repository boundary by importing {1} directly.".format(
|
|
1065
|
+
file_path, hits[0].get("module")
|
|
1066
|
+
),
|
|
1067
|
+
problem="Direct database access was introduced in {0}.".format(file_path),
|
|
1068
|
+
evidence=["{0} -> {1}".format(file_path, hits[0].get("module"))],
|
|
1069
|
+
established_pattern=baseline.get("summary_path") or "service -> repository -> database",
|
|
1070
|
+
affected_files=[file_path],
|
|
1071
|
+
why_it_matters="The baseline established a persistence boundary. This change bypasses it.",
|
|
1072
|
+
classification="proven",
|
|
1073
|
+
file=file_path,
|
|
1074
|
+
imported=hits[0].get("module"),
|
|
1075
|
+
layer=cluster,
|
|
1076
|
+
imported_layer="database",
|
|
1077
|
+
line=hits[0].get("line"),
|
|
1078
|
+
))
|
|
1079
|
+
|
|
1080
|
+
for item in new_groups:
|
|
1081
|
+
drift.append(_cycle_drift_item(item, cluster_of))
|
|
1082
|
+
|
|
1083
|
+
unique = []
|
|
1084
|
+
seen = set()
|
|
1085
|
+
for item in drift:
|
|
1086
|
+
key = (item.get("issue_type"), item.get("file"), item.get("imported"))
|
|
1087
|
+
if key in seen:
|
|
1088
|
+
continue
|
|
1089
|
+
seen.add(key)
|
|
1090
|
+
unique.append(item)
|
|
1091
|
+
|
|
1092
|
+
if unique:
|
|
1093
|
+
summary = "{0} architectural drift finding(s) versus the saved baseline.".format(len(unique))
|
|
1094
|
+
elif added_edges:
|
|
1095
|
+
summary = "Dependencies changed, but none crossed an established architectural boundary."
|
|
1096
|
+
else:
|
|
1097
|
+
summary = "No architectural drift detected versus the saved baseline."
|
|
1098
|
+
|
|
1099
|
+
return {
|
|
1100
|
+
"baseline_enough_structure": True,
|
|
1101
|
+
"current_enough_structure": bool(current.get("enough_structure")),
|
|
1102
|
+
"added_dependencies": [{"source": source, "target": target} for source, target in added_edges],
|
|
1103
|
+
"removed_dependencies": [{"source": source, "target": target} for source, target in removed_edges],
|
|
1104
|
+
"new_cycles": new_cycles,
|
|
1105
|
+
"new_cycle_groups": new_groups,
|
|
1106
|
+
"resolved_cycles": resolved_cycles,
|
|
1107
|
+
"drift": unique,
|
|
1108
|
+
"summary": summary,
|
|
1109
|
+
"baseline_path": baseline.get("project_root"),
|
|
1110
|
+
"baseline_summary_path": baseline.get("summary_path") or "",
|
|
1111
|
+
"current_summary_path": current.get("summary_path") or analysis.get("established_pattern") or "",
|
|
1112
|
+
"comparison_mode": comparison_mode,
|
|
1113
|
+
"renamed_files": [{"from": old, "to": new} for old, new in sorted(renames.items())],
|
|
1114
|
+
"baseline_analyzer_version": baseline.get("analyzer_version"),
|
|
1115
|
+
"current_analyzer_version": ANALYZER_VERSION,
|
|
1116
|
+
"analyzer_version_mismatch": bool(
|
|
1117
|
+
baseline.get("analyzer_version") and baseline.get("analyzer_version") != ANALYZER_VERSION
|
|
1118
|
+
),
|
|
1119
|
+
}
|
|
1120
|
+
|
|
1121
|
+
|
|
1122
|
+
def compare_to_baseline(baseline, analysis, reference=None, renames=None, declared=None):
|
|
1123
|
+
"""Compare against the inferred baseline and, if given, declared rules.
|
|
1124
|
+
|
|
1125
|
+
`declared` is a parsed `.adre/architecture.json` (see
|
|
1126
|
+
adre.core.declared). Its findings are added whether or not inference
|
|
1127
|
+
found enough structure, and replace inferred findings for the same edge.
|
|
1128
|
+
"""
|
|
1129
|
+
comparison = _compare_inferred(baseline, analysis, reference=reference, renames=renames)
|
|
1130
|
+
comparison["declared_rules"] = bool(declared)
|
|
1131
|
+
if not declared:
|
|
1132
|
+
return comparison
|
|
1133
|
+
|
|
1134
|
+
renames = dict(renames or {})
|
|
1135
|
+
if reference is not None:
|
|
1136
|
+
prior_raw = _analysis_edge_set(reference)
|
|
1137
|
+
else:
|
|
1138
|
+
prior_raw = _edge_set(baseline)
|
|
1139
|
+
prior_edges = {
|
|
1140
|
+
(renames.get(source, source), renames.get(target, target))
|
|
1141
|
+
for source, target in prior_raw
|
|
1142
|
+
}
|
|
1143
|
+
dependency_graph = analysis.get("dependency_graph") or {}
|
|
1144
|
+
|
|
1145
|
+
def line_for(source, target):
|
|
1146
|
+
return import_line_for_file(dependency_graph.get(source), target)
|
|
1147
|
+
|
|
1148
|
+
declared_findings = check_declared(
|
|
1149
|
+
declared,
|
|
1150
|
+
analysis.get("resolved_graph") or {},
|
|
1151
|
+
prior_edges,
|
|
1152
|
+
line_for=line_for,
|
|
1153
|
+
)
|
|
1154
|
+
if not declared_findings:
|
|
1155
|
+
return comparison
|
|
1156
|
+
declared_edges = {(item["file"], item["imported"]) for item in declared_findings}
|
|
1157
|
+
inferred = [
|
|
1158
|
+
item for item in comparison.get("drift") or []
|
|
1159
|
+
if (item.get("file"), item.get("imported")) not in declared_edges
|
|
1160
|
+
]
|
|
1161
|
+
comparison["drift"] = declared_findings + inferred
|
|
1162
|
+
comparison["summary"] = "{0} architectural drift finding(s) ({1} against the declared architecture).".format(
|
|
1163
|
+
len(comparison["drift"]), len(declared_findings)
|
|
1164
|
+
)
|
|
1165
|
+
return comparison
|