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,411 @@
1
+ """Federated multi-repository analysis orchestrator with bounded concurrency and incremental reuse.
2
+
3
+ Design invariants:
4
+ - Reuses the canonical single-repository `run_repository_analysis` engine per repository.
5
+ - Bounded global concurrency (`MAX_CONCURRENT_REPOS = 4`); no nested worker explosion.
6
+ - Per-workspace cancellation tokens prevent cancelling Workspace A from interrupting Workspace B.
7
+ - Re-verifies repository Git HEAD / dirty state before snapshot publication (`CHANGES_PENDING` honesty).
8
+ - Caches per-repository static artifacts keyed by canonical repository_id + content fingerprint
9
+ so editing one repository reuses unchanged repositories cleanly.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import hashlib
15
+ import threading
16
+ import time
17
+ from concurrent.futures import ThreadPoolExecutor, as_completed
18
+ from dataclasses import dataclass
19
+ from pathlib import Path
20
+
21
+ from repodna.core.analyzer import run_repository_analysis
22
+ from repodna.schemas.models import ScanRequest, SourceType
23
+ from repodna.workspace.contracts import discover_repository_contracts
24
+ from repodna.workspace.identity import (
25
+ build_workspace_snapshot,
26
+ compute_canonical_repository_id,
27
+ detect_git_metadata,
28
+ )
29
+ from repodna.workspace.manifest import (
30
+ compute_policies_fingerprint,
31
+ load_and_validate_workspace_manifest,
32
+ resolve_member_path,
33
+ )
34
+ from repodna.workspace.models import (
35
+ MAX_CONCURRENT_REPOS,
36
+ ContractDefinition,
37
+ PackageDependencyDecl,
38
+ PackageIdentity,
39
+ RepositoryMembershipStatus,
40
+ RepositorySnapshotRef,
41
+ ServiceIdentity,
42
+ WorkspaceAnalysisResult,
43
+ WorkspaceManifest,
44
+ WorkspaceRepositoryEntry,
45
+ )
46
+ from repodna.workspace.packages import evaluate_version_constraints, extract_repository_packages
47
+ from repodna.workspace.policies import evaluate_workspace_policies
48
+ from repodna.workspace.services import discover_repository_services
49
+ from repodna.workspace.topology import build_workspace_topology, resolve_cross_repository_edges
50
+
51
+
52
+ @dataclass
53
+ class _RepoFederationArtifact:
54
+ fingerprint: str
55
+ ref: RepositorySnapshotRef
56
+ packages: list[PackageIdentity]
57
+ dependencies: list[PackageDependencyDecl]
58
+ contracts: list[ContractDefinition]
59
+ services: list[ServiceIdentity]
60
+
61
+
62
+ class FederatedWorkspaceOrchestrator:
63
+ """Coordinates bounded, incremental multi-repository analysis across workspace members."""
64
+
65
+ def __init__(self, *, max_cached_repos: int = 128) -> None:
66
+ self._lock = threading.Lock()
67
+ self._repo_cache: dict[str, _RepoFederationArtifact] = {}
68
+ self._max_cached_repos = max_cached_repos
69
+
70
+ def clear_cache(self) -> None:
71
+ with self._lock:
72
+ self._repo_cache.clear()
73
+
74
+ @staticmethod
75
+ def _compute_repo_content_fingerprint(repo_path: Path, commit_sha: str | None, is_dirty: bool) -> str:
76
+ """Computes a fast deterministic fingerprint over mtimes/sizes of source & manifest files."""
77
+ h = hashlib.sha256()
78
+ h.update(f"{commit_sha or 'nogit'}|{int(is_dirty)}|".encode())
79
+ count = 0
80
+ for p in sorted(repo_path.rglob("*")):
81
+ if count >= 600:
82
+ break
83
+ if not p.is_file():
84
+ continue
85
+ if any(part in (".git", "node_modules", ".venv", "venv", "dist", "__pycache__") for part in p.parts):
86
+ continue
87
+ try:
88
+ st = p.stat()
89
+ rel = p.relative_to(repo_path).as_posix()
90
+ h.update(f"{rel}:{st.st_size}:{st.st_mtime_ns}|".encode())
91
+ count += 1
92
+ except OSError:
93
+ continue
94
+ return h.hexdigest()[:16]
95
+
96
+ def _analyze_member(
97
+ self,
98
+ entry: WorkspaceRepositoryEntry,
99
+ manifest_dir: Path,
100
+ *,
101
+ authorized_roots: list[Path] | None,
102
+ use_incremental_cache: bool,
103
+ cancel_event: threading.Event | None,
104
+ ) -> _RepoFederationArtifact:
105
+ t0 = time.perf_counter()
106
+ if cancel_event and cancel_event.is_set():
107
+ return _RepoFederationArtifact(
108
+ fingerprint="cancelled",
109
+ ref=RepositorySnapshotRef(
110
+ repository_id=f"cancelled_{entry.alias}",
111
+ alias=entry.alias,
112
+ display_name=entry.alias,
113
+ canonical_path=entry.path,
114
+ status=RepositoryMembershipStatus.FAILED,
115
+ error_message="Workspace analysis cancelled before repository start.",
116
+ ),
117
+ packages=[],
118
+ dependencies=[],
119
+ contracts=[],
120
+ services=[],
121
+ )
122
+
123
+ try:
124
+ resolved = resolve_member_path(entry.path, manifest_dir, authorized_roots=authorized_roots)
125
+ except Exception as exc:
126
+ return _RepoFederationArtifact(
127
+ fingerprint="unauthorized",
128
+ ref=RepositorySnapshotRef(
129
+ repository_id=f"unauth_{entry.alias}",
130
+ alias=entry.alias,
131
+ display_name=entry.alias,
132
+ canonical_path=entry.path,
133
+ status=RepositoryMembershipStatus.INACCESSIBLE,
134
+ error_message=str(exc),
135
+ ),
136
+ packages=[],
137
+ dependencies=[],
138
+ contracts=[],
139
+ services=[],
140
+ )
141
+
142
+ if not resolved.exists() or not resolved.is_dir():
143
+ return _RepoFederationArtifact(
144
+ fingerprint="missing",
145
+ ref=RepositorySnapshotRef(
146
+ repository_id=compute_canonical_repository_id(resolved),
147
+ alias=entry.alias,
148
+ display_name=resolved.name or entry.alias,
149
+ canonical_path=str(resolved),
150
+ status=RepositoryMembershipStatus.MISSING,
151
+ error_message=f"Repository directory does not exist: '{resolved}'.",
152
+ ),
153
+ packages=[],
154
+ dependencies=[],
155
+ contracts=[],
156
+ services=[],
157
+ )
158
+
159
+ repo_id = compute_canonical_repository_id(resolved)
160
+ commit_sha, remote_url, is_dirty, is_worktree = detect_git_metadata(resolved)
161
+ fp = self._compute_repo_content_fingerprint(resolved, commit_sha, is_dirty)
162
+ cache_key = f"{repo_id}|{entry.alias}|{','.join(entry.contracts)}|{fp}"
163
+
164
+ if use_incremental_cache:
165
+ with self._lock:
166
+ cached = self._repo_cache.get(cache_key)
167
+ if cached is not None:
168
+ reused_ref = cached.ref.model_copy(
169
+ update={
170
+ "reused_from_cache": True,
171
+ "duration_ms": round((time.perf_counter() - t0) * 1000.0, 2),
172
+ }
173
+ )
174
+ return _RepoFederationArtifact(
175
+ fingerprint=cached.fingerprint,
176
+ ref=reused_ref,
177
+ packages=list(cached.packages),
178
+ dependencies=list(cached.dependencies),
179
+ contracts=list(cached.contracts),
180
+ services=list(cached.services),
181
+ )
182
+
183
+ try:
184
+ analysis = run_repository_analysis(
185
+ ScanRequest(source_type=SourceType.LOCAL, target=str(resolved))
186
+ )
187
+ pkgs, deps = extract_repository_packages(
188
+ resolved, repository_id=repo_id, repository_alias=entry.alias
189
+ )
190
+ contracts = discover_repository_contracts(
191
+ resolved,
192
+ repository_id=repo_id,
193
+ repository_alias=entry.alias,
194
+ explicit_paths=entry.contracts,
195
+ )
196
+ services = discover_repository_services(
197
+ resolved,
198
+ repository_id=repo_id,
199
+ repository_alias=entry.alias,
200
+ contracts=contracts,
201
+ )
202
+ langs = sorted({ls.language for ls in analysis.languages})
203
+ from repodna.workspace.identity import compute_repo_snapshot_id
204
+
205
+ snap_id = compute_repo_snapshot_id(resolved, commit_sha, is_dirty)
206
+ ref = RepositorySnapshotRef(
207
+ repository_id=repo_id,
208
+ alias=entry.alias,
209
+ display_name=analysis.repo_name,
210
+ canonical_path=str(resolved),
211
+ status=RepositoryMembershipStatus.AVAILABLE,
212
+ snapshot_id=snap_id,
213
+ commit_sha=commit_sha,
214
+ is_dirty=is_dirty,
215
+ is_worktree=is_worktree,
216
+ remote_url=remote_url,
217
+ languages=langs,
218
+ total_files=analysis.total_files,
219
+ health_score=analysis.health_report.overall_score,
220
+ health_grade=analysis.health_report.grade,
221
+ reused_from_cache=False,
222
+ duration_ms=round((time.perf_counter() - t0) * 1000.0, 2),
223
+ )
224
+ artifact = _RepoFederationArtifact(
225
+ fingerprint=fp,
226
+ ref=ref,
227
+ packages=pkgs,
228
+ dependencies=deps,
229
+ contracts=contracts,
230
+ services=services,
231
+ )
232
+ if use_incremental_cache:
233
+ with self._lock:
234
+ if len(self._repo_cache) >= self._max_cached_repos:
235
+ oldest = next(iter(self._repo_cache))
236
+ del self._repo_cache[oldest]
237
+ self._repo_cache[cache_key] = artifact
238
+ return artifact
239
+ except Exception as exc:
240
+ return _RepoFederationArtifact(
241
+ fingerprint=fp,
242
+ ref=RepositorySnapshotRef(
243
+ repository_id=repo_id,
244
+ alias=entry.alias,
245
+ display_name=resolved.name or entry.alias,
246
+ canonical_path=str(resolved),
247
+ status=RepositoryMembershipStatus.FAILED,
248
+ commit_sha=commit_sha,
249
+ is_dirty=is_dirty,
250
+ is_worktree=is_worktree,
251
+ remote_url=remote_url,
252
+ error_message=str(exc),
253
+ duration_ms=round((time.perf_counter() - t0) * 1000.0, 2),
254
+ ),
255
+ packages=[],
256
+ dependencies=[],
257
+ contracts=[],
258
+ services=[],
259
+ )
260
+
261
+ def analyze_workspace(
262
+ self,
263
+ manifest: WorkspaceManifest,
264
+ *,
265
+ authorized_roots: list[Path] | None = None,
266
+ use_incremental_cache: bool = True,
267
+ cancel_event: threading.Event | None = None,
268
+ ) -> WorkspaceAnalysisResult:
269
+ """Executes federated multi-repository analysis with bounded concurrency."""
270
+ t0 = time.perf_counter()
271
+ manifest_dir = Path(manifest.manifest_dir) if manifest.manifest_dir else Path.cwd()
272
+ max_workers = min(
273
+ max(manifest.limits.max_concurrent_repos, 1),
274
+ MAX_CONCURRENT_REPOS,
275
+ max(len(manifest.repositories), 1),
276
+ )
277
+
278
+ artifacts: list[_RepoFederationArtifact] = []
279
+ if max_workers == 1 or len(manifest.repositories) <= 1:
280
+ for entry in manifest.repositories:
281
+ artifacts.append(
282
+ self._analyze_member(
283
+ entry,
284
+ manifest_dir,
285
+ authorized_roots=authorized_roots,
286
+ use_incremental_cache=use_incremental_cache,
287
+ cancel_event=cancel_event,
288
+ )
289
+ )
290
+ else:
291
+ with ThreadPoolExecutor(max_workers=max_workers) as pool:
292
+ futs = [
293
+ pool.submit(
294
+ self._analyze_member,
295
+ entry,
296
+ manifest_dir,
297
+ authorized_roots=authorized_roots,
298
+ use_incremental_cache=use_incremental_cache,
299
+ cancel_event=cancel_event,
300
+ )
301
+ for entry in manifest.repositories
302
+ ]
303
+ for fut in as_completed(futs):
304
+ artifacts.append(fut.result())
305
+
306
+ artifacts.sort(key=lambda a: (a.ref.alias, a.ref.repository_id))
307
+
308
+ # Re-check Git HEAD / dirty state before snapshot publication to detect concurrent drift
309
+ post_drift = False
310
+ for art in artifacts:
311
+ if art.ref.status == RepositoryMembershipStatus.AVAILABLE:
312
+ c_sha, _, dirty_now, _ = detect_git_metadata(Path(art.ref.canonical_path))
313
+ if c_sha != art.ref.commit_sha or dirty_now != art.ref.is_dirty:
314
+ post_drift = True
315
+
316
+ repo_refs = [a.ref for a in artifacts]
317
+ all_packages = [p for a in artifacts for p in a.packages]
318
+ all_deps = [d for a in artifacts for d in a.dependencies]
319
+ all_contracts = [c for a in artifacts for c in a.contracts]
320
+ all_services = [s for a in artifacts for s in a.services]
321
+
322
+ policy_fp = compute_policies_fingerprint(manifest)
323
+ snapshot = build_workspace_snapshot(
324
+ workspace_id=manifest.workspace_id,
325
+ manifest_fingerprint=manifest.manifest_fingerprint,
326
+ policy_fingerprint=policy_fp,
327
+ repo_refs=repo_refs,
328
+ post_check_dirty_drift=post_drift,
329
+ )
330
+
331
+ version_findings = evaluate_version_constraints(all_packages, all_deps)
332
+ edges = resolve_cross_repository_edges(
333
+ manifest=manifest,
334
+ repo_refs=repo_refs,
335
+ packages=all_packages,
336
+ package_deps=all_deps,
337
+ services=all_services,
338
+ contracts=all_contracts,
339
+ snapshot_vector_id=snapshot.workspace_snapshot_id,
340
+ )
341
+ topology = build_workspace_topology(
342
+ workspace_id=manifest.workspace_id,
343
+ repo_refs=repo_refs,
344
+ services=all_services,
345
+ contracts=all_contracts,
346
+ edges=edges,
347
+ )
348
+ policy_report = evaluate_workspace_policies(
349
+ manifest=manifest,
350
+ snapshot=snapshot,
351
+ topology=topology,
352
+ )
353
+
354
+ reused = sum(1 for r in repo_refs if r.reused_from_cache)
355
+ recomputed = sum(
356
+ 1 for r in repo_refs if r.status == RepositoryMembershipStatus.AVAILABLE and not r.reused_from_cache
357
+ )
358
+
359
+ limitations = [
360
+ "Static federated analysis only; target repository code and services were never executed.",
361
+ snapshot.consistency_note,
362
+ ]
363
+ if snapshot.missing_or_failed_count > 0:
364
+ limitations.append(
365
+ f"{snapshot.missing_or_failed_count} repository member(s) could not be analyzed; cross-repository edges may be incomplete."
366
+ )
367
+
368
+ return WorkspaceAnalysisResult(
369
+ workspace_id=manifest.workspace_id,
370
+ workspace_name=manifest.name,
371
+ snapshot=snapshot,
372
+ packages=all_packages,
373
+ package_dependencies=all_deps,
374
+ version_findings=version_findings,
375
+ services=all_services,
376
+ contracts=all_contracts,
377
+ topology=topology,
378
+ policy_report=policy_report,
379
+ duration_ms=round((time.perf_counter() - t0) * 1000.0, 2),
380
+ reused_repositories=reused,
381
+ recomputed_repositories=recomputed,
382
+ limitations=limitations,
383
+ )
384
+
385
+ def analyze_manifest_file(
386
+ self,
387
+ manifest_path: Path | str,
388
+ *,
389
+ authorized_roots: list[Path] | None = None,
390
+ require_authorized_roots: bool = False,
391
+ use_incremental_cache: bool = True,
392
+ cancel_event: threading.Event | None = None,
393
+ ) -> WorkspaceAnalysisResult:
394
+ manifest = load_and_validate_workspace_manifest(
395
+ manifest_path,
396
+ authorized_roots=authorized_roots,
397
+ require_authorized_roots=require_authorized_roots,
398
+ )
399
+ return self.analyze_workspace(
400
+ manifest,
401
+ authorized_roots=authorized_roots,
402
+ use_incremental_cache=use_incremental_cache,
403
+ cancel_event=cancel_event,
404
+ )
405
+
406
+
407
+ _GLOBAL_ORCHESTRATOR = FederatedWorkspaceOrchestrator()
408
+
409
+
410
+ def get_workspace_orchestrator() -> FederatedWorkspaceOrchestrator:
411
+ return _GLOBAL_ORCHESTRATOR
@@ -0,0 +1,202 @@
1
+ """Canonical repository identity and composite workspace snapshot vector helpers.
2
+
3
+ Guarantees:
4
+ - Repository ID is derived from canonical realpath (never directory basename or remote URL alone).
5
+ - Two sibling checkouts, forks, or Git worktrees of the same remote receive distinct repository IDs.
6
+ - Remote URLs have embedded userinfo/credentials stripped before storage.
7
+ - WorkspaceSnapshot explicitly models non-atomic vector consistency across repositories.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import hashlib
13
+ import os
14
+ import re
15
+ import subprocess
16
+ from pathlib import Path
17
+
18
+ from repodna.workspace.models import (
19
+ RepositoryMembershipStatus,
20
+ RepositorySnapshotRef,
21
+ WorkspaceConsistencyStatus,
22
+ WorkspaceSnapshot,
23
+ )
24
+
25
+ _URL_CREDS_RE = re.compile(r"(https?://)([^/@\s]+)@", re.IGNORECASE)
26
+
27
+
28
+ def normalize_canonical_path(path: Path | str) -> str:
29
+ """Resolves symlinks/junctions to a canonical path string (case-normalized on Windows)."""
30
+ resolved = os.path.realpath(str(path))
31
+ if os.name == "nt":
32
+ resolved = os.path.normcase(resolved)
33
+ return resolved
34
+
35
+
36
+ def compute_canonical_repository_id(repo_path: Path | str) -> str:
37
+ """Computes a stable, collision-resistant repository_id from canonical realpath."""
38
+ canon = normalize_canonical_path(repo_path)
39
+ digest = hashlib.sha256(canon.encode("utf-8")).hexdigest()[:16]
40
+ return f"repo_{digest}"
41
+
42
+
43
+ def sanitize_remote_url(raw_url: str | None) -> str | None:
44
+ """Strips embedded credentials from Git remote URLs."""
45
+ if not raw_url:
46
+ return None
47
+ cleaned = raw_url.strip()
48
+ if not cleaned:
49
+ return None
50
+ return _URL_CREDS_RE.sub(r"\1[REDACTED]@", cleaned)
51
+
52
+
53
+ def detect_git_metadata(repo_path: Path) -> tuple[str | None, str | None, bool, bool]:
54
+ """Reads read-only Git metadata (commit_sha, sanitized_remote, is_dirty, is_worktree).
55
+
56
+ Never runs hooks, fetches remotes, or executes repository code.
57
+ """
58
+ if not repo_path.exists() or not repo_path.is_dir():
59
+ return None, None, False, False
60
+
61
+ def _run_git(args: list[str]) -> str | None:
62
+ try:
63
+ proc = subprocess.run(
64
+ ["git", "-C", str(repo_path), *args],
65
+ capture_output=True,
66
+ text=True,
67
+ timeout=5,
68
+ check=False,
69
+ )
70
+ if proc.returncode == 0:
71
+ return proc.stdout.strip()
72
+ except Exception:
73
+ return None
74
+ return None
75
+
76
+ commit_sha = _run_git(["rev-parse", "HEAD"])
77
+ if not commit_sha:
78
+ return None, None, False, False
79
+
80
+ remote_raw = _run_git(["config", "--get", "remote.origin.url"])
81
+ remote_url = sanitize_remote_url(remote_raw)
82
+ status_out = _run_git(["status", "--porcelain"])
83
+ is_dirty = bool(status_out)
84
+
85
+ git_dir = _run_git(["rev-parse", "--git-dir"])
86
+ common_dir = _run_git(["rev-parse", "--git-common-dir"])
87
+ is_worktree = bool(
88
+ git_dir and common_dir and normalize_canonical_path(repo_path / git_dir) != normalize_canonical_path(repo_path / common_dir)
89
+ )
90
+ return commit_sha, remote_url, is_dirty, is_worktree
91
+
92
+
93
+ def build_workspace_snapshot(
94
+ *,
95
+ workspace_id: str,
96
+ manifest_fingerprint: str,
97
+ policy_fingerprint: str,
98
+ repo_refs: list[RepositorySnapshotRef],
99
+ post_check_dirty_drift: bool = False,
100
+ ) -> WorkspaceSnapshot:
101
+ """Builds a composite WorkspaceSnapshot vector with honest consistency classification."""
102
+ ordered = sorted(repo_refs, key=lambda r: (r.alias, r.repository_id))
103
+ parts = [
104
+ workspace_id,
105
+ manifest_fingerprint,
106
+ policy_fingerprint,
107
+ *(
108
+ f"{r.repository_id}:{r.status.value}:{r.snapshot_id or 'none'}:{r.commit_sha or 'nogit'}:{int(r.is_dirty)}"
109
+ for r in ordered
110
+ ),
111
+ ]
112
+ vec_hash = hashlib.sha256("|".join(parts).encode("utf-8")).hexdigest()[:16]
113
+ ws_snap_id = f"wsnap_{vec_hash}"
114
+
115
+ available = sum(1 for r in ordered if r.status == RepositoryMembershipStatus.AVAILABLE)
116
+ missing_or_failed = len(ordered) - available
117
+
118
+ if not ordered:
119
+ status = WorkspaceConsistencyStatus.UNKNOWN
120
+ note = "Workspace contains no repositories."
121
+ elif missing_or_failed > 0:
122
+ status = WorkspaceConsistencyStatus.INCOMPLETE
123
+ note = (
124
+ f"{missing_or_failed} of {len(ordered)} repository members are missing, inaccessible, or failed; "
125
+ "workspace results are incomplete."
126
+ )
127
+ elif post_check_dirty_drift:
128
+ status = WorkspaceConsistencyStatus.CHANGES_PENDING
129
+ note = "One or more repositories changed while federated analysis was in flight; re-analysis recommended."
130
+ elif any(r.is_dirty for r in ordered):
131
+ status = WorkspaceConsistencyStatus.PARTIALLY_VERIFIED
132
+ note = (
133
+ "All repositories analyzed; one or more have uncommitted working-tree changes "
134
+ "(composite snapshot vector, not globally atomic)."
135
+ )
136
+ else:
137
+ status = WorkspaceConsistencyStatus.VERIFIED_VECTOR
138
+ note = (
139
+ "All repository snapshots verified against current Git HEADs "
140
+ "(composite snapshot vector across independent repositories)."
141
+ )
142
+
143
+ return WorkspaceSnapshot(
144
+ workspace_id=workspace_id,
145
+ workspace_snapshot_id=ws_snap_id,
146
+ manifest_fingerprint=manifest_fingerprint,
147
+ policy_fingerprint=policy_fingerprint,
148
+ consistency_status=status,
149
+ consistency_note=note,
150
+ repositories=ordered,
151
+ available_count=available,
152
+ missing_or_failed_count=missing_or_failed,
153
+ )
154
+
155
+
156
+ def compute_repo_snapshot_id(repo_path: Path, commit_sha: str | None, is_dirty: bool) -> str:
157
+ """Computes a content-verified snapshot ID for dirty Git or non-Git repositories (COR-02)."""
158
+ hasher = hashlib.sha256()
159
+ hasher.update(f"{commit_sha or 'nogit'}|{int(is_dirty)}|".encode())
160
+ ignored = {".git", "node_modules", ".venv", "venv", "dist", "build", "__pycache__"}
161
+ files_hashed = 0
162
+ for root, dirs, files in os.walk(repo_path):
163
+ dirs[:] = sorted(d for d in dirs if d not in ignored and (not d.startswith(".") or d == ".repodna"))
164
+ for fname in sorted(files):
165
+ fpath = Path(root) / fname
166
+ if fpath.is_symlink():
167
+ continue
168
+ try:
169
+ st = fpath.stat()
170
+ if st.st_size > 2 * 1024 * 1024:
171
+ continue
172
+ rel = fpath.relative_to(repo_path).as_posix()
173
+ digest = hashlib.blake2b(fpath.read_bytes(), digest_size=12).hexdigest()
174
+ hasher.update(f"{rel}:{digest}\n".encode())
175
+ files_hashed += 1
176
+ if files_hashed >= 2000:
177
+ break
178
+ except OSError:
179
+ continue
180
+ if files_hashed >= 2000:
181
+ break
182
+ prefix = f"git:{commit_sha[:12]}+dirty:" if (commit_sha and is_dirty) else ("dir:" if commit_sha is None else f"git:{commit_sha[:12]}:")
183
+ return f"{prefix}{hasher.hexdigest()[:16]}"
184
+
185
+
186
+ def check_workspace_freshness(snapshot: WorkspaceSnapshot) -> WorkspaceConsistencyStatus:
187
+ """Re-checks repository HEAD, dirty state, and content identity to detect stale workspace snapshots."""
188
+ if snapshot.missing_or_failed_count > 0:
189
+ return WorkspaceConsistencyStatus.INCOMPLETE
190
+ for ref in snapshot.repositories:
191
+ p = Path(ref.canonical_path)
192
+ if not p.exists() or not p.is_dir():
193
+ return WorkspaceConsistencyStatus.INCOMPLETE
194
+ commit_sha, _, is_dirty, _ = detect_git_metadata(p)
195
+ if commit_sha != ref.commit_sha or is_dirty != ref.is_dirty:
196
+ return WorkspaceConsistencyStatus.STALE
197
+ # For dirty Git repos or non-Git repos, also verify actual file content digest (COR-02)
198
+ if is_dirty or commit_sha is None:
199
+ current_snap_id = compute_repo_snapshot_id(p, commit_sha, is_dirty)
200
+ if ref.snapshot_id and ref.snapshot_id.startswith(("dir:", "git:")) and current_snap_id != ref.snapshot_id:
201
+ return WorkspaceConsistencyStatus.STALE
202
+ return snapshot.consistency_status