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,570 @@
1
+ """Read-only Repository Intelligence Service for AI Agents and Workstations."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from collections import defaultdict, deque
7
+ from pathlib import PurePosixPath
8
+
9
+ from repodna.intelligence.models import (
10
+ AnalysisCoverageReport,
11
+ ArchitectureFindingsResponse,
12
+ ArchitectureMap,
13
+ ChangeImpactResponse,
14
+ DependencyQueryResponse,
15
+ DependencyTraceItem,
16
+ ModuleDetails,
17
+ PackageCluster,
18
+ RelevantModuleMatch,
19
+ RelevantModulesResponse,
20
+ RepositoryOverview,
21
+ )
22
+ from repodna.schemas.models import (
23
+ AnalysisResult,
24
+ FileNode,
25
+ LanguageSupportLevel,
26
+ RuleFinding,
27
+ SeverityLevel,
28
+ )
29
+
30
+
31
+ class RepositoryIntelligenceService:
32
+ """Provides high-precision architectural queries over immutable AnalysisResults."""
33
+
34
+ def __init__(self, analysis: AnalysisResult) -> None:
35
+ self.analysis = analysis
36
+ self._files_by_id: dict[str, FileNode] = {f.id: f for f in analysis.files}
37
+ self._edges_by_source: dict[str, list] = defaultdict(list)
38
+ self._edges_by_target: dict[str, list] = defaultdict(list)
39
+ for edge in analysis.edges:
40
+ self._edges_by_source[edge.source].append(edge)
41
+ self._edges_by_target[edge.target].append(edge)
42
+
43
+ self._findings_by_file: dict[str, list[RuleFinding]] = defaultdict(list)
44
+ for finding in analysis.health_report.findings:
45
+ for aff in finding.affected_files:
46
+ self._findings_by_file[aff].append(finding)
47
+
48
+ def get_repository_overview(self) -> RepositoryOverview:
49
+ """Returns executive architectural scorecard, health status, and key hubs."""
50
+ res = self.analysis
51
+ hr = res.health_report
52
+ gm = res.graph_metrics
53
+ tr = res.transparency
54
+
55
+ hubs = [f.id for f in res.files if f.is_hub]
56
+ if not hubs:
57
+ hubs = [f.id for f in sorted(res.files, key=lambda f: -f.fan_in) if f.fan_in > 0]
58
+ primary_langs = [lg.language for lg in res.languages[:5]]
59
+
60
+ score_desc = (
61
+ f"{hr.overall_score:.1f}/100 (Grade {hr.grade})"
62
+ if hr.overall_score is not None
63
+ else f"N/A ({hr.status})"
64
+ )
65
+
66
+ summary_lines = [
67
+ f"Repository: {res.repo_name} ({res.target_display})",
68
+ f"Health Score: {score_desc} | Confidence: {hr.confidence.upper()}",
69
+ f"AST Coverage: {tr.ast_loc_coverage_pct:.1f}% LOC ({tr.ast_file_coverage_pct:.1f}% files)",
70
+ f"Scale: {res.total_files:,} files, {res.total_lines_code:,} LOC across {', '.join(primary_langs) or 'unspecified'}.",
71
+ f"Architecture: {gm.total_nodes} nodes, {gm.total_edges} internal dependencies, {gm.cycle_count} cycles ({gm.scc_count} cyclic SCCs).",
72
+ ]
73
+ if hubs:
74
+ summary_lines.append(f"Primary Architectural Hubs ({len(hubs)}): {', '.join(hubs[:5])}")
75
+ if hr.unverified_rules:
76
+ summary_lines.append(
77
+ f"Unverified Rules ({len(hr.unverified_rules)} due to limited AST coverage): {', '.join(hr.unverified_rules)}"
78
+ )
79
+
80
+ return RepositoryOverview(
81
+ repo_name=res.repo_name,
82
+ target_display=res.target_display,
83
+ analyzed_at=res.analyzed_at,
84
+ analysis_version="0.3.0",
85
+ total_files=res.total_files,
86
+ total_lines_code=res.total_lines_code,
87
+ total_size_bytes=res.total_size_bytes,
88
+ health_score=hr.overall_score,
89
+ health_grade=hr.grade,
90
+ health_status=hr.status,
91
+ confidence=hr.confidence,
92
+ ast_loc_coverage_pct=tr.ast_loc_coverage_pct,
93
+ ast_file_coverage_pct=tr.ast_file_coverage_pct,
94
+ cycle_count=gm.cycle_count,
95
+ cyclic_scc_count=gm.scc_count,
96
+ hub_modules_count=len(hubs),
97
+ primary_languages=primary_langs,
98
+ unverified_rules=hr.unverified_rules,
99
+ key_architectural_hubs=hubs[:10],
100
+ summary_text="\n".join(summary_lines),
101
+ )
102
+
103
+ def get_architecture_map(
104
+ self, level: str = "clusters", limit: int = 50
105
+ ) -> ArchitectureMap:
106
+ """Computes hierarchical package clusters and inter-cluster dependency links."""
107
+ res = self.analysis
108
+ clusters_dict: dict[str, list[str]] = defaultdict(list)
109
+
110
+ for f in res.files:
111
+ posix_path = PurePosixPath(f.id)
112
+ parts = posix_path.parts
113
+ if len(parts) > 1:
114
+ cluster_name = "/".join(parts[:2]) if len(parts) > 2 else parts[0]
115
+ else:
116
+ cluster_name = "(root)"
117
+ clusters_dict[cluster_name].append(f.id)
118
+
119
+ clusters: list[PackageCluster] = []
120
+ for cname, files in sorted(clusters_dict.items(), key=lambda x: -len(x[1])):
121
+ external_pkgs = set()
122
+ for fid in files:
123
+ node = self._files_by_id.get(fid)
124
+ if node:
125
+ external_pkgs.update(node.imports_external)
126
+ clusters.append(
127
+ PackageCluster(
128
+ name=cname,
129
+ file_count=len(files),
130
+ files=sorted(files)[:limit] if level == "overview" else sorted(files),
131
+ external_dependencies=sorted(external_pkgs)[:10],
132
+ )
133
+ )
134
+
135
+ # Inter-cluster edges
136
+ cluster_by_file = {}
137
+ for c in clusters:
138
+ for fid in c.files:
139
+ cluster_by_file[fid] = c.name
140
+
141
+ inter_edges_counts: dict[tuple[str, str], int] = defaultdict(int)
142
+ for edge in res.edges:
143
+ src_cluster = cluster_by_file.get(edge.source)
144
+ tgt_cluster = cluster_by_file.get(edge.target)
145
+ if src_cluster and tgt_cluster and src_cluster != tgt_cluster:
146
+ inter_edges_counts[(src_cluster, tgt_cluster)] += 1
147
+
148
+ inter_edges = [
149
+ {"source_cluster": src, "target_cluster": tgt, "edge_count": count}
150
+ for (src, tgt), count in sorted(inter_edges_counts.items(), key=lambda x: -x[1])[:30]
151
+ ]
152
+
153
+ summary_lines = [
154
+ f"Architecture Map ({level}) — {len(clusters)} package clusters across {res.total_files} files.",
155
+ f"Top clusters: {', '.join(f'{c.name} ({c.file_count})' for c in clusters[:6])}",
156
+ ]
157
+
158
+ return ArchitectureMap(
159
+ level=level,
160
+ total_modules=res.total_files,
161
+ total_clusters=len(clusters),
162
+ clusters=clusters[:limit] if level == "overview" else clusters,
163
+ inter_cluster_edges=inter_edges,
164
+ summary_text="\n".join(summary_lines),
165
+ )
166
+
167
+ def find_relevant_modules(
168
+ self, query: str, limit: int = 10
169
+ ) -> RelevantModulesResponse:
170
+ """Finds modules relevant to a query based on file path, symbols, language, and hub status."""
171
+ query_terms = [t.lower() for t in re.split(r"[\s/\\._-]+", query) if len(t) >= 2]
172
+ if not query_terms:
173
+ query_terms = [query.lower()]
174
+
175
+ scored_matches: list[RelevantModuleMatch] = []
176
+
177
+ for f in self.analysis.files:
178
+ file_id_lower = f.id.lower()
179
+ name_lower = f.name.lower()
180
+ reasons = []
181
+ score = 0.0
182
+
183
+ # Exact path or name match
184
+ if query.lower() == name_lower:
185
+ score += 8.0
186
+ reasons.append(f"Exact filename match on '{query}'")
187
+ elif query.lower() in file_id_lower or query.lower() in name_lower:
188
+ score += 5.0
189
+ reasons.append(f"Path substring match on '{query}'")
190
+
191
+ # Term matches
192
+ term_matches = sum(1 for t in query_terms if t in file_id_lower)
193
+ if term_matches > 0:
194
+ score += term_matches * 2.0
195
+ reasons.append(f"{term_matches} term(s) matched in path")
196
+
197
+ # Symbol match (function, class, interface, struct)
198
+ matching_symbols = []
199
+ for sym in f.symbols:
200
+ sym_lower = sym.name.lower()
201
+ if any(t in sym_lower for t in query_terms):
202
+ matching_symbols.append(sym)
203
+ score += 3.5
204
+
205
+ if matching_symbols:
206
+ reasons.append(
207
+ f"Matched {len(matching_symbols)} symbol(s): {', '.join(s.name for s in matching_symbols[:3])}"
208
+ )
209
+
210
+ # Architectural hub boost
211
+ if f.is_hub and score > 0:
212
+ score += 1.5
213
+ reasons.append("Hub module boost (high afferent coupling)")
214
+
215
+ # In cycle note
216
+ if f.in_cycle and score > 0:
217
+ reasons.append("Participates in circular dependency")
218
+
219
+ if score > 0:
220
+ scored_matches.append(
221
+ RelevantModuleMatch(
222
+ file_id=f.id,
223
+ language=f.language,
224
+ support_level=f.support_level,
225
+ relevance_score=round(score, 2),
226
+ match_reasons=reasons,
227
+ matching_symbols=matching_symbols[:5],
228
+ fan_in=f.fan_in,
229
+ fan_out=f.fan_out,
230
+ in_cycle=f.in_cycle,
231
+ is_hub=f.is_hub,
232
+ )
233
+ )
234
+
235
+ scored_matches.sort(key=lambda m: (-m.relevance_score, -m.fan_in, m.file_id))
236
+ top_matches = scored_matches[:limit]
237
+
238
+ if top_matches:
239
+ summary = (
240
+ f"Found {len(scored_matches)} relevant module(s) for query '{query}'. "
241
+ f"Top match: {top_matches[0].file_id} (score {top_matches[0].relevance_score})."
242
+ )
243
+ else:
244
+ summary = f"No modules matched query '{query}'. Try searching by directory name, symbol name, or package."
245
+
246
+ return RelevantModulesResponse(
247
+ query=query,
248
+ total_matches=len(scored_matches),
249
+ matches=top_matches,
250
+ summary_text=summary,
251
+ )
252
+
253
+ def get_module_details(self, file_path: str) -> ModuleDetails:
254
+ """Returns deep architectural forensics and health findings for a specific file."""
255
+ norm_path = file_path.replace("\\", "/").lstrip("/")
256
+ node = self._files_by_id.get(norm_path)
257
+ if not node:
258
+ # Try fuzzy suffix match
259
+ for fid, candidate in self._files_by_id.items():
260
+ if fid.endswith(norm_path) or norm_path.endswith(fid):
261
+ node = candidate
262
+ norm_path = fid
263
+ break
264
+
265
+ if not node:
266
+ raise KeyError(
267
+ f"Module '{file_path}' not found in analyzed repository. Available files: {len(self._files_by_id)}"
268
+ )
269
+
270
+ findings = self._findings_by_file.get(norm_path, [])
271
+ limitations: list[str] = []
272
+
273
+ if node.support_level == LanguageSupportLevel.PARTIAL_STATIC:
274
+ limitations.append(
275
+ f"Language '{node.language}' analyzed with partial static pattern scanner. Internal dependency graph is not evaluated for this file."
276
+ )
277
+ elif node.support_level == LanguageSupportLevel.UNSUPPORTED:
278
+ limitations.append(
279
+ f"Language '{node.language}' is unsupported for AST analysis. Only file size and LOC were captured."
280
+ )
281
+
282
+ if node.unresolved_imports:
283
+ limitations.append(
284
+ f"{len(node.unresolved_imports)} unresolved import(s) (e.g. external package or dynamic import)."
285
+ )
286
+
287
+ summary_lines = [
288
+ f"Module: {node.id} ({node.language}, {node.support_level.value})",
289
+ f"Metrics: {node.lines_code} LOC, Fan-In: {node.fan_in}, Fan-Out: {node.fan_out}, Instability: {node.instability:.2f}",
290
+ f"State: {'In Circular Dependency' if node.in_cycle else 'No Cycles'} | {'Hub Module' if node.is_hub else 'Regular Node'}",
291
+ f"Dependencies: {len(node.imports_internal)} internal, {len(node.imports_external)} external | Dependents: {len(node.imported_by)} internal",
292
+ ]
293
+ if findings:
294
+ summary_lines.append(f"Health Findings ({len(findings)}): {', '.join(f.rule_id for f in findings)}")
295
+
296
+ return ModuleDetails(
297
+ file_id=node.id,
298
+ name=node.name,
299
+ directory=node.directory,
300
+ language=node.language,
301
+ support_level=node.support_level,
302
+ size_bytes=node.size_bytes,
303
+ lines_total=node.lines_total,
304
+ lines_code=node.lines_code,
305
+ lines_comment=node.lines_comment,
306
+ fan_in=node.fan_in,
307
+ fan_out=node.fan_out,
308
+ instability=node.instability,
309
+ in_cycle=node.in_cycle,
310
+ cycle_ids=node.cycle_ids,
311
+ is_hub=node.is_hub,
312
+ is_orphan=node.is_orphan,
313
+ symbols=node.symbols,
314
+ dependencies_internal=node.imports_internal,
315
+ dependents_internal=node.imported_by,
316
+ external_packages=node.imports_external,
317
+ health_findings=findings,
318
+ secret_warnings=node.secret_warnings,
319
+ analysis_limitations=limitations,
320
+ summary_text="\n".join(summary_lines),
321
+ )
322
+
323
+ def get_dependencies(
324
+ self, file_path: str, direction: str = "outgoing", depth: int = 1
325
+ ) -> DependencyQueryResponse:
326
+ """Returns direct and transitive dependencies or reverse dependents."""
327
+ norm_path = file_path.replace("\\", "/").lstrip("/")
328
+ if norm_path not in self._files_by_id:
329
+ # Fuzzy match
330
+ for fid in self._files_by_id:
331
+ if fid.endswith(norm_path):
332
+ norm_path = fid
333
+ break
334
+
335
+ if norm_path not in self._files_by_id:
336
+ raise KeyError(f"Module '{file_path}' not found.")
337
+
338
+ visited_edges: list[DependencyTraceItem] = []
339
+ visited_nodes: set[str] = {norm_path}
340
+ queue: deque[tuple[str, int]] = deque([(norm_path, 0)])
341
+
342
+ while queue:
343
+ curr, curr_depth = queue.popleft()
344
+ if curr_depth >= depth:
345
+ continue
346
+
347
+ # Outgoing (imports made by curr)
348
+ if direction in ("outgoing", "both"):
349
+ for edge in self._edges_by_source.get(curr, []):
350
+ visited_edges.append(
351
+ DependencyTraceItem(
352
+ source=edge.source,
353
+ target=edge.target,
354
+ import_names=edge.import_names,
355
+ line=edge.line,
356
+ depth=curr_depth + 1,
357
+ in_cycle=edge.in_cycle,
358
+ )
359
+ )
360
+ if edge.target not in visited_nodes:
361
+ visited_nodes.add(edge.target)
362
+ queue.append((edge.target, curr_depth + 1))
363
+
364
+ # Incoming (modules importing curr)
365
+ if direction in ("incoming", "both"):
366
+ for edge in self._edges_by_target.get(curr, []):
367
+ visited_edges.append(
368
+ DependencyTraceItem(
369
+ source=edge.source,
370
+ target=edge.target,
371
+ import_names=edge.import_names,
372
+ line=edge.line,
373
+ depth=curr_depth + 1,
374
+ in_cycle=edge.in_cycle,
375
+ )
376
+ )
377
+ if edge.source not in visited_nodes:
378
+ visited_nodes.add(edge.source)
379
+ queue.append((edge.source, curr_depth + 1))
380
+
381
+ summary = (
382
+ f"Traced {len(visited_edges)} {direction} dependency link(s) for '{norm_path}' "
383
+ f"at depth {depth} across {len(visited_nodes)} module(s)."
384
+ )
385
+
386
+ return DependencyQueryResponse(
387
+ root_file=norm_path,
388
+ direction=direction,
389
+ depth=depth,
390
+ total_items=len(visited_edges),
391
+ items=visited_edges,
392
+ summary_text=summary,
393
+ )
394
+
395
+ def get_dependents(self, file_path: str, depth: int = 1) -> DependencyQueryResponse:
396
+ """Returns reverse dependencies (modules that import this file)."""
397
+ return self.get_dependencies(file_path, direction="incoming", depth=depth)
398
+
399
+ def get_architecture_findings(
400
+ self,
401
+ rule_id: str | None = None,
402
+ severity: str | None = None,
403
+ category: str | None = None,
404
+ ) -> ArchitectureFindingsResponse:
405
+ """Returns architectural health rule findings filtered by rule ID, severity, or category."""
406
+ all_findings = self.analysis.health_report.findings
407
+ filtered: list[RuleFinding] = []
408
+
409
+ for f in all_findings:
410
+ if rule_id and f.rule_id != rule_id:
411
+ continue
412
+ if severity and f.severity.value.lower() != severity.lower():
413
+ continue
414
+ if category and f.category != category:
415
+ continue
416
+ filtered.append(f)
417
+
418
+ crit = sum(1 for f in filtered if f.severity == SeverityLevel.CRITICAL)
419
+ warn = sum(1 for f in filtered if f.severity == SeverityLevel.WARNING)
420
+ inf = sum(1 for f in filtered if f.severity == SeverityLevel.INFO)
421
+
422
+ summary = (
423
+ f"Total Architectural Findings: {len(filtered)} "
424
+ f"({crit} critical, {warn} warnings, {inf} info). "
425
+ f"Unverified rules: {len(self.analysis.health_report.unverified_rules)}."
426
+ )
427
+
428
+ return ArchitectureFindingsResponse(
429
+ total_findings=len(filtered),
430
+ critical_count=crit,
431
+ warning_count=warn,
432
+ info_count=inf,
433
+ findings=filtered,
434
+ unverified_rules=self.analysis.health_report.unverified_rules,
435
+ summary_text=summary,
436
+ )
437
+
438
+ def get_analysis_coverage(self) -> AnalysisCoverageReport:
439
+ """Returns comprehensive AST coverage transparency and unsupported language disclosures."""
440
+ tr = self.analysis.transparency
441
+ hr = self.analysis.health_report
442
+
443
+ guarantee = (
444
+ "RepoDNA strictly bounds analysis to parseable AST structures. "
445
+ "Unsupported languages or files with insufficient dependency coverage are marked N/A "
446
+ "rather than generating speculative 100/100 passes."
447
+ )
448
+
449
+ summary_lines = [
450
+ f"Analysis Confidence: {hr.confidence.upper()} ({hr.confidence_reason or 'Full structural analysis'})",
451
+ f"AST LOC Coverage: {tr.ast_loc_coverage_pct:.1f}% ({tr.ast_file_coverage_pct:.1f}% of files)",
452
+ f"Supported Languages: {', '.join(tr.supported_languages_detected) or 'None'}",
453
+ ]
454
+ if tr.partial_static_languages_detected:
455
+ summary_lines.append(
456
+ f"Partial Static: {', '.join(tr.partial_static_languages_detected)} "
457
+ f"({tr.partial_static_files_count} files / {tr.partial_static_loc_coverage_pct:.1f}% LOC)"
458
+ )
459
+ if tr.unsupported_languages_detected:
460
+ summary_lines.append(
461
+ f"Unsupported: {', '.join(tr.unsupported_languages_detected)} "
462
+ f"({tr.unsupported_files_count} files / {tr.unsupported_loc_coverage_pct:.1f}% LOC)"
463
+ )
464
+ if hr.unverified_rules:
465
+ summary_lines.append(f"Unverified Rules: {', '.join(hr.unverified_rules)}")
466
+
467
+ return AnalysisCoverageReport(
468
+ confidence=hr.confidence,
469
+ confidence_reason=hr.confidence_reason,
470
+ ast_file_coverage_pct=tr.ast_file_coverage_pct,
471
+ ast_loc_coverage_pct=tr.ast_loc_coverage_pct,
472
+ supported_languages=tr.supported_languages_detected,
473
+ partial_static_languages=tr.partial_static_languages_detected,
474
+ partial_static_files_count=tr.partial_static_files_count,
475
+ unsupported_languages=tr.unsupported_languages_detected,
476
+ unsupported_files_count=tr.unsupported_files_count,
477
+ skipped_files_count=len(tr.skipped_files),
478
+ unverified_rules=hr.unverified_rules,
479
+ honest_coverage_guarantee=guarantee,
480
+ summary_text="\n".join(summary_lines),
481
+ )
482
+
483
+ def get_change_impact(
484
+ self, changed_files: list[str], max_depth: int = 2
485
+ ) -> ChangeImpactResponse:
486
+ """Evaluates architectural risk and blast radius of proposed file changes."""
487
+ normalized_targets = []
488
+ for cf in changed_files:
489
+ norm = cf.replace("\\", "/").lstrip("/")
490
+ if norm in self._files_by_id:
491
+ normalized_targets.append(norm)
492
+ else:
493
+ for fid in self._files_by_id:
494
+ if fid.endswith(norm):
495
+ normalized_targets.append(fid)
496
+ break
497
+
498
+ if not normalized_targets:
499
+ normalized_targets = [cf.replace("\\", "/").lstrip("/") for cf in changed_files]
500
+
501
+ direct_dependents: set[str] = set()
502
+ transitive_dependents: set[str] = set()
503
+ affected_hubs: set[str] = set()
504
+ impacted_cycles: set[str] = set()
505
+ risk_factors: list[str] = []
506
+
507
+ # Find direct dependents
508
+ for target in normalized_targets:
509
+ node = self._files_by_id.get(target)
510
+ if node:
511
+ if node.is_hub:
512
+ affected_hubs.add(target)
513
+ risk_factors.append(f"Target module '{target}' is an architectural hub (Fan-In: {node.fan_in}).")
514
+ if node.in_cycle:
515
+ impacted_cycles.update(node.cycle_ids)
516
+ risk_factors.append(f"Target module '{target}' is locked inside circular dependency cycle(s).")
517
+ for dep in node.imported_by:
518
+ direct_dependents.add(dep)
519
+
520
+ # Transitive dependents BFS
521
+ queue: deque[tuple[str, int]] = deque([(d, 1) for d in direct_dependents])
522
+ visited: set[str] = set(direct_dependents) | set(normalized_targets)
523
+
524
+ while queue:
525
+ curr, depth = queue.popleft()
526
+ if depth >= max_depth:
527
+ continue
528
+ curr_node = self._files_by_id.get(curr)
529
+ if curr_node:
530
+ if curr_node.is_hub:
531
+ affected_hubs.add(curr)
532
+ for next_dep in curr_node.imported_by:
533
+ if next_dep not in visited:
534
+ visited.add(next_dep)
535
+ transitive_dependents.add(next_dep)
536
+ queue.append((next_dep, depth + 1))
537
+
538
+ # Check cycles in all affected modules
539
+ for aff in direct_dependents | transitive_dependents:
540
+ node = self._files_by_id.get(aff)
541
+ if node and node.in_cycle:
542
+ impacted_cycles.update(node.cycle_ids)
543
+
544
+ # Determine severity
545
+ if affected_hubs or len(impacted_cycles) >= 2 or len(direct_dependents) > 10:
546
+ severity = SeverityLevel.CRITICAL
547
+ elif direct_dependents or impacted_cycles:
548
+ severity = SeverityLevel.WARNING
549
+ else:
550
+ severity = SeverityLevel.INFO
551
+
552
+ summary_lines = [
553
+ f"Change Impact Analysis: {len(normalized_targets)} target file(s) evaluated.",
554
+ f"Severity: {severity.value.upper()} | Direct Dependents: {len(direct_dependents)} | Transitive Dependents: {len(transitive_dependents)}",
555
+ ]
556
+ if affected_hubs:
557
+ summary_lines.append(f"Affected Architectural Hubs: {', '.join(affected_hubs)}")
558
+ if impacted_cycles:
559
+ summary_lines.append(f"Impacted Circular Cycles ({len(impacted_cycles)}): {', '.join(sorted(impacted_cycles))}")
560
+
561
+ return ChangeImpactResponse(
562
+ target_files=normalized_targets,
563
+ direct_dependents=sorted(direct_dependents),
564
+ transitive_dependents=sorted(transitive_dependents),
565
+ impacted_cycles=sorted(impacted_cycles),
566
+ impact_severity=severity,
567
+ risk_factors=risk_factors,
568
+ affected_hubs=sorted(affected_hubs),
569
+ summary_text="\n".join(summary_lines),
570
+ )
@@ -0,0 +1,94 @@
1
+ """RepoDNA Live Architecture Engine — continuous working-tree monitoring and streaming."""
2
+
3
+ from repodna.live.alerts import LiveAlertManager
4
+ from repodna.live.coordinator import EventCoordinator
5
+ from repodna.live.diff import LiveDiffEngine
6
+ from repodna.live.events import LiveEventBus, format_sse_event, format_sse_heartbeat
7
+ from repodna.live.filtering import LivePathFilter
8
+ from repodna.live.history import (
9
+ LiveHistoryStore,
10
+ LiveStatePersistence,
11
+ summarize_live_state_for_mcp,
12
+ )
13
+ from repodna.live.models import (
14
+ LIVE_EVENT_SCHEMA_VERSION,
15
+ LIVE_STATE_SCHEMA_VERSION,
16
+ AlertCategory,
17
+ AlertStatus,
18
+ CoalescedChangeBatch,
19
+ FilesystemEvent,
20
+ FreshnessLevel,
21
+ InvalidStateTransitionError,
22
+ LiveAlert,
23
+ LiveAlertsResponse,
24
+ LiveArchitectureDelta,
25
+ LiveEventEnvelope,
26
+ LiveEventType,
27
+ LiveHealthDiagnostics,
28
+ LiveHistoryEntry,
29
+ LiveResourceLimits,
30
+ LiveSessionCreateRequest,
31
+ LiveSessionInfo,
32
+ LiveSessionState,
33
+ LiveTimelineResponse,
34
+ NormalizedEventKind,
35
+ WatcherBackend,
36
+ validate_state_transition,
37
+ )
38
+ from repodna.live.observer import (
39
+ NativeWatchfilesObserver,
40
+ PollingFilesystemObserver,
41
+ ResilientObserver,
42
+ )
43
+ from repodna.live.reconciliation import ReconciliationEngine, ReconciliationResult
44
+ from repodna.live.session import (
45
+ LiveSession,
46
+ LiveSessionManager,
47
+ get_live_session_manager,
48
+ validate_live_workspace_root,
49
+ )
50
+
51
+ __all__ = [
52
+ "AlertCategory",
53
+ "AlertStatus",
54
+ "CoalescedChangeBatch",
55
+ "EventCoordinator",
56
+ "FilesystemEvent",
57
+ "FreshnessLevel",
58
+ "InvalidStateTransitionError",
59
+ "LIVE_EVENT_SCHEMA_VERSION",
60
+ "LIVE_STATE_SCHEMA_VERSION",
61
+ "LiveAlert",
62
+ "LiveAlertManager",
63
+ "LiveAlertsResponse",
64
+ "LiveArchitectureDelta",
65
+ "LiveDiffEngine",
66
+ "LiveEventBus",
67
+ "LiveEventEnvelope",
68
+ "LiveEventType",
69
+ "LiveHealthDiagnostics",
70
+ "LiveHistoryEntry",
71
+ "LiveHistoryStore",
72
+ "LivePathFilter",
73
+ "LiveResourceLimits",
74
+ "LiveSession",
75
+ "LiveSessionCreateRequest",
76
+ "LiveSessionInfo",
77
+ "LiveSessionManager",
78
+ "LiveSessionState",
79
+ "LiveStatePersistence",
80
+ "LiveTimelineResponse",
81
+ "NativeWatchfilesObserver",
82
+ "NormalizedEventKind",
83
+ "PollingFilesystemObserver",
84
+ "ReconciliationEngine",
85
+ "ReconciliationResult",
86
+ "ResilientObserver",
87
+ "WatcherBackend",
88
+ "format_sse_event",
89
+ "format_sse_heartbeat",
90
+ "get_live_session_manager",
91
+ "summarize_live_state_for_mcp",
92
+ "validate_live_workspace_root",
93
+ "validate_state_transition",
94
+ ]