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,518 @@
1
+ """Evidence-backed Hybrid Task Localization Engine for RepoDNA v0.11.0.
2
+
3
+ Combines:
4
+ - Exact file path & stack trace reference matching
5
+ - Exact & qualified AST symbol matching (outweighing comment matches)
6
+ - Identifier-aware BM25 lexical scoring
7
+ - Bounded Personalized PageRank / multi-hop graph propagation (verified vs candidate edges)
8
+ - Entrypoint, static test relationship, architecture contract, quality finding, and live signals
9
+ - Honest abstention when no grounded repository signal matches the task
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from collections import defaultdict
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ from repodna.agent.models import (
19
+ AgentEvidenceReference,
20
+ AgentTask,
21
+ ContextCandidate,
22
+ EvidenceValidationStatus,
23
+ FreshnessMetadata,
24
+ RankExplanation,
25
+ TaskIntent,
26
+ TaskLocalization,
27
+ )
28
+ from repodna.agent.ranking import (
29
+ BM25Index,
30
+ compute_bounded_graph_relevance,
31
+ expand_task_terms,
32
+ score_symbol_match,
33
+ )
34
+ from repodna.agent.safety import sanitize_untrusted_text
35
+ from repodna.agent.task import normalize_turkish_fold, split_code_tokens
36
+ from repodna.brain.indexer import SymbolIndexer
37
+ from repodna.brain.retrieval import EXTENDED_GENERIC_WORDS, SYNONYM_MAP
38
+ from repodna.intelligence.service import RepositoryIntelligenceService
39
+ from repodna.quality.models import QualityReport
40
+ from repodna.schemas.models import AnalysisResult, FileNode
41
+
42
+
43
+ class TaskLocalizationEngine:
44
+ """Deterministic, explainable, evidence-backed task localization engine."""
45
+
46
+ def __init__(
47
+ self,
48
+ analysis: AnalysisResult,
49
+ indexer: SymbolIndexer,
50
+ repo_id: str,
51
+ snapshot_id: str,
52
+ quality_report: QualityReport | None = None,
53
+ live_changed_files: list[str] | None = None,
54
+ live_session_active: bool = False,
55
+ pending_live_analysis: bool = False,
56
+ core_freshness: str = "fresh",
57
+ quality_freshness: str = "not_evaluated",
58
+ ) -> None:
59
+ self.analysis = analysis
60
+ self.indexer = indexer
61
+ self.repo_id = repo_id
62
+ self.snapshot_id = snapshot_id
63
+ self.quality_report = quality_report
64
+ self.live_changed_files = {
65
+ f.replace("\\", "/").lstrip("./") for f in (live_changed_files or [])
66
+ }
67
+ self.live_session_active = live_session_active
68
+ self.pending_live_analysis = pending_live_analysis
69
+ self.core_freshness = core_freshness
70
+ self.quality_freshness = quality_freshness
71
+
72
+ self._files_by_id: dict[str, FileNode] = {f.id: f for f in analysis.files}
73
+ self._bm25 = BM25Index.build(self._files_by_id, self.indexer)
74
+ self._repo_vocab: set[str] = set(self._bm25.doc_freq.keys())
75
+ for fid in self._files_by_id:
76
+ self._repo_vocab.add(normalize_turkish_fold(fid))
77
+ self._repo_vocab.add(normalize_turkish_fold(Path(fid).stem))
78
+
79
+ # Index static test relationships from QualityReport if available
80
+ self._tests_by_prod: dict[str, list[str]] = defaultdict(list)
81
+ self._prod_by_test: dict[str, list[str]] = defaultdict(list)
82
+ self._quality_by_file: dict[str, list[str]] = defaultdict(list)
83
+ if quality_report is not None:
84
+ for entry in quality_report.test_mapping.entries:
85
+ if entry.production_file and entry.mapped_test_files:
86
+ for tf in entry.mapped_test_files:
87
+ if tf not in self._tests_by_prod[entry.production_file]:
88
+ self._tests_by_prod[entry.production_file].append(tf)
89
+ if entry.production_file not in self._prod_by_test[tf]:
90
+ self._prod_by_test[tf].append(entry.production_file)
91
+ for finding in quality_report.findings:
92
+ if finding.file_path:
93
+ self._quality_by_file[finding.file_path].append(finding.finding_id)
94
+
95
+ # Index architecture findings by file
96
+ self._arch_findings_by_file: dict[str, list[str]] = defaultdict(list)
97
+ for arch_f in analysis.health_report.findings:
98
+ for mod_id in arch_f.affected_files:
99
+ self._arch_findings_by_file[mod_id].append(arch_f.rule_id)
100
+
101
+ def _build_freshness(self) -> FreshnessMetadata:
102
+ return FreshnessMetadata(
103
+ repo_id=self.repo_id,
104
+ repository=self.analysis.repo_name,
105
+ snapshot_id=self.snapshot_id,
106
+ revision=self.indexer.revision or "WORKING_TREE",
107
+ core_freshness=self.core_freshness,
108
+ quality_freshness=self.quality_freshness,
109
+ live_session_active=self.live_session_active,
110
+ pending_live_analysis=self.pending_live_analysis,
111
+ )
112
+
113
+ def _should_abstain(self, task: AgentTask, literal_terms: list[str]) -> str | None:
114
+ """Determines whether the task clearly refers to concepts outside repository scope."""
115
+ if task.explicit_file_paths or task.stack_trace_refs:
116
+ return None
117
+ if not literal_terms and not task.symbol_names:
118
+ return "Task contains no actionable identifiers, paths, or search terms."
119
+
120
+ # Check specific domain anchors (>= 4 chars, not generic structural words, and not the repo's own name)
121
+ repo_name_tokens = set(split_code_tokens(self.analysis.repo_name))
122
+ anchors = [
123
+ t
124
+ for t in literal_terms
125
+ if len(t) >= 4 and t not in EXTENDED_GENERIC_WORDS and t not in repo_name_tokens
126
+ ]
127
+ if not anchors:
128
+ return None
129
+
130
+ matched = [
131
+ a
132
+ for a in anchors
133
+ if a in self._repo_vocab
134
+ or any(syn in self._repo_vocab for syn in SYNONYM_MAP.get(a, set()))
135
+ or (len(a) >= 5 and any(v.startswith(a) for v in self._repo_vocab))
136
+ ]
137
+ # Abstain if zero anchors match OR if alien domain terms dominate with weak overlap
138
+ if not matched or (len(anchors) >= 3 and (len(matched) / len(anchors)) < 0.34):
139
+ return (
140
+ f"Insufficient repository signal for task domain anchors ({', '.join(anchors[:5])}). "
141
+ "Abstaining honestly rather than returning unrelated hubs."
142
+ )
143
+ return None
144
+
145
+ def localize(self, task: AgentTask) -> TaskLocalization:
146
+ """Runs deterministic hybrid localization and returns ranked, evidence-backed candidates."""
147
+ freshness = self._build_freshness()
148
+ service = RepositoryIntelligenceService(self.analysis)
149
+ cov = service.get_analysis_coverage()
150
+ coverage_summary: dict[str, Any] = {
151
+ "confidence": cov.confidence,
152
+ "ast_loc_coverage_pct": cov.ast_loc_coverage_pct,
153
+ "ast_file_coverage_pct": cov.ast_file_coverage_pct,
154
+ "supported_languages": cov.supported_languages,
155
+ "partial_static_languages": cov.partial_static_languages,
156
+ "unsupported_languages": cov.unsupported_languages,
157
+ }
158
+ limitations: list[str] = []
159
+ if cov.partial_static_languages:
160
+ limitations.append(
161
+ f"Partial static analysis only for languages: {', '.join(cov.partial_static_languages)}."
162
+ )
163
+ if cov.unsupported_languages:
164
+ limitations.append(
165
+ f"Unsupported languages (file stats only, no AST symbols): {', '.join(cov.unsupported_languages)}."
166
+ )
167
+ if self.pending_live_analysis:
168
+ limitations.append(
169
+ "Live architecture analysis is currently pending; localization reflects the last committed snapshot."
170
+ )
171
+ if self.quality_freshness == "stale":
172
+ limitations.append(
173
+ "Quality findings are stale relative to core architecture snapshot."
174
+ )
175
+
176
+ literal_terms, expanded_terms = expand_task_terms(task)
177
+ abstention_reason = self._should_abstain(task, literal_terms)
178
+ if abstention_reason is not None:
179
+ return TaskLocalization(
180
+ task=task,
181
+ freshness=freshness,
182
+ abstained=True,
183
+ abstention_reason=abstention_reason,
184
+ total_files_evaluated=len(self._files_by_id),
185
+ candidates=[],
186
+ evidence=[],
187
+ coverage_summary=coverage_summary,
188
+ limitations=limitations,
189
+ )
190
+
191
+ # Pre-filter files by constraints (languages, path_prefixes, exclude_paths)
192
+ req_langs = {normalize_turkish_fold(lg) for lg in task.constraints.languages}
193
+ req_prefixes = [p.replace("\\", "/").strip("/") for p in task.constraints.path_prefixes]
194
+ excl_prefixes = [p.replace("\\", "/").strip("/") for p in task.constraints.exclude_paths]
195
+
196
+ all_file_ids = sorted(set(self._files_by_id.keys()) | set(self.indexer._symbols_by_file.keys()))
197
+ filtered_ids: list[str] = []
198
+ for fid in all_file_ids:
199
+ norm_fid = fid.replace("\\", "/").lstrip("/")
200
+ if req_prefixes and not any(
201
+ norm_fid == p or norm_fid.startswith(p + "/") for p in req_prefixes
202
+ ):
203
+ continue
204
+ if excl_prefixes and any(
205
+ norm_fid == p or norm_fid.startswith(p + "/") for p in excl_prefixes
206
+ ):
207
+ continue
208
+ node = self._files_by_id.get(fid)
209
+ if req_langs and node:
210
+ flang = normalize_turkish_fold(node.language)
211
+ # Keep if language matches or if file was explicitly named in task
212
+ if not any(rl in flang or flang in rl for rl in req_langs):
213
+ if norm_fid not in task.explicit_file_paths:
214
+ continue
215
+ filtered_ids.append(fid)
216
+
217
+ # Stage 1: Direct per-file lexical + BM25 + exact path + AST symbol scoring
218
+ direct_scores: dict[str, float] = {}
219
+ stage1_data: dict[str, dict[str, Any]] = {}
220
+
221
+ explicit_path_set = {p.replace("\\", "/").lstrip("./").lower() for p in task.explicit_file_paths}
222
+ stack_file_set = {
223
+ ref.rsplit(":", 1)[0].replace("\\", "/").lstrip("./").lower()
224
+ for ref in task.stack_trace_refs
225
+ }
226
+
227
+ for fid in filtered_ids:
228
+ node = self._files_by_id.get(fid)
229
+ fid_low = fid.replace("\\", "/").lower()
230
+ fid_name = Path(fid_low).name
231
+ fid_tokens = set(split_code_tokens(fid))
232
+ symbols = self.indexer.find_by_file(fid)
233
+
234
+ exact_path_score = 0.0
235
+ structural_evidence: list[str] = []
236
+ matched_terms: list[str] = []
237
+
238
+ # Exact path / stack trace match
239
+ if fid_low in explicit_path_set or any(
240
+ fid_low.endswith("/" + ep) or fid_name == ep for ep in explicit_path_set
241
+ ):
242
+ exact_path_score += 55.0
243
+ structural_evidence.append(f"Explicitly referenced file path: {fid}")
244
+ if fid_low in stack_file_set or any(
245
+ fid_low.endswith("/" + sf) or fid_name == sf for sf in stack_file_set
246
+ ):
247
+ exact_path_score += 45.0
248
+ structural_evidence.append(f"Referenced in stack trace: {fid}")
249
+
250
+ # Path token overlap
251
+ lexical_score = 0.0
252
+ for t in literal_terms:
253
+ if t in fid_tokens:
254
+ lexical_score += 7.0
255
+ matched_terms.append(t)
256
+ elif len(t) >= 4 and t in fid_low:
257
+ lexical_score += 3.5
258
+ matched_terms.append(t)
259
+ for syn in expanded_terms - set(literal_terms):
260
+ if syn in fid_tokens:
261
+ lexical_score += 2.5
262
+
263
+ # BM25 lexical score over path + AST symbol identifiers
264
+ bm25_raw = self._bm25.score(fid, list(expanded_terms))
265
+ bm25_score = min(30.0, round(bm25_raw * 3.2, 3))
266
+
267
+ # AST symbol matching
268
+ exact_symbol_score = 0.0
269
+ matched_syms = []
270
+ for sym in symbols:
271
+ s_score, s_reasons = score_symbol_match(sym, task, literal_terms)
272
+ if s_score > 0:
273
+ matched_syms.append((s_score, sym, s_reasons))
274
+ matched_syms.sort(key=lambda item: (-item[0], item[1].line_start, item[1].name))
275
+ if matched_syms:
276
+ # Top symbol contributes full score; additional symbols add diminishing returns
277
+ exact_symbol_score = round(
278
+ matched_syms[0][0] + sum(ms[0] * 0.2 for ms in matched_syms[1:4]),
279
+ 3,
280
+ )
281
+ for _, _sym, reasons in matched_syms[:3]:
282
+ structural_evidence.extend(reasons[:1])
283
+
284
+ # Entrypoint, test, contract, quality, and live boosts (only if file has some base relevance or task intent specifically requests it)
285
+ base_signal = exact_path_score + lexical_score + bm25_score + exact_symbol_score
286
+
287
+ entrypoint_boost = 0.0
288
+ if node and node.fan_in == 0 and node.fan_out > 0 and base_signal > 0:
289
+ entrypoint_boost = 2.0
290
+
291
+ test_boost = 0.0
292
+ related_tests = self._tests_by_prod.get(fid, [])
293
+ if task.constraints.include_tests and task.intent == TaskIntent.TESTING:
294
+ if fid in self._prod_by_test and base_signal > 0:
295
+ test_boost = 6.0
296
+ structural_evidence.append("Static test file matching task scope")
297
+ elif related_tests and base_signal > 0:
298
+ test_boost = 4.0
299
+ structural_evidence.append(f"Mapped static tests: {len(related_tests)}")
300
+
301
+ contract_boost = 0.0
302
+ arch_rules = self._arch_findings_by_file.get(fid, [])
303
+ if arch_rules and (
304
+ task.intent == TaskIntent.ARCHITECTURE_REVIEW or base_signal > 0
305
+ ):
306
+ contract_boost = 5.0 if task.intent == TaskIntent.ARCHITECTURE_REVIEW else 2.0
307
+ structural_evidence.append(f"Architecture findings: {', '.join(sorted(set(arch_rules))[:3])}")
308
+
309
+ quality_boost = 0.0
310
+ q_findings = self._quality_by_file.get(fid, [])
311
+ if task.constraints.include_quality_findings and q_findings and base_signal > 0:
312
+ if task.intent in (TaskIntent.REFACTOR, TaskIntent.PERFORMANCE, TaskIntent.SECURITY_REVIEW, TaskIntent.BUG_FIX):
313
+ quality_boost = min(5.0, 1.5 * len(q_findings))
314
+ structural_evidence.append(f"Quality findings present: {len(q_findings)}")
315
+
316
+ live_boost = 0.0
317
+ if task.constraints.include_live_signals and fid in self.live_changed_files and base_signal > 0:
318
+ live_boost = 5.5
319
+ structural_evidence.append("Recently modified in active working tree")
320
+
321
+ # Hub damping: if a hub only matched weak generic terms (no exact path or exact symbol), dampen it
322
+ hub_damping = 0.0
323
+ if node and node.is_hub and exact_path_score == 0 and exact_symbol_score < 15.0 and base_signal > 0:
324
+ hub_damping = round(min(6.0, base_signal * 0.25), 3)
325
+
326
+ total_stage1 = max(
327
+ 0.0,
328
+ round(
329
+ base_signal
330
+ + entrypoint_boost
331
+ + test_boost
332
+ + contract_boost
333
+ + quality_boost
334
+ + live_boost
335
+ - hub_damping,
336
+ 3,
337
+ ),
338
+ )
339
+ if total_stage1 > 0:
340
+ direct_scores[fid] = total_stage1
341
+ stage1_data[fid] = {
342
+ "exact_path_score": exact_path_score,
343
+ "lexical_score": round(lexical_score, 3),
344
+ "bm25_score": bm25_score,
345
+ "exact_symbol_score": exact_symbol_score,
346
+ "entrypoint_boost": entrypoint_boost,
347
+ "test_boost": test_boost,
348
+ "contract_boost": contract_boost,
349
+ "quality_boost": quality_boost,
350
+ "live_boost": live_boost,
351
+ "hub_damping": hub_damping,
352
+ "matched_terms": sorted(set(matched_terms)),
353
+ "matched_syms": [sym for _, sym, _ in matched_syms[:6]],
354
+ "structural_evidence": structural_evidence,
355
+ "related_tests": related_tests[:8],
356
+ "quality_findings": q_findings[:8],
357
+ }
358
+
359
+ # Stage 2: Bounded Personalized PageRank / multi-hop graph propagation
360
+ graph_res = compute_bounded_graph_relevance(
361
+ seed_scores=direct_scores,
362
+ analysis=self.analysis,
363
+ indexer=self.indexer,
364
+ max_hops=task.constraints.max_graph_hops,
365
+ )
366
+
367
+ # Merge stage 1 and graph propagation candidates
368
+ candidate_fids = sorted(set(direct_scores.keys()) | set(graph_res.scores.keys()))
369
+ scored_rows: list[tuple[float, int, int, str, ContextCandidate]] = []
370
+ evidence_by_id: dict[str, AgentEvidenceReference] = {}
371
+
372
+ for fid in candidate_fids:
373
+ node = self._files_by_id.get(fid)
374
+ s1 = stage1_data.get(fid)
375
+ g_score = graph_res.scores.get(fid, 0.0)
376
+ v_boost = graph_res.verified_boosts.get(fid, 0.0)
377
+ c_boost = graph_res.candidate_boosts.get(fid, 0.0)
378
+
379
+ base_s = direct_scores.get(fid, 0.0)
380
+ total_score = round(base_s + g_score, 3)
381
+ if total_score < 2.0:
382
+ continue
383
+
384
+ matched_syms_list: list[Any] = s1["matched_syms"] if s1 else []
385
+ structural_ev = list(s1["structural_evidence"]) if s1 else []
386
+ if g_score > 0:
387
+ structural_ev.append(
388
+ f"Bounded graph proximity (+{g_score:.2f}; verified={v_boost:.2f}, candidate={c_boost:.2f})"
389
+ )
390
+
391
+ # Confidence tier
392
+ if (s1 and (s1["exact_path_score"] > 0 or s1["exact_symbol_score"] >= 30.0)) or total_score >= 40.0:
393
+ conf = "high"
394
+ elif total_score >= 15.0:
395
+ conf = "medium"
396
+ else:
397
+ conf = "low"
398
+
399
+ # Attach verified evidence references from SymbolIndexer / EvidenceLedger
400
+ cand_ev_ids: list[str] = []
401
+ for m_sym in matched_syms_list[:4]:
402
+ if m_sym.evidence_id:
403
+ ev_obj = self.indexer.ledger.get_by_id(m_sym.evidence_id)
404
+ if ev_obj is not None:
405
+ cand_ev_ids.append(ev_obj.evidence_id)
406
+ if ev_obj.evidence_id not in evidence_by_id:
407
+ safe_snip, _, _ = sanitize_untrusted_text(ev_obj.code_snippet or "")
408
+ evidence_by_id[ev_obj.evidence_id] = AgentEvidenceReference(
409
+ evidence_id=ev_obj.evidence_id,
410
+ repo_id=self.repo_id,
411
+ snapshot_id=self.snapshot_id,
412
+ revision=ev_obj.repository_revision,
413
+ file_path=ev_obj.file_path,
414
+ line_start=ev_obj.line_start,
415
+ line_end=ev_obj.line_end,
416
+ evidence_type=ev_obj.evidence_type.value,
417
+ symbol_name=ev_obj.symbol_name,
418
+ content_hash=ev_obj.content_hash or "",
419
+ snippet=safe_snip,
420
+ capability_level=ev_obj.support_level.value,
421
+ status=(
422
+ EvidenceValidationStatus.STALE
423
+ if ev_obj.is_stale
424
+ else EvidenceValidationStatus.VERIFIED
425
+ ),
426
+ staleness_reason=ev_obj.staleness_reason.value,
427
+ confidence_reason=ev_obj.confidence_reason,
428
+ )
429
+
430
+ explanation = RankExplanation(
431
+ relevance_score=total_score,
432
+ lexical_score=s1["lexical_score"] if s1 else 0.0,
433
+ bm25_score=s1["bm25_score"] if s1 else 0.0,
434
+ exact_path_score=s1["exact_path_score"] if s1 else 0.0,
435
+ exact_symbol_score=s1["exact_symbol_score"] if s1 else 0.0,
436
+ graph_proximity_score=g_score,
437
+ verified_edge_boost=v_boost,
438
+ candidate_edge_boost=c_boost,
439
+ entrypoint_boost=s1["entrypoint_boost"] if s1 else 0.0,
440
+ test_relevance_boost=s1["test_boost"] if s1 else 0.0,
441
+ contract_relevance_boost=s1["contract_boost"] if s1 else 0.0,
442
+ quality_relevance_boost=s1["quality_boost"] if s1 else 0.0,
443
+ live_change_boost=s1["live_boost"] if s1 else 0.0,
444
+ hub_damping_applied=s1["hub_damping"] if s1 else 0.0,
445
+ matched_task_terms=s1["matched_terms"] if s1 else [],
446
+ matched_symbols=[m_sym.name for m_sym in matched_syms_list],
447
+ structural_evidence=structural_ev[:6],
448
+ confidence=conf,
449
+ explanation_summary="; ".join(structural_ev[:3]) or "Lexical/BM25 relevance match",
450
+ )
451
+
452
+ cand = ContextCandidate(
453
+ file_id=fid,
454
+ language=node.language if node else "",
455
+ lines_code=node.lines_code if node else 0,
456
+ fan_in=node.fan_in if node else 0,
457
+ fan_out=node.fan_out if node else 0,
458
+ instability=node.instability if node else 0.0,
459
+ is_hub=node.is_hub if node else False,
460
+ in_cycle=node.in_cycle if node else False,
461
+ rank=1, # Assigned after deterministic sort
462
+ score=total_score,
463
+ explanation=explanation,
464
+ matched_symbol_ids=[m_sym.id for m_sym in matched_syms_list],
465
+ matched_symbol_names=[m_sym.name for m_sym in matched_syms_list],
466
+ matched_symbol_signatures=[
467
+ (m_sym.signature or f"{m_sym.kind.value} {m_sym.name}") for m_sym in matched_syms_list
468
+ ],
469
+ related_tests=s1["related_tests"] if s1 else self._tests_by_prod.get(fid, [])[:8],
470
+ quality_finding_ids=s1["quality_findings"] if s1 else self._quality_by_file.get(fid, [])[:8],
471
+ evidence_ids=cand_ev_ids,
472
+ )
473
+
474
+ has_exact = 1 if (s1 and (s1["exact_path_score"] > 0 or s1["exact_symbol_score"] >= 30.0)) else 0
475
+ scored_rows.append((total_score, has_exact, len(cand_ev_ids), fid, cand))
476
+
477
+ # Deterministic sort: score desc, exact match desc, verified evidence count desc, file_id asc
478
+ scored_rows.sort(key=lambda r: (-r[0], -r[1], -r[2], r[3]))
479
+
480
+ limit = task.constraints.max_candidates
481
+ top_candidates: list[ContextCandidate] = []
482
+ used_evidence_ids: set[str] = set()
483
+ for idx, (_, _, _, _, cand) in enumerate(scored_rows[:limit], 1):
484
+ cand.rank = idx
485
+ top_candidates.append(cand)
486
+ used_evidence_ids.update(cand.evidence_ids)
487
+
488
+ if not top_candidates:
489
+ return TaskLocalization(
490
+ task=task,
491
+ freshness=freshness,
492
+ abstained=True,
493
+ abstention_reason="No candidates met the minimum grounded relevance threshold.",
494
+ total_files_evaluated=len(filtered_ids),
495
+ graph_nodes_visited=graph_res.nodes_visited,
496
+ graph_hops_used=graph_res.hops_used,
497
+ candidates=[],
498
+ evidence=[],
499
+ coverage_summary=coverage_summary,
500
+ limitations=limitations,
501
+ )
502
+
503
+ selected_evidence = [
504
+ evidence_by_id[eid] for eid in sorted(used_evidence_ids) if eid in evidence_by_id
505
+ ]
506
+
507
+ return TaskLocalization(
508
+ task=task,
509
+ freshness=freshness,
510
+ abstained=False,
511
+ total_files_evaluated=len(filtered_ids),
512
+ graph_nodes_visited=graph_res.nodes_visited,
513
+ graph_hops_used=graph_res.hops_used,
514
+ candidates=top_candidates,
515
+ evidence=selected_evidence,
516
+ coverage_summary=coverage_summary,
517
+ limitations=limitations,
518
+ )