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,447 @@
1
+ """Progressive Context Expansion Engine for RepoDNA v0.11.0.
2
+
3
+ Allows an AI agent to expand specific targets on demand (file, symbol, evidence,
4
+ dependency path, finding, test relationship, architecture rule, live change) while
5
+ re-validating repository boundary, snapshot freshness, cursor integrity, secret
6
+ redaction, and token budget on every call.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ from collections import deque
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ from repodna.agent.context import (
17
+ decode_and_validate_cursor,
18
+ make_content_addressable_block,
19
+ )
20
+ from repodna.agent.models import (
21
+ AgentEvidenceReference,
22
+ ContextBlock,
23
+ ContextExpansionRequest,
24
+ ContextExpansionResponse,
25
+ EvidenceValidationStatus,
26
+ ExpansionTargetType,
27
+ FreshnessMetadata,
28
+ )
29
+ from repodna.agent.safety import build_trust_boundary, sanitize_untrusted_text, sha256_short
30
+ from repodna.agent.token_budget import build_context_budget, clamp_token_budget
31
+ from repodna.brain.evidence import extract_evidence_snippet
32
+ from repodna.brain.indexer import SymbolIndexer
33
+ from repodna.quality.models import QualityReport
34
+ from repodna.schemas.models import AnalysisResult
35
+ from repodna.security.validators import SecurityValidationError, safe_read_evidence_file
36
+
37
+
38
+ class ProgressiveContextExpander:
39
+ """Bounded, re-validated progressive context disclosure engine."""
40
+
41
+ def __init__(
42
+ self,
43
+ repo_root: Path | None,
44
+ analysis: AnalysisResult,
45
+ indexer: SymbolIndexer,
46
+ repo_id: str,
47
+ snapshot_id: str,
48
+ quality_report: QualityReport | None = None,
49
+ live_changed_files: list[str] | None = None,
50
+ core_freshness: str = "fresh",
51
+ quality_freshness: str = "not_evaluated",
52
+ live_session_active: bool = False,
53
+ pending_live_analysis: bool = False,
54
+ ) -> None:
55
+ self.repo_root = repo_root.resolve() if repo_root else None
56
+ self.analysis = analysis
57
+ self.indexer = indexer
58
+ self.repo_id = repo_id
59
+ self.snapshot_id = snapshot_id
60
+ self.quality_report = quality_report
61
+ self.live_changed_files = [
62
+ f.replace("\\", "/").lstrip("./") for f in (live_changed_files or [])
63
+ ]
64
+ self.core_freshness = core_freshness
65
+ self.quality_freshness = quality_freshness
66
+ self.live_session_active = live_session_active
67
+ self.pending_live_analysis = pending_live_analysis
68
+ self._files_by_id = {f.id: f for f in analysis.files}
69
+
70
+ def _freshness(self) -> FreshnessMetadata:
71
+ return FreshnessMetadata(
72
+ repo_id=self.repo_id,
73
+ repository=self.analysis.repo_name,
74
+ snapshot_id=self.snapshot_id,
75
+ revision=self.indexer.revision or "WORKING_TREE",
76
+ core_freshness=self.core_freshness,
77
+ quality_freshness=self.quality_freshness,
78
+ live_session_active=self.live_session_active,
79
+ pending_live_analysis=self.pending_live_analysis,
80
+ )
81
+
82
+ def _error_response(
83
+ self,
84
+ req: ContextExpansionRequest,
85
+ status: str,
86
+ message: str,
87
+ ) -> ContextExpansionResponse:
88
+ clamped = clamp_token_budget(req.token_budget)
89
+ payload = json.dumps({"status": status, "message": message}, sort_keys=True)
90
+ budget = build_context_budget(
91
+ serialized_payload=payload,
92
+ requested_budget=clamped,
93
+ required_minimum_budget=16,
94
+ tokenizer_pref=req.tokenizer,
95
+ )
96
+ return ContextExpansionResponse(
97
+ target_type=req.target_type,
98
+ target_id=req.target_id,
99
+ status=status,
100
+ freshness=self._freshness(),
101
+ budget=budget,
102
+ message=message,
103
+ )
104
+
105
+ def expand(self, req: ContextExpansionRequest) -> ContextExpansionResponse:
106
+ """Expands a single bounded target after verifying scope, snapshot, and cursor."""
107
+ # 1. Snapshot identity check (if caller pinned a snapshot)
108
+ if req.snapshot_id and req.snapshot_id != self.snapshot_id:
109
+ return self._error_response(
110
+ req,
111
+ "stale",
112
+ f"Requested snapshot '{req.snapshot_id}' is stale; current snapshot is '{self.snapshot_id}'.",
113
+ )
114
+
115
+ # 2. Cursor validation (if provided)
116
+ if req.cursor:
117
+ _, c_status = decode_and_validate_cursor(
118
+ req.cursor,
119
+ expected_repo_id=self.repo_id,
120
+ expected_snapshot_id=self.snapshot_id,
121
+ )
122
+ if c_status != "ok":
123
+ return self._error_response(
124
+ req,
125
+ c_status,
126
+ f"Continuation cursor rejected with status '{c_status}'.",
127
+ )
128
+
129
+ clamped_budget = clamp_token_budget(req.token_budget)
130
+ blocks: list[ContextBlock] = []
131
+ evidence_out: list[AgentEvidenceReference] = []
132
+ redacted_count = 0
133
+ injection_signals: list[str] = []
134
+
135
+ target_id = req.target_id.strip()
136
+
137
+ if req.target_type == ExpansionTargetType.FILE:
138
+ raw_norm = target_id.replace("\\", "/")
139
+ if ".." in raw_norm.split("/") or raw_norm.startswith("/") or (len(raw_norm) >= 2 and raw_norm[1] == ":"):
140
+ return self._error_response(req, "scope_violation", "Path traversal or absolute path rejected.")
141
+ norm_path = raw_norm
142
+ while norm_path.startswith("./"):
143
+ norm_path = norm_path[2:]
144
+ node = self._files_by_id.get(norm_path)
145
+ if node is None:
146
+ return self._error_response(req, "unavailable", f"File '{norm_path}' not found in repository snapshot.")
147
+ snippet = ""
148
+ if self.repo_root is not None:
149
+ try:
150
+ raw_text, _, file_exists = safe_read_evidence_file(self.repo_root, norm_path)
151
+ if not file_exists:
152
+ snippet = "[File unreadable on disk]"
153
+ else:
154
+ raw_snip, _ = extract_evidence_snippet(raw_text, 1, req.max_lines, max_lines=req.max_lines)
155
+ snippet, sec_c, inj_s = sanitize_untrusted_text(raw_snip)
156
+ redacted_count += sec_c
157
+ injection_signals.extend(inj_s)
158
+ except SecurityValidationError as exc:
159
+ return self._error_response(req, "scope_violation", exc.message)
160
+ except OSError:
161
+ snippet = "[File unreadable on disk]"
162
+ syms = self.indexer.find_by_file(norm_path)[:20]
163
+ blocks.append(
164
+ make_content_addressable_block(
165
+ block_type="file_expansion",
166
+ scope=norm_path,
167
+ snapshot_id=self.snapshot_id,
168
+ priority=90,
169
+ payload={
170
+ "file_id": norm_path,
171
+ "language": node.language,
172
+ "lines_code": node.lines_code,
173
+ "fan_in": node.fan_in,
174
+ "fan_out": node.fan_out,
175
+ "imports_internal": node.imports_internal[:20],
176
+ "imported_by": node.imported_by[:20],
177
+ "symbols": [
178
+ {"id": s.id, "name": s.name, "kind": s.kind.value, "line": s.line_start}
179
+ for s in syms
180
+ ],
181
+ "bounded_excerpt": snippet,
182
+ },
183
+ tokenizer_pref=req.tokenizer,
184
+ )
185
+ )
186
+
187
+ elif req.target_type == ExpansionTargetType.SYMBOL:
188
+ sym = self.indexer._symbols_by_id.get(target_id)
189
+ if sym is None:
190
+ matches = self.indexer._symbols_by_name_lower.get(target_id.lower(), [])
191
+ if matches:
192
+ sym = matches[0]
193
+ if sym is None:
194
+ return self._error_response(req, "unavailable", f"Symbol '{target_id}' not found in index.")
195
+ snippet = ""
196
+ if self.repo_root is not None:
197
+ try:
198
+ raw_text, _, file_exists = safe_read_evidence_file(self.repo_root, sym.file_path)
199
+ if file_exists:
200
+ span_end = min(sym.line_end, sym.line_start + req.max_lines - 1)
201
+ raw_snip, _ = extract_evidence_snippet(raw_text, sym.line_start, span_end, max_lines=req.max_lines)
202
+ snippet, sec_c, inj_s = sanitize_untrusted_text(raw_snip)
203
+ redacted_count += sec_c
204
+ injection_signals.extend(inj_s)
205
+ except SecurityValidationError as exc:
206
+ return self._error_response(req, "scope_violation", exc.message)
207
+ except OSError:
208
+ snippet = ""
209
+ blocks.append(
210
+ make_content_addressable_block(
211
+ block_type="symbol_expansion",
212
+ scope=sym.id,
213
+ snapshot_id=self.snapshot_id,
214
+ priority=90,
215
+ evidence_ids=[sym.evidence_id] if sym.evidence_id else [],
216
+ payload={
217
+ "symbol_id": sym.id,
218
+ "name": sym.name,
219
+ "qualified_name": sym.qualified_name or sym.name,
220
+ "kind": sym.kind.value,
221
+ "file_path": sym.file_path,
222
+ "line_start": sym.line_start,
223
+ "line_end": sym.line_end,
224
+ "signature": sym.signature or "",
225
+ "verified_references": [
226
+ {"file": r.target_file_path or r.file_path, "symbol": r.symbol_name, "line": r.line}
227
+ for r in sym.verified_references[:12]
228
+ ],
229
+ "candidate_references": [
230
+ {"file": r.target_file_path or r.file_path, "symbol": r.symbol_name, "line": r.line}
231
+ for r in sym.candidate_references[:8]
232
+ ],
233
+ "bounded_excerpt": snippet,
234
+ },
235
+ tokenizer_pref=req.tokenizer,
236
+ )
237
+ )
238
+
239
+ elif req.target_type == ExpansionTargetType.EVIDENCE:
240
+ ev = self.indexer.ledger.get_by_id(target_id)
241
+ if ev is None:
242
+ return self._error_response(req, "unavailable", f"Evidence '{target_id}' not found in current snapshot ledger.")
243
+ status_val = EvidenceValidationStatus.VERIFIED
244
+ staleness_reason = ev.staleness_reason.value
245
+ if self.repo_root is not None:
246
+ try:
247
+ disk_text, _, file_exists = safe_read_evidence_file(self.repo_root, ev.file_path)
248
+ if not file_exists:
249
+ status_val = EvidenceValidationStatus.UNAVAILABLE
250
+ staleness_reason = "FILE_DELETED"
251
+ else:
252
+ self.indexer.ledger.check_staleness(ev.file_path, disk_text, self.indexer.revision)
253
+ staleness_reason = ev.staleness_reason.value
254
+ if ev.is_stale:
255
+ status_val = EvidenceValidationStatus.STALE
256
+ except SecurityValidationError as exc:
257
+ return self._error_response(req, "scope_violation", exc.message)
258
+ except OSError:
259
+ status_val = EvidenceValidationStatus.UNAVAILABLE
260
+ staleness_reason = "FILE_DELETED"
261
+ safe_snip, sec_c, inj_s = sanitize_untrusted_text(ev.code_snippet or "")
262
+ redacted_count += sec_c
263
+ injection_signals.extend(inj_s)
264
+ ev_ref = AgentEvidenceReference(
265
+ evidence_id=ev.evidence_id,
266
+ repo_id=self.repo_id,
267
+ snapshot_id=self.snapshot_id,
268
+ revision=ev.repository_revision,
269
+ file_path=ev.file_path,
270
+ line_start=ev.line_start,
271
+ line_end=ev.line_end,
272
+ evidence_type=ev.evidence_type.value,
273
+ symbol_name=ev.symbol_name,
274
+ content_hash=ev.content_hash or "",
275
+ redacted=sec_c > 0,
276
+ redacted_snippet_hash=sha256_short(safe_snip, 16) if sec_c > 0 else None,
277
+ snippet=safe_snip,
278
+ capability_level=ev.support_level.value,
279
+ status=status_val,
280
+ staleness_reason=staleness_reason,
281
+ confidence_reason=ev.confidence_reason,
282
+ )
283
+ evidence_out.append(ev_ref)
284
+ if status_val == EvidenceValidationStatus.STALE:
285
+ return ContextExpansionResponse(
286
+ target_type=req.target_type,
287
+ target_id=target_id,
288
+ status="stale",
289
+ freshness=self._freshness(),
290
+ budget=build_context_budget(
291
+ ev_ref.model_dump_json(), clamped_budget, 32, tokenizer_pref=req.tokenizer
292
+ ),
293
+ trust_boundary=build_trust_boundary(redacted_count, injection_signals),
294
+ evidence=evidence_out,
295
+ message=f"Evidence '{target_id}' is STALE ({staleness_reason}).",
296
+ )
297
+ blocks.append(
298
+ make_content_addressable_block(
299
+ block_type="evidence_expansion",
300
+ scope=ev.evidence_id,
301
+ snapshot_id=self.snapshot_id,
302
+ priority=95,
303
+ evidence_ids=[ev.evidence_id],
304
+ payload=ev_ref.model_dump(mode="json"),
305
+ tokenizer_pref=req.tokenizer,
306
+ )
307
+ )
308
+
309
+ elif req.target_type == ExpansionTargetType.DEPENDENCY_PATH:
310
+ parts = [p.strip().replace("\\", "/").lstrip("./") for p in target_id.split("->")]
311
+ if len(parts) != 2 or parts[0] not in self._files_by_id or parts[1] not in self._files_by_id:
312
+ return self._error_response(
313
+ req,
314
+ "unavailable",
315
+ "Dependency path target must be 'source_file->target_file' within repository.",
316
+ )
317
+ src, dst = parts
318
+ # Bounded BFS up to 6 hops
319
+ q: deque[list[str]] = deque([[src]])
320
+ seen: set[str] = {src}
321
+ found_path: list[str] | None = None
322
+ while q:
323
+ path = q.popleft()
324
+ if len(path) > 7:
325
+ continue
326
+ curr = path[-1]
327
+ if curr == dst:
328
+ found_path = path
329
+ break
330
+ node = self._files_by_id.get(curr)
331
+ if node:
332
+ for nxt in sorted(node.imports_internal):
333
+ if nxt not in seen:
334
+ seen.add(nxt)
335
+ q.append([*path, nxt])
336
+ blocks.append(
337
+ make_content_addressable_block(
338
+ block_type="dependency_path",
339
+ scope=f"{src}->{dst}",
340
+ snapshot_id=self.snapshot_id,
341
+ priority=85,
342
+ payload={"source": src, "target": dst, "path": found_path, "reachable": found_path is not None},
343
+ tokenizer_pref=req.tokenizer,
344
+ )
345
+ )
346
+
347
+ elif req.target_type == ExpansionTargetType.FINDING:
348
+ found_payload: dict[str, Any] | None = None
349
+ if self.quality_report is not None:
350
+ for qf in self.quality_report.findings:
351
+ if qf.finding_id == target_id or qf.rule_id == target_id:
352
+ found_payload = qf.model_dump(mode="json")
353
+ break
354
+ if found_payload is None:
355
+ for af in self.analysis.health_report.findings:
356
+ if af.rule_id == target_id:
357
+ found_payload = af.model_dump(mode="json")
358
+ break
359
+ if found_payload is None:
360
+ return self._error_response(req, "unavailable", f"Finding '{target_id}' not found.")
361
+ blocks.append(
362
+ make_content_addressable_block(
363
+ block_type="finding_expansion",
364
+ scope=target_id,
365
+ snapshot_id=self.snapshot_id,
366
+ priority=85,
367
+ payload=found_payload,
368
+ tokenizer_pref=req.tokenizer,
369
+ )
370
+ )
371
+
372
+ elif req.target_type == ExpansionTargetType.TEST_RELATIONSHIP:
373
+ norm_path = target_id.replace("\\", "/").lstrip("./")
374
+ entries: list[dict[str, Any]] = []
375
+ if self.quality_report is not None:
376
+ for entry in self.quality_report.test_mapping.entries:
377
+ if entry.production_file == norm_path or norm_path in entry.mapped_test_files:
378
+ entries.append(entry.model_dump(mode="json"))
379
+ if not entries:
380
+ return self._error_response(req, "unavailable", f"No static test relationships found for '{norm_path}'.")
381
+ blocks.append(
382
+ make_content_addressable_block(
383
+ block_type="test_relationship_expansion",
384
+ scope=norm_path,
385
+ snapshot_id=self.snapshot_id,
386
+ priority=80,
387
+ payload={
388
+ "note": "Static AST/naming relationships only (not runtime test coverage).",
389
+ "entries": entries[:15],
390
+ },
391
+ tokenizer_pref=req.tokenizer,
392
+ )
393
+ )
394
+
395
+ elif req.target_type == ExpansionTargetType.ARCHITECTURE_RULE:
396
+ rule_findings = [
397
+ af.model_dump(mode="json")
398
+ for af in self.analysis.health_report.findings
399
+ if af.rule_id == target_id
400
+ ]
401
+ if not rule_findings:
402
+ return self._error_response(req, "unavailable", f"Architecture rule '{target_id}' has no active findings.")
403
+ blocks.append(
404
+ make_content_addressable_block(
405
+ block_type="architecture_rule_expansion",
406
+ scope=target_id,
407
+ snapshot_id=self.snapshot_id,
408
+ priority=85,
409
+ payload={"rule_id": target_id, "findings": rule_findings[:10]},
410
+ tokenizer_pref=req.tokenizer,
411
+ )
412
+ )
413
+
414
+ elif req.target_type == ExpansionTargetType.LIVE_CHANGE:
415
+ blocks.append(
416
+ make_content_addressable_block(
417
+ block_type="live_change_expansion",
418
+ scope=target_id or "live",
419
+ snapshot_id=self.snapshot_id,
420
+ priority=80,
421
+ payload={
422
+ "live_session_active": self.live_session_active,
423
+ "pending_live_analysis": self.pending_live_analysis,
424
+ "changed_files": self.live_changed_files[:20],
425
+ },
426
+ tokenizer_pref=req.tokenizer,
427
+ )
428
+ )
429
+
430
+ serialized = json.dumps([b.model_dump(mode="json") for b in blocks], sort_keys=True)
431
+ budget = build_context_budget(
432
+ serialized_payload=serialized,
433
+ requested_budget=clamped_budget,
434
+ required_minimum_budget=32,
435
+ tokenizer_pref=req.tokenizer,
436
+ )
437
+ return ContextExpansionResponse(
438
+ target_type=req.target_type,
439
+ target_id=target_id,
440
+ status="ok",
441
+ freshness=self._freshness(),
442
+ budget=budget,
443
+ trust_boundary=build_trust_boundary(redacted_count, injection_signals),
444
+ blocks=blocks,
445
+ evidence=evidence_out,
446
+ message="Expanded target successfully.",
447
+ )