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,494 @@
1
+ """Zero-execution multilingual package metadata extractor and version constraint evaluator.
2
+
3
+ Supports static manifest inspection for Python, npm/TypeScript, C# (.csproj),
4
+ Java (pom.xml), Go (go.mod), and Rust (Cargo.toml) without executing build scripts
5
+ or querying external package registries.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import re
12
+ import tomllib
13
+ import xml.etree.ElementTree as ET
14
+ from pathlib import Path
15
+
16
+ from repodna.workspace.models import (
17
+ PackageDependencyDecl,
18
+ PackageIdentity,
19
+ VersionCompatibilityStatus,
20
+ VersionConstraintFinding,
21
+ )
22
+
23
+ _MAX_META_BYTES = 524_288
24
+ _PY_REQ_RE = re.compile(r"^([A-Za-z0-9_.-]+)\s*(.*)$")
25
+ _SEMVER_RE = re.compile(r"^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?")
26
+ _GO_REQ_RE = re.compile(r"^\s*([^\s]+)\s+(v[\d.A-Za-z+-]+)")
27
+ _GO_REPLACE_RE = re.compile(r"^\s*([^\s]+)\s+=>\s+(\.{1,2}/[^\s]+)")
28
+
29
+
30
+ def _safe_read_text(path: Path) -> str | None:
31
+ try:
32
+ if not path.exists() or not path.is_file() or path.stat().st_size > _MAX_META_BYTES:
33
+ return None
34
+ return path.read_text(encoding="utf-8", errors="replace")
35
+ except OSError:
36
+ return None
37
+
38
+
39
+ def _parse_semver_tuple(raw: str | None) -> tuple[int, int, int] | None:
40
+ if not raw:
41
+ return None
42
+ m = _SEMVER_RE.match(raw.strip())
43
+ if not m:
44
+ return None
45
+ return (int(m.group(1)), int(m.group(2) or 0), int(m.group(3) or 0))
46
+
47
+
48
+ def extract_repository_packages(
49
+ repo_root: Path,
50
+ *,
51
+ repository_id: str,
52
+ repository_alias: str,
53
+ ) -> tuple[list[PackageIdentity], list[PackageDependencyDecl]]:
54
+ """Extracts static PackageIdentity and PackageDependencyDecl records from a repository."""
55
+ packages: list[PackageIdentity] = []
56
+ deps: list[PackageDependencyDecl] = []
57
+
58
+ # 1. Python: pyproject.toml + requirements.txt
59
+ pyproj = repo_root / "pyproject.toml"
60
+ pyproj_txt = _safe_read_text(pyproj)
61
+ if pyproj_txt:
62
+ try:
63
+ data = tomllib.loads(pyproj_txt)
64
+ proj = data.get("project", {})
65
+ if isinstance(proj, dict) and isinstance(proj.get("name"), str):
66
+ pname = proj["name"].strip()
67
+ pver = str(proj["version"]) if isinstance(proj.get("version"), str) else None
68
+ packages.append(
69
+ PackageIdentity(
70
+ package_key=f"python:{pname.lower()}",
71
+ ecosystem="python",
72
+ name=pname,
73
+ version=pver,
74
+ repository_id=repository_id,
75
+ repository_alias=repository_alias,
76
+ manifest_file="pyproject.toml",
77
+ evidence=f"pyproject.toml:[project].name={pname}",
78
+ )
79
+ )
80
+ raw_deps = proj.get("dependencies", []) if isinstance(proj, dict) else []
81
+ if isinstance(raw_deps, list):
82
+ for item in raw_deps:
83
+ if not isinstance(item, str):
84
+ continue
85
+ cleaned = item.split(";")[0].split("[")[0].strip()
86
+ m = _PY_REQ_RE.match(cleaned)
87
+ if m:
88
+ dname, dspec = m.group(1), m.group(2).strip() or None
89
+ deps.append(
90
+ PackageDependencyDecl(
91
+ source_repository_id=repository_id,
92
+ source_alias=repository_alias,
93
+ ecosystem="python",
94
+ target_name=dname,
95
+ version_constraint=dspec,
96
+ manifest_file="pyproject.toml",
97
+ evidence=f"pyproject.toml:dependencies:{item.strip()}",
98
+ )
99
+ )
100
+ except Exception:
101
+ pass
102
+
103
+ req_txt = _safe_read_text(repo_root / "requirements.txt")
104
+ if req_txt:
105
+ for idx, line in enumerate(req_txt.splitlines(), 1):
106
+ stripped = line.strip()
107
+ if not stripped or stripped.startswith("#") or stripped.startswith("-"):
108
+ continue
109
+ cleaned = stripped.split(";")[0].split("[")[0].strip()
110
+ m = _PY_REQ_RE.match(cleaned)
111
+ if m:
112
+ deps.append(
113
+ PackageDependencyDecl(
114
+ source_repository_id=repository_id,
115
+ source_alias=repository_alias,
116
+ ecosystem="python",
117
+ target_name=m.group(1),
118
+ version_constraint=m.group(2).strip() or None,
119
+ manifest_file="requirements.txt",
120
+ evidence=f"requirements.txt:{idx}:{stripped}",
121
+ )
122
+ )
123
+
124
+ # 2. JS/TS: package.json
125
+ pkg_json_txt = _safe_read_text(repo_root / "package.json")
126
+ if pkg_json_txt:
127
+ try:
128
+ pdata = json.loads(pkg_json_txt)
129
+ if isinstance(pdata, dict):
130
+ if isinstance(pdata.get("name"), str) and pdata["name"].strip():
131
+ pname = pdata["name"].strip()
132
+ pver = str(pdata["version"]) if isinstance(pdata.get("version"), str) else None
133
+ packages.append(
134
+ PackageIdentity(
135
+ package_key=f"npm:{pname.lower()}",
136
+ ecosystem="npm",
137
+ name=pname,
138
+ version=pver,
139
+ repository_id=repository_id,
140
+ repository_alias=repository_alias,
141
+ manifest_file="package.json",
142
+ evidence=f"package.json:name={pname}",
143
+ )
144
+ )
145
+ for sec in ("dependencies", "devDependencies", "peerDependencies"):
146
+ mapping = pdata.get(sec)
147
+ if isinstance(mapping, dict):
148
+ for dname, dspec in mapping.items():
149
+ if not isinstance(dname, str) or not isinstance(dspec, str):
150
+ continue
151
+ is_local = dspec.startswith("file:") or dspec.startswith("link:") or dspec.startswith("workspace:")
152
+ local_path = dspec.split(":", 1)[1] if dspec.startswith(("file:", "link:")) else None
153
+ deps.append(
154
+ PackageDependencyDecl(
155
+ source_repository_id=repository_id,
156
+ source_alias=repository_alias,
157
+ ecosystem="npm",
158
+ target_name=dname,
159
+ version_constraint=None if is_local else dspec,
160
+ is_local_path_ref=is_local,
161
+ local_target_path=local_path,
162
+ manifest_file="package.json",
163
+ evidence=f"package.json:{sec}.{dname}={dspec}",
164
+ )
165
+ )
166
+ except Exception:
167
+ pass
168
+
169
+ # 3. C#: *.csproj (XXE-safe)
170
+ for csproj in sorted(repo_root.glob("**/*.csproj"))[:25]:
171
+ rel = csproj.relative_to(repo_root).as_posix()
172
+ txt = _safe_read_text(csproj)
173
+ if not txt or "<!DOCTYPE" in txt.upper() or "<!ENTITY" in txt.upper():
174
+ continue
175
+ try:
176
+ root = ET.fromstring(txt)
177
+ asm = root.findtext(".//PackageId") or root.findtext(".//AssemblyName") or csproj.stem
178
+ ver = root.findtext(".//Version")
179
+ packages.append(
180
+ PackageIdentity(
181
+ package_key=f"nuget:{asm.lower()}",
182
+ ecosystem="nuget",
183
+ name=asm,
184
+ version=ver,
185
+ repository_id=repository_id,
186
+ repository_alias=repository_alias,
187
+ manifest_file=rel,
188
+ evidence=f"{rel}:PackageId/AssemblyName={asm}",
189
+ )
190
+ )
191
+ for pref in root.findall(".//ProjectReference"):
192
+ inc = pref.attrib.get("Include", "").strip()
193
+ if inc:
194
+ deps.append(
195
+ PackageDependencyDecl(
196
+ source_repository_id=repository_id,
197
+ source_alias=repository_alias,
198
+ ecosystem="nuget",
199
+ target_name=Path(inc.replace("\\", "/")).stem,
200
+ is_local_path_ref=True,
201
+ local_target_path=inc.replace("\\", "/"),
202
+ manifest_file=rel,
203
+ evidence=f"{rel}:ProjectReference={inc}",
204
+ )
205
+ )
206
+ for pkgref in root.findall(".//PackageReference"):
207
+ inc = pkgref.attrib.get("Include", "").strip()
208
+ pver = pkgref.attrib.get("Version")
209
+ if inc:
210
+ deps.append(
211
+ PackageDependencyDecl(
212
+ source_repository_id=repository_id,
213
+ source_alias=repository_alias,
214
+ ecosystem="nuget",
215
+ target_name=inc,
216
+ version_constraint=pver,
217
+ manifest_file=rel,
218
+ evidence=f"{rel}:PackageReference={inc}@{pver or '*'}",
219
+ )
220
+ )
221
+ except ET.ParseError:
222
+ continue
223
+
224
+ # 4. Go: go.mod
225
+ gomod_txt = _safe_read_text(repo_root / "go.mod")
226
+ if gomod_txt:
227
+ for idx, line in enumerate(gomod_txt.splitlines(), 1):
228
+ s = line.strip()
229
+ if s.startswith("module "):
230
+ mod_name = s.split()[1].strip()
231
+ packages.append(
232
+ PackageIdentity(
233
+ package_key=f"go:{mod_name.lower()}",
234
+ ecosystem="go",
235
+ name=mod_name,
236
+ version=None,
237
+ repository_id=repository_id,
238
+ repository_alias=repository_alias,
239
+ manifest_file="go.mod",
240
+ evidence=f"go.mod:{idx}:module {mod_name}",
241
+ )
242
+ )
243
+ else:
244
+ rm = _GO_REPLACE_RE.match(line)
245
+ if rm:
246
+ deps.append(
247
+ PackageDependencyDecl(
248
+ source_repository_id=repository_id,
249
+ source_alias=repository_alias,
250
+ ecosystem="go",
251
+ target_name=rm.group(1),
252
+ is_local_path_ref=True,
253
+ local_target_path=rm.group(2),
254
+ manifest_file="go.mod",
255
+ evidence=f"go.mod:{idx}:replace {rm.group(1)} => {rm.group(2)}",
256
+ )
257
+ )
258
+ else:
259
+ qm = _GO_REQ_RE.match(line)
260
+ if qm and not s.startswith(("module ", "go ", "//", "replace ")):
261
+ deps.append(
262
+ PackageDependencyDecl(
263
+ source_repository_id=repository_id,
264
+ source_alias=repository_alias,
265
+ ecosystem="go",
266
+ target_name=qm.group(1),
267
+ version_constraint=qm.group(2),
268
+ manifest_file="go.mod",
269
+ evidence=f"go.mod:{idx}:require {qm.group(1)} {qm.group(2)}",
270
+ )
271
+ )
272
+
273
+ # 5. Rust: Cargo.toml
274
+ cargo_txt = _safe_read_text(repo_root / "Cargo.toml")
275
+ if cargo_txt:
276
+ try:
277
+ cdata = tomllib.loads(cargo_txt)
278
+ cpkg = cdata.get("package", {})
279
+ if isinstance(cpkg, dict) and isinstance(cpkg.get("name"), str):
280
+ cname = cpkg["name"].strip()
281
+ cver = str(cpkg["version"]) if isinstance(cpkg.get("version"), str) else None
282
+ packages.append(
283
+ PackageIdentity(
284
+ package_key=f"cargo:{cname.lower()}",
285
+ ecosystem="cargo",
286
+ name=cname,
287
+ version=cver,
288
+ repository_id=repository_id,
289
+ repository_alias=repository_alias,
290
+ manifest_file="Cargo.toml",
291
+ evidence=f"Cargo.toml:[package].name={cname}",
292
+ )
293
+ )
294
+ cdeps = cdata.get("dependencies", {})
295
+ if isinstance(cdeps, dict):
296
+ for dname, spec in cdeps.items():
297
+ if isinstance(spec, str):
298
+ deps.append(
299
+ PackageDependencyDecl(
300
+ source_repository_id=repository_id,
301
+ source_alias=repository_alias,
302
+ ecosystem="cargo",
303
+ target_name=dname,
304
+ version_constraint=spec,
305
+ manifest_file="Cargo.toml",
306
+ evidence=f"Cargo.toml:dependencies.{dname}={spec}",
307
+ )
308
+ )
309
+ elif isinstance(spec, dict):
310
+ lpath = spec.get("path") if isinstance(spec.get("path"), str) else None
311
+ cver = spec.get("version") if isinstance(spec.get("version"), str) else None
312
+ deps.append(
313
+ PackageDependencyDecl(
314
+ source_repository_id=repository_id,
315
+ source_alias=repository_alias,
316
+ ecosystem="cargo",
317
+ target_name=dname,
318
+ version_constraint=cver,
319
+ is_local_path_ref=bool(lpath),
320
+ local_target_path=lpath,
321
+ manifest_file="Cargo.toml",
322
+ evidence=f"Cargo.toml:dependencies.{dname}",
323
+ )
324
+ )
325
+ except Exception:
326
+ pass
327
+
328
+ # 6. Java: pom.xml (XXE-safe)
329
+ pom_txt = _safe_read_text(repo_root / "pom.xml")
330
+ if pom_txt and "<!DOCTYPE" not in pom_txt.upper() and "<!ENTITY" not in pom_txt.upper():
331
+ try:
332
+ proot = ET.fromstring(pom_txt)
333
+ ns_strip = lambda tag: tag.split("}", 1)[-1] # noqa: E731
334
+ gid = next((el.text.strip() for el in proot if ns_strip(el.tag) == "groupId" and el.text), None)
335
+ aid = next((el.text.strip() for el in proot if ns_strip(el.tag) == "artifactId" and el.text), None)
336
+ ver = next((el.text.strip() for el in proot if ns_strip(el.tag) == "version" and el.text), None)
337
+ if aid:
338
+ coord = f"{gid}:{aid}" if gid else aid
339
+ packages.append(
340
+ PackageIdentity(
341
+ package_key=f"maven:{coord.lower()}",
342
+ ecosystem="maven",
343
+ name=coord,
344
+ version=ver,
345
+ repository_id=repository_id,
346
+ repository_alias=repository_alias,
347
+ manifest_file="pom.xml",
348
+ evidence=f"pom.xml:{coord}",
349
+ )
350
+ )
351
+ except ET.ParseError:
352
+ pass
353
+
354
+ return packages, deps
355
+
356
+
357
+ def _check_single_constraint(ecosystem: str, constraint: str, provider_version: str) -> VersionCompatibilityStatus:
358
+ """Ecosystem-aware version constraint check; returns CONSTRAINT_UNSUPPORTED when syntax is outside scope."""
359
+ c = constraint.strip()
360
+ if not c or c == "*":
361
+ return VersionCompatibilityStatus.DECLARED_COMPATIBLE
362
+
363
+ if ecosystem == "python":
364
+ try:
365
+ from packaging.specifiers import SpecifierSet
366
+ from packaging.version import Version
367
+
368
+ spec = SpecifierSet(c)
369
+ ver = Version(provider_version)
370
+ return (
371
+ VersionCompatibilityStatus.DECLARED_COMPATIBLE
372
+ if ver in spec
373
+ else VersionCompatibilityStatus.DECLARED_INCOMPATIBLE
374
+ )
375
+ except Exception:
376
+ return VersionCompatibilityStatus.CONSTRAINT_UNSUPPORTED
377
+
378
+ pv = _parse_semver_tuple(provider_version)
379
+ if pv is None:
380
+ return VersionCompatibilityStatus.VERSION_UNKNOWN
381
+
382
+ if ecosystem in ("npm", "cargo"):
383
+ if "||" in c or " - " in c:
384
+ return VersionCompatibilityStatus.CONSTRAINT_UNSUPPORTED
385
+ if c.startswith("^"):
386
+ base = _parse_semver_tuple(c[1:])
387
+ if base is None:
388
+ return VersionCompatibilityStatus.CONSTRAINT_UNSUPPORTED
389
+ ok = (pv >= base) and (pv[0] == base[0] if base[0] > 0 else pv[0] == 0 and pv[1] == base[1])
390
+ return VersionCompatibilityStatus.DECLARED_COMPATIBLE if ok else VersionCompatibilityStatus.DECLARED_INCOMPATIBLE
391
+ if c.startswith("~"):
392
+ base = _parse_semver_tuple(c[1:])
393
+ if base is None:
394
+ return VersionCompatibilityStatus.CONSTRAINT_UNSUPPORTED
395
+ ok = (pv >= base) and (pv[0] == base[0] and pv[1] == base[1])
396
+ return VersionCompatibilityStatus.DECLARED_COMPATIBLE if ok else VersionCompatibilityStatus.DECLARED_INCOMPATIBLE
397
+ if c.startswith(">="):
398
+ base = _parse_semver_tuple(c[2:])
399
+ if base is None:
400
+ return VersionCompatibilityStatus.CONSTRAINT_UNSUPPORTED
401
+ return VersionCompatibilityStatus.DECLARED_COMPATIBLE if pv >= base else VersionCompatibilityStatus.DECLARED_INCOMPATIBLE
402
+ if c.startswith("<="):
403
+ base = _parse_semver_tuple(c[2:])
404
+ if base is None:
405
+ return VersionCompatibilityStatus.CONSTRAINT_UNSUPPORTED
406
+ return VersionCompatibilityStatus.DECLARED_COMPATIBLE if pv <= base else VersionCompatibilityStatus.DECLARED_INCOMPATIBLE
407
+ if c.startswith("=="):
408
+ base = _parse_semver_tuple(c[2:])
409
+ if base is None:
410
+ return VersionCompatibilityStatus.CONSTRAINT_UNSUPPORTED
411
+ return VersionCompatibilityStatus.DECLARED_COMPATIBLE if pv == base else VersionCompatibilityStatus.DECLARED_INCOMPATIBLE
412
+ exact = _parse_semver_tuple(c.lstrip("="))
413
+ if exact is not None:
414
+ return VersionCompatibilityStatus.DECLARED_COMPATIBLE if pv == exact else VersionCompatibilityStatus.DECLARED_INCOMPATIBLE
415
+ return VersionCompatibilityStatus.CONSTRAINT_UNSUPPORTED
416
+
417
+ # NuGet / Go / Maven: exact version match only, ranges honestly marked CONSTRAINT_UNSUPPORTED
418
+ if any(ch in c for ch in ("[", "]", "(", ")", ",")):
419
+ return VersionCompatibilityStatus.CONSTRAINT_UNSUPPORTED
420
+ exact = _parse_semver_tuple(c)
421
+ if exact is not None:
422
+ return VersionCompatibilityStatus.DECLARED_COMPATIBLE if pv == exact else VersionCompatibilityStatus.DECLARED_INCOMPATIBLE
423
+ return VersionCompatibilityStatus.CONSTRAINT_UNSUPPORTED
424
+
425
+
426
+ def evaluate_version_constraints(
427
+ packages: list[PackageIdentity],
428
+ dependencies: list[PackageDependencyDecl],
429
+ ) -> list[VersionConstraintFinding]:
430
+ """Evaluates declared consumer version constraints against workspace package providers."""
431
+ by_key: dict[str, list[PackageIdentity]] = {}
432
+ for pkg in packages:
433
+ by_key.setdefault(pkg.package_key, []).append(pkg)
434
+
435
+ findings: list[VersionConstraintFinding] = []
436
+ for dep in dependencies:
437
+ if not dep.version_constraint:
438
+ continue
439
+ key = f"{dep.ecosystem}:{dep.target_name.lower()}"
440
+ providers = [p for p in by_key.get(key, []) if p.repository_id != dep.source_repository_id]
441
+ if not providers:
442
+ continue
443
+ if len(providers) > 1:
444
+ findings.append(
445
+ VersionConstraintFinding(
446
+ source_repository_id=dep.source_repository_id,
447
+ source_alias=dep.source_alias,
448
+ ecosystem=dep.ecosystem,
449
+ package_name=dep.target_name,
450
+ declared_constraint=dep.version_constraint,
451
+ status=VersionCompatibilityStatus.AMBIGUOUS_PROVIDER,
452
+ reason=f"Multiple workspace repositories declare package '{dep.target_name}': {[p.repository_alias for p in providers]}.",
453
+ evidence=dep.evidence,
454
+ )
455
+ )
456
+ continue
457
+
458
+ prov = providers[0]
459
+ if not prov.version:
460
+ findings.append(
461
+ VersionConstraintFinding(
462
+ source_repository_id=dep.source_repository_id,
463
+ source_alias=dep.source_alias,
464
+ target_repository_id=prov.repository_id,
465
+ target_alias=prov.repository_alias,
466
+ ecosystem=dep.ecosystem,
467
+ package_name=dep.target_name,
468
+ declared_constraint=dep.version_constraint,
469
+ provider_version=None,
470
+ status=VersionCompatibilityStatus.VERSION_UNKNOWN,
471
+ reason=f"Provider '{prov.repository_alias}' does not declare a static version.",
472
+ evidence=dep.evidence,
473
+ )
474
+ )
475
+ continue
476
+
477
+ status = _check_single_constraint(dep.ecosystem, dep.version_constraint, prov.version)
478
+ findings.append(
479
+ VersionConstraintFinding(
480
+ source_repository_id=dep.source_repository_id,
481
+ source_alias=dep.source_alias,
482
+ target_repository_id=prov.repository_id,
483
+ target_alias=prov.repository_alias,
484
+ ecosystem=dep.ecosystem,
485
+ package_name=dep.target_name,
486
+ declared_constraint=dep.version_constraint,
487
+ provider_version=prov.version,
488
+ status=status,
489
+ reason=f"Consumer declares '{dep.version_constraint}' vs local checkout version '{prov.version}' ({status.value}).",
490
+ evidence=f"{dep.evidence} -> {prov.evidence}",
491
+ )
492
+ )
493
+
494
+ return findings
@@ -0,0 +1,142 @@
1
+ """Declarative zero-execution Workspace Architecture Guardian policy engine."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from repodna.workspace.models import (
6
+ CompatibilityClassification,
7
+ ContractCompatibilityFinding,
8
+ ResolutionStatus,
9
+ WorkspaceManifest,
10
+ WorkspacePolicyFinding,
11
+ WorkspacePolicyKind,
12
+ WorkspacePolicyReport,
13
+ WorkspacePolicyVerdict,
14
+ WorkspaceSnapshot,
15
+ WorkspaceTopologyGraph,
16
+ )
17
+
18
+
19
+ def evaluate_workspace_policies(
20
+ *,
21
+ manifest: WorkspaceManifest,
22
+ snapshot: WorkspaceSnapshot,
23
+ topology: WorkspaceTopologyGraph,
24
+ compatibility_findings: list[ContractCompatibilityFinding] | None = None,
25
+ ) -> WorkspacePolicyReport:
26
+ """Evaluates declarative workspace policies.
27
+
28
+ Critical invariant:
29
+ - If any repository member is missing/inaccessible/failed, workspace policy verdict
30
+ cannot be PASS; it MUST be INCONCLUSIVE (or FAIL if a verified violation already exists).
31
+ - Candidate edges are advisory (WARNING) unless `rule.enforce_on_candidates` is True.
32
+ """
33
+ findings: list[WorkspacePolicyFinding] = []
34
+ has_fail = False
35
+ has_warning = False
36
+
37
+ for rule in manifest.policies:
38
+ if rule.kind == WorkspacePolicyKind.FORBIDDEN_REPO_DEPENDENCY:
39
+ src_alias = str(rule.params.get("from_alias", ""))
40
+ dst_alias = str(rule.params.get("to_alias", ""))
41
+ for edge in topology.edges:
42
+ if edge.source_alias == src_alias and edge.target_alias == dst_alias:
43
+ is_verified = edge.resolution_status == ResolutionStatus.VERIFIED
44
+ if is_verified or rule.enforce_on_candidates:
45
+ verdict = WorkspacePolicyVerdict.FAIL if rule.severity == "critical" else WorkspacePolicyVerdict.WARNING
46
+ else:
47
+ verdict = WorkspacePolicyVerdict.WARNING
48
+ has_fail = has_fail or (verdict == WorkspacePolicyVerdict.FAIL)
49
+ has_warning = has_warning or (verdict == WorkspacePolicyVerdict.WARNING)
50
+ findings.append(
51
+ WorkspacePolicyFinding(
52
+ rule_id=rule.rule_id,
53
+ kind=rule.kind,
54
+ severity=rule.severity,
55
+ verdict=verdict,
56
+ message=f"Forbidden dependency '{src_alias}' -> '{dst_alias}' detected ({edge.resolution_status.value}).",
57
+ source_alias=src_alias,
58
+ target_alias=dst_alias,
59
+ evidence=edge.evidence,
60
+ )
61
+ )
62
+
63
+ elif rule.kind == WorkspacePolicyKind.NO_CIRCULAR_REPO_DEPENDENCIES:
64
+ target_cycles = topology.candidate_cycles if rule.enforce_on_candidates else topology.verified_cycles
65
+ for cyc in target_cycles:
66
+ verdict = WorkspacePolicyVerdict.FAIL if rule.severity == "critical" else WorkspacePolicyVerdict.WARNING
67
+ has_fail = has_fail or (verdict == WorkspacePolicyVerdict.FAIL)
68
+ has_warning = has_warning or (verdict == WorkspacePolicyVerdict.WARNING)
69
+ findings.append(
70
+ WorkspacePolicyFinding(
71
+ rule_id=rule.rule_id,
72
+ kind=rule.kind,
73
+ severity=rule.severity,
74
+ verdict=verdict,
75
+ message=f"Circular cross-repository dependency: {' -> '.join(cyc.repository_aliases)}.",
76
+ evidence=cyc.edge_ids,
77
+ )
78
+ )
79
+
80
+ elif rule.kind == WorkspacePolicyKind.MAX_CROSS_REPO_COUPLING:
81
+ max_out = int(rule.params.get("max_outgoing", 5))
82
+ counts: dict[str, int] = {}
83
+ for edge in topology.edges:
84
+ if edge.resolution_status == ResolutionStatus.VERIFIED or rule.enforce_on_candidates:
85
+ counts[edge.source_alias] = counts.get(edge.source_alias, 0) + 1
86
+ for alias, cnt in sorted(counts.items()):
87
+ if cnt > max_out:
88
+ verdict = WorkspacePolicyVerdict.FAIL if rule.severity == "critical" else WorkspacePolicyVerdict.WARNING
89
+ has_fail = has_fail or (verdict == WorkspacePolicyVerdict.FAIL)
90
+ has_warning = has_warning or (verdict == WorkspacePolicyVerdict.WARNING)
91
+ findings.append(
92
+ WorkspacePolicyFinding(
93
+ rule_id=rule.rule_id,
94
+ kind=rule.kind,
95
+ severity=rule.severity,
96
+ verdict=verdict,
97
+ message=f"Repository '{alias}' has {cnt} outgoing cross-repo edges (max {max_out}).",
98
+ source_alias=alias,
99
+ )
100
+ )
101
+
102
+ elif rule.kind == WorkspacePolicyKind.API_COMPATIBILITY_ENFORCEMENT:
103
+ for cf in compatibility_findings or []:
104
+ if cf.classification == CompatibilityClassification.BREAKING:
105
+ verdict = WorkspacePolicyVerdict.FAIL if rule.severity == "critical" else WorkspacePolicyVerdict.WARNING
106
+ has_fail = has_fail or (verdict == WorkspacePolicyVerdict.FAIL)
107
+ has_warning = has_warning or (verdict == WorkspacePolicyVerdict.WARNING)
108
+ findings.append(
109
+ WorkspacePolicyFinding(
110
+ rule_id=rule.rule_id,
111
+ kind=rule.kind,
112
+ severity=rule.severity,
113
+ verdict=verdict,
114
+ message=f"Breaking contract change in '{cf.provider_alias}' ({cf.endpoint}): {cf.message}",
115
+ source_alias=cf.provider_alias,
116
+ evidence=[cf.evidence],
117
+ )
118
+ )
119
+
120
+ incomplete_reason: str | None = None
121
+ if snapshot.missing_or_failed_count > 0:
122
+ incomplete_reason = (
123
+ f"{snapshot.missing_or_failed_count} repository member(s) missing/inaccessible/failed; "
124
+ "workspace policy cannot be certified PASS."
125
+ )
126
+
127
+ if has_fail:
128
+ overall = WorkspacePolicyVerdict.FAIL
129
+ elif incomplete_reason is not None:
130
+ overall = WorkspacePolicyVerdict.INCONCLUSIVE
131
+ elif has_warning:
132
+ overall = WorkspacePolicyVerdict.WARNING
133
+ else:
134
+ overall = WorkspacePolicyVerdict.PASS
135
+
136
+ return WorkspacePolicyReport(
137
+ workspace_id=manifest.workspace_id,
138
+ verdict=overall,
139
+ findings=findings,
140
+ evaluated_rules=len(manifest.policies),
141
+ incomplete_reason=incomplete_reason,
142
+ )