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,334 @@
1
+ """Bounded Zero-Execution Declarative Plugin Rule Evaluator for RepoDNA v0.12.0.
2
+
3
+ Evaluates validated DeclarativePluginManifest rules against AnalysisResult, SymbolIndexer,
4
+ and optional QualityReport without importing or executing any repository or plugin code.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ import time
11
+ from collections.abc import Callable
12
+
13
+ from repodna.brain.indexer import SymbolIndexer
14
+ from repodna.plugins.models import (
15
+ MAX_EVAL_TIME_MS,
16
+ MAX_FINDINGS_PER_RULE,
17
+ DeclarativePluginManifest,
18
+ DeclarativeRule,
19
+ PluginEvaluationResult,
20
+ PluginFinding,
21
+ PluginRuleKind,
22
+ )
23
+ from repodna.plugins.validator import compute_plugins_fingerprint, validate_safe_regex
24
+ from repodna.quality.models import QualityReport
25
+ from repodna.schemas.models import AnalysisResult, FileNode
26
+
27
+
28
+ def _make_finding_id(plugin_id: str, rule_id: str, file_path: str, symbol: str | None, line: int) -> str:
29
+ raw = f"{plugin_id}|{rule_id}|{file_path}|{symbol or ''}|{line}"
30
+ return f"pf_{hashlib.sha256(raw.encode('utf-8')).hexdigest()[:14]}"
31
+
32
+
33
+ def _lang_matches(rule: DeclarativeRule, file_lang: str) -> bool:
34
+ if not rule.languages:
35
+ return True
36
+ fl = (file_lang or "").strip().lower()
37
+ return any(rl.strip().lower() in fl or fl in rl.strip().lower() for rl in rule.languages)
38
+
39
+
40
+ def evaluate_declarative_plugins(
41
+ manifests: list[DeclarativePluginManifest],
42
+ analysis: AnalysisResult,
43
+ indexer: SymbolIndexer | None = None,
44
+ quality_report: QualityReport | None = None,
45
+ *,
46
+ max_eval_time_ms: int = MAX_EVAL_TIME_MS,
47
+ is_cancelled: Callable[[], bool] | None = None,
48
+ ) -> PluginEvaluationResult:
49
+ """Evaluates declarative rule packs with strict time, finding-count, and isolation bounds."""
50
+ t0 = time.perf_counter()
51
+ fingerprint = compute_plugins_fingerprint(manifests)
52
+ findings: list[PluginFinding] = []
53
+ truncated_rules: list[str] = []
54
+ errors: list[str] = []
55
+ evaluated_ids: list[str] = []
56
+
57
+ # Reject duplicate plugin_ids safely
58
+ seen_plugins: set[str] = set()
59
+ files_by_id = {f.id: f for f in analysis.files}
60
+
61
+ for manifest in manifests:
62
+ if manifest.plugin_id in seen_plugins:
63
+ errors.append(f"Duplicate plugin_id '{manifest.plugin_id}' skipped.")
64
+ continue
65
+ seen_plugins.add(manifest.plugin_id)
66
+ evaluated_ids.append(f"{manifest.plugin_id}@{manifest.plugin_version}")
67
+
68
+ for rule in manifest.rules:
69
+ if not rule.enabled:
70
+ continue
71
+ if is_cancelled and is_cancelled():
72
+ errors.append("Plugin evaluation cancelled.")
73
+ break
74
+ elapsed_ms = (time.perf_counter() - t0) * 1000.0
75
+ if elapsed_ms > max_eval_time_ms:
76
+ truncated_rules.append(f"{manifest.plugin_id}:{rule.rule_id} (time_limit)")
77
+ break
78
+
79
+ try:
80
+ rule_hits = _eval_single_rule(
81
+ manifest, rule, analysis, files_by_id, indexer, quality_report
82
+ )
83
+ if len(rule_hits) > MAX_FINDINGS_PER_RULE:
84
+ truncated_rules.append(f"{manifest.plugin_id}:{rule.rule_id}")
85
+ rule_hits = rule_hits[:MAX_FINDINGS_PER_RULE]
86
+ findings.extend(rule_hits)
87
+ except Exception as exc:
88
+ # Plugin failure MUST NEVER crash core analysis
89
+ errors.append(f"Rule '{manifest.plugin_id}:{rule.rule_id}' failed safely: {exc}")
90
+
91
+ # Deterministic ordering
92
+ findings.sort(key=lambda f: (f.severity, f.plugin_id, f.rule_id, f.file_path, f.line_start, f.finding_id))
93
+ return PluginEvaluationResult(
94
+ plugins_evaluated=evaluated_ids,
95
+ plugins_fingerprint=fingerprint,
96
+ findings=findings,
97
+ truncated_rules=sorted(set(truncated_rules)),
98
+ errors=errors,
99
+ duration_ms=round((time.perf_counter() - t0) * 1000.0, 2),
100
+ )
101
+
102
+
103
+ def _eval_single_rule(
104
+ manifest: DeclarativePluginManifest,
105
+ rule: DeclarativeRule,
106
+ analysis: AnalysisResult,
107
+ files_by_id: dict[str, FileNode],
108
+ indexer: SymbolIndexer | None,
109
+ quality_report: QualityReport | None,
110
+ ) -> list[PluginFinding]:
111
+ hits: list[PluginFinding] = []
112
+ params = rule.params
113
+
114
+ if rule.kind == PluginRuleKind.PROHIBITED_DEPENDENCY_DIRECTION:
115
+ src_prefix = str(params.get("from_prefix", "")).replace("\\", "/").strip("/")
116
+ dst_prefix = str(params.get("to_prefix", "")).replace("\\", "/").strip("/")
117
+ if not src_prefix or not dst_prefix:
118
+ return hits
119
+ for f in analysis.files:
120
+ if not _lang_matches(rule, f.language):
121
+ continue
122
+ if f.id == src_prefix or f.id.startswith(src_prefix + "/"):
123
+ for imp in sorted(f.imports_internal):
124
+ if imp == dst_prefix or imp.startswith(dst_prefix + "/"):
125
+ hits.append(
126
+ PluginFinding(
127
+ finding_id=_make_finding_id(manifest.plugin_id, rule.rule_id, f.id, imp, 1),
128
+ plugin_id=manifest.plugin_id,
129
+ plugin_version=manifest.plugin_version,
130
+ rule_id=rule.rule_id,
131
+ kind=rule.kind,
132
+ severity=rule.severity,
133
+ file_path=f.id,
134
+ line_start=1,
135
+ line_end=1,
136
+ message=f"Prohibited dependency direction: '{f.id}' imports '{imp}' ({src_prefix} -> {dst_prefix}).",
137
+ remediation=rule.remediation,
138
+ )
139
+ )
140
+
141
+ elif rule.kind == PluginRuleKind.FORBIDDEN_IMPORT:
142
+ pat_str = str(params.get("import_pattern", ""))
143
+ if not pat_str:
144
+ return hits
145
+ rx = validate_safe_regex(pat_str)
146
+ for f in analysis.files:
147
+ if not _lang_matches(rule, f.language):
148
+ continue
149
+ all_imps = [*f.imports_internal, *f.imports_external]
150
+ for imp in sorted(set(all_imps)):
151
+ if rx.search(imp):
152
+ hits.append(
153
+ PluginFinding(
154
+ finding_id=_make_finding_id(manifest.plugin_id, rule.rule_id, f.id, imp, 1),
155
+ plugin_id=manifest.plugin_id,
156
+ plugin_version=manifest.plugin_version,
157
+ rule_id=rule.rule_id,
158
+ kind=rule.kind,
159
+ severity=rule.severity,
160
+ file_path=f.id,
161
+ line_start=1,
162
+ line_end=1,
163
+ message=f"Forbidden import '{imp}' matched pattern '{pat_str}' in '{f.id}'.",
164
+ remediation=rule.remediation,
165
+ )
166
+ )
167
+
168
+ elif rule.kind == PluginRuleKind.REQUIRED_BOUNDARY:
169
+ layer_prefix = str(params.get("layer_prefix", "")).replace("\\", "/").strip("/")
170
+ allowed_targets = [str(p).replace("\\", "/").strip("/") for p in params.get("allowed_target_prefixes", [])]
171
+ if not layer_prefix:
172
+ return hits
173
+ for f in analysis.files:
174
+ if not _lang_matches(rule, f.language):
175
+ continue
176
+ if f.id == layer_prefix or f.id.startswith(layer_prefix + "/"):
177
+ for imp in sorted(f.imports_internal):
178
+ if imp == layer_prefix or imp.startswith(layer_prefix + "/"):
179
+ continue
180
+ if not any(imp == a or imp.startswith(a + "/") for a in allowed_targets):
181
+ hits.append(
182
+ PluginFinding(
183
+ finding_id=_make_finding_id(manifest.plugin_id, rule.rule_id, f.id, imp, 1),
184
+ plugin_id=manifest.plugin_id,
185
+ plugin_version=manifest.plugin_version,
186
+ rule_id=rule.rule_id,
187
+ kind=rule.kind,
188
+ severity=rule.severity,
189
+ file_path=f.id,
190
+ line_start=1,
191
+ line_end=1,
192
+ message=f"Boundary violation: '{f.id}' imports '{imp}' outside allowed prefixes {allowed_targets}.",
193
+ remediation=rule.remediation,
194
+ )
195
+ )
196
+
197
+ elif rule.kind == PluginRuleKind.NAMING_CONVENTION and indexer is not None:
198
+ pat_str = str(params.get("required_pattern", ""))
199
+ symbol_kinds = {str(k).lower() for k in params.get("symbol_kinds", [])}
200
+ if not pat_str:
201
+ return hits
202
+ rx = validate_safe_regex(pat_str)
203
+ for fid, syms in sorted(indexer._symbols_by_file.items()):
204
+ for sym in syms:
205
+ if not _lang_matches(rule, sym.language):
206
+ continue
207
+ if symbol_kinds and sym.kind.value.lower() not in symbol_kinds:
208
+ continue
209
+ if sym.name.startswith("__") and sym.name.endswith("__"):
210
+ continue
211
+ if not rx.match(sym.name):
212
+ hits.append(
213
+ PluginFinding(
214
+ finding_id=_make_finding_id(manifest.plugin_id, rule.rule_id, fid, sym.name, sym.line_start),
215
+ plugin_id=manifest.plugin_id,
216
+ plugin_version=manifest.plugin_version,
217
+ rule_id=rule.rule_id,
218
+ kind=rule.kind,
219
+ severity=rule.severity,
220
+ file_path=fid,
221
+ line_start=sym.line_start,
222
+ line_end=sym.line_end,
223
+ symbol_name=sym.name,
224
+ message=f"Symbol '{sym.name}' ({sym.kind.value}) does not match naming pattern '{pat_str}'.",
225
+ remediation=rule.remediation,
226
+ evidence_id=sym.evidence_id,
227
+ )
228
+ )
229
+
230
+ elif rule.kind == PluginRuleKind.SYMBOL_VISIBILITY and indexer is not None:
231
+ max_public_per_file = int(params.get("max_exported_symbols_per_file", 50))
232
+ for fid, syms in sorted(indexer._symbols_by_file.items()):
233
+ exported = [s for s in syms if s.is_exported and _lang_matches(rule, s.language)]
234
+ if len(exported) > max_public_per_file:
235
+ hits.append(
236
+ PluginFinding(
237
+ finding_id=_make_finding_id(manifest.plugin_id, rule.rule_id, fid, None, 1),
238
+ plugin_id=manifest.plugin_id,
239
+ plugin_version=manifest.plugin_version,
240
+ rule_id=rule.rule_id,
241
+ kind=rule.kind,
242
+ severity=rule.severity,
243
+ file_path=fid,
244
+ line_start=1,
245
+ line_end=1,
246
+ message=f"File '{fid}' exports {len(exported)} symbols (threshold: {max_public_per_file}).",
247
+ remediation=rule.remediation,
248
+ )
249
+ )
250
+
251
+ elif rule.kind == PluginRuleKind.COMPLEXITY_THRESHOLD and quality_report is not None:
252
+ max_cc = int(params.get("max_cyclomatic", 15))
253
+ max_len = int(params.get("max_function_length", 120))
254
+ for cm in quality_report.complexity_metrics:
255
+ if not _lang_matches(rule, cm.language):
256
+ continue
257
+ cc = cm.cyclomatic_complexity
258
+ if (cc is not None and cc > max_cc) or cm.function_length > max_len:
259
+ hits.append(
260
+ PluginFinding(
261
+ finding_id=_make_finding_id(manifest.plugin_id, rule.rule_id, cm.file_path, cm.symbol_name, cm.line_start),
262
+ plugin_id=manifest.plugin_id,
263
+ plugin_version=manifest.plugin_version,
264
+ rule_id=rule.rule_id,
265
+ kind=rule.kind,
266
+ severity=rule.severity,
267
+ file_path=cm.file_path,
268
+ line_start=cm.line_start,
269
+ line_end=cm.line_end,
270
+ symbol_name=cm.symbol_name,
271
+ message=(
272
+ f"Symbol '{cm.symbol_name}' exceeds plugin complexity threshold "
273
+ f"(CC={cc}/{max_cc}, length={cm.function_length}/{max_len})."
274
+ ),
275
+ remediation=rule.remediation,
276
+ evidence_id=cm.evidence_id,
277
+ )
278
+ )
279
+
280
+ elif rule.kind == PluginRuleKind.PROHIBITED_AST_CONSTRUCT and indexer is not None:
281
+ pat_str = str(params.get("forbidden_pattern", ""))
282
+ if not pat_str:
283
+ return hits
284
+ rx = validate_safe_regex(pat_str)
285
+ for fid, syms in sorted(indexer._symbols_by_file.items()):
286
+ for sym in syms:
287
+ if not _lang_matches(rule, sym.language):
288
+ continue
289
+ sig_text = sym.signature or sym.name
290
+ if rx.search(sig_text):
291
+ hits.append(
292
+ PluginFinding(
293
+ finding_id=_make_finding_id(manifest.plugin_id, rule.rule_id, fid, sym.name, sym.line_start),
294
+ plugin_id=manifest.plugin_id,
295
+ plugin_version=manifest.plugin_version,
296
+ rule_id=rule.rule_id,
297
+ kind=rule.kind,
298
+ severity=rule.severity,
299
+ file_path=fid,
300
+ line_start=sym.line_start,
301
+ line_end=sym.line_end,
302
+ symbol_name=sym.name,
303
+ message=f"Prohibited AST signature pattern '{pat_str}' matched on '{sym.name}'.",
304
+ remediation=rule.remediation,
305
+ evidence_id=sym.evidence_id,
306
+ )
307
+ )
308
+
309
+ elif rule.kind == PluginRuleKind.TEST_RELATIONSHIP and quality_report is not None:
310
+ target_prefix = str(params.get("production_prefix", "")).replace("\\", "/").strip("/")
311
+ for entry in quality_report.test_mapping.entries:
312
+ if not _lang_matches(rule, entry.language):
313
+ continue
314
+ if target_prefix and not (entry.production_file == target_prefix or entry.production_file.startswith(target_prefix + "/")):
315
+ continue
316
+ if entry.relationship_kind.value == "no_observed_relationship":
317
+ hits.append(
318
+ PluginFinding(
319
+ finding_id=_make_finding_id(manifest.plugin_id, rule.rule_id, entry.production_file, None, 1),
320
+ plugin_id=manifest.plugin_id,
321
+ plugin_version=manifest.plugin_version,
322
+ rule_id=rule.rule_id,
323
+ kind=rule.kind,
324
+ severity=rule.severity,
325
+ file_path=entry.production_file,
326
+ line_start=1,
327
+ line_end=1,
328
+ message=f"No static test relationship observed for '{entry.production_file}' (static check, not runtime coverage).",
329
+ remediation=rule.remediation,
330
+ )
331
+ )
332
+
333
+ _ = files_by_id
334
+ return hits
@@ -0,0 +1,113 @@
1
+ """Typed Pydantic schemas and resource bounds for RepoDNA Declarative Plugin SDK.
2
+
3
+ Security invariant:
4
+ - Declarative plugins contain ZERO executable code (no Python imports, no eval/exec, no shell).
5
+ - Strict resource bounds cap manifest bytes, rule counts, regex length, match counts, and runtime.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from enum import StrEnum
11
+ from typing import Any
12
+
13
+ from pydantic import BaseModel, Field
14
+
15
+ PLUGIN_SCHEMA_VERSION = "1.0"
16
+ MAX_MANIFEST_BYTES = 262_144 # 256 KB
17
+ MAX_RULES_PER_PACK = 50
18
+ MAX_REGEX_LEN = 160
19
+ MAX_FINDINGS_PER_RULE = 200
20
+ MAX_EVAL_TIME_MS = 5_000
21
+ MAX_YAML_DEPTH = 12
22
+
23
+
24
+ class PluginTrustLevel(StrEnum):
25
+ """Explicit trust model separation."""
26
+
27
+ DECLARATIVE_ZERO_EXECUTION = "declarative_zero_execution"
28
+ # Note: In-process executable Python plugins are NOT auto-loaded in v0.12.0.
29
+
30
+
31
+ class PluginRuleKind(StrEnum):
32
+ """Explicit allowlist of supported declarative rule predicates."""
33
+
34
+ COMPLEXITY_THRESHOLD = "complexity_threshold"
35
+ PROHIBITED_AST_CONSTRUCT = "prohibited_ast_construct"
36
+ NAMING_CONVENTION = "naming_convention"
37
+ PROHIBITED_DEPENDENCY_DIRECTION = "prohibited_dependency_direction"
38
+ FORBIDDEN_IMPORT = "forbidden_import"
39
+ REQUIRED_BOUNDARY = "required_boundary"
40
+ SYMBOL_VISIBILITY = "symbol_visibility"
41
+ TEST_RELATIONSHIP = "test_relationship"
42
+
43
+
44
+ class PluginValidationError(ValueError):
45
+ """Raised when a declarative plugin manifest violates schema, safety, or ReDoS guards."""
46
+
47
+ def __init__(self, code: str, message: str) -> None:
48
+ super().__init__(message)
49
+ self.code = code
50
+ self.message = message
51
+
52
+
53
+ class DeclarativeRule(BaseModel):
54
+ """Single bounded declarative rule inside a plugin manifest."""
55
+
56
+ rule_id: str = Field(..., min_length=3, max_length=64, pattern=r"^[A-Z][A-Z0-9_-]{2,63}$")
57
+ kind: PluginRuleKind
58
+ title: str = Field(..., min_length=3, max_length=160)
59
+ severity: str = Field(default="warning", pattern=r"^(critical|warning|info)$")
60
+ languages: list[str] = Field(default_factory=list)
61
+ enabled: bool = True
62
+ params: dict[str, Any] = Field(default_factory=dict)
63
+ remediation: str = ""
64
+
65
+
66
+ class DeclarativePluginManifest(BaseModel):
67
+ """Versioned, zero-execution declarative rule pack manifest."""
68
+
69
+ plugin_id: str = Field(..., min_length=3, max_length=80, pattern=r"^[a-z0-9][a-z0-9._-]{2,79}$")
70
+ plugin_version: str = Field(..., pattern=r"^\d+\.\d+\.\d+$")
71
+ schema_version: str = Field(default=PLUGIN_SCHEMA_VERSION)
72
+ compatible_repodna_versions: str = Field(default=">=0.12.0,<1.0.0")
73
+ description: str = Field(..., min_length=4, max_length=500)
74
+ author: str = Field(default="Community", max_length=120)
75
+ license: str = Field(default="MIT", max_length=64)
76
+ trust_level: PluginTrustLevel = PluginTrustLevel.DECLARATIVE_ZERO_EXECUTION
77
+ capabilities: list[str] = Field(default_factory=lambda: ["declarative_rules"])
78
+ supported_languages: list[str] = Field(default_factory=list)
79
+ rules: list[DeclarativeRule] = Field(default_factory=list, max_length=MAX_RULES_PER_PACK)
80
+
81
+
82
+ class PluginFinding(BaseModel):
83
+ """Deterministic finding emitted by a declarative plugin rule."""
84
+
85
+ finding_id: str
86
+ plugin_id: str
87
+ plugin_version: str
88
+ rule_id: str
89
+ kind: PluginRuleKind
90
+ severity: str
91
+ file_path: str
92
+ line_start: int = 1
93
+ line_end: int = 1
94
+ symbol_name: str | None = None
95
+ message: str
96
+ remediation: str = ""
97
+ evidence_id: str | None = None
98
+
99
+
100
+ class PluginEvaluationResult(BaseModel):
101
+ """Bounded result of evaluating one or more declarative rule packs."""
102
+
103
+ schema_version: str = PLUGIN_SCHEMA_VERSION
104
+ plugins_evaluated: list[str] = Field(default_factory=list)
105
+ plugins_fingerprint: str = ""
106
+ findings: list[PluginFinding] = Field(default_factory=list)
107
+ truncated_rules: list[str] = Field(default_factory=list)
108
+ errors: list[str] = Field(default_factory=list)
109
+ duration_ms: float = 0.0
110
+ trust_notice: str = (
111
+ "Declarative plugins executed strictly via zero-execution AST/metric predicates. "
112
+ "No plugin Python code or shell commands were imported or executed."
113
+ )