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,336 @@
1
+ """Read-Only Change Preflight Engine for RepoDNA v0.11.0.
2
+
3
+ Evaluates an explicit ChangeIntent BEFORE edits are made:
4
+ - Computes directly and transitively affected modules (bounded BFS).
5
+ - Separates verified impacted symbols from candidate impacted symbols.
6
+ - Identifies related static tests, existing architectural/quality risks, and boundaries.
7
+ - Evaluates hypothetical risks (e.g., hypothetical cycles from proposed dependency edges)
8
+ STRICTLY labeled `is_hypothetical=True` and NEVER persisted as actual repository cycles.
9
+ - Never mutates source code and never executes shell commands.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from collections import defaultdict, deque
15
+ from typing import Any
16
+
17
+ from repodna.agent.models import (
18
+ MAX_GRAPH_HOPS,
19
+ AgentEvidenceReference,
20
+ ChangeIntent,
21
+ EvidenceValidationStatus,
22
+ FreshnessMetadata,
23
+ HypotheticalRisk,
24
+ ImpactPlan,
25
+ )
26
+ from repodna.agent.safety import build_trust_boundary, sanitize_untrusted_text, sha256_short
27
+ from repodna.brain.indexer import SymbolIndexer
28
+ from repodna.intelligence.service import RepositoryIntelligenceService
29
+ from repodna.quality.models import QualityReport
30
+ from repodna.schemas.models import AnalysisResult
31
+
32
+
33
+ class ChangePreflightEngine:
34
+ """Deterministic, read-only preflight impact analyzer."""
35
+
36
+ def __init__(
37
+ self,
38
+ analysis: AnalysisResult,
39
+ indexer: SymbolIndexer,
40
+ repo_id: str,
41
+ snapshot_id: str,
42
+ quality_report: QualityReport | None = None,
43
+ core_freshness: str = "fresh",
44
+ quality_freshness: str = "not_evaluated",
45
+ live_session_active: bool = False,
46
+ pending_live_analysis: bool = False,
47
+ ) -> None:
48
+ self.analysis = analysis
49
+ self.indexer = indexer
50
+ self.repo_id = repo_id
51
+ self.snapshot_id = snapshot_id
52
+ self.quality_report = quality_report
53
+ self.core_freshness = core_freshness
54
+ self.quality_freshness = quality_freshness
55
+ self.live_session_active = live_session_active
56
+ self.pending_live_analysis = pending_live_analysis
57
+ self._files_by_id = {f.id: f for f in analysis.files}
58
+
59
+ def _detect_hypothetical_cycle(
60
+ self,
61
+ src: str,
62
+ dst: str,
63
+ ) -> list[str] | None:
64
+ """Checks if adding directed edge src -> dst would close a path from dst back to src."""
65
+ if src == dst:
66
+ return [src, dst]
67
+ q: deque[list[str]] = deque([[dst]])
68
+ seen: set[str] = {dst}
69
+ while q:
70
+ path = q.popleft()
71
+ if len(path) > 8:
72
+ continue
73
+ curr = path[-1]
74
+ if curr == src:
75
+ return [*path, dst]
76
+ node = self._files_by_id.get(curr)
77
+ if node:
78
+ for nxt in sorted(node.imports_internal):
79
+ if nxt not in seen:
80
+ seen.add(nxt)
81
+ q.append([*path, nxt])
82
+ return None
83
+
84
+ def evaluate(self, intent: ChangeIntent) -> ImpactPlan:
85
+ """Evaluates ChangeIntent and produces a bounded, evidence-backed ImpactPlan."""
86
+ freshness = FreshnessMetadata(
87
+ repo_id=self.repo_id,
88
+ repository=self.analysis.repo_name,
89
+ snapshot_id=self.snapshot_id,
90
+ revision=self.indexer.revision or "WORKING_TREE",
91
+ core_freshness=self.core_freshness,
92
+ quality_freshness=self.quality_freshness,
93
+ live_session_active=self.live_session_active,
94
+ pending_live_analysis=self.pending_live_analysis,
95
+ )
96
+
97
+ service = RepositoryIntelligenceService(self.analysis)
98
+ cov = service.get_analysis_coverage()
99
+ limitations: list[str] = []
100
+ if cov.partial_static_languages:
101
+ limitations.append(f"Partial static analysis only for: {', '.join(cov.partial_static_languages)}.")
102
+ if cov.unsupported_languages:
103
+ limitations.append(f"Unsupported AST languages: {', '.join(cov.unsupported_languages)}.")
104
+ limitations.append(
105
+ "Preflight analysis is static and hypothetical; it does not prove runtime behavior or execute tests."
106
+ )
107
+
108
+ intended_files = [
109
+ f.replace("\\", "/").lstrip("./")
110
+ for f in intent.intended_files
111
+ if f.strip()
112
+ ]
113
+ # Resolve symbols to files as well
114
+ target_symbol_objs = []
115
+ for sym_q in intent.intended_symbols:
116
+ s_obj = self.indexer._symbols_by_id.get(sym_q)
117
+ if s_obj is None:
118
+ matches = self.indexer._symbols_by_name_lower.get(sym_q.lower(), [])
119
+ target_symbol_objs.extend(matches[:3])
120
+ else:
121
+ target_symbol_objs.append(s_obj)
122
+ for s_obj in target_symbol_objs:
123
+ if s_obj.file_path not in intended_files:
124
+ intended_files.append(s_obj.file_path)
125
+
126
+ valid_intended = [f for f in intended_files if f in self._files_by_id]
127
+ missing_intended = [f for f in intended_files if f not in self._files_by_id]
128
+ for mf in missing_intended:
129
+ limitations.append(f"Intended file '{mf}' does not currently exist in snapshot '{self.snapshot_id}'.")
130
+
131
+ # Direct dependents (1-hop imported_by) & transitive dependents (up to MAX_GRAPH_HOPS)
132
+ direct_set: set[str] = set()
133
+ for f in valid_intended:
134
+ node = self._files_by_id[f]
135
+ direct_set.update(node.imported_by)
136
+ direct_set -= set(valid_intended)
137
+
138
+ transitive_set: set[str] = set()
139
+ queue: deque[tuple[str, int]] = deque((d, 1) for d in sorted(direct_set))
140
+ visited: set[str] = set(valid_intended) | set(direct_set)
141
+ while queue:
142
+ curr, depth = queue.popleft()
143
+ if depth >= MAX_GRAPH_HOPS:
144
+ continue
145
+ curr_node = self._files_by_id.get(curr)
146
+ if curr_node:
147
+ for dep in sorted(curr_node.imported_by):
148
+ if dep not in visited:
149
+ visited.add(dep)
150
+ transitive_set.add(dep)
151
+ queue.append((dep, depth + 1))
152
+
153
+ # Verified vs candidate impacted symbols
154
+ verified_impacted: list[dict[str, Any]] = []
155
+ candidate_impacted: list[dict[str, Any]] = []
156
+ evidence_map: dict[str, AgentEvidenceReference] = {}
157
+ redacted_count = 0
158
+ injection_signals: list[str] = []
159
+
160
+ target_sym_names = {s.name for s in target_symbol_objs}
161
+ for f in valid_intended:
162
+ for s in self.indexer.find_by_file(f):
163
+ target_sym_names.add(s.name)
164
+ if s.evidence_id and s.evidence_id not in evidence_map:
165
+ ev = self.indexer.ledger.get_by_id(s.evidence_id)
166
+ if ev is not None:
167
+ safe_snip, sc, inj = sanitize_untrusted_text(ev.code_snippet or "")
168
+ redacted_count += sc
169
+ injection_signals.extend(inj)
170
+ evidence_map[ev.evidence_id] = AgentEvidenceReference(
171
+ evidence_id=ev.evidence_id,
172
+ repo_id=self.repo_id,
173
+ snapshot_id=self.snapshot_id,
174
+ revision=ev.repository_revision,
175
+ file_path=ev.file_path,
176
+ line_start=ev.line_start,
177
+ line_end=ev.line_end,
178
+ evidence_type=ev.evidence_type.value,
179
+ symbol_name=ev.symbol_name,
180
+ content_hash=ev.content_hash or "",
181
+ redacted=sc > 0,
182
+ snippet=safe_snip[:240],
183
+ capability_level=ev.support_level.value,
184
+ status=(
185
+ EvidenceValidationStatus.STALE
186
+ if ev.is_stale
187
+ else EvidenceValidationStatus.VERIFIED
188
+ ),
189
+ staleness_reason=ev.staleness_reason.value,
190
+ confidence_reason=ev.confidence_reason,
191
+ )
192
+
193
+ affected_scope = set(valid_intended) | direct_set
194
+ for fid in sorted(affected_scope):
195
+ for sym in self.indexer.find_by_file(fid):
196
+ for vr in sym.verified_references:
197
+ if vr.target_file_path in valid_intended or vr.symbol_name in target_sym_names:
198
+ verified_impacted.append(
199
+ {
200
+ "caller_file": fid,
201
+ "caller_symbol": sym.name,
202
+ "target_symbol": vr.symbol_name,
203
+ "target_file": vr.target_file_path,
204
+ "line": vr.line,
205
+ "verified": True,
206
+ }
207
+ )
208
+ for cr in sym.candidate_references:
209
+ if cr.target_file_path in valid_intended or cr.symbol_name in target_sym_names:
210
+ candidate_impacted.append(
211
+ {
212
+ "caller_file": fid,
213
+ "caller_symbol": sym.name,
214
+ "target_symbol": cr.symbol_name,
215
+ "target_file": cr.target_file_path,
216
+ "line": cr.line,
217
+ "verified": False,
218
+ }
219
+ )
220
+
221
+ # Related static tests & existing quality findings
222
+ related_tests: set[str] = set()
223
+ existing_quality: list[dict[str, Any]] = []
224
+ if self.quality_report is not None:
225
+ for entry in self.quality_report.test_mapping.entries:
226
+ if entry.production_file in affected_scope:
227
+ related_tests.update(entry.mapped_test_files)
228
+ for qf in self.quality_report.findings:
229
+ if qf.file_path in affected_scope:
230
+ existing_quality.append(
231
+ {
232
+ "finding_id": qf.finding_id,
233
+ "rule_id": qf.rule_id,
234
+ "severity": qf.severity.value,
235
+ "file_path": qf.file_path,
236
+ "explanation": qf.explanation,
237
+ }
238
+ )
239
+
240
+ # Current architectural risks & boundaries
241
+ current_arch_risks: list[dict[str, Any]] = []
242
+ boundaries: list[str] = []
243
+ layers_touched = sorted({f.split("/")[0] if "/" in f else "root" for f in valid_intended})
244
+ if layers_touched:
245
+ boundaries.append(f"Intended edit touches top-level layer(s): {', '.join(layers_touched)}")
246
+ for af in self.analysis.health_report.findings:
247
+ overlap = sorted(set(af.affected_files) & affected_scope)
248
+ if overlap:
249
+ current_arch_risks.append(
250
+ {
251
+ "rule_id": af.rule_id,
252
+ "severity": af.severity.value,
253
+ "title": af.title,
254
+ "affected_files": overlap[:6],
255
+ }
256
+ )
257
+
258
+ # Hypothetical risks (STRICTLY labeled is_hypothetical=True)
259
+ hypothetical_risks: list[HypotheticalRisk] = []
260
+ for f in valid_intended:
261
+ node = self._files_by_id[f]
262
+ if node.is_hub:
263
+ hypothetical_risks.append(
264
+ HypotheticalRisk(
265
+ risk_id=f"hyp_hub_{sha256_short(f, 8)}",
266
+ category="high_fan_in_hub_modification",
267
+ severity="warning",
268
+ is_hypothetical=True,
269
+ description=(
270
+ f"Hypothetical blast-radius risk: '{f}' is an architectural hub "
271
+ f"(fan_in={node.fan_in}). Interface changes may affect {len(node.imported_by)} direct dependents."
272
+ ),
273
+ involved_modules=[f, *sorted(node.imported_by)[:5]],
274
+ )
275
+ )
276
+ if node.in_cycle:
277
+ hypothetical_risks.append(
278
+ HypotheticalRisk(
279
+ risk_id=f"hyp_cyc_{sha256_short(f, 8)}",
280
+ category="existing_cycle_participant",
281
+ severity="warning",
282
+ is_hypothetical=True,
283
+ description=(
284
+ f"Hypothetical coupling risk: '{f}' participates in an existing circular dependency SCC."
285
+ ),
286
+ involved_modules=[f],
287
+ )
288
+ )
289
+
290
+ # Hypothetical cycle detection for explicitly proposed new dependency edges
291
+ for src_raw, dst_raw in intent.proposed_dependency_edges:
292
+ src = src_raw.replace("\\", "/").lstrip("./")
293
+ dst = dst_raw.replace("\\", "/").lstrip("./")
294
+ if src in self._files_by_id and dst in self._files_by_id:
295
+ cycle_path = self._detect_hypothetical_cycle(src, dst)
296
+ if cycle_path is not None:
297
+ hypothetical_risks.append(
298
+ HypotheticalRisk(
299
+ risk_id=f"hyp_new_cycle_{sha256_short(f'{src}->{dst}', 8)}",
300
+ category="hypothetical_circular_dependency",
301
+ severity="high",
302
+ is_hypothetical=True,
303
+ description=(
304
+ f"Hypothetical circular dependency risk (NOT yet an actual cycle): "
305
+ f"adding edge '{src} -> {dst}' would close cycle {' -> '.join(cycle_path)}."
306
+ ),
307
+ involved_modules=sorted(set(cycle_path)),
308
+ )
309
+ )
310
+
311
+ # Suggested verification targets
312
+ verification_targets = sorted(related_tests)[:10]
313
+ if not verification_targets:
314
+ verification_targets = [
315
+ f"Review direct dependents: {', '.join(sorted(direct_set)[:5])}"
316
+ ] if direct_set else ["Run project test suite via authorized development workflow after edits."]
317
+
318
+ # Deduplicate direct/transitive lists
319
+ _ = defaultdict(list)
320
+ return ImpactPlan(
321
+ intent=intent,
322
+ freshness=freshness,
323
+ relevant_architectural_boundaries=boundaries,
324
+ directly_affected_modules=sorted(direct_set)[:50],
325
+ transitively_affected_modules=sorted(transitive_set)[:50],
326
+ verified_impacted_symbols=verified_impacted[:40],
327
+ candidate_impacted_symbols=candidate_impacted[:30],
328
+ related_tests=sorted(related_tests)[:20],
329
+ existing_quality_findings=existing_quality[:20],
330
+ current_architectural_risks=current_arch_risks[:20],
331
+ hypothetical_risks=hypothetical_risks[:20],
332
+ suggested_verification_targets=verification_targets,
333
+ evidence=list(evidence_map.values())[:25],
334
+ coverage_limitations=limitations,
335
+ trust_boundary=build_trust_boundary(redacted_count, injection_signals),
336
+ )
@@ -0,0 +1,318 @@
1
+ """Hybrid Lexical (BM25) + Bounded Graph Relevance (Personalized PageRank) for Agent Localization.
2
+
3
+ Design guarantees:
4
+ - Exact file paths and AST symbol names strictly outrank comment/docstring matches.
5
+ - Verified AST reference edges carry higher weight than candidate edges.
6
+ - Hub damping prevents task-unrelated architectural hubs from dominating unrelated tasks.
7
+ - Bounded graph traversal (MAX_GRAPH_HOPS, MAX_GRAPH_NODES) prevents runaway expansion.
8
+ - Scores are deterministic relevance weights (NOT probabilities); tie-breaks are stable.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import math
14
+ from collections import defaultdict
15
+ from dataclasses import dataclass
16
+
17
+ from repodna.agent.models import (
18
+ MAX_GRAPH_HOPS,
19
+ MAX_GRAPH_NODES,
20
+ AgentTask,
21
+ )
22
+ from repodna.agent.task import normalize_turkish_fold, split_code_tokens
23
+ from repodna.brain.indexer import SymbolIndexer
24
+ from repodna.brain.models import SymbolDefinition
25
+ from repodna.brain.retrieval import SYNONYM_MAP
26
+ from repodna.schemas.models import AnalysisResult, FileNode
27
+
28
+ # Edge weights: verified AST edges strictly outweigh candidate heuristic edges
29
+ VERIFIED_EDGE_WEIGHT = 1.0
30
+ CANDIDATE_EDGE_WEIGHT = 0.35
31
+ IMPORT_EDGE_WEIGHT = 0.75
32
+
33
+
34
+ @dataclass(frozen=True)
35
+ class BM25Index:
36
+ """Lightweight deterministic BM25 index over repository file paths and AST symbol names."""
37
+
38
+ doc_tokens: dict[str, list[str]]
39
+ doc_freq: dict[str, int]
40
+ avg_doc_len: float
41
+ total_docs: int
42
+
43
+ @classmethod
44
+ def build(
45
+ cls,
46
+ files_by_id: dict[str, FileNode],
47
+ indexer: SymbolIndexer,
48
+ ) -> BM25Index:
49
+ doc_tokens: dict[str, list[str]] = {}
50
+ doc_freq: dict[str, int] = defaultdict(int)
51
+ all_ids = sorted(set(files_by_id.keys()) | set(indexer._symbols_by_file.keys()))
52
+
53
+ total_len = 0
54
+ for fid in all_ids:
55
+ tokens: list[str] = []
56
+ # Path tokens (weighted x2 by repetition for path specificity)
57
+ path_toks = split_code_tokens(fid)
58
+ tokens.extend(path_toks)
59
+ tokens.extend(path_toks)
60
+ # AST symbol tokens (weighted x2; docstrings are NOT added to prevent misleading comment hijacking)
61
+ for sym in indexer.find_by_file(fid):
62
+ sym_toks = split_code_tokens(sym.name)
63
+ tokens.extend(sym_toks)
64
+ tokens.extend(sym_toks)
65
+ if sym.qualified_name and sym.qualified_name != sym.name:
66
+ tokens.extend(split_code_tokens(sym.qualified_name))
67
+ doc_tokens[fid] = tokens
68
+ total_len += len(tokens)
69
+ for unique_tok in set(tokens):
70
+ doc_freq[unique_tok] += 1
71
+
72
+ total_docs = max(1, len(all_ids))
73
+ avg_len = max(1.0, total_len / total_docs)
74
+ return cls(
75
+ doc_tokens=doc_tokens,
76
+ doc_freq=dict(doc_freq),
77
+ avg_doc_len=avg_len,
78
+ total_docs=total_docs,
79
+ )
80
+
81
+ def score(self, file_id: str, query_terms: list[str], k1: float = 1.2, b: float = 0.75) -> float:
82
+ """Computes Okapi BM25 relevance score for a file against normalized query terms."""
83
+ tokens = self.doc_tokens.get(file_id)
84
+ if not tokens or not query_terms:
85
+ return 0.0
86
+ tf_map: dict[str, int] = defaultdict(int)
87
+ for tok in tokens:
88
+ tf_map[tok] += 1
89
+ doc_len = len(tokens)
90
+ score = 0.0
91
+ for term in set(query_terms):
92
+ tf = tf_map.get(term, 0)
93
+ if tf == 0:
94
+ continue
95
+ df = self.doc_freq.get(term, 0)
96
+ idf = math.log(1.0 + (self.total_docs - df + 0.5) / (df + 0.5))
97
+ denom = tf + k1 * (1.0 - b + b * (doc_len / self.avg_doc_len))
98
+ score += idf * ((tf * (k1 + 1.0)) / max(1e-9, denom))
99
+ return round(score, 4)
100
+
101
+
102
+ @dataclass
103
+ class GraphPropagationResult:
104
+ """Bounded Personalized PageRank / multi-hop graph relevance output."""
105
+
106
+ scores: dict[str, float]
107
+ verified_boosts: dict[str, float]
108
+ candidate_boosts: dict[str, float]
109
+ nodes_visited: int
110
+ hops_used: int
111
+
112
+
113
+ def compute_bounded_graph_relevance(
114
+ seed_scores: dict[str, float],
115
+ analysis: AnalysisResult,
116
+ indexer: SymbolIndexer,
117
+ max_hops: int = 2,
118
+ max_nodes: int = MAX_GRAPH_NODES,
119
+ damping: float = 0.72,
120
+ ) -> GraphPropagationResult:
121
+ """Runs bounded task-seeded Personalized PageRank / multi-hop propagation.
122
+
123
+ - Strictly respects max_hops (<= MAX_GRAPH_HOPS) and max_nodes (<= MAX_GRAPH_NODES).
124
+ - Separates verified AST reference edges from candidate edges.
125
+ - Applies inverse-degree normalization so high-degree unrelated hubs do not absorb mass.
126
+ """
127
+ bounded_hops = max(0, min(max_hops, MAX_GRAPH_HOPS))
128
+ bounded_nodes = max(1, min(max_nodes, MAX_GRAPH_NODES))
129
+ if not seed_scores or bounded_hops == 0:
130
+ return GraphPropagationResult(
131
+ scores={},
132
+ verified_boosts={},
133
+ candidate_boosts={},
134
+ nodes_visited=len(seed_scores),
135
+ hops_used=0,
136
+ )
137
+
138
+ files_by_id: dict[str, FileNode] = {f.id: f for f in analysis.files}
139
+
140
+ # Build bounded adjacency list around top seeds via BFS up to bounded_hops
141
+ # Edge structure: src -> list[(dst, weight, is_verified_symbol_edge)]
142
+ adj: dict[str, list[tuple[str, float, bool]]] = defaultdict(list)
143
+
144
+ # Pre-index verified & candidate symbol references per file
145
+ sym_edges: dict[str, list[tuple[str, float, bool]]] = defaultdict(list)
146
+ for fid, syms in indexer._symbols_by_file.items():
147
+ for sym in syms:
148
+ for ref in sym.verified_references:
149
+ tgt = ref.target_file_path
150
+ if tgt and tgt != fid and tgt in files_by_id:
151
+ sym_edges[fid].append((tgt, VERIFIED_EDGE_WEIGHT, True))
152
+ sym_edges[tgt].append((fid, VERIFIED_EDGE_WEIGHT * 0.8, True))
153
+ for ref in sym.candidate_references:
154
+ tgt = ref.target_file_path
155
+ if tgt and tgt != fid and tgt in files_by_id:
156
+ sym_edges[fid].append((tgt, CANDIDATE_EDGE_WEIGHT, False))
157
+
158
+ # Top seeds normalized as personalization vector
159
+ sorted_seeds = sorted(seed_scores.items(), key=lambda kv: (-kv[1], kv[0]))[:12]
160
+ total_seed_mass = sum(max(0.0, s) for _, s in sorted_seeds) or 1.0
161
+ personalization: dict[str, float] = {
162
+ fid: max(0.0, sc) / total_seed_mass for fid, sc in sorted_seeds
163
+ }
164
+
165
+ visited: set[str] = set(personalization.keys())
166
+ frontier: set[str] = set(personalization.keys())
167
+ hops_executed = 0
168
+
169
+ for _ in range(bounded_hops):
170
+ if not frontier or len(visited) >= bounded_nodes:
171
+ break
172
+ hops_executed += 1
173
+ next_frontier: set[str] = set()
174
+ for fid in sorted(frontier):
175
+ node = files_by_id.get(fid)
176
+ neighbors: list[tuple[str, float, bool]] = []
177
+ if node is not None:
178
+ for imp in node.imports_internal:
179
+ if imp in files_by_id and imp != fid:
180
+ neighbors.append((imp, IMPORT_EDGE_WEIGHT, True))
181
+ for dep in node.imported_by:
182
+ if dep in files_by_id and dep != fid:
183
+ neighbors.append((dep, IMPORT_EDGE_WEIGHT * 0.85, True))
184
+ neighbors.extend(sym_edges.get(fid, []))
185
+
186
+ # Deduplicate neighbor keeping highest weight
187
+ best_by_nbr: dict[str, tuple[float, bool]] = {}
188
+ for nbr, w, is_ver in neighbors:
189
+ prev = best_by_nbr.get(nbr)
190
+ if prev is None or w > prev[0]:
191
+ best_by_nbr[nbr] = (w, is_ver)
192
+
193
+ for nbr, (w, is_ver) in sorted(best_by_nbr.items()):
194
+ if nbr not in visited:
195
+ if len(visited) >= bounded_nodes:
196
+ break
197
+ visited.add(nbr)
198
+ next_frontier.add(nbr)
199
+ adj[fid].append((nbr, w, is_ver))
200
+ frontier = next_frontier
201
+
202
+ # Power iterations of Personalized PageRank on the bounded subgraph
203
+ ranks: dict[str, float] = {fid: personalization.get(fid, 0.0) for fid in visited}
204
+ verified_contrib: dict[str, float] = defaultdict(float)
205
+ candidate_contrib: dict[str, float] = defaultdict(float)
206
+
207
+ iterations = min(8, bounded_hops * 3 + 2)
208
+ for _ in range(iterations):
209
+ new_ranks: dict[str, float] = {
210
+ fid: (1.0 - damping) * personalization.get(fid, 0.0) for fid in visited
211
+ }
212
+ for src in sorted(visited):
213
+ src_rank = ranks.get(src, 0.0)
214
+ if src_rank <= 0.0:
215
+ continue
216
+ out_edges = adj.get(src, [])
217
+ if not out_edges:
218
+ continue
219
+ total_w = sum(w for _, w, _ in out_edges) or 1.0
220
+ for dst, w, is_ver in out_edges:
221
+ if dst not in new_ranks:
222
+ continue
223
+ delta = damping * src_rank * (w / total_w)
224
+ new_ranks[dst] += delta
225
+ if is_ver:
226
+ verified_contrib[dst] += delta
227
+ else:
228
+ candidate_contrib[dst] += delta
229
+ ranks = new_ranks
230
+
231
+ # Scale PPR mass into interpretable bounded boost points (0..18)
232
+ scaled_scores: dict[str, float] = {}
233
+ scaled_verified: dict[str, float] = {}
234
+ scaled_candidate: dict[str, float] = {}
235
+ for fid, raw_r in ranks.items():
236
+ if fid in personalization:
237
+ continue # Seeds already hold direct lexical/symbol score
238
+ # Apply gentle hub damping for high fan-in modules that were not direct seeds
239
+ node = files_by_id.get(fid)
240
+ hub_factor = 0.65 if (node and node.is_hub) else 1.0
241
+ boost = min(18.0, round(raw_r * 85.0 * hub_factor, 3))
242
+ if boost > 0.05:
243
+ scaled_scores[fid] = boost
244
+ v_mass = verified_contrib.get(fid, 0.0)
245
+ c_mass = candidate_contrib.get(fid, 0.0)
246
+ total_mass = v_mass + c_mass
247
+ if total_mass > 0:
248
+ scaled_verified[fid] = round(boost * (v_mass / total_mass), 3)
249
+ scaled_candidate[fid] = round(boost * (c_mass / total_mass), 3)
250
+
251
+ return GraphPropagationResult(
252
+ scores=scaled_scores,
253
+ verified_boosts=scaled_verified,
254
+ candidate_boosts=scaled_candidate,
255
+ nodes_visited=len(visited),
256
+ hops_used=hops_executed,
257
+ )
258
+
259
+
260
+ def expand_task_terms(task: AgentTask) -> tuple[list[str], set[str]]:
261
+ """Returns (literal_terms, expanded_terms_with_synonyms) for a normalized AgentTask."""
262
+ literal = list(dict.fromkeys(task.search_terms))
263
+ expanded: set[str] = set(literal)
264
+ for term in literal:
265
+ if term in SYNONYM_MAP:
266
+ expanded.update(SYNONYM_MAP[term])
267
+ for sym in task.symbol_names:
268
+ folded = normalize_turkish_fold(sym)
269
+ if folded:
270
+ expanded.add(folded)
271
+ for sub in split_code_tokens(sym):
272
+ expanded.add(sub)
273
+ return literal, expanded
274
+
275
+
276
+ def score_symbol_match(
277
+ sym: SymbolDefinition,
278
+ task: AgentTask,
279
+ literal_terms: list[str],
280
+ ) -> tuple[float, list[str]]:
281
+ """Scores an individual AST symbol against task symbol names, qualified names, and terms."""
282
+ score = 0.0
283
+ reasons: list[str] = []
284
+ sym_name_low = normalize_turkish_fold(sym.name)
285
+ sym_qual_low = normalize_turkish_fold(sym.qualified_name or sym.name)
286
+ sym_tokens = set(split_code_tokens(sym.name))
287
+
288
+ # 1. Exact qualified name match (highest precision)
289
+ for qn in task.qualified_names:
290
+ qn_low = normalize_turkish_fold(qn)
291
+ if sym_qual_low == qn_low or sym_qual_low.endswith(f".{qn_low}") or sym_qual_low.endswith(f"::{qn_low}"):
292
+ score += 42.0
293
+ reasons.append(f"Exact qualified symbol match: {sym.qualified_name}")
294
+ break
295
+
296
+ # 2. Exact symbol name match
297
+ for req_sym in task.symbol_names:
298
+ req_low = normalize_turkish_fold(req_sym)
299
+ if sym_name_low == req_low:
300
+ score += 36.0
301
+ reasons.append(f"Exact AST symbol match: {sym.name}")
302
+ break
303
+ if len(req_low) >= 4 and req_low in sym_name_low:
304
+ score += 14.0
305
+ reasons.append(f"Partial AST symbol match: {sym.name}")
306
+ break
307
+
308
+ # 3. Identifier token overlap
309
+ matched_toks = [t for t in literal_terms if t in sym_tokens and len(t) >= 2]
310
+ if matched_toks:
311
+ score += min(20.0, len(matched_toks) * 5.5)
312
+ reasons.append(f"Symbol token overlap: {', '.join(matched_toks[:3])}")
313
+
314
+ # 4. Exported symbol tie-breaker (small, never overwhelms exact match)
315
+ if score > 0 and sym.is_exported:
316
+ score += 1.5
317
+
318
+ return round(score, 3), reasons