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,562 @@
1
+ """Dependency graph engine: Tarjan SCC, integer-indexed Johnson cycle finder, fan-in/out & topology metrics."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import time
6
+ from collections import defaultdict, deque
7
+ from dataclasses import dataclass, field
8
+
9
+ from repodna.schemas.models import (
10
+ CycleGroup,
11
+ DependencyEdge,
12
+ FileNode,
13
+ GraphMetrics,
14
+ LanguageSupportLevel,
15
+ SeverityLevel,
16
+ )
17
+
18
+
19
+ @dataclass
20
+ class GraphIndex:
21
+ """Compact integer-indexed adjacency structure for fast SCC partitioning and traversal."""
22
+
23
+ nodes: list[str]
24
+ node_to_idx: dict[str, int]
25
+ adj_idx: list[list[int]]
26
+ rev_adj_idx: list[list[int]]
27
+ scc_by_node: dict[str, int] = field(default_factory=dict)
28
+
29
+ @classmethod
30
+ def build(cls, sorted_nodes: list[str], edge_pairs: list[tuple[str, str]]) -> GraphIndex:
31
+ n = len(sorted_nodes)
32
+ node_to_idx = {nid: i for i, nid in enumerate(sorted_nodes)}
33
+ adj_idx: list[list[int]] = [[] for _ in range(n)]
34
+ rev_adj_idx: list[list[int]] = [[] for _ in range(n)]
35
+ for src, dst in edge_pairs:
36
+ u = node_to_idx.get(src)
37
+ v = node_to_idx.get(dst)
38
+ if u is not None and v is not None and u != v:
39
+ adj_idx[u].append(v)
40
+ rev_adj_idx[v].append(u)
41
+ return cls(
42
+ nodes=sorted_nodes,
43
+ node_to_idx=node_to_idx,
44
+ adj_idx=adj_idx,
45
+ rev_adj_idx=rev_adj_idx,
46
+ )
47
+
48
+ def reverse_closure(self, seeds: set[str]) -> set[str]:
49
+ """Compute transitive reverse dependents of `seeds` via integer-indexed BFS."""
50
+ visited_idx: set[int] = set()
51
+ queue: deque[int] = deque()
52
+ for s in seeds:
53
+ idx = self.node_to_idx.get(s)
54
+ if idx is not None and idx not in visited_idx:
55
+ visited_idx.add(idx)
56
+ queue.append(idx)
57
+ while queue:
58
+ curr = queue.popleft()
59
+ for prv in self.rev_adj_idx[curr]:
60
+ if prv not in visited_idx:
61
+ visited_idx.add(prv)
62
+ queue.append(prv)
63
+ return {self.nodes[i] for i in visited_idx}
64
+
65
+ ENTRYPOINT_FILENAMES = {
66
+ "main.py",
67
+ "app.py",
68
+ "cli.py",
69
+ "__init__.py",
70
+ "__main__.py",
71
+ "manage.py",
72
+ "conftest.py",
73
+ "setup.py",
74
+ "index.ts",
75
+ "index.tsx",
76
+ "index.js",
77
+ "index.jsx",
78
+ "main.ts",
79
+ "main.tsx",
80
+ "main.js",
81
+ "main.go",
82
+ "main.rs",
83
+ "lib.rs",
84
+ "vite.config.ts",
85
+ "playwright.config.ts",
86
+ }
87
+
88
+
89
+ def build_dependency_graph(
90
+ files: list[FileNode],
91
+ raw_edges: list[tuple[str, str, list[str], int]],
92
+ ) -> tuple[list[DependencyEdge], list[CycleGroup], GraphMetrics]:
93
+ """
94
+ Compute directed dependency graph, node topological metrics, and circular dependencies.
95
+
96
+ Args:
97
+ files: List of FileNode objects (mutated in-place with fan_in, fan_out, instability, cycle flags).
98
+ raw_edges: List of (source_id, target_id, imported_names, line_number).
99
+ """
100
+ node_map: dict[str, FileNode] = {f.id: f for f in files}
101
+
102
+ # Deduplicate edges between the same (source, target) pair while aggregating imported symbol names
103
+ edge_agg: dict[tuple[str, str], tuple[set[str], int]] = {}
104
+ for src, dst, names, line in raw_edges:
105
+ if src not in node_map or dst not in node_map or src == dst:
106
+ continue
107
+ key = (src, dst)
108
+ if key not in edge_agg:
109
+ edge_agg[key] = (set(names), line)
110
+ else:
111
+ existing_names, existing_line = edge_agg[key]
112
+ existing_names.update(names)
113
+ edge_agg[key] = (existing_names, min(existing_line, line))
114
+
115
+ sorted_nodes = sorted(node_map.keys())
116
+ sorted_edge_pairs = sorted(edge_agg.keys())
117
+ g_index = GraphIndex.build(sorted_nodes, sorted_edge_pairs)
118
+
119
+ adj: dict[str, list[str]] = defaultdict(list)
120
+ rev_adj: dict[str, list[str]] = defaultdict(list)
121
+ for src, dst in sorted_edge_pairs:
122
+ adj[src].append(dst)
123
+ rev_adj[dst].append(src)
124
+
125
+ # Find Strongly Connected Components via integer-indexed iterative Tarjan's algorithm
126
+ sccs = _tarjan_scc_indexed(g_index)
127
+ cyclic_sccs = [comp for comp in sccs if len(comp) > 1]
128
+
129
+ # Extract deterministic elementary cycles within each non-trivial SCC
130
+ # with explicit max_total_cycles, per-SCC max_cycles, operation budget, and timeout
131
+ max_total_cycles = 100
132
+ max_cycles_per_scc = 25
133
+ max_ops_per_scc = 25000
134
+ max_time_per_scc_sec = 0.75
135
+
136
+ cycles: list[CycleGroup] = []
137
+ edge_in_cycle: set[tuple[str, str]] = set()
138
+ node_to_cycles: dict[str, list[str]] = defaultdict(list)
139
+ truncation_reasons: list[str] = []
140
+
141
+ cycle_counter = 1
142
+ for scc in cyclic_sccs:
143
+ scc_set = set(scc)
144
+ remaining_cap = max(0, max_total_cycles - len(cycles))
145
+ if remaining_cap == 0:
146
+ truncation_reasons.append(f"Reached global cycle reporting cap ({max_total_cycles} cycles).")
147
+ found_cycles: list[list[str]] = []
148
+ else:
149
+ found_cycles, scc_trunc_reason = _extract_cycles_in_scc(
150
+ sorted(scc),
151
+ scc_set,
152
+ adj,
153
+ max_cycles=min(max_cycles_per_scc, remaining_cap),
154
+ max_ops=max_ops_per_scc,
155
+ timeout_sec=max_time_per_scc_sec,
156
+ )
157
+ if scc_trunc_reason:
158
+ truncation_reasons.append(scc_trunc_reason)
159
+
160
+ for cyc_nodes in found_cycles:
161
+ cid = f"CYCLE-{cycle_counter:03d}"
162
+ cycle_counter += 1
163
+ length = len(cyc_nodes) - 1
164
+ severity = SeverityLevel.CRITICAL if length >= 3 else SeverityLevel.WARNING
165
+ chain_str = " → ".join(cyc_nodes)
166
+ cycles.append(
167
+ CycleGroup(
168
+ id=cid,
169
+ nodes=cyc_nodes,
170
+ length=length,
171
+ severity=severity,
172
+ description=f"Circular dependency chain of {length} modules: {chain_str}",
173
+ )
174
+ )
175
+ for i in range(length):
176
+ u, v = cyc_nodes[i], cyc_nodes[i + 1]
177
+ edge_in_cycle.add((u, v))
178
+ if cid not in node_to_cycles[u]:
179
+ node_to_cycles[u].append(cid)
180
+
181
+ # Ensure every node in a cyclic SCC is marked even if cycle cap or budget was hit
182
+ fallback_cid = f"CYCLE-SCC-{cycle_counter:03d}"
183
+ for u in scc:
184
+ for v in adj.get(u, []):
185
+ if v in scc_set:
186
+ edge_in_cycle.add((u, v))
187
+ if not node_to_cycles[u]:
188
+ node_to_cycles[u].append(fallback_cid)
189
+
190
+ edges: list[DependencyEdge] = []
191
+ for (src, dst), (names_set, line_no) in sorted(edge_agg.items()):
192
+ edges.append(
193
+ DependencyEdge(
194
+ id=f"{src}->{dst}",
195
+ source=src,
196
+ target=dst,
197
+ import_names=sorted(names_set)[:15],
198
+ line=line_no,
199
+ in_cycle=(src, dst) in edge_in_cycle,
200
+ )
201
+ )
202
+
203
+ # Populate FileNode metrics
204
+ max_fan_in = 0
205
+ max_fan_out = 0
206
+ instability_sum = 0.0
207
+ instability_count = 0
208
+ orphan_count = 0
209
+ hub_count = 0
210
+
211
+ for f in files:
212
+ imports_out = sorted(adj.get(f.id, []))
213
+ imports_in = sorted(rev_adj.get(f.id, []))
214
+ f.imports_internal = imports_out
215
+ f.imported_by = imports_in
216
+ f.fan_out = len(imports_out)
217
+ f.fan_in = len(imports_in)
218
+ max_fan_in = max(max_fan_in, f.fan_in)
219
+ max_fan_out = max(max_fan_out, f.fan_out)
220
+
221
+ total_deg = f.fan_in + f.fan_out
222
+ if total_deg > 0:
223
+ f.instability = round(f.fan_out / total_deg, 3)
224
+ instability_sum += f.instability
225
+ instability_count += 1
226
+ else:
227
+ f.instability = 0.0
228
+
229
+ f.cycle_ids = node_to_cycles.get(f.id, [])
230
+ f.in_cycle = len(f.cycle_ids) > 0
231
+
232
+ # Hub threshold: high total coupling (fan_in + fan_out >= 6 or fan_in >= 4)
233
+ f.is_hub = (f.fan_in >= 4) or (total_deg >= 6)
234
+ if f.is_hub:
235
+ hub_count += 1
236
+
237
+ # Orphan: full_ast code file with 0 internal edges and not a known entrypoint/test.
238
+ # partial_static files (e.g. C#, Java) do not have full AST cross-file import resolution
239
+ # and must not be falsely flagged as unreferenced orphans.
240
+ is_test = "test" in f.id.lower() or "spec" in f.id.lower()
241
+ is_entry = f.name.lower() in ENTRYPOINT_FILENAMES
242
+ if (
243
+ f.support_level == LanguageSupportLevel.FULL_AST
244
+ and total_deg == 0
245
+ and not is_test
246
+ and not is_entry
247
+ ):
248
+ f.is_orphan = True
249
+ orphan_count += 1
250
+ else:
251
+ f.is_orphan = False
252
+
253
+ # Connected components (weakly connected among all nodes) via integer-indexed BFS
254
+ components = _count_weak_components_indexed(g_index)
255
+ n_nodes = len(files)
256
+ n_edges = len(edges)
257
+ density = round(n_edges / (n_nodes * (n_nodes - 1)), 4) if n_nodes > 1 else 0.0
258
+ avg_instability = round(instability_sum / instability_count, 3) if instability_count > 0 else 0.0
259
+
260
+ unique_trunc = list(dict.fromkeys(truncation_reasons))
261
+ metrics = GraphMetrics(
262
+ total_nodes=n_nodes,
263
+ total_edges=n_edges,
264
+ connected_components=components,
265
+ scc_count=len(cyclic_sccs),
266
+ cycle_count=len(cycles),
267
+ nodes_in_cycles=sum(1 for f in files if f.in_cycle),
268
+ cycles_truncated=len(unique_trunc) > 0,
269
+ cycle_truncation_reason="; ".join(unique_trunc) if unique_trunc else None,
270
+ orphan_files_count=orphan_count,
271
+ hub_files_count=hub_count,
272
+ max_fan_in=max_fan_in,
273
+ max_fan_out=max_fan_out,
274
+ average_instability=avg_instability,
275
+ graph_density=density,
276
+ )
277
+ return edges, cycles, metrics
278
+
279
+
280
+ def _tarjan_scc_indexed(g_index: GraphIndex) -> list[list[str]]:
281
+ """Integer-indexed iterative Tarjan SCC (O(V + E), zero string dict lookups in hot loop)."""
282
+ n = len(g_index.nodes)
283
+ adj_idx = g_index.adj_idx
284
+ nodes = g_index.nodes
285
+
286
+ index_counter = 0
287
+ indices = [-1] * n
288
+ lowlink = [0] * n
289
+ on_stack = [False] * n
290
+ tarjan_stack: list[int] = []
291
+ sccs: list[list[str]] = []
292
+
293
+ for start in range(n):
294
+ if indices[start] != -1:
295
+ continue
296
+
297
+ call_stack: list[tuple[int, int]] = [(start, 0)]
298
+ indices[start] = lowlink[start] = index_counter
299
+ index_counter += 1
300
+ tarjan_stack.append(start)
301
+ on_stack[start] = True
302
+
303
+ while call_stack:
304
+ u, n_idx = call_stack[-1]
305
+ neighbors = adj_idx[u]
306
+ if n_idx < len(neighbors):
307
+ v = neighbors[n_idx]
308
+ call_stack[-1] = (u, n_idx + 1)
309
+ if indices[v] == -1:
310
+ indices[v] = lowlink[v] = index_counter
311
+ index_counter += 1
312
+ tarjan_stack.append(v)
313
+ on_stack[v] = True
314
+ call_stack.append((v, 0))
315
+ elif on_stack[v]:
316
+ if indices[v] < lowlink[u]:
317
+ lowlink[u] = indices[v]
318
+ else:
319
+ call_stack.pop()
320
+ if call_stack:
321
+ parent = call_stack[-1][0]
322
+ if lowlink[u] < lowlink[parent]:
323
+ lowlink[parent] = lowlink[u]
324
+
325
+ if lowlink[u] == indices[u]:
326
+ comp_ids: list[int] = []
327
+ while True:
328
+ w = tarjan_stack.pop()
329
+ on_stack[w] = False
330
+ comp_ids.append(w)
331
+ if w == u:
332
+ break
333
+ comp_ids.sort()
334
+ scc_idx = len(sccs)
335
+ comp_names = [nodes[i] for i in comp_ids]
336
+ for name in comp_names:
337
+ g_index.scc_by_node[name] = scc_idx
338
+ sccs.append(comp_names)
339
+
340
+ return sccs
341
+
342
+
343
+ def _count_weak_components_indexed(g_index: GraphIndex) -> int:
344
+ """Integer-indexed BFS for weakly connected components (O(V + E))."""
345
+ n = len(g_index.nodes)
346
+ visited = [False] * n
347
+ adj_idx = g_index.adj_idx
348
+ rev_adj_idx = g_index.rev_adj_idx
349
+ count = 0
350
+
351
+ for start in range(n):
352
+ if visited[start]:
353
+ continue
354
+ count += 1
355
+ visited[start] = True
356
+ queue: deque[int] = deque([start])
357
+ while queue:
358
+ curr = queue.popleft()
359
+ for nxt in adj_idx[curr]:
360
+ if not visited[nxt]:
361
+ visited[nxt] = True
362
+ queue.append(nxt)
363
+ for prv in rev_adj_idx[curr]:
364
+ if not visited[prv]:
365
+ visited[prv] = True
366
+ queue.append(prv)
367
+ return count
368
+
369
+
370
+ def _tarjan_scc(nodes: list[str], adj: dict[str, list[str]]) -> list[list[str]]:
371
+ index = 0
372
+ indices: dict[str, int] = {}
373
+ lowlink: dict[str, int] = {}
374
+ on_stack: set[str] = set()
375
+ stack: list[str] = []
376
+ sccs: list[list[str]] = []
377
+
378
+ for start_node in nodes:
379
+ if start_node in indices:
380
+ continue
381
+
382
+ # Iterative Tarjan to prevent RecursionError on deep dependency graphs
383
+ call_stack: list[tuple[str, int]] = [(start_node, 0)]
384
+ indices[start_node] = lowlink[start_node] = index
385
+ index += 1
386
+ stack.append(start_node)
387
+ on_stack.add(start_node)
388
+
389
+ while call_stack:
390
+ u, neighbor_idx = call_stack[-1]
391
+ neighbors = adj.get(u, [])
392
+ if neighbor_idx < len(neighbors):
393
+ v = neighbors[neighbor_idx]
394
+ call_stack[-1] = (u, neighbor_idx + 1)
395
+ if v not in indices:
396
+ indices[v] = lowlink[v] = index
397
+ index += 1
398
+ stack.append(v)
399
+ on_stack.add(v)
400
+ call_stack.append((v, 0))
401
+ elif v in on_stack:
402
+ lowlink[u] = min(lowlink[u], indices[v])
403
+ else:
404
+ call_stack.pop()
405
+ if call_stack:
406
+ parent = call_stack[-1][0]
407
+ lowlink[parent] = min(lowlink[parent], lowlink[u])
408
+
409
+ if lowlink[u] == indices[u]:
410
+ comp: list[str] = []
411
+ while True:
412
+ w = stack.pop()
413
+ on_stack.remove(w)
414
+ comp.append(w)
415
+ if w == u:
416
+ break
417
+ sccs.append(sorted(comp))
418
+
419
+ return sccs
420
+
421
+
422
+ def _extract_cycles_in_scc(
423
+ scc_nodes: list[str],
424
+ scc_set: set[str],
425
+ adj: dict[str, list[str]],
426
+ max_cycles: int = 25,
427
+ max_ops: int = 25000,
428
+ timeout_sec: float = 0.75,
429
+ ) -> tuple[list[list[str]], str | None]:
430
+ """
431
+ Find canonical elementary cycles within an SCC using integer-indexed Johnson's blocked-set algorithm,
432
+ bounded by `max_cycles`, `max_ops` operation budget, and `timeout_sec` wall-clock budget.
433
+ """
434
+ m = len(scc_nodes)
435
+ node_order = {n: idx for idx, n in enumerate(scc_nodes)}
436
+ local_adj: list[list[int]] = [
437
+ [node_order[nxt] for nxt in adj.get(node_name, ()) if nxt in scc_set]
438
+ for node_name in scc_nodes
439
+ ]
440
+
441
+ seen_canonical: set[tuple[int, ...]] = set()
442
+ results_idx: list[list[int]] = []
443
+ ops_used = 0
444
+ truncation_reason: str | None = None
445
+ deadline = time.monotonic() + timeout_sec
446
+
447
+ for start_rank in range(m):
448
+ if len(results_idx) >= max_cycles or truncation_reason is not None:
449
+ break
450
+ path: list[int] = [start_rank]
451
+ blocked = [False] * m
452
+ blocked[start_rank] = True
453
+ blocked_map: list[set[int]] = [set() for _ in range(m)]
454
+
455
+ def unblock(
456
+ u: int,
457
+ _blocked: list[bool] = blocked,
458
+ _blocked_map: list[set[int]] = blocked_map,
459
+ ) -> None:
460
+ nonlocal ops_used
461
+ stack = [u]
462
+ while stack:
463
+ ops_used += 1
464
+ curr = stack.pop()
465
+ if _blocked[curr]:
466
+ _blocked[curr] = False
467
+ bset = _blocked_map[curr]
468
+ if bset:
469
+ for w in list(bset):
470
+ if _blocked[w]:
471
+ stack.append(w)
472
+ bset.clear()
473
+
474
+ def circuit(
475
+ curr: int,
476
+ _start_rank: int = start_rank,
477
+ _path: list[int] = path,
478
+ _blocked: list[bool] = blocked,
479
+ _blocked_map: list[set[int]] = blocked_map,
480
+ ) -> bool:
481
+ nonlocal ops_used, truncation_reason
482
+ found_cycle = False
483
+ ops_used += 1
484
+
485
+ if len(results_idx) >= max_cycles:
486
+ truncation_reason = f"Reached per-SCC cycle cap ({max_cycles} cycles)."
487
+ return True
488
+ if ops_used >= max_ops:
489
+ truncation_reason = f"Reached Johnson cycle enumeration operation budget ({max_ops} ops)."
490
+ return True
491
+ if (ops_used & 63) == 0 and time.monotonic() > deadline:
492
+ truncation_reason = f"Reached Johnson cycle enumeration timeout ({timeout_sec:.2f}s)."
493
+ return True
494
+
495
+ for nxt in local_adj[curr]:
496
+ if nxt < _start_rank:
497
+ continue
498
+ if nxt == _start_rank and len(_path) >= 2:
499
+ # Since start_rank is minimum rank in _path, _path is already canonically rotated!
500
+ canon = tuple(_path)
501
+ if canon not in seen_canonical:
502
+ seen_canonical.add(canon)
503
+ results_idx.append([*_path, _start_rank])
504
+ found_cycle = True
505
+ if len(results_idx) >= max_cycles:
506
+ truncation_reason = f"Reached per-SCC cycle cap ({max_cycles} cycles)."
507
+ break
508
+ elif not _blocked[nxt] and len(_path) < 16:
509
+ _blocked[nxt] = True
510
+ _path.append(nxt)
511
+ if circuit(nxt, _start_rank, _path, _blocked, _blocked_map):
512
+ found_cycle = True
513
+ _path.pop()
514
+ if truncation_reason is not None:
515
+ break
516
+
517
+ if found_cycle:
518
+ unblock(curr)
519
+ else:
520
+ for nxt in local_adj[curr]:
521
+ if nxt >= _start_rank:
522
+ _blocked_map[nxt].add(curr)
523
+ return found_cycle
524
+
525
+ circuit(start_rank)
526
+
527
+ results = [[scc_nodes[i] for i in cyc] for cyc in results_idx]
528
+ return results, truncation_reason
529
+
530
+
531
+ def _canonicalize_cycle(cycle_nodes: list[str]) -> tuple[str, ...]:
532
+ if not cycle_nodes:
533
+ return ()
534
+ min_idx = min(range(len(cycle_nodes)), key=lambda i: cycle_nodes[i])
535
+ rotated = cycle_nodes[min_idx:] + cycle_nodes[:min_idx]
536
+ return tuple(rotated)
537
+
538
+
539
+ def _count_weak_components(
540
+ nodes: list[str],
541
+ adj: dict[str, list[str]],
542
+ rev_adj: dict[str, list[str]],
543
+ ) -> int:
544
+ visited: set[str] = set()
545
+ count = 0
546
+ for n in nodes:
547
+ if n in visited:
548
+ continue
549
+ count += 1
550
+ queue: deque[str] = deque([n])
551
+ visited.add(n)
552
+ while queue:
553
+ curr = queue.popleft()
554
+ for nxt in adj.get(curr, []):
555
+ if nxt not in visited:
556
+ visited.add(nxt)
557
+ queue.append(nxt)
558
+ for prv in rev_adj.get(curr, []):
559
+ if prv not in visited:
560
+ visited.add(prv)
561
+ queue.append(prv)
562
+ return count
@@ -0,0 +1,17 @@
1
+ """RepoDNA PR Architecture Guardian package."""
2
+
3
+ from repodna.guardian.engine import PRArchitectureGuardian
4
+ from repodna.guardian.models import (
5
+ GuardianReport,
6
+ GuardianVerdict,
7
+ RiskAssessment,
8
+ RiskLevel,
9
+ )
10
+
11
+ __all__ = [
12
+ "PRArchitectureGuardian",
13
+ "GuardianReport",
14
+ "GuardianVerdict",
15
+ "RiskAssessment",
16
+ "RiskLevel",
17
+ ]