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,318 @@
1
+ """Deterministic evaluator for RepoDNA Architecture Contracts against AnalysisResult graphs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ import pathspec
8
+
9
+ from repodna.contract.loader import load_baseline_file
10
+ from repodna.contract.models import (
11
+ ArchitectureContract,
12
+ ContractEvaluationReport,
13
+ ContractMode,
14
+ ContractSeverity,
15
+ ContractUnknown,
16
+ ContractViolation,
17
+ UnknownBehavior,
18
+ )
19
+ from repodna.schemas.models import AnalysisResult, DependencyEdge, FileNode, LanguageSupportLevel
20
+
21
+
22
+ class ContractEvaluator:
23
+ """Evaluates architecture contract policies and rules against an AnalysisResult."""
24
+
25
+ def __init__(
26
+ self,
27
+ contract: ArchitectureContract,
28
+ baseline: set[tuple[str, str, str]] | Path | str | None = None,
29
+ mode_override: ContractMode | None = None,
30
+ ) -> None:
31
+ self.contract = contract
32
+ self.mode = mode_override or contract.policy.mode
33
+ self.unknown_behavior = contract.policy.unknown_behavior
34
+
35
+ if isinstance(baseline, (Path, str)):
36
+ self.baseline_set = load_baseline_file(baseline)
37
+ elif isinstance(baseline, set):
38
+ self.baseline_set = baseline
39
+ else:
40
+ self.baseline_set = set()
41
+
42
+ def evaluate(self, analysis: AnalysisResult) -> ContractEvaluationReport:
43
+ # Outgoing edges grouped by source
44
+ edges_by_source: dict[str, list[DependencyEdge]] = {}
45
+ for edge in analysis.edges:
46
+ edges_by_source.setdefault(edge.source, []).append(edge)
47
+
48
+ violations: list[ContractViolation] = []
49
+ unknowns: list[ContractUnknown] = []
50
+ rules_violated_set: set[str] = set()
51
+ rules_passed_set: set[str] = set()
52
+ rules_unmatched_set: set[str] = set()
53
+ rules_unknown_set: set[str] = set()
54
+ rules_evaluated_count = 0
55
+
56
+ # Pre-compile specs for all rules
57
+ compiled_from_specs: dict[str, pathspec.PathSpec] = {
58
+ rule.id: pathspec.PathSpec.from_lines("gitignore", rule.from_patterns)
59
+ for rule in self.contract.rules
60
+ }
61
+
62
+ # Track all files in repo matched by at least one rule
63
+ all_matched_files: list[FileNode] = [
64
+ f for f in analysis.files
65
+ if any(spec.match_file(f.id) for spec in compiled_from_specs.values())
66
+ ]
67
+
68
+ for rule in self.contract.rules:
69
+ rules_evaluated_count += 1
70
+ rule_has_violation = False
71
+ rule_has_unknown = False
72
+ rule_has_full_ast = False
73
+
74
+ from_spec = compiled_from_specs[rule.id]
75
+ disallow_spec = (
76
+ pathspec.PathSpec.from_lines("gitignore", rule.disallow_imports)
77
+ if rule.disallow_imports
78
+ else None
79
+ )
80
+ allow_spec = (
81
+ pathspec.PathSpec.from_lines("gitignore", rule.allow_imports)
82
+ if rule.allow_imports is not None
83
+ else None
84
+ )
85
+
86
+ # Match files in repository matching 'from'
87
+ matching_files: list[FileNode] = [
88
+ f for f in analysis.files if from_spec.match_file(f.id)
89
+ ]
90
+
91
+ if not matching_files:
92
+ rules_unmatched_set.add(rule.id)
93
+ continue
94
+
95
+ for file_node in matching_files:
96
+ # 1. Check support level limitations for the source file
97
+ if file_node.support_level == LanguageSupportLevel.UNSUPPORTED:
98
+ rule_has_unknown = True
99
+ unknowns.append(
100
+ ContractUnknown(
101
+ rule_id=rule.id,
102
+ rule_title=rule.title,
103
+ source_file=file_node.id,
104
+ raw_import="<unsupported_language_ast>",
105
+ line=1,
106
+ reason="unsupported_language",
107
+ detail=f"Source file '{file_node.id}' is in language '{file_node.language}' without AST import resolution support.",
108
+ )
109
+ )
110
+ continue
111
+
112
+ if file_node.support_level == LanguageSupportLevel.PARTIAL_STATIC:
113
+ rule_has_unknown = True
114
+ unknowns.append(
115
+ ContractUnknown(
116
+ rule_id=rule.id,
117
+ rule_title=rule.title,
118
+ source_file=file_node.id,
119
+ raw_import="<partial_static_ast>",
120
+ line=1,
121
+ reason="partial_static_language",
122
+ detail=f"Source file '{file_node.id}' uses regex pattern extraction; complete internal dependency graph is not guaranteed.",
123
+ )
124
+ )
125
+ else:
126
+ rule_has_full_ast = True
127
+
128
+ # 2. Check unresolved imports in source file
129
+ for unresolved in file_node.unresolved_imports:
130
+ # Check if the unresolved import string matches disallow patterns
131
+ is_suspicious = False
132
+ if disallow_spec and disallow_spec.match_file(unresolved.raw_import):
133
+ is_suspicious = True
134
+
135
+ if is_suspicious or unresolved.reason not in ("external_package", "standard_library"):
136
+ rule_has_unknown = True
137
+ unknowns.append(
138
+ ContractUnknown(
139
+ rule_id=rule.id,
140
+ rule_title=rule.title,
141
+ source_file=file_node.id,
142
+ raw_import=unresolved.raw_import,
143
+ line=unresolved.line,
144
+ reason=unresolved.reason,
145
+ detail=f"Unresolved reference '{unresolved.raw_import}' from '{file_node.id}:{unresolved.line}' could not be verified.",
146
+ )
147
+ )
148
+
149
+ # 3. Check resolved internal edges originating from file_node
150
+ outgoing_edges = edges_by_source.get(file_node.id, [])
151
+ for edge in outgoing_edges:
152
+ target_id = edge.target
153
+ is_violation = False
154
+ reason_msg = ""
155
+
156
+ # Disallow check
157
+ if disallow_spec and disallow_spec.match_file(target_id):
158
+ is_violation = True
159
+ reason_msg = (
160
+ f"Module '{file_node.id}' imports '{target_id}', which matches prohibited pattern(s): "
161
+ f"{rule.disallow_imports}"
162
+ )
163
+
164
+ # Whitelist (allow_imports) check
165
+ elif allow_spec is not None and not allow_spec.match_file(target_id):
166
+ is_violation = True
167
+ reason_msg = (
168
+ f"Module '{file_node.id}' imports '{target_id}', which is not in the allowed imports whitelist: "
169
+ f"{rule.allow_imports}"
170
+ )
171
+
172
+ if is_violation:
173
+ rule_has_violation = True
174
+ rules_violated_set.add(rule.id)
175
+ is_in_baseline = (rule.id, file_node.id, target_id) in self.baseline_set
176
+
177
+ violations.append(
178
+ ContractViolation(
179
+ rule_id=rule.id,
180
+ rule_title=rule.title,
181
+ severity=rule.severity,
182
+ source_file=file_node.id,
183
+ target_file=target_id,
184
+ import_names=edge.import_names,
185
+ line=edge.line,
186
+ message=reason_msg,
187
+ remediation=rule.remediation,
188
+ is_baseline=is_in_baseline,
189
+ )
190
+ )
191
+
192
+ if rule_has_violation:
193
+ rules_violated_set.add(rule.id)
194
+ elif not rule_has_full_ast:
195
+ # Rule only matched unsupported or partial static files
196
+ rules_unknown_set.add(rule.id)
197
+ elif rule_has_unknown and self.unknown_behavior != UnknownBehavior.IGNORE:
198
+ rules_unknown_set.add(rule.id)
199
+ else:
200
+ rules_passed_set.add(rule.id)
201
+
202
+ # Partition violations into new vs baseline
203
+ new_violations = [v for v in violations if not v.is_baseline]
204
+ baseline_violations = [v for v in violations if v.is_baseline]
205
+
206
+ # Determine overall verdict
207
+ ast_cov = analysis.transparency.ast_loc_coverage_pct
208
+ all_matched_are_non_full_ast = (
209
+ len(all_matched_files) > 0
210
+ and all(f.support_level != LanguageSupportLevel.FULL_AST for f in all_matched_files)
211
+ )
212
+
213
+ if all_matched_are_non_full_ast and not new_violations:
214
+ if self.mode == ContractMode.ENFORCE and self.unknown_behavior == UnknownBehavior.FAIL:
215
+ verdict = "FAIL"
216
+ is_compliant = False
217
+ elif self.unknown_behavior == UnknownBehavior.WARN:
218
+ verdict = "WARNING"
219
+ is_compliant = True
220
+ elif self.unknown_behavior == UnknownBehavior.IGNORE:
221
+ verdict = "PASS"
222
+ is_compliant = True
223
+ else:
224
+ verdict = "INCONCLUSIVE"
225
+ is_compliant = False
226
+ elif (
227
+ analysis.total_files > 0
228
+ and ast_cov < 40.0
229
+ and len(all_matched_files) > 0
230
+ and len(rules_passed_set) == 0
231
+ and len(rules_violated_set) == 0
232
+ and self.unknown_behavior != UnknownBehavior.WARN
233
+ ):
234
+ verdict = "INCONCLUSIVE"
235
+ is_compliant = False
236
+ elif self.mode == ContractMode.ENFORCE:
237
+ # In enforce mode, any new error/warning violation causes FAIL
238
+ enforce_breakers = [v for v in new_violations if v.severity in (ContractSeverity.ERROR, ContractSeverity.WARNING)]
239
+ if enforce_breakers:
240
+ verdict = "FAIL"
241
+ is_compliant = False
242
+ elif self.unknown_behavior == UnknownBehavior.FAIL and unknowns:
243
+ verdict = "FAIL"
244
+ is_compliant = False
245
+ elif unknowns and self.unknown_behavior == UnknownBehavior.WARN:
246
+ verdict = "WARNING"
247
+ is_compliant = True
248
+ elif not rules_passed_set and rules_unknown_set and not new_violations:
249
+ verdict = "INCONCLUSIVE" if self.unknown_behavior != UnknownBehavior.IGNORE else "PASS"
250
+ is_compliant = False if verdict == "INCONCLUSIVE" else True
251
+ elif new_violations:
252
+ verdict = "WARNING"
253
+ is_compliant = True
254
+ else:
255
+ verdict = "PASS"
256
+ is_compliant = True
257
+ else:
258
+ # Advisory mode
259
+ if new_violations:
260
+ verdict = "WARNING"
261
+ is_compliant = False
262
+ elif unknowns and self.unknown_behavior == UnknownBehavior.WARN:
263
+ verdict = "WARNING"
264
+ is_compliant = True
265
+ elif unknowns and self.unknown_behavior == UnknownBehavior.FAIL:
266
+ verdict = "WARNING"
267
+ is_compliant = False
268
+ elif not rules_passed_set and rules_unknown_set and not new_violations:
269
+ verdict = "INCONCLUSIVE" if self.unknown_behavior != UnknownBehavior.IGNORE else "PASS"
270
+ is_compliant = False if verdict == "INCONCLUSIVE" else True
271
+ else:
272
+ verdict = "PASS"
273
+ is_compliant = True
274
+
275
+ # Generate summary text
276
+ summary_lines = [
277
+ f"RepoDNA Architecture Contract Evaluation (Mode: {self.mode.value.upper()})",
278
+ f"Verdict: {verdict}",
279
+ f"Rules Evaluated: {rules_evaluated_count} ({len(rules_passed_set)} passed, {len(rules_violated_set)} triggered, {len(rules_unmatched_set)} unmatched, {len(rules_unknown_set)} inconclusive)",
280
+ f"Violations: {len(new_violations)} new, {len(baseline_violations)} existing baseline",
281
+ f"Unknowns / Unverified Evaluations: {len(unknowns)}",
282
+ ]
283
+ if rules_unmatched_set:
284
+ summary_lines.append(f"Unmatched Rules (0 files matched): {', '.join(sorted(rules_unmatched_set))}")
285
+ if rules_unknown_set:
286
+ summary_lines.append(f"Inconclusive / Unknown Rules: {', '.join(sorted(rules_unknown_set))}")
287
+
288
+ if new_violations:
289
+ summary_lines.append("\nTop New Violations:")
290
+ for v in new_violations[:5]:
291
+ syms = f" ({', '.join(v.import_names)})" if v.import_names else ""
292
+ summary_lines.append(f" [{v.severity.value.upper()}] {v.rule_id}: {v.source_file} -> {v.target_file}{syms}")
293
+ if v.remediation:
294
+ summary_lines.append(f" Remediation: {v.remediation}")
295
+
296
+ if unknowns:
297
+ summary_lines.append(f"\nUnknown / Unverified Notes ({len(unknowns)}):")
298
+ for u in unknowns[:3]:
299
+ summary_lines.append(f" [{u.rule_id}] {u.source_file}: {u.detail}")
300
+
301
+ return ContractEvaluationReport(
302
+ contract_version=self.contract.version,
303
+ mode=self.mode,
304
+ unknown_behavior=self.unknown_behavior,
305
+ total_rules=len(self.contract.rules),
306
+ rules_evaluated=rules_evaluated_count,
307
+ rules_passed=sorted(rules_passed_set),
308
+ rules_violated=sorted(rules_violated_set),
309
+ rules_unmatched=sorted(rules_unmatched_set),
310
+ rules_unknown=sorted(rules_unknown_set),
311
+ violations=violations,
312
+ new_violations=new_violations,
313
+ baseline_violations=baseline_violations,
314
+ unknowns=unknowns,
315
+ is_compliant=is_compliant,
316
+ verdict=verdict,
317
+ summary_text="\n".join(summary_lines),
318
+ )
@@ -0,0 +1,260 @@
1
+ """Safe YAML parser, validator, and starter generator for Architecture Contracts."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ from repodna.contract.models import ArchitectureContract
10
+ from repodna.security.validators import SecurityValidationError, is_safe_subpath
11
+
12
+ MAX_CONTRACT_SIZE_BYTES = 524_288 # 512 KB
13
+ MAX_BASELINE_SIZE_BYTES = 5_242_880 # 5 MB
14
+ DEFAULT_CONTRACT_FILENAME = "architecture.yml"
15
+ DEFAULT_CONTRACT_PATH = Path(".repodna") / DEFAULT_CONTRACT_FILENAME
16
+
17
+ STARTER_CONTRACT_YAML = """# RepoDNA Architecture Contract Specification
18
+ # Schema version: 1
19
+ version: 1
20
+
21
+ policy:
22
+ mode: advisory # Options: advisory | enforce
23
+ unknown_behavior: warn # Options: warn | ignore | fail
24
+
25
+ rules:
26
+ - id: LAYER-001
27
+ title: Domain Layer Isolation
28
+ description: Core domain models must not import presentation, API, or infrastructure modules.
29
+ from:
30
+ - "domain/**"
31
+ - "**/domain/**"
32
+ disallow_imports:
33
+ - "api/**"
34
+ - "frontend/**"
35
+ - "infrastructure/**"
36
+ severity: error
37
+ remediation: Invert the dependency using domain interfaces or repository abstractions.
38
+
39
+ - id: BOUNDARY-001
40
+ title: Frontend to Backend Boundary
41
+ description: Client-side UI modules must not directly import server-side backend implementations.
42
+ from:
43
+ - "frontend/**"
44
+ disallow_imports:
45
+ - "backend/**"
46
+ severity: warning
47
+ remediation: Call backend endpoints via REST API or shared client contracts instead of direct import.
48
+ """
49
+
50
+
51
+ def load_contract_from_yaml(content: str) -> ArchitectureContract:
52
+ """Parses and validates an ArchitectureContract from a YAML string safely."""
53
+ if len(content.encode("utf-8")) > MAX_CONTRACT_SIZE_BYTES:
54
+ raise SecurityValidationError(
55
+ "CONTRACT_SIZE_LIMIT_EXCEEDED",
56
+ f"Architecture contract exceeds maximum allowed size of {MAX_CONTRACT_SIZE_BYTES} bytes.",
57
+ )
58
+
59
+ try:
60
+ from repodna.security.safe_yaml import safe_load_bounded_yaml
61
+
62
+ data: Any = safe_load_bounded_yaml(content, max_bytes=MAX_CONTRACT_SIZE_BYTES, max_aliases=0)
63
+ except SecurityValidationError:
64
+ raise
65
+ except Exception as exc:
66
+ raise ValueError(f"Failed to parse contract YAML: {exc}") from exc
67
+
68
+ if not isinstance(data, dict):
69
+ raise ValueError("Contract YAML must define a mapping/dictionary at the top level.")
70
+
71
+ return ArchitectureContract.model_validate(data)
72
+
73
+
74
+ def load_contract_file(path: Path | str, *, repo_root: Path | str | None = None) -> ArchitectureContract:
75
+ """Loads an ArchitectureContract from a file with symlink, containment, size, and binary checks."""
76
+ from repodna.security.validators import safe_read_evidence_file
77
+
78
+ raw_path = Path(path)
79
+ if raw_path.is_symlink():
80
+ raise SecurityValidationError(
81
+ "CONTRACT_SYMLINK_REJECTED",
82
+ f"Symbolic link contract file is not permitted: '{raw_path}'.",
83
+ )
84
+ if repo_root is not None:
85
+ root_res = Path(repo_root).resolve()
86
+ if not is_safe_subpath(root_res, raw_path):
87
+ raise SecurityValidationError(
88
+ "CONTRACT_PATH_ESCAPE",
89
+ f"Architecture contract '{raw_path}' escapes repository root '{root_res}'.",
90
+ )
91
+ rel = raw_path.resolve().relative_to(root_res).as_posix()
92
+ content, _, file_exists = safe_read_evidence_file(root_res, rel, max_file_bytes=MAX_CONTRACT_SIZE_BYTES)
93
+ if not file_exists:
94
+ raise FileNotFoundError(f"Architecture contract file not found: {raw_path}")
95
+ return load_contract_from_yaml(content)
96
+
97
+ file_path = raw_path.resolve()
98
+ if not file_path.exists():
99
+ raise FileNotFoundError(f"Architecture contract file not found: {file_path}")
100
+ if not file_path.is_file():
101
+ raise ValueError(f"Path is not a regular file: {file_path}")
102
+
103
+ size = file_path.stat().st_size
104
+ if size > MAX_CONTRACT_SIZE_BYTES:
105
+ raise SecurityValidationError(
106
+ "CONTRACT_SIZE_LIMIT_EXCEEDED",
107
+ f"Architecture contract '{file_path.name}' exceeds limit ({size} > {MAX_CONTRACT_SIZE_BYTES} bytes).",
108
+ )
109
+
110
+ raw_bytes = file_path.read_bytes()
111
+ if b"\x00" in raw_bytes[:8192]:
112
+ raise SecurityValidationError(
113
+ "BINARY_FILE_BLOCKED",
114
+ f"Architecture contract '{file_path.name}' appears to be a binary file.",
115
+ )
116
+ return load_contract_from_yaml(raw_bytes.decode("utf-8", errors="replace"))
117
+
118
+
119
+ def find_contract_file(repo_path: Path | str) -> Path | None:
120
+ """Discovers standard architecture contract file in repository root or .repodna/ directory safely."""
121
+ root = Path(repo_path).resolve()
122
+ candidates = [
123
+ root / ".repodna" / "architecture.yml",
124
+ root / ".repodna" / "architecture.yaml",
125
+ root / "architecture.yml",
126
+ root / "architecture.yaml",
127
+ ]
128
+ for c in candidates:
129
+ if c.is_symlink():
130
+ continue
131
+ if not is_safe_subpath(root, c):
132
+ continue
133
+ if c.exists() and c.is_file():
134
+ return c
135
+ return None
136
+
137
+
138
+ def init_starter_contract(repo_path: Path | str, overwrite: bool = False) -> Path:
139
+ """Generates starter .repodna/architecture.yml in target repository."""
140
+ root = Path(repo_path).resolve()
141
+ target_dir = root / ".repodna"
142
+ target_dir.mkdir(parents=True, exist_ok=True)
143
+ target_file = target_dir / DEFAULT_CONTRACT_FILENAME
144
+
145
+ if target_file.exists() and not overwrite:
146
+ raise FileExistsError(f"Architecture contract already exists at '{target_file}'. Pass overwrite=True to replace.")
147
+
148
+ target_file.write_text(STARTER_CONTRACT_YAML, encoding="utf-8")
149
+ return target_file
150
+
151
+
152
+ def load_baseline_file(
153
+ path: Path | str | None,
154
+ repo_root: Path | str | None = None,
155
+ ) -> set[tuple[str, str, str]]:
156
+ """Loads a set of (rule_id, source_file, target_file) baseline entries from JSON file.
157
+
158
+ Fail-safe policy:
159
+ - If path is None or empty: returns empty set (baseline is optional).
160
+ - If path is specified but does not exist: raises FileNotFoundError.
161
+ - If path escapes repository root: raises SecurityValidationError.
162
+ - If path exceeds size limit: raises SecurityValidationError.
163
+ - If JSON is malformed or invalid schema: raises ValueError.
164
+ - If valid and empty: returns empty set.
165
+ - If valid and populated: returns validated set of violations.
166
+ """
167
+ if path is None or (isinstance(path, str) and not path.strip()):
168
+ return set()
169
+
170
+ file_path = Path(path).resolve()
171
+
172
+ if repo_root is not None:
173
+ safe_root = Path(repo_root).resolve()
174
+ if not is_safe_subpath(safe_root, file_path):
175
+ raise SecurityValidationError(
176
+ "PATH_TRAVERSAL_DETECTED",
177
+ f"Baseline file path '{file_path}' escapes repository root '{safe_root}'.",
178
+ )
179
+
180
+ if not file_path.exists():
181
+ raise FileNotFoundError(f"Baseline file explicitly specified but does not exist: {file_path}")
182
+
183
+ if not file_path.is_file():
184
+ raise ValueError(f"Baseline path is not a regular file: {file_path}")
185
+
186
+ size = file_path.stat().st_size
187
+ if size > MAX_BASELINE_SIZE_BYTES:
188
+ raise SecurityValidationError(
189
+ "BASELINE_SIZE_EXCEEDED",
190
+ f"Baseline file '{file_path.name}' exceeds limit ({size} > {MAX_BASELINE_SIZE_BYTES} bytes).",
191
+ )
192
+
193
+ try:
194
+ content = file_path.read_text(encoding="utf-8")
195
+ data = json.loads(content)
196
+ except Exception as exc:
197
+ raise ValueError(f"Corrupted or invalid JSON in baseline file '{file_path}': {exc}") from exc
198
+
199
+ if isinstance(data, list):
200
+ items: set[tuple[str, str, str]] = set()
201
+ for idx, entry in enumerate(data):
202
+ if not isinstance(entry, dict):
203
+ raise ValueError(
204
+ f"Corrupted baseline entry at index {idx} in '{file_path}': expected object/dict, got {type(entry).__name__}."
205
+ )
206
+ rid = entry.get("rule_id")
207
+ src = entry.get("source_file")
208
+ tgt = entry.get("target_file")
209
+ if not (
210
+ isinstance(rid, str)
211
+ and isinstance(src, str)
212
+ and isinstance(tgt, str)
213
+ and rid.strip()
214
+ and src.strip()
215
+ and tgt.strip()
216
+ ):
217
+ raise ValueError(
218
+ f"Corrupted baseline entry at index {idx} in '{file_path}': "
219
+ f"must contain non-empty 'rule_id', 'source_file', and 'target_file'. Got: {entry}"
220
+ )
221
+ items.add((rid.strip(), src.strip(), tgt.strip()))
222
+ return items
223
+
224
+ if isinstance(data, dict):
225
+ if "baseline_violations" not in data:
226
+ raise ValueError(
227
+ f"Invalid baseline format in '{file_path}': root object must contain 'baseline_violations' array."
228
+ )
229
+ violations = data["baseline_violations"]
230
+ if not isinstance(violations, list):
231
+ raise ValueError(
232
+ f"Invalid baseline format in '{file_path}': 'baseline_violations' must be a list."
233
+ )
234
+ items = set()
235
+ for idx, entry in enumerate(violations):
236
+ if not isinstance(entry, dict):
237
+ raise ValueError(
238
+ f"Corrupted baseline violation at index {idx} in '{file_path}': expected object/dict."
239
+ )
240
+ rid = entry.get("rule_id")
241
+ src = entry.get("source_file")
242
+ tgt = entry.get("target_file")
243
+ if not (
244
+ isinstance(rid, str)
245
+ and isinstance(src, str)
246
+ and isinstance(tgt, str)
247
+ and rid.strip()
248
+ and src.strip()
249
+ and tgt.strip()
250
+ ):
251
+ raise ValueError(
252
+ f"Corrupted baseline violation at index {idx} in '{file_path}': "
253
+ f"must contain non-empty 'rule_id', 'source_file', and 'target_file'. Got: {entry}"
254
+ )
255
+ items.add((rid.strip(), src.strip(), tgt.strip()))
256
+ return items
257
+
258
+ raise ValueError(
259
+ f"Invalid baseline schema in '{file_path}': root must be a list of violation objects or a dict with 'baseline_violations'."
260
+ )