repodna-engine 1.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. repodna/__init__.py +3 -0
  2. repodna/__main__.py +10 -0
  3. repodna/advisor/__init__.py +17 -0
  4. repodna/advisor/engine.py +502 -0
  5. repodna/advisor/models.py +101 -0
  6. repodna/agent/__init__.py +87 -0
  7. repodna/agent/context.py +558 -0
  8. repodna/agent/deltas.py +198 -0
  9. repodna/agent/evidence.py +134 -0
  10. repodna/agent/expansion.py +447 -0
  11. repodna/agent/localization.py +518 -0
  12. repodna/agent/models.py +695 -0
  13. repodna/agent/patch.py +378 -0
  14. repodna/agent/postflight.py +278 -0
  15. repodna/agent/preflight.py +336 -0
  16. repodna/agent/ranking.py +318 -0
  17. repodna/agent/repo_map.py +392 -0
  18. repodna/agent/safety.py +111 -0
  19. repodna/agent/service.py +574 -0
  20. repodna/agent/sessions.py +264 -0
  21. repodna/agent/task.py +660 -0
  22. repodna/agent/telemetry.py +101 -0
  23. repodna/agent/token_budget.py +231 -0
  24. repodna/api/__init__.py +1 -0
  25. repodna/api/agent_routes.py +248 -0
  26. repodna/api/app.py +2904 -0
  27. repodna/benchmarks/__init__.py +29 -0
  28. repodna/benchmarks/baselines.py +126 -0
  29. repodna/benchmarks/budget_bench.py +162 -0
  30. repodna/benchmarks/engine.py +418 -0
  31. repodna/benchmarks/evaluator.py +310 -0
  32. repodna/benchmarks/metrics.py +206 -0
  33. repodna/benchmarks/models.py +194 -0
  34. repodna/benchmarks/scalability.py +166 -0
  35. repodna/brain/__init__.py +46 -0
  36. repodna/brain/evidence.py +276 -0
  37. repodna/brain/extractor.py +1207 -0
  38. repodna/brain/indexer.py +766 -0
  39. repodna/brain/models.py +275 -0
  40. repodna/brain/multilang_extractors.py +889 -0
  41. repodna/brain/retrieval.py +469 -0
  42. repodna/brain/tracer.py +203 -0
  43. repodna/cli/__init__.py +1 -0
  44. repodna/cli/__main__.py +10 -0
  45. repodna/cli/agent_cmd.py +228 -0
  46. repodna/cli/installer.py +590 -0
  47. repodna/cli/main.py +2173 -0
  48. repodna/cli/plugin_cmd.py +130 -0
  49. repodna/cli/workspace_cmd.py +211 -0
  50. repodna/context/__init__.py +9 -0
  51. repodna/context/builder.py +379 -0
  52. repodna/context/models.py +133 -0
  53. repodna/contract/__init__.py +39 -0
  54. repodna/contract/evaluator.py +318 -0
  55. repodna/contract/loader.py +260 -0
  56. repodna/contract/models.py +185 -0
  57. repodna/core/__init__.py +1 -0
  58. repodna/core/analyzer.py +1424 -0
  59. repodna/diff/__init__.py +35 -0
  60. repodna/diff/engine.py +332 -0
  61. repodna/diff/models.py +117 -0
  62. repodna/diff/snapshot.py +248 -0
  63. repodna/ecosystem/__init__.py +27 -0
  64. repodna/ecosystem/contracts.py +129 -0
  65. repodna/ecosystem/doctor.py +253 -0
  66. repodna/git_insights/__init__.py +1 -0
  67. repodna/git_insights/analyzer.py +273 -0
  68. repodna/graph/__init__.py +1 -0
  69. repodna/graph/engine.py +562 -0
  70. repodna/guardian/__init__.py +17 -0
  71. repodna/guardian/engine.py +369 -0
  72. repodna/guardian/models.py +104 -0
  73. repodna/history/__init__.py +40 -0
  74. repodna/history/cache.py +240 -0
  75. repodna/history/diff.py +394 -0
  76. repodna/history/engine.py +557 -0
  77. repodna/history/evidence.py +160 -0
  78. repodna/history/models.py +258 -0
  79. repodna/history/timeline.py +164 -0
  80. repodna/intelligence/__init__.py +33 -0
  81. repodna/intelligence/models.py +165 -0
  82. repodna/intelligence/service.py +570 -0
  83. repodna/live/__init__.py +94 -0
  84. repodna/live/alerts.py +443 -0
  85. repodna/live/coordinator.py +351 -0
  86. repodna/live/diff.py +444 -0
  87. repodna/live/events.py +471 -0
  88. repodna/live/filtering.py +329 -0
  89. repodna/live/history.py +637 -0
  90. repodna/live/models.py +505 -0
  91. repodna/live/observer.py +653 -0
  92. repodna/live/reconciliation.py +253 -0
  93. repodna/live/session.py +1547 -0
  94. repodna/mcp/__init__.py +5 -0
  95. repodna/mcp/__main__.py +6 -0
  96. repodna/mcp/agent_tools.py +258 -0
  97. repodna/mcp/server.py +3283 -0
  98. repodna/mcp/workspace_tools.py +200 -0
  99. repodna/parsers/__init__.py +13 -0
  100. repodna/parsers/base.py +126 -0
  101. repodna/parsers/capabilities.py +361 -0
  102. repodna/parsers/project_metadata.py +232 -0
  103. repodna/parsers/resolver.py +621 -0
  104. repodna/parsers/treesitter_parser.py +830 -0
  105. repodna/passport/__init__.py +64 -0
  106. repodna/passport/generator.py +546 -0
  107. repodna/passport/migrator.py +139 -0
  108. repodna/passport/models.py +224 -0
  109. repodna/passport/validator.py +143 -0
  110. repodna/performance/__init__.py +89 -0
  111. repodna/performance/cache.py +1584 -0
  112. repodna/performance/identity.py +341 -0
  113. repodna/performance/incremental.py +317 -0
  114. repodna/performance/models.py +157 -0
  115. repodna/performance/parallel.py +291 -0
  116. repodna/plugins/__init__.py +47 -0
  117. repodna/plugins/evaluator.py +334 -0
  118. repodna/plugins/models.py +113 -0
  119. repodna/plugins/validator.py +256 -0
  120. repodna/quality/__init__.py +91 -0
  121. repodna/quality/complexity.py +352 -0
  122. repodna/quality/config.py +159 -0
  123. repodna/quality/debt.py +73 -0
  124. repodna/quality/duplicates.py +330 -0
  125. repodna/quality/engine.py +282 -0
  126. repodna/quality/impact.py +198 -0
  127. repodna/quality/models.py +427 -0
  128. repodna/quality/rules.py +364 -0
  129. repodna/quality/sarif.py +107 -0
  130. repodna/quality/security_signals.py +278 -0
  131. repodna/quality/test_mapping.py +271 -0
  132. repodna/quality/unused.py +201 -0
  133. repodna/reports/__init__.py +1 -0
  134. repodna/reports/exporter.py +374 -0
  135. repodna/rules/__init__.py +1 -0
  136. repodna/rules/health.py +436 -0
  137. repodna/schemas/__init__.py +1 -0
  138. repodna/schemas/models.py +348 -0
  139. repodna/security/__init__.py +1 -0
  140. repodna/security/safe_yaml.py +81 -0
  141. repodna/security/validators.py +583 -0
  142. repodna/skills/__init__.py +0 -0
  143. repodna/skills/repodna/SKILL.md +59 -0
  144. repodna/skills/repodna/__init__.py +0 -0
  145. repodna/skills/repodna/examples/workflows.md +85 -0
  146. repodna/skills/repodna/references/architecture-rules.md +26 -0
  147. repodna/storage/__init__.py +1 -0
  148. repodna/storage/workspace.py +199 -0
  149. repodna/webui/__init__.py +1 -0
  150. repodna/webui/assets/DependencyGraph-km_Qo-nG.js +43 -0
  151. repodna/webui/assets/HealthReportView-WVL39aNO.js +1 -0
  152. repodna/webui/assets/index-ByZ5e5pe.js +506 -0
  153. repodna/webui/assets/index-CDj3e8hw.css +1 -0
  154. repodna/webui/index.html +21 -0
  155. repodna/workspace/__init__.py +131 -0
  156. repodna/workspace/compatibility.py +317 -0
  157. repodna/workspace/context.py +175 -0
  158. repodna/workspace/contracts.py +369 -0
  159. repodna/workspace/federation.py +411 -0
  160. repodna/workspace/identity.py +202 -0
  161. repodna/workspace/impact.py +111 -0
  162. repodna/workspace/manifest.py +266 -0
  163. repodna/workspace/models.py +461 -0
  164. repodna/workspace/packages.py +494 -0
  165. repodna/workspace/policies.py +142 -0
  166. repodna/workspace/services.py +238 -0
  167. repodna/workspace/topology.py +316 -0
  168. repodna_engine-1.0.1.dist-info/METADATA +129 -0
  169. repodna_engine-1.0.1.dist-info/RECORD +173 -0
  170. repodna_engine-1.0.1.dist-info/WHEEL +5 -0
  171. repodna_engine-1.0.1.dist-info/entry_points.txt +2 -0
  172. repodna_engine-1.0.1.dist-info/licenses/LICENSE +21 -0
  173. repodna_engine-1.0.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,436 @@
1
+ """Explainable, deterministic Rule-Based Architecture Health Engine."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from repodna.schemas.models import (
6
+ ArchitectureHealthReport,
7
+ CategoryScore,
8
+ CycleGroup,
9
+ DependencyEdge,
10
+ FileNode,
11
+ GraphMetrics,
12
+ LanguageSupportLevel,
13
+ RuleFinding,
14
+ SeverityLevel,
15
+ )
16
+
17
+
18
+ def evaluate_architecture_health(
19
+ files: list[FileNode],
20
+ edges: list[DependencyEdge],
21
+ cycles: list[CycleGroup],
22
+ metrics: GraphMetrics,
23
+ ) -> ArchitectureHealthReport:
24
+ """
25
+ Evaluate deterministic architectural health rules.
26
+ No LLM or opaque heuristics: every score deduction has an explicit mathematical formula,
27
+ threshold, evidence list, and actionable remediation.
28
+ """
29
+ findings: list[RuleFinding] = []
30
+ passed_rules: list[str] = []
31
+ unverified_rules: list[str] = []
32
+ node_map = {f.id: f for f in files}
33
+
34
+ category_meta = [
35
+ ("cycles", "Acyclicity & Layering", 30.0),
36
+ ("coupling", "Coupling & Stability", 30.0),
37
+ ("complexity", "Module Size & Complexity", 15.0),
38
+ ("hygiene", "Structural Hygiene", 15.0),
39
+ ("security", "Secret & Config Safety", 10.0),
40
+ ]
41
+
42
+ if not files:
43
+ return ArchitectureHealthReport(
44
+ overall_score=None,
45
+ grade="N/A",
46
+ status="insufficient_data",
47
+ confidence="none",
48
+ confidence_reason="Repository contains 0 analyzable files.",
49
+ ast_file_coverage_pct=0.0,
50
+ ast_loc_coverage_pct=0.0,
51
+ dependency_graph_evaluated=False,
52
+ cycle_analysis_summary="Not evaluated — Empty repository (0 files).",
53
+ methodology=(
54
+ "Insufficient data: repository contains 0 analyzable files. "
55
+ "RepoDNA reports N/A rather than a synthetic 100/100 score when no source modules are present."
56
+ ),
57
+ category_scores=[
58
+ CategoryScore(
59
+ category=cat_key,
60
+ label=cat_label,
61
+ score=None,
62
+ status="insufficient_data",
63
+ weight=weight,
64
+ deductions=0.0,
65
+ findings_count=0,
66
+ )
67
+ for cat_key, cat_label, weight in category_meta
68
+ ],
69
+ findings=[],
70
+ passed_rules=[],
71
+ unverified_rules=[],
72
+ summary_metrics={
73
+ "total_deductions": 0.0,
74
+ "rules_evaluated": 0,
75
+ "rules_passed": 0,
76
+ "rules_triggered": 0,
77
+ "rules_unverified": 0,
78
+ },
79
+ )
80
+
81
+ total_files = len(files)
82
+ total_loc = sum(f.lines_code for f in files)
83
+ full_ast_files = [f for f in files if f.support_level == LanguageSupportLevel.FULL_AST]
84
+ partial_files = [f for f in files if f.support_level == LanguageSupportLevel.PARTIAL_STATIC]
85
+ unsupported_files = [f for f in files if f.support_level == LanguageSupportLevel.UNSUPPORTED]
86
+
87
+ full_ast_loc = sum(f.lines_code for f in full_ast_files)
88
+ partial_loc = sum(f.lines_code for f in partial_files)
89
+ unsupported_loc = sum(f.lines_code for f in unsupported_files)
90
+
91
+ ast_file_cov = round((len(full_ast_files) / total_files) * 100.0, 1)
92
+ ast_loc_cov = round((full_ast_loc / total_loc) * 100.0, 1) if total_loc > 0 else ast_file_cov
93
+ partial_loc_cov = round((partial_loc / total_loc) * 100.0, 1) if total_loc > 0 else 0.0
94
+ unsupported_loc_cov = round((unsupported_loc / total_loc) * 100.0, 1) if total_loc > 0 else 0.0
95
+
96
+ # Dependency graph rules (cycles, coupling, SDP, orphans) require >= 50% full_ast coverage
97
+ dependency_graph_evaluated = (ast_loc_cov >= 50.0) or (
98
+ ast_file_cov >= 50.0 and partial_loc_cov < 50.0
99
+ )
100
+
101
+ if ast_loc_cov >= 80.0:
102
+ confidence = "high"
103
+ confidence_reason = (
104
+ f"High AST dependency coverage: {ast_loc_cov:.1f}% of LOC "
105
+ f"({len(full_ast_files)}/{total_files} files, {ast_file_cov:.1f}%) parsed with full Tree-sitter AST."
106
+ )
107
+ elif dependency_graph_evaluated:
108
+ confidence = "medium"
109
+ confidence_reason = (
110
+ f"Moderate AST dependency coverage: {ast_loc_cov:.1f}% of LOC "
111
+ f"({len(full_ast_files)}/{total_files} files, {ast_file_cov:.1f}%) have full_ast support "
112
+ f"({partial_loc_cov:.1f}% LOC partial_static, {unsupported_loc_cov:.1f}% LOC unsupported)."
113
+ )
114
+ else:
115
+ confidence = "low"
116
+ confidence_reason = (
117
+ f"Insufficient dependency coverage: only {ast_loc_cov:.1f}% of LOC "
118
+ f"({len(full_ast_files)}/{total_files} files, {ast_file_cov:.1f}%) have full_ast import resolution, "
119
+ f"while {partial_loc_cov:.1f}% of LOC ({len(partial_files)} files) is partial_static and "
120
+ f"{unsupported_loc_cov:.1f}% of LOC ({len(unsupported_files)} files) is unsupported. "
121
+ "Missing dependency edges are not treated as proof of healthy architecture."
122
+ )
123
+
124
+ # --- RULE ARCH-001: Acyclic Dependencies Principle (ADP) ---
125
+ if cycles:
126
+ deduction = min(30.0, round(len(cycles) * 6.0 + metrics.nodes_in_cycles * 1.2, 1))
127
+ severity = SeverityLevel.CRITICAL if len(cycles) >= 2 or any(c.length >= 3 for c in cycles) else SeverityLevel.WARNING
128
+ affected = sorted({n for c in cycles for n in c.nodes})
129
+ evidence = [f"{c.id} ({c.length} hops): {' -> '.join(c.nodes)}" for c in cycles[:10]]
130
+ findings.append(
131
+ RuleFinding(
132
+ rule_id="ARCH-001",
133
+ title="Circular Dependency Violations (ADP)",
134
+ category="cycles",
135
+ severity=severity,
136
+ score_deduction=deduction,
137
+ max_deduction=30.0,
138
+ formula_explanation="deduction = min(30.0, 6.0 * cycle_count + 1.2 * nodes_in_cycles)",
139
+ threshold_description="0 circular dependency cycles allowed (Acyclic Dependencies Principle).",
140
+ affected_files=affected,
141
+ evidence=evidence,
142
+ remediation="Extract shared contracts/interfaces into a lower-level module or apply Dependency Inversion to break mutual imports.",
143
+ )
144
+ )
145
+ cycle_analysis_summary = (
146
+ f"{len(cycles)} circular dependency chain(s) detected in {metrics.scc_count} cyclic SCC(s) "
147
+ f"across analyzed graph ({ast_loc_cov:.1f}% full_ast LOC)."
148
+ )
149
+ elif dependency_graph_evaluated:
150
+ passed_rules.append(
151
+ f"ARCH-001: Circular Dependency Check (No cycles detected in analyzed graph — {ast_loc_cov:.1f}% full_ast LOC)"
152
+ )
153
+ cycle_analysis_summary = (
154
+ f"No cycles detected in analyzed graph ({ast_loc_cov:.1f}% full_ast LOC, "
155
+ f"{ast_file_cov:.1f}% full_ast files)"
156
+ )
157
+ else:
158
+ unverified_rules.append(
159
+ f"ARCH-001: Circular Dependency Check — Not evaluated (Insufficient dependency coverage: "
160
+ f"{ast_loc_cov:.1f}% full_ast LOC, {ast_file_cov:.1f}% full_ast files)"
161
+ )
162
+ cycle_analysis_summary = (
163
+ f"Not evaluated — Insufficient dependency coverage ({ast_loc_cov:.1f}% full_ast LOC, "
164
+ f"{ast_file_cov:.1f}% full_ast files; no cycles detected in analyzed graph subset)"
165
+ )
166
+
167
+ # --- RULE ARCH-002: High Efferent Coupling (Fan-Out Overload) ---
168
+ high_fanout_files = [f for f in files if f.fan_out >= 8]
169
+ if high_fanout_files:
170
+ high_fanout_files.sort(key=lambda x: x.fan_out, reverse=True)
171
+ deduction = min(15.0, round(sum((f.fan_out - 7) * 1.5 for f in high_fanout_files), 1))
172
+ findings.append(
173
+ RuleFinding(
174
+ rule_id="ARCH-002",
175
+ title="Excessive Efferent Coupling (High Fan-Out)",
176
+ category="coupling",
177
+ severity=SeverityLevel.WARNING if deduction < 10.0 else SeverityLevel.CRITICAL,
178
+ score_deduction=deduction,
179
+ max_deduction=15.0,
180
+ formula_explanation="deduction = min(15.0, sum((fan_out - 7) * 1.5 for file with fan_out >= 8))",
181
+ threshold_description="Internal fan-out per module should remain < 8 direct internal dependencies.",
182
+ affected_files=[f.id for f in high_fanout_files],
183
+ evidence=[f"{f.id}: fan_out={f.fan_out}, instability={f.instability:.2f}" for f in high_fanout_files[:10]],
184
+ remediation="Decompose orchestrator modules into focused domain services or facade sub-packages to reduce direct fan-out.",
185
+ )
186
+ )
187
+ elif dependency_graph_evaluated:
188
+ passed_rules.append("ARCH-002: Bounded Efferent Coupling (All analyzed modules have internal fan-out < 8)")
189
+ else:
190
+ unverified_rules.append(
191
+ "ARCH-002: Bounded Efferent Coupling — Not evaluated (Insufficient dependency coverage)"
192
+ )
193
+
194
+ # --- RULE ARCH-003: Stable Dependencies Principle (SDP) Violations ---
195
+ # A stable module (I <= 0.30, fan_in >= 2) should not depend on a much more unstable module (I >= 0.70, delta >= 0.45)
196
+ sdp_violations: list[tuple[str, str, float, float]] = []
197
+ for e in edges:
198
+ src = node_map.get(e.source)
199
+ dst = node_map.get(e.target)
200
+ if not src or not dst:
201
+ continue
202
+ if src.fan_in >= 2 and src.instability <= 0.35 and dst.instability >= 0.70 and (dst.instability - src.instability) >= 0.40:
203
+ sdp_violations.append((src.id, dst.id, src.instability, dst.instability))
204
+
205
+ if sdp_violations:
206
+ deduction = min(15.0, round(len(sdp_violations) * 3.0, 1))
207
+ affected = sorted({u for u, _, _, _ in sdp_violations} | {v for _, v, _, _ in sdp_violations})
208
+ evidence = [
209
+ f"{u} (I={iu:.2f}, stable) imports {v} (I={iv:.2f}, unstable)"
210
+ for u, v, iu, iv in sdp_violations[:10]
211
+ ]
212
+ findings.append(
213
+ RuleFinding(
214
+ rule_id="ARCH-003",
215
+ title="Stable Dependencies Principle (SDP) Inversion",
216
+ category="coupling",
217
+ severity=SeverityLevel.WARNING,
218
+ score_deduction=deduction,
219
+ max_deduction=15.0,
220
+ formula_explanation="deduction = min(15.0, 3.0 * sdp_violation_edges) where I_target - I_source >= 0.40",
221
+ threshold_description="Modules with high incoming dependency stability (I <= 0.35) must not depend on volatile modules (I >= 0.70).",
222
+ affected_files=affected,
223
+ evidence=evidence,
224
+ remediation="Invert the dependency using an abstract interface or move shared types into the stable core layer.",
225
+ )
226
+ )
227
+ elif dependency_graph_evaluated:
228
+ passed_rules.append("ARCH-003: Stable Dependencies Principle (Dependencies flow in the direction of stability in analyzed graph)")
229
+ else:
230
+ unverified_rules.append(
231
+ "ARCH-003: Stable Dependencies Principle — Not evaluated (Insufficient dependency coverage)"
232
+ )
233
+
234
+ # --- RULE ARCH-004: God Module / Oversized Source File Complexity ---
235
+ code_files = [f for f in files if f.support_level != LanguageSupportLevel.UNSUPPORTED]
236
+ god_files = [f for f in code_files if f.lines_code > 450]
237
+ if god_files:
238
+ god_files.sort(key=lambda x: x.lines_code, reverse=True)
239
+ deduction = min(15.0, round(sum((f.lines_code - 450) / 100.0 * 2.0 for f in god_files), 1))
240
+ deduction = max(2.0, deduction)
241
+ findings.append(
242
+ RuleFinding(
243
+ rule_id="ARCH-004",
244
+ title="Oversized Modules / God File Risk",
245
+ category="complexity",
246
+ severity=SeverityLevel.CRITICAL if any(f.lines_code > 900 for f in god_files) else SeverityLevel.WARNING,
247
+ score_deduction=deduction,
248
+ max_deduction=15.0,
249
+ formula_explanation="deduction = min(15.0, max(2.0, sum((lines_code - 450) / 100 * 2.0)))",
250
+ threshold_description="Source code modules should not exceed 450 non-comment lines of code (LOC).",
251
+ affected_files=[f.id for f in god_files],
252
+ evidence=[f"{f.id}: {f.lines_code} LOC ({len(f.symbols)} top-level symbols)" for f in god_files[:10]],
253
+ remediation="Split large modules along cohesive responsibility boundaries into smaller, testable modules.",
254
+ )
255
+ )
256
+ else:
257
+ passed_rules.append("ARCH-004: Module Size Discipline (All code modules <= 450 LOC)")
258
+
259
+ # --- RULE ARCH-005: Disconnected / Orphaned Code Modules (evaluated only on full_ast files) ---
260
+ full_ast_files = [f for f in files if f.support_level == LanguageSupportLevel.FULL_AST]
261
+ orphans = [f for f in full_ast_files if f.is_orphan]
262
+ if orphans and len(full_ast_files) > 2:
263
+ orphan_ratio = len(orphans) / len(full_ast_files)
264
+ if orphan_ratio > 0.25 or len(orphans) >= 3:
265
+ deduction = min(10.0, round(len(orphans) * 1.5, 1))
266
+ findings.append(
267
+ RuleFinding(
268
+ rule_id="ARCH-005",
269
+ title="Isolated / Potentially Unreferenced Modules",
270
+ category="hygiene",
271
+ severity=SeverityLevel.INFO if orphan_ratio <= 0.4 else SeverityLevel.WARNING,
272
+ score_deduction=deduction,
273
+ max_deduction=10.0,
274
+ formula_explanation="deduction = min(10.0, 1.5 * orphan_files_count) when >= 3 orphans or > 25% of code files",
275
+ threshold_description="Non-entrypoint source files should participate in the internal module graph.",
276
+ affected_files=[f.id for f in orphans[:20]],
277
+ evidence=[f"{f.id}: fan_in=0, fan_out=0 ({f.lines_code} LOC)" for f in orphans[:10]],
278
+ remediation="Verify whether isolated modules are dead code, dynamically loaded plugins, or standalone scripts, and remove unused files.",
279
+ )
280
+ )
281
+ elif dependency_graph_evaluated:
282
+ passed_rules.append("ARCH-005: Low Orphan Module Ratio (<= 25% isolated modules in analyzed AST graph)")
283
+ else:
284
+ unverified_rules.append(
285
+ "ARCH-005: Orphan Module Connectivity — Not evaluated (Insufficient dependency coverage)"
286
+ )
287
+ elif dependency_graph_evaluated:
288
+ passed_rules.append("ARCH-005: High Module Graph Connectivity (Minimal isolated code files in analyzed AST graph)")
289
+ else:
290
+ unverified_rules.append(
291
+ "ARCH-005: Orphan Module Connectivity — Not evaluated (Insufficient dependency coverage)"
292
+ )
293
+
294
+ # --- RULE ARCH-006: Deep Directory Nesting ---
295
+ deep_files = [f for f in files if f.id.count("/") >= 6]
296
+ if deep_files:
297
+ deduction = min(5.0, round(len(deep_files) * 0.5, 1))
298
+ deduction = max(1.0, deduction)
299
+ findings.append(
300
+ RuleFinding(
301
+ rule_id="ARCH-006",
302
+ title="Excessive Directory Hierarchy Depth",
303
+ category="hygiene",
304
+ severity=SeverityLevel.INFO,
305
+ score_deduction=deduction,
306
+ max_deduction=5.0,
307
+ formula_explanation="deduction = min(5.0, max(1.0, 0.5 * files_with_depth_ge_6))",
308
+ threshold_description="Directory depth should remain < 6 levels from repository root.",
309
+ affected_files=[f.id for f in deep_files[:15]],
310
+ evidence=[f"{f.id} (depth={f.id.count('/')})" for f in deep_files[:10]],
311
+ remediation="Flatten deeply nested package directories to improve discoverability and shorten import paths.",
312
+ )
313
+ )
314
+ else:
315
+ passed_rules.append("ARCH-006: Clean Directory Hierarchy (All paths < 6 directory levels deep)")
316
+
317
+ # --- RULE SEC-001: Secret & Credential Hygiene ---
318
+ secret_files = [f for f in files if f.secret_warnings]
319
+ if secret_files:
320
+ deduction = min(20.0, round(len(secret_files) * 7.5, 1))
321
+ sec_evidence: list[str] = []
322
+ for sf in secret_files[:10]:
323
+ for w in sf.secret_warnings[:3]:
324
+ sec_evidence.append(f"{sf.id}: {w}")
325
+ findings.append(
326
+ RuleFinding(
327
+ rule_id="SEC-001",
328
+ title="Potential Secret or Sensitive File Exposure",
329
+ category="security",
330
+ severity=SeverityLevel.CRITICAL,
331
+ score_deduction=deduction,
332
+ max_deduction=20.0,
333
+ formula_explanation="deduction = min(20.0, 7.5 * files_with_secret_warnings)",
334
+ threshold_description="0 committed credential files (.env, private keys) or hardcoded API token patterns.",
335
+ affected_files=[f.id for f in secret_files],
336
+ evidence=sec_evidence,
337
+ remediation="Remove sensitive files from version control, rotate any exposed credentials immediately, and add patterns to .gitignore.",
338
+ )
339
+ )
340
+ else:
341
+ passed_rules.append("SEC-001: Credential & Secret Hygiene (No sensitive files or token patterns detected)")
342
+
343
+ # Calculate category scores and overall health score
344
+ category_scores: list[CategoryScore] = []
345
+ total_deduction = 0.0
346
+
347
+ for cat_key, cat_label, weight in category_meta:
348
+ cat_findings = [fn for fn in findings if fn.category == cat_key]
349
+ cat_ded = sum(fn.score_deduction for fn in cat_findings)
350
+ total_deduction += cat_ded
351
+ # Normalize category score to 0..100
352
+ cat_pct = max(0.0, round(100.0 * (1.0 - min(weight, cat_ded) / weight), 1))
353
+ if not dependency_graph_evaluated and cat_key in ("cycles", "coupling") and len(cat_findings) == 0:
354
+ category_scores.append(
355
+ CategoryScore(
356
+ category=cat_key,
357
+ label=cat_label,
358
+ score=None,
359
+ status="not_evaluated",
360
+ weight=weight,
361
+ deductions=0.0,
362
+ findings_count=0,
363
+ )
364
+ )
365
+ elif not dependency_graph_evaluated and cat_key == "hygiene":
366
+ category_scores.append(
367
+ CategoryScore(
368
+ category=cat_key,
369
+ label=cat_label,
370
+ score=cat_pct,
371
+ status="partial",
372
+ weight=weight,
373
+ deductions=round(cat_ded, 1),
374
+ findings_count=len(cat_findings),
375
+ )
376
+ )
377
+ else:
378
+ category_scores.append(
379
+ CategoryScore(
380
+ category=cat_key,
381
+ label=cat_label,
382
+ score=cat_pct,
383
+ status="evaluated",
384
+ weight=weight,
385
+ deductions=round(cat_ded, 1),
386
+ findings_count=len(cat_findings),
387
+ )
388
+ )
389
+
390
+ if not dependency_graph_evaluated:
391
+ overall_score: float | None = None
392
+ grade = "N/A"
393
+ report_status = "insufficient_dependency_coverage"
394
+ else:
395
+ overall_score = max(0.0, min(100.0, round(100.0 - total_deduction, 1)))
396
+ if overall_score >= 90.0:
397
+ grade = "A"
398
+ elif overall_score >= 80.0:
399
+ grade = "B"
400
+ elif overall_score >= 65.0:
401
+ grade = "C"
402
+ elif overall_score >= 50.0:
403
+ grade = "D"
404
+ else:
405
+ grade = "F"
406
+ report_status = "evaluated"
407
+
408
+ return ArchitectureHealthReport(
409
+ overall_score=overall_score,
410
+ grade=grade,
411
+ status=report_status,
412
+ confidence=confidence,
413
+ confidence_reason=confidence_reason,
414
+ ast_file_coverage_pct=ast_file_cov,
415
+ ast_loc_coverage_pct=ast_loc_cov,
416
+ dependency_graph_evaluated=dependency_graph_evaluated,
417
+ cycle_analysis_summary=cycle_analysis_summary,
418
+ methodology=(
419
+ "Deterministic, rule-based engineering rubric starting at 100.0 points. "
420
+ "Deductions are computed strictly from static AST dependency topology (Tarjan SCC cycles, "
421
+ "Robert C. Martin Instability & Fan-Out metrics), LOC complexity thresholds, and secret hygiene checks. "
422
+ "When full_ast dependency coverage is below 50% of total LOC, dependency-graph rules (ARCH-001/002/003/005) "
423
+ "are marked as Not evaluated rather than assumed healthy."
424
+ ),
425
+ category_scores=category_scores,
426
+ findings=findings,
427
+ passed_rules=passed_rules,
428
+ unverified_rules=unverified_rules,
429
+ summary_metrics={
430
+ "total_deductions": round(total_deduction, 1),
431
+ "rules_evaluated": len(findings) + len(passed_rules),
432
+ "rules_passed": len(passed_rules),
433
+ "rules_triggered": len(findings),
434
+ "rules_unverified": len(unverified_rules),
435
+ },
436
+ )
@@ -0,0 +1 @@
1
+ """Schemas package."""