Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(mcp): make relationship and history caps recoverable (#1930)
Raghav Chamadiyaed60dcf6194b
diff --git a/packages/server/src/repowise/server/mcp_server/_budget/__init__.py b/packages/server/src/repowise/server/mcp_server/_budget/__init__.pyindex a1c249e5c..681bac84c 100644--- a/packages/server/src/repowise/server/mcp_server/_budget/__init__.py+++ b/packages/server/src/repowise/server/mcp_server/_budget/__init__.py@@ -33,7 +33,7 @@ from repowise.server.mcp_server._budget.budgeter import (over_budget,truncate_to_budget,)-from repowise.server.mcp_server._budget.collector import OmissionCollector+from repowise.server.mcp_server._budget.collector import OmissionCollector, cap_collectionfrom repowise.server.mcp_server._budget.contracts import (DEFAULT_RESPONSE_CHARS,EXPANDED_RESPONSE_CHARS,@@ -53,6 +53,7 @@ __all__ = ["TOKEN_BUDGET","OmissionCollector","budgeted_tool_names",+ "cap_collection","effective_char_budget","enforce_response_budget","estimate_response_tokens",diff --git a/packages/server/src/repowise/server/mcp_server/_budget/budgeter.py b/packages/server/src/repowise/server/mcp_server/_budget/budgeter.pyindex 10bfa502a..83e590ab0 100644--- a/packages/server/src/repowise/server/mcp_server/_budget/budgeter.py+++ b/packages/server/src/repowise/server/mcp_server/_budget/budgeter.py@@ -203,10 +203,10 @@ def _shed_tail(container[f"{leaf}_emitted"] = len(rows)container[f"{leaf}_reduced_reason"] = _with_budget_reason(prior_reason)container[f"{leaf}_truncated"] = True- # The omission reference persists only rows dropped by this pass.- # Earlier projection reductions remain visible in total/emitted and- # their combined reason, but are not falsely advertised as stored.- container[f"{leaf}_omitted"] = len(dropped)+ # Construction and delivery collectors both advertise their refs+ # on the final response, so omitted is the complete recoverable+ # population difference across both passes.+ container[f"{leaf}_omitted"] = collection_total - len(rows)response["truncated"] = True@@ -227,7 +227,7 @@ def _record_reduction(container[f"{field}_emitted"] = emittedcontainer[f"{field}_reduced_reason"] = _with_budget_reason(prior_reason)container[f"{field}_truncated"] = True- container[f"{field}_omitted"] = len(value)+ container[f"{field}_omitted"] = total - emittedreturnif not isinstance(value, dict):returndiff --git a/packages/server/src/repowise/server/mcp_server/_budget/collector.py b/packages/server/src/repowise/server/mcp_server/_budget/collector.pyindex 0ba65d71c..64f35ff4d 100644--- a/packages/server/src/repowise/server/mcp_server/_budget/collector.py+++ b/packages/server/src/repowise/server/mcp_server/_budget/collector.py@@ -1,24 +1,12 @@"""OmissionCollector — reversible drops for MCP tool responses.-When a tool trims its response to fit the transport budget, the dropped-content is handed to a collector instead of vanishing. The collector persists-it to the same durable omission store the CLI/hook surfaces use-(``.repowise/omissions/omissions.db``) and stamps the response with the-standard ``[repowise#<ref>]`` marker plus a ``_meta.omitted`` block, so any-truncation an agent sees is recoverable:--* ``repowise expand <ref>`` from a shell, or-* ``get_symbol("repowise#<ref>")`` for shell-less MCP clients.--Failure posture mirrors the distill engine: the store is best-effort. If a-write fails, the tool falls back to the pre-existing silent-drop behaviour —-a degraded response is always preferred over a failed one. Content is stored-BEFORE any marker is rendered, so a marker can never dangle.--Lifecycle: the underlying SQLite handle is opened lazily on the first drop-and closed in :meth:`attach`. The MCP server is long-running, but truncation-events are rare and writes are small, so open-per-event avoids holding a WAL-handle that would contend with hook-side writers between events.+Dropped content is persisted to the same durable omission store used by the+CLI and advertised through ``_meta.omitted``. Clients recover it with either+``repowise expand <ref>`` or ``get_symbol("repowise#<ref>")``.++The store is best-effort. A failed write returns the reduced tool response with+an explicit ``_meta.recovery_unavailable`` warning and never advertises a dead+reference. The SQLite handle opens lazily and closes in :meth:`attach`."""from __future__ import annotations@@ -43,9 +31,6 @@ _RESTORE_HINT = ()_DOC_SECTION_RULE = "==== {label} ===="-_OMISSION_DOC_CHARS = 28_000--def render_chunk(label: str, value: Any) -> str:"""Render one dropped value as line-oriented text for the omission doc.@@ -57,6 +42,55 @@ def render_chunk(label: str, value: Any) -> str:return json.dumps(value, indent=1, default=str)+def cap_collection(+ container: dict[str, Any],+ key: str,+ population: list[Any],+ limit: int,+ collector: OmissionCollector | None = None,+ *,+ emitted: list[Any] | None = None,+ label: str | None = None,+ reason: str = "construction_cap",+ preserve_counts: bool = False,+) -> list[Any]:+ """Keep a deterministic head while making every real reduction recoverable.++ ``population`` is the complete post-policy population. ``emitted`` may+ supply a deliberately diversified projection (for example, retaining one+ transitive dependent beside direct ones); omitted rows are then computed as+ a stable multiset difference instead of assuming a simple tail.++ Small collections stay compact unless ``preserve_counts`` keeps an existing+ public count family. A reduced collection always receives the shared+ total/emitted/reason fields plus compatibility truncation counts, and its+ exact omitted rows are queued on the caller's :class:`OmissionCollector`.+ """+ full = list(population)+ visible = list(emitted) if emitted is not None else full[:limit]+ container[key] = visible+ total = len(full)+ emitted_count = len(visible)+ reduced = emitted_count < total++ if preserve_counts or reduced:+ container[f"{key}_total"] = total+ container[f"{key}_emitted"] = emitted_count+ container[f"{key}_truncated"] = reduced+ if not reduced:+ return visible++ remaining = list(full)+ for row in visible:+ with contextlib.suppress(ValueError):+ remaining.remove(row)+ container[f"{key}_reduced_reason"] = reason+ container[f"{key}_omitted"] = len(remaining)+ if collector is not None and remaining:+ collector.add(label or f"{key} beyond cap={limit}", remaining)+ return visible++class OmissionCollector:"""Collects content dropped from one MCP tool response.@@ -85,7 +119,10 @@ class OmissionCollector:self._store_path = Path(store_path)else:self._store_path = default_store_path(Path(repo_root) if repo_root else None)- self._chunks: list[tuple[str, str]] = []+ # Keep values live until attach. Why-mode evidence annotation happens+ # after ranking but before delivery; eagerly rendering here would freeze+ # omitted rows before they receive provenance and evidence refs.+ self._chunks: list[tuple[str, Any]] = []self._refs: list[str] = []self._omitted_tokens = 0self._store: OmissionStore | None = None@@ -95,9 +132,8 @@ class OmissionCollector:def add(self, label: str, value: Any) -> None:"""Queue a dropped chunk for the combined omission document."""- text = render_chunk(label, value)- if text:- self._chunks.append((label, text))+ if value is not None:+ self._chunks.append((label, value))def add_inline(self, label: str, content: str) -> str | None:"""Store *content* as its own row and return its marker.@@ -136,18 +172,13 @@ class OmissionCollector:try:if self._chunks:doc = self._render_doc()- markers: list[str] = []- for start in range(0, len(doc), _OMISSION_DOC_CHARS):- part = doc[start : start + _OMISSION_DOC_CHARS]- ref = self._put(part)- if ref is not None:- tokens = estimate_tokens(part)- self._omitted_tokens += tokens- markers.append(render_marker(ref, part.count("\n") + 1, tokens))- if markers:- response["omission_marker"] = markers[0]- if len(markers) > 1:- response["omission_markers"] = markers+ ref = self._put(doc)+ if ref is not None:+ tokens = estimate_tokens(doc)+ self._omitted_tokens += tokens+ response["omission_marker"] = render_marker(+ ref, doc.count("\n") + 1, tokens+ )elif self._chunks:response.setdefault("_meta", {})["recovery_unavailable"] = ("Omission storage failed; dropped evidence could not be persisted."@@ -186,7 +217,10 @@ class OmissionCollector:"transport budget; sections are verbatim.\n")parts = [head]- for label, text in self._chunks:+ for label, value in self._chunks:+ text = render_chunk(label, value)+ if not text:+ continueparts.append(_DOC_SECTION_RULE.format(label=label))parts.append(text)return "\n".join(parts)diff --git a/packages/server/src/repowise/server/mcp_server/_code_rationale.py b/packages/server/src/repowise/server/mcp_server/_code_rationale.pyindex 7e63ab54a..e7595f0ab 100644--- a/packages/server/src/repowise/server/mcp_server/_code_rationale.py+++ b/packages/server/src/repowise/server/mcp_server/_code_rationale.py@@ -234,6 +234,7 @@ def mine_rationale(near_lines: dict[str, int] | None = None,max_files: int = _MAX_FILES,max_results: int = _MAX_RESULTS,+ truncate_blocks: bool = True,) -> list[dict]:"""Mine in-code rationale comments from ``file_paths``.@@ -305,7 +306,7 @@ def mine_rationale({"path": path,"lines": [start, end],- "comment": _truncate_block(comment),+ "comment": _truncate_block(comment) if truncate_blocks else comment,"matched_terms": matched + matched_nums,},)diff --git a/packages/server/src/repowise/server/mcp_server/_episodes.py b/packages/server/src/repowise/server/mcp_server/_episodes.pyindex 08a36bf86..a37c73032 100644--- a/packages/server/src/repowise/server/mcp_server/_episodes.py+++ b/packages/server/src/repowise/server/mcp_server/_episodes.py@@ -27,6 +27,7 @@ from repowise.core.precedent.currency import (free_currency as _free_currency,)from repowise.core.precedent.store import (+ DEFAULT_MAX_ROWS,SHAREABLE_TIERS,EpisodeStore,default_store_path,@@ -124,6 +125,7 @@ def episode_evidence(query: str | None = None,limit: int = _MAX_EVIDENCE_EPISODES,max_body_chars: int = _MAX_EVIDENCE_BODY_CHARS,+ full_population: list[dict] | None = None,) -> tuple[list[dict], list[tuple[dict, str, str]]]:"""Episodes as an evidence block, bounded. Never raises.@@ -165,10 +167,11 @@ def episode_evidence(try:with EpisodeStore(store_path) as store:+ query_limit = DEFAULT_MAX_ROWS if full_population is not None else limitrows = (- store.list_by_node(list(paths), tiers=SERVED_TIERS, limit=limit)+ store.list_by_node(list(paths), tiers=SERVED_TIERS, limit=query_limit)if paths- else store.search(query or "", tiers=SERVED_TIERS, limit=limit)+ else store.search(query or "", tiers=SERVED_TIERS, limit=query_limit))except Exception:_log.warning("episode store read failed", exc_info=True)@@ -178,7 +181,7 @@ def episode_evidence(entries: list[dict] = []pending: list[tuple[dict, str, str]] = []- for rank, row in enumerate(rows[:limit]):+ for rank, row in enumerate(rows):body = row.get("body") or ""entry: dict = {"tier": row.get("tier"),@@ -195,11 +198,17 @@ def episode_evidence(if verdict:entry["still_true"] = verdictentries.append(entry)- return entries, pending+ if full_population is not None:+ full_population.extend(entries)+ return entries[:limit], pendingdef bank_overflow(- pending: Sequence[tuple[dict, str, str]], *, tool: str, repo_root: Path+ pending: Sequence[tuple[dict, str, str]],+ *,+ tool: str,+ repo_root: Path,+ collector: OmissionCollector | None = None,) -> OmissionCollector | None:"""Persist capped bodies and stamp each entry with its recovery marker.@@ -212,8 +221,9 @@ def bank_overflow(and counted its tokens three times over."""if not pending:- return None- collector = OmissionCollector(tool, repo_root)+ return collector+ if collector is None:+ collector = OmissionCollector(tool, repo_root)markers: dict[str, str | None] = {}for entry, label, body in pending:if body not in markers:@@ -236,8 +246,6 @@ def _scope_field(row: dict) -> list[str] | str:if len(nodes) <= _MAX_SCOPE_NODES:return nodesreturn [*nodes[:_MAX_SCOPE_NODES], f"… and {len(nodes) - _MAX_SCOPE_NODES} more"]--def episode_counts(root: Path, paths: Sequence[str]) -> dict[str, int]:"""How many episodes each of *paths* carries. Never raises.diff --git a/packages/server/src/repowise/server/mcp_server/_helpers.py b/packages/server/src/repowise/server/mcp_server/_helpers.pyindex 953c27bbb..f421178a6 100644--- a/packages/server/src/repowise/server/mcp_server/_helpers.py+++ b/packages/server/src/repowise/server/mcp_server/_helpers.py@@ -446,12 +446,12 @@ def _build_origin_story("available": True,"primary_author": primary,"author_commit_pct": git_meta.primary_owner_commit_pct,- "contributors": authors[:5],+ "contributors": authors,"total_commits": total,"first_commit": first_date,"last_commit": last_date,"age_days": age,- "key_commits": commits[:5],+ "key_commits": commits,"linked_decisions": linked_decisions,"summary": " ".join(parts),}diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/context.py b/packages/server/src/repowise/server/mcp_server/tool_context/context.pyindex 02482c77a..772fcee9a 100644--- a/packages/server/src/repowise/server/mcp_server/tool_context/context.py+++ b/packages/server/src/repowise/server/mcp_server/tool_context/context.py@@ -39,6 +39,7 @@ from repowise.core.persistence.database import get_sessionfrom repowise.core.registry import ToolRecipefrom repowise.core.registry import mcp_tool_registry as mcpfrom repowise.server.mcp_server import _state+from repowise.server.mcp_server._budget import OmissionCollectorfrom repowise.server.mcp_server._episodes import enrich_episode_counts as _enrich_episodesfrom repowise.server.mcp_server._helpers import (_get_exclude_spec,@@ -122,6 +123,7 @@ async def get_context(if repo == "all":return _unsupported_repo_all("get_context")ctx = await _resolve_repo_context(repo)+ collector = OmissionCollector("get_context", repo_root=ctx.path)# docs + freshness are ALWAYS returned (the tool contract says# "defaults are always returned"); ``include`` only adds blocks on top.@@ -165,6 +167,7 @@ async def get_context(compact,exclude_spec=exclude_spec,repo_root=ctx.path,+ collector=collector,)for t in targets],@@ -249,4 +252,5 @@ async def get_context(target_data["cross_repo"] = cross_repoattach_ignored_arguments(response, ignored)+ collector.attach(response)return responsediff --git a/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py b/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.pyindex 917092b91..d568eaffe 100644--- a/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py+++ b/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py@@ -12,7 +12,7 @@ import jsonfrom dataclasses import asdictfrom typing import Any-from sqlalchemy import distinct, func, select+from sqlalchemy import func, selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom repowise.core.analysis.health.signals import file_signals@@ -38,6 +38,7 @@ from repowise.core.persistence.models import (HealthFinding,Repository,)+from repowise.server.mcp_server._budget import OmissionCollector, cap_collectionfrom repowise.server.mcp_server._graph_files import keep_projected_edge, node_to_filefrom repowise.server.mcp_server._helpers import filter_dicts_by_key, filter_path_listfrom repowise.server.schemas.intelligence import SYMBOL_RELATION_GROUP_OF@@ -115,24 +116,15 @@ def _unique_by_symbol(entries: list[dict[str, Any]]) -> list[dict[str, Any]]:async def _count_neighbors_by_edge_type(session: AsyncSession, repo_id: str, node_id: str, *, inbound: bool) -> dict[str, int]:- """Count distinct inbound (or outbound) symbols per edge type, above the- confidence floor — the TRUE totals, independent of the display limit.-- Without this the callers list capped silently at the limit and reported- ``truncated: false``, which misled an agent doing a find-all-callers sweep- on a high-fan-in symbol into thinking 20 was the whole set (S2 dogfood).-- `crud.get_node_degree_by_edge_type` answers the same shape for the REST- symbol page and is deliberately **not** reused: it counts edges with no- confidence floor, while this surface counts distinct symbols above 0.7. Two- symbols can be joined by more than one edge, so borrowing it would make the- total exceed what the rows can ever show and re-arm the bug above. The- rows and the totals have to be cut by the same rule.+ """Count qualifying edge rows per type to size each directional fetch.++ The emitted true total is computed after policy filtering and symbol+ deduplication. These raw counts only ensure each ranked fetch is large+ enough to contain that complete post-policy population."""matched = GraphEdge.target_node_id if inbound else GraphEdge.source_node_id- other = GraphEdge.source_node_id if inbound else GraphEdge.target_node_idstmt = (- select(GraphEdge.edge_type, func.count(distinct(other)))+ select(GraphEdge.edge_type, func.count(GraphEdge.id)).where(GraphEdge.repository_id == repo_id,matched == node_id,@@ -154,6 +146,7 @@ async def _resolve_call_graph(want_callers: bool = False,want_callees: bool = False,exclude_spec: Any = None,+ collector: OmissionCollector | None = None,) -> None:"""Resolve callers/callees for a symbol and attach to result_data."""repo_id = repository.id@@ -183,7 +176,9 @@ async def _resolve_call_graph(# an empty callers list forced a second round-trip per orientation# pass for no reason; the graph has the answer at file granularity.if node is not None and node.node_type == "file" and want_callers:- await _resolve_file_level_callers(session, repo_id, node, result_data, exclude_spec)+ await _resolve_file_level_callers(+ session, repo_id, node, result_data, exclude_spec, collector+ )if want_callees:result_data["callees"] = []return@@ -201,12 +196,12 @@ async def _resolve_call_graph(# Totals per edge type, per direction, before any rows. They say which# relation kinds exist at all, so nothing is fetched speculatively, and# they are the numbers reported — the rows are cut from the same rule.- totals_in = (+ row_counts_in = (await _count_neighbors_by_edge_type(session, repo_id, node.node_id, inbound=True)if want_callerselse {})- totals_out = (+ row_counts_out = (await _count_neighbors_by_edge_type(session, repo_id, node.node_id, inbound=False)if want_calleeselse {}@@ -246,11 +241,11 @@ async def _resolve_call_graph(# django, where `Model` served 39 subclasses and 1 of its 8 callers. It is# mild on this repo (6 rows lost, all where `extends` ties `calls` at 0.9)# but it is the same mechanism and it is repo-dependent.- present = sorted(set(totals_in) | set(totals_out))+ present = sorted(set(row_counts_in) | set(row_counts_out))edges_by_type: dict[str, list[GraphEdge]] = {}for edge_type in present:- want_in = want_callers and edge_type in totals_in- want_out = want_callees and edge_type in totals_out+ want_in = want_callers and edge_type in row_counts_in+ want_out = want_callees and edge_type in row_counts_outif not (want_in or want_out):continueedges_by_type[edge_type] = await get_graph_edges_for_node(@@ -259,7 +254,7 @@ async def _resolve_call_graph(node.node_id,direction=("both" if want_in and want_out else ("callers" if want_in else "callees")),edge_types=[edge_type],- limit=limit if edge_type == "calls" else _RELATION_ROW_CAP,+ limit=max(row_counts_in.get(edge_type, 0), row_counts_out.get(edge_type, 0), 1),)# Hydrated once for every edge type at once: the neighbour lookup is the@@ -295,18 +290,16 @@ async def _resolve_call_graph(if e.source_node_id == node.node_id:outbound.append(_entry(e, e.target_node_id, with_edge_type=is_call))- for direction, rows, totals in (- ("in", inbound, totals_in),- ("out", outbound, totals_out),+ for direction, rows in (+ ("in", inbound),+ ("out", outbound),):rows = filter_dicts_by_key(rows, "file", exclude_spec)rows.sort(key=lambda x: -(x.get("confidence") or 0))- # One entry per neighbouring symbol, highest-confidence edge kept.- # The truncation check compares this length against a- # COUNT(DISTINCT), so counting edges here would report "not- # truncated" while real callers are missing (the S2 dogfood).+ # One entry per neighbouring symbol, highest-confidence edge kept;+ # this post-policy list is the source of the public true total.rows = _unique_by_symbol(rows)- total = totals.get(edge_type, 0)+ total = len(rows)if edge_type == "calls":key = "callers" if direction == "in" else "callees"@@ -314,16 +307,21 @@ async def _resolve_call_graph(direction == "out" and not want_callees):continue- result_data[key] = rows- if total > len(rows):- result_data[f"{key}_total"] = total- result_data[f"{key}_truncated"] = True- if direction == "in":- result_data["_callers_note"] = (- f"Showing top {len(rows)} of {total} callers by confidence. "- f"The graph view caps here; for the complete set (e.g. a "- f"signature change) grep '{node.name}('."- )+ visible = cap_collection(+ result_data,+ key,+ rows,+ limit,+ collector,+ label=f"{target} :: {key} beyond cap={limit}",+ )+ if total > len(visible) and direction == "in":+ result_data["_callers_note"] = (+ f"Showing top {len(visible)} of {total} callers by confidence. "+ "Recover the omitted rows with get_symbol on the response's "+ "repowise omission reference; grep remains useful when graph "+ "coverage itself may be incomplete."+ )continueif not total:@@ -332,15 +330,24 @@ async def _resolve_call_graph(# are different sentences and an agent needs to know which it is# in. `group` is the shared vocabulary #1660 pinned, imported# rather than re-listed so a new edge type cannot land unnamed.- relations.append(- {- "edge_type": edge_type,- "group": SYMBOL_RELATION_GROUP_OF[edge_type],- "direction": direction,- "total": total,- "rows": rows,- }+ relation = {+ "edge_type": edge_type,+ "group": SYMBOL_RELATION_GROUP_OF[edge_type],+ "direction": direction,+ "total": total,+ }+ cap_collection(+ relation,+ "rows",+ rows,+ _RELATION_ROW_CAP,+ collector,+ label=(+ f"{target} :: relations.{edge_type}.{direction} "+ f"beyond cap={_RELATION_ROW_CAP}"+ ),)+ relations.append(relation)# `calls` may be absent entirely, and an omitted key reads as "not asked# for" rather than "none" — the distinction an agent needs before deciding@@ -363,7 +370,7 @@ async def _resolve_call_graph(# calls X" would contradict the `_callers_note` telling the agent to go# and grep for them.inbound_kinds = [r for r in relations if r["direction"] == "in"]- if want_callers and not totals_in.get("calls") and inbound_kinds:+ if want_callers and not row_counts_in.get("calls") and inbound_kinds:reached = ", ".join(f"{r['total']} {r['edge_type']}" for r in inbound_kinds)result_data["_call_graph_note"] = (f"Nothing calls '{node.name}'; it is reached by {reached}. See `relations`."@@ -376,6 +383,7 @@ async def _resolve_file_level_callers(node: GraphNode,result_data: dict[str, Any],exclude_spec: Any = None,+ collector: OmissionCollector | None = None,) -> None:"""File-target callers: importing files + inbound symbol-call rollup.@@ -386,9 +394,14 @@ async def _resolve_file_level_callers(from repowise.core.persistence.models import GraphEdge# Who imports this file (file-node inbound import edges).- import_edges = await get_graph_edges_for_node(- session, repo_id, node.node_id, direction="callers", edge_types=["imports"], limit=50+ import_res = await session.execute(+ select(GraphEdge).where(+ GraphEdge.repository_id == repo_id,+ GraphEdge.target_node_id == node.node_id,+ GraphEdge.edge_type == "imports",+ ))+ import_edges = list(import_res.scalars().all())importer_ids = [e.source_node_id for e in import_edges if e.target_node_id == node.node_id]importer_nodes = await get_graph_nodes_by_ids(session, repo_id, importer_ids)# For file nodes the node_id IS the path; file_path may be unset.@@ -443,7 +456,14 @@ async def _resolve_file_level_callers(entries = filter_dicts_by_key(entries, "file", exclude_spec)entries.sort(key=lambda x: -(x.get("inbound_calls") or 0))- result_data["callers"] = entries[:20]+ cap_collection(+ result_data,+ "callers",+ entries,+ 20,+ collector,+ label=f"{node.node_id} :: file callers beyond cap=20",+ )result_data["_call_graph_note"] = ("File-level rollup: importing files plus inbound cross-file call ""counts. For symbol-precise callers pass 'file.py::Symbol'."diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/targets.py b/packages/server/src/repowise/server/mcp_server/tool_context/targets.pyindex 5e1807055..26b314483 100644--- a/packages/server/src/repowise/server/mcp_server/tool_context/targets.py+++ b/packages/server/src/repowise/server/mcp_server/tool_context/targets.py@@ -30,6 +30,7 @@ from repowise.core.persistence.models import (Repository,WikiSymbol,)+from repowise.server.mcp_server._budget import OmissionCollector, cap_collectionfrom repowise.server.mcp_server._helpers import (LIKE_ESCAPE,_decision_body,@@ -240,6 +241,7 @@ async def _resolve_one_target(*,exclude_spec: Any = None,repo_root: Any = None,+ collector: OmissionCollector | None = None,) -> dict:"""Resolve a single target and return its full context."""repo_id = repository.id@@ -480,6 +482,7 @@ async def _resolve_one_target(compact,exclude_spec=exclude_spec,repo_root=repo_root,+ collector=collector,)if "error" not in card:card["target"] = target@@ -822,9 +825,17 @@ async def _resolve_one_target(rank = float(pagerank or 0.0)if rank > best_rank.get(source_node_id, -1.0):best_rank[source_node_id] = rank- docs["used_by"] = filter_path_list(+ used_by = filter_path_list(sorted(best_rank, key=lambda p: (-best_rank[p], p)), exclude_spec- )[:_MAX_USED_BY]+ )+ cap_collection(+ docs,+ "used_by",+ used_by,+ _MAX_USED_BY,+ collector,+ label=f"{target} :: docs.used_by beyond cap={_MAX_USED_BY}",+ )# Candidatesif len(sym_matches) > 1: # type: ignore[possibly-undefined]docs["candidates"] = filter_dicts_by_key(@@ -1107,6 +1118,7 @@ async def _resolve_one_target(want_callers=want_callers,want_callees=want_callees,exclude_spec=exclude_spec,+ collector=collector,)# --- Metrics (replaces get_graph_metrics) ---diff --git a/packages/server/src/repowise/server/mcp_server/tool_risk/assessment.py b/packages/server/src/repowise/server/mcp_server/tool_risk/assessment.pyindex 57669cb16..6731b738d 100644--- a/packages/server/src/repowise/server/mcp_server/tool_risk/assessment.py+++ b/packages/server/src/repowise/server/mcp_server/tool_risk/assessment.py@@ -16,6 +16,7 @@ from repowise.core.persistence.models import (GraphNode,Repository,)+from repowise.server.mcp_server._budget import OmissionCollector, cap_collectionfrom repowise.server.mcp_server._helpers import (filter_dicts_by_key,is_excluded,@@ -349,7 +350,7 @@ def _build_co_changes(row["support"] = supportrows.append(row)population = filter_dicts_by_key(rows, "file_path", exclude_spec)- return population[:_RELATIONSHIP_LIMIT], len(population)+ return population, len(population)def fix_annotation(meta: Any) -> dict | None:@@ -461,6 +462,8 @@ async def _assess_one_target(node_meta: dict[str, Any],exclude_spec: Any = None,team_size: int | None = None,+ collector: OmissionCollector | None = None,+ include_graph: bool = False,) -> dict:"""Assess risk for a single target file.@@ -540,6 +543,26 @@ async def _assess_one_target(},})+ cap_collection(+ result_data,+ "dependents",+ dependency_population,+ _RELATIONSHIP_LIMIT,+ collector if include_graph else None,+ emitted=dependents,+ label=f"{target} :: dependents beyond cap={_RELATIONSHIP_LIMIT}",+ preserve_counts=True,+ )+ cap_collection(+ result_data,+ "impact_surface",+ sorted(dependency_population, key=lambda row: (-row["pagerank"], row["file_path"])),+ 3,+ collector if include_graph else None,+ emitted=impact_surface,+ label=f"{target} :: impact_surface beyond cap=3",+ preserve_counts=True,+ )# Git metadatares = await session.execute(@@ -573,9 +596,10 @@ async def _assess_one_target(hotspot_score = meta.churn_percentile or 0.0- co_changes, co_changes_total = _build_co_changes(+ co_change_population, co_changes_total = _build_co_changes(meta, import_links.get(target, {}), exclude_spec)+ co_changes = co_change_population[:_RELATIONSHIP_LIMIT]owner = meta.primary_owner_name or "unknown"pct = meta.primary_owner_commit_pct or 0.0@@ -603,6 +627,15 @@ async def _assess_one_target(result_data["co_change_partners_total"] = co_changes_totalresult_data["co_change_partners_emitted"] = len(co_changes)result_data["co_change_partners_truncated"] = len(co_changes) < co_changes_total+ cap_collection(+ result_data,+ "co_change_partners",+ co_change_population,+ _RELATIONSHIP_LIMIT,+ collector,+ label=f"{target} :: co_change_partners beyond cap={_RELATIONSHIP_LIMIT}",+ preserve_counts=True,+ )result_data["relationship_analysis"]["co_change"] = {"status": "available","scope": "git_history",diff --git a/packages/server/src/repowise/server/mcp_server/tool_risk/directives.py b/packages/server/src/repowise/server/mcp_server/tool_risk/directives.pyindex 54c8e1cf0..e723612a8 100644--- a/packages/server/src/repowise/server/mcp_server/tool_risk/directives.py+++ b/packages/server/src/repowise/server/mcp_server/tool_risk/directives.py@@ -4,11 +4,14 @@ from __future__ import annotationsfrom typing import Any+from sqlalchemy import select+from repowise.core.analysis.risk_semantics import structural_impact_contractfrom repowise.core.persistence.database import get_session-from repowise.core.persistence.decision_graph import get_governing_decisions, list_conflict_edges+from repowise.core.persistence.decision_graph import list_conflict_edges+from repowise.core.persistence.models import DecisionNodeLink, DecisionRecordfrom repowise.server.mcp_server import _state-from repowise.server.mcp_server._budget import OmissionCollector+from repowise.server.mcp_server._budget import OmissionCollector, cap_collectionfrom repowise.server.mcp_server._helpers import (_get_repo,_is_workspace_mode,@@ -55,7 +58,9 @@ _MAY_BREAK_TESTS_LIMIT = 3_TESTS_TO_RUN_LIMIT = 10-def _breaking_change_directive(repo_alias: str) -> tuple[list[dict[str, Any]], int]:+def _breaking_change_directive(+ repo_alias: str, collector: OmissionCollector | None = None+) -> tuple[list[dict[str, Any]], int]:"""Breaking-change half of the PR directive: incompatible provider changes.Reads the persisted breaking-change report (current HEAD vs the previously@@ -83,11 +88,7 @@ def _breaking_change_directive(repo_alias: str) -> tuple[list[dict[str, Any]], icross = [c for c in consumers if c.get("repo") != repo_alias]if not cross:continue- if len(out) >= _BC_PROVIDER_LIMIT:- dropped += 1- continue- out.append(- {+ entry = {"contract_id": change.get("contract_id"),"type": change.get("contract_type"),"kind": change.get("kind"),@@ -112,16 +113,39 @@ def _breaking_change_directive(repo_alias: str) -> tuple[list[dict[str, Any]], i"file": c.get("file"),**({"symbol_id": sid} if (sid := c.get("symbol_id")) else {}),}- for c in cross[:_BC_CONSUMER_LIMIT]+ for c in cross],}+ cap_collection(+ entry,+ "impacted_consumers",+ entry["impacted_consumers"],+ _BC_CONSUMER_LIMIT,+ collector,+ label=(+ f"breaking_changes.{entry.get('contract_id')}.impacted_consumers "+ f"beyond cap={_BC_CONSUMER_LIMIT}"+ ),)+ out.append(entry)except Exception:return [], 0- return out, dropped+ total = len(out)+ visible = out[:_BC_PROVIDER_LIMIT]+ dropped = total - len(visible)+ if dropped and collector is not None:+ collector.add(+ f"directive.breaking_changes beyond cap={_BC_PROVIDER_LIMIT}",+ out[_BC_PROVIDER_LIMIT:],+ )+ return visible, dropped-def _conformance_directive(repo_alias: str) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:+def _conformance_directive(+ repo_alias: str,+ collector: OmissionCollector | None = None,+ totals: dict[str, int] | None = None,+) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:"""Conformance half of the PR directive: architecture findings touching this repo.Reads the persisted conformance report (rule violations + dependency cycles@@ -139,7 +163,7 @@ def _conformance_directive(repo_alias: str) -> tuple[list[dict[str, Any]], list[if enricher is None or not getattr(enricher, "has_conformance", False):return violations, cyclesscoped = enricher.get_conformance_for_repo(repo_alias)- for v in scoped.get("violations", [])[:_CF_VIOLATION_LIMIT]:+ for v in scoped.get("violations", []):violations.append({"source": v.get("source"),@@ -149,14 +173,30 @@ def _conformance_directive(repo_alias: str) -> tuple[list[dict[str, Any]], list["description": v.get("rule_description") or None,})- for c in scoped.get("cycles", [])[:_CF_CYCLE_LIMIT]:+ for c in scoped.get("cycles", []):cycles.append({"nodes": c.get("nodes", []), "length": c.get("length", 0)})except Exception:return [], []- return violations, cycles+ if totals is not None:+ totals["conformance_violations"] = len(violations)+ totals["dependency_cycles"] = len(cycles)+ if collector is not None:+ if len(violations) > _CF_VIOLATION_LIMIT:+ collector.add(+ f"directive.conformance_violations beyond cap={_CF_VIOLATION_LIMIT}",+ violations[_CF_VIOLATION_LIMIT:],+ )+ if len(cycles) > _CF_CYCLE_LIMIT:+ collector.add(+ f"directive.dependency_cycles beyond cap={_CF_CYCLE_LIMIT}",+ cycles[_CF_CYCLE_LIMIT:],+ )+ return violations[:_CF_VIOLATION_LIMIT], cycles[:_CF_CYCLE_LIMIT]-def _cross_repo_relationships(repo_alias: str) -> dict[str, Any]:+def _cross_repo_relationships(+ repo_alias: str, collector: OmissionCollector | None = None+) -> dict[str, Any]:"""Cross-repo half of the PR directive: downstream services in other repos.Resolves the changed repo to its system-graph nodes and ranks reachable@@ -222,6 +262,17 @@ def _cross_repo_relationships(repo_alias: str) -> dict[str, Any]:"provenance": "workspace_system_graph",})+ if collector is not None:+ if len(structural) > _XR_WILL_BREAK_LIMIT:+ collector.add(+ f"directive.will_break_consumers beyond cap={_XR_WILL_BREAK_LIMIT}",+ structural[_XR_WILL_BREAK_LIMIT:],+ )+ if len(historical) > _XR_COCHANGE_LIMIT:+ collector.add(+ f"directive.missing_cross_repo_cochanges beyond cap={_XR_COCHANGE_LIMIT}",+ historical[_XR_COCHANGE_LIMIT:],+ )return {"structural": structural[:_XR_WILL_BREAK_LIMIT],"structural_total": len(structural),@@ -319,9 +370,27 @@ async def _governance_directive(ctx: Any, changed_files: list[str]) -> list[dictfor ce in conflict_edges:conflict_decision_ids.add(ce.src_decision_id)conflict_decision_ids.add(ce.dst_decision_id)+ linked_rows = list(+ (+ await _gr_session.execute(+ select(DecisionRecord, DecisionNodeLink.node_id)+ .join(+ DecisionNodeLink,+ DecisionNodeLink.decision_id == DecisionRecord.id,+ )+ .where(+ DecisionNodeLink.repository_id == _gr_repo_id,+ DecisionNodeLink.node_id.in_(changed_files),+ )+ )+ ).all()+ )+ by_file: dict[str, list[Any]] = {}+ for record, node_id in linked_rows:+ by_file.setdefault(node_id, []).append(record)seen_dr_ids: set[str] = set()for cf in changed_files:- for dr in await get_governing_decisions(_gr_session, _gr_repo_id, cf):+ for dr in by_file.get(cf, []):if dr.id in seen_dr_ids:continueseen_dr_ids.add(dr.id)@@ -337,10 +406,6 @@ async def _governance_directive(ctx: Any, changed_files: list[str]) -> list[dict"reason": reason,})- if len(governance_risk) >= 5:- break- if len(governance_risk) >= 5:- breakexcept Exception:passreturn governance_risk@@ -401,20 +466,23 @@ def _build_pr_directive(# "what should I do about this PR" in three lines.affected = filter_path_list(- [p for p in (_as_path(e) for e in trimmed_blast.get("transitive_affected", [])) if p],+ [p for p in (_as_path(e) for e in pr_blast_radius.get("transitive_affected", [])) if p],exclude_spec,)# "may", not "will": this is a reverse-import reachability walk over a file# list, and get_risk is never given a diff, so nothing here knows whether the# symbol an importer uses actually changed. The diff-backed fields below keep# "will".- may_break = [p for p in affected if p not in test_paths][:_MAY_BREAK_LIMIT]- may_break_tests = [p for p in affected if p in test_paths][:_MAY_BREAK_TESTS_LIMIT]+ all_may_break = [p for p in affected if p not in test_paths]+ all_may_break_tests = [p for p in affected if p in test_paths]+ may_break = all_may_break[:_MAY_BREAK_LIMIT]+ may_break_tests = all_may_break_tests[:_MAY_BREAK_TESTS_LIMIT]- missing_cochanges = filter_path_list(- [p for p in (_as_path(e) for e in trimmed_blast.get("cochange_warnings", [])) if p],+ all_missing_cochanges = filter_path_list(+ [p for p in (_as_path(e) for e in pr_blast_radius.get("cochange_warnings", [])) if p],exclude_spec,- )[:3]+ )+ missing_cochanges = all_missing_cochanges[:3]# Run-list: consume the analyzer's canonical typed population instead of# independently deriving test ids. Every row retains its basis through# de-duplication, sorting, exclusions, and the directive cap.@@ -423,12 +491,6 @@ def _build_pr_directive(test_recommendations = all_recommendations[:_TESTS_TO_RUN_LIMIT]test_recommendations_total = len(all_recommendations)recommendations_capped = test_recommendations_total > _TESTS_TO_RUN_LIMIT- if recommendations_capped:- collector.add(- f"directive.test_recommendations beyond cap={_TESTS_TO_RUN_LIMIT} "- f"({test_recommendations_total - _TESTS_TO_RUN_LIMIT} dropped)",- all_recommendations[_TESTS_TO_RUN_LIMIT:],- )# Preserve the measured-first legacy projection and its existing scalar# domain. The additive typed rows above are the union of evidence kinds.@@ -438,12 +500,6 @@ def _build_pr_directive(tests_to_run = all_tests_to_run[:_TESTS_TO_RUN_LIMIT]tests_to_run_total = len(all_tests_to_run)tests_capped = tests_to_run_total > _TESTS_TO_RUN_LIMIT- if tests_capped:- collector.add(- f"directive.tests_to_run beyond cap={_TESTS_TO_RUN_LIMIT} "- f"({tests_to_run_total - _TESTS_TO_RUN_LIMIT} dropped)",- all_tests_to_run[_TESTS_TO_RUN_LIMIT:],- )if not all_recommendations:tests_to_run_suffix = ""else:@@ -478,12 +534,6 @@ def _build_pr_directive(all_missing_tests = [path for path in changed_files if path in full_gap_paths]missing_tests = all_missing_tests[:3]missing_tests_total = len(all_missing_tests)- if missing_tests_total > len(missing_tests):- collector.add(- f"directive.missing_tests beyond cap=3 "- f"({missing_tests_total - len(missing_tests)} dropped)",- all_missing_tests[3:],- )missing_tests_summary = (f"Showing {len(missing_tests)} of {missing_tests_total} changed-file test gap(s).")@@ -504,7 +554,7 @@ def _build_pr_directive(# (co-change only). Repo-scoped: it answers "can this PR's repo break# something across a repo boundary?" using the same reachability the map# and get_blast_radius use.- cross_repo_relationships = _cross_repo_relationships(alias)+ cross_repo_relationships = _cross_repo_relationships(alias, collector)will_break_consumers = cross_repo_relationships["structural"]missing_cross_repo_cochanges = cross_repo_relationships["historical"]will_break_total = cross_repo_relationships["structural_total"]@@ -521,7 +571,7 @@ def _build_pr_directive(# Breaking-change guard — incompatible provider changes (removed route /# field, type change, ...) in this repo and the consumers they endanger.# Schema-level truth, distinct from the topology-level will_break_consumers.- breaking_changes, breaking_changes_dropped = _breaking_change_directive(alias)+ breaking_changes, breaking_changes_dropped = _breaking_change_directive(alias, collector)bc_suffix = ""if breaking_changes:bc_consumers = sum(len(b["impacted_consumers"]) for b in breaking_changes)@@ -535,7 +585,10 @@ def _build_pr_directive(# Architecture conformance — declared dependency-rule violations and# dependency cycles this repo participates in. Governance-level truth,# distinct from the topology / schema directives above.- conformance_violations, dependency_cycles = _conformance_directive(alias)+ conformance_totals: dict[str, int] = {}+ conformance_violations, dependency_cycles = _conformance_directive(+ alias, collector, conformance_totals+ )cf_suffix = ""if conformance_violations or dependency_cycles:cf_suffix = (@@ -544,7 +597,7 @@ def _build_pr_directive(f"this repo.")- response["directive"] = {+ directive = {"may_break": may_break,"may_break_tests": may_break_tests,"missing_cochanges": missing_cochanges,@@ -554,7 +607,7 @@ def _build_pr_directive("missing_tests_emitted": len(missing_tests),"missing_tests_truncated": len(missing_tests) < missing_tests_total,"missing_tests_omitted": missing_tests_total - len(missing_tests),- "files_without_measured_tests": list(test_impact.get("files_without_measured_tests") or []),+ "files_without_measured_tests": [],"tests_to_run": tests_to_run,"tests_to_run_basis": tests_to_run_basis,"tests_to_run_total": tests_to_run_total,@@ -571,7 +624,7 @@ def _build_pr_directive("test_analysis": test_impact.get("analysis") or {"status": "unavailable"},"coverage_analysis": coverage,"test_inference_analysis": test_impact.get("inference") or {"status": "unavailable"},- "test_unknown_files": list(test_impact.get("unknown_files") or []),+ "test_unknown_files": [],"will_break_consumers": will_break_consumers,"will_break_consumers_semantics": "structural_reach_only","will_break_consumers_deprecated": True,@@ -599,3 +652,50 @@ def _build_pr_directive(f"{tests_to_run_suffix}{gov_suffix}{xr_suffix}{bc_suffix}{cf_suffix}"),}+ for key, population, cap in (+ ("may_break", all_may_break, _MAY_BREAK_LIMIT),+ ("may_break_tests", all_may_break_tests, _MAY_BREAK_TESTS_LIMIT),+ ("missing_cochanges", all_missing_cochanges, 3),+ ("missing_tests", all_missing_tests if coverage_usable else [], 3),+ ("tests_to_run", all_tests_to_run, _TESTS_TO_RUN_LIMIT),+ ("test_recommendations", all_recommendations, _TESTS_TO_RUN_LIMIT),+ (+ "files_without_measured_tests",+ list(test_impact.get("files_without_measured_tests") or []),+ 10,+ ),+ ("test_unknown_files", list(test_impact.get("unknown_files") or []), 10),+ ("governance_risk", governance_risk, 5),+ ):+ cap_collection(+ directive,+ key,+ population,+ cap,+ collector,+ label=f"directive.{key} beyond cap={cap}",+ preserve_counts=(key in {"missing_tests", "tests_to_run", "test_recommendations"}),+ )++ for key, total in (+ ("will_break_consumers", will_break_total),+ ("missing_cross_repo_cochanges", missing_cross_repo_total),+ ("breaking_changes", len(breaking_changes) + breaking_changes_dropped),+ ("conformance_violations", conformance_totals.get("conformance_violations", 0)),+ ("dependency_cycles", conformance_totals.get("dependency_cycles", 0)),+ ):+ emitted_count = len(directive.get(key) or [])+ is_legacy_count_family = key in {+ "will_break_consumers",+ "missing_cross_repo_cochanges",+ }+ if is_legacy_count_family or emitted_count < total:+ directive[f"{key}_total"] = total+ directive[f"{key}_emitted"] = emitted_count+ if emitted_count < total:+ directive[f"{key}_reduced_reason"] = "construction_cap"+ if key != "breaking_changes":+ directive[f"{key}_truncated"] = True+ directive[f"{key}_omitted"] = total - emitted_count++ response["directive"] = directivediff --git a/packages/server/src/repowise/server/mcp_server/tool_risk/enrichment.py b/packages/server/src/repowise/server/mcp_server/tool_risk/enrichment.pyindex 40a192441..e8f9d1926 100644--- a/packages/server/src/repowise/server/mcp_server/tool_risk/enrichment.py+++ b/packages/server/src/repowise/server/mcp_server/tool_risk/enrichment.py@@ -8,6 +8,7 @@ from sqlalchemy import selectfrom repowise.core.persistence.database import get_sessionfrom repowise.server.mcp_server import _state+from repowise.server.mcp_server._budget import OmissionCollector, cap_collectionfrom repowise.server.mcp_server._helpers import (_is_workspace_mode,)@@ -116,7 +117,13 @@ def _combined_analysis(cross_state: dict, contract_state: dict, rows: list[dict]}-async def _enrich_cross_repo(results: list[dict], alias: str) -> None:+async def _enrich_cross_repo(+ results: list[dict],+ alias: str,+ collector: OmissionCollector | None = None,+ *,+ include_graph: bool = False,+) -> None:"""Add typed workspace relationships without changing dependency counts.Co-change is historical and undirected. Consumers exist only when a typed@@ -140,6 +147,15 @@ async def _enrich_cross_repo(results: list[dict], alias: str) -> None:r["consumers_total"] = len(consumers)r["consumers_emitted"] = len(r["consumers"])r["consumers_truncated"] = len(r["consumers"]) < len(consumers)+ cap_collection(+ r,+ "consumers",+ consumers,+ _RELATIONSHIP_LIMIT,+ collector if include_graph else None,+ label=f"{target} :: consumers beyond cap={_RELATIONSHIP_LIMIT}",+ preserve_counts=True,+ )r["relationship_analysis"]["consumers"] = {**contract_state,"scope": "workspace_contract_links",@@ -174,6 +190,15 @@ async def _enrich_cross_repo(results: list[dict], alias: str) -> None:r["cross_repo_links_total"] = len(cross_repo_links)r["cross_repo_links_emitted"] = len(r["cross_repo_links"])r["cross_repo_links_truncated"] = len(r["cross_repo_links"]) < len(cross_repo_links)+ cap_collection(+ r,+ "cross_repo_links",+ cross_repo_links,+ _RELATIONSHIP_LIMIT,+ collector if include_graph else None,+ label=f"{target} :: cross_repo_links beyond cap={_RELATIONSHIP_LIMIT}",+ preserve_counts=True,+ )r["relationship_analysis"]["cross_repo"] = _combined_analysis(cross_state, contract_state, cross_repo_links)@@ -217,6 +242,15 @@ async def _enrich_cross_repo(results: list[dict], alias: str) -> None:impact["cross_repo_consumers_truncated"] = len(impact["cross_repo_consumers"]) < len(legacy_co_changes)+ cap_collection(+ impact,+ "cross_repo_consumers",+ legacy_co_changes,+ _RELATIONSHIP_LIMIT,+ collector,+ label=f"{target} :: cross_repo_consumers beyond cap={_RELATIONSHIP_LIMIT}",+ preserve_counts=True,+ )impact["cross_repo_consumers_analysis"] = cross_stateimpact["affected_repos"] = affected_reposimpact["affected_repos_total"] = len(affected_repos)@@ -229,7 +263,7 @@ async def _enrich_cross_repo(results: list[dict], alias: str) -> None:link for link in consumer_links if link.get("provider_repo") != alias]if cross_provider_links:- impact["contract_consumers"] = [+ contract_consumers = [{"consumer_repo": lk["consumer_repo"],"consumer_file": lk["consumer_file"],@@ -239,15 +273,25 @@ async def _enrich_cross_repo(results: list[dict], alias: str) -> None:"direction": "provider_to_consumer","evidence_kind": "contract",}- for lk in cross_provider_links[:_RELATIONSHIP_LIMIT]+ for lk in cross_provider_links]+ impact["contract_consumers"] = contract_consumers[:_RELATIONSHIP_LIMIT]impact["contract_consumers_total"] = len(cross_provider_links)impact["contract_consumers_emitted"] = len(impact["contract_consumers"])impact["contract_consumers_truncated"] = len(impact["contract_consumers"]) < len(cross_provider_links)+ cap_collection(+ impact,+ "contract_consumers",+ contract_consumers,+ _RELATIONSHIP_LIMIT,+ collector,+ label=f"{target} :: contract_consumers beyond cap={_RELATIONSHIP_LIMIT}",+ preserve_counts=True,+ )if cross_consumer_links:- impact["contract_providers"] = [+ contract_providers = [{"provider_repo": lk["provider_repo"],"provider_file": lk["provider_file"],@@ -257,13 +301,23 @@ async def _enrich_cross_repo(results: list[dict], alias: str) -> None:"direction": "provider_to_consumer","evidence_kind": "contract",}- for lk in cross_consumer_links[:_RELATIONSHIP_LIMIT]+ for lk in cross_consumer_links]+ impact["contract_providers"] = contract_providers[:_RELATIONSHIP_LIMIT]impact["contract_providers_total"] = len(cross_consumer_links)impact["contract_providers_emitted"] = len(impact["contract_providers"])impact["contract_providers_truncated"] = len(impact["contract_providers"]) < len(cross_consumer_links)+ cap_collection(+ impact,+ "contract_providers",+ contract_providers,+ _RELATIONSHIP_LIMIT,+ collector,+ label=f"{target} :: contract_providers beyond cap={_RELATIONSHIP_LIMIT}",+ preserve_counts=True,+ )async def _enrich_health(results: list[dict], ctx: Any, repo_id: str) -> None:diff --git a/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py b/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.pyindex d90cd7d5c..9c0abb663 100644--- a/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py+++ b/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py@@ -16,7 +16,7 @@ from repowise.core.persistence.models import ()from repowise.core.registry import ToolRecipefrom repowise.core.registry import mcp_tool_registry as mcp-from repowise.server.mcp_server._budget import OmissionCollector+from repowise.server.mcp_server._budget import OmissionCollector, cap_collectionfrom repowise.server.mcp_server._episodes import enrich_episode_counts as _enrich_episodesfrom repowise.server.mcp_server._helpers import (_get_exclude_spec,@@ -43,20 +43,28 @@ _TARGET_CARD_INCLUDES: dict[str, tuple[str, ...]] = {"impact_surface_total","impact_surface_emitted","impact_surface_truncated",+ "impact_surface_reduced_reason",+ "impact_surface_omitted","dependents","dependents_total","dependents_emitted","dependents_truncated",+ "dependents_reduced_reason",+ "dependents_omitted","direct_dependents_total","transitive_dependents_total","consumers","consumers_total","consumers_emitted","consumers_truncated",+ "consumers_reduced_reason",+ "consumers_omitted","cross_repo_links","cross_repo_links_total","cross_repo_links_emitted","cross_repo_links_truncated",+ "cross_repo_links_reduced_reason",+ "cross_repo_links_omitted","relationship_analysis",),"churn": ("change_magnitude", "risk_type", "change_pattern"),@@ -138,6 +146,7 @@ async def get_risk(if resolve_enum_argument(block, _INCLUDE_BLOCKS, argument="include", ignored=ignored)}ctx = await _resolve_repo_context(repo)+ collector = OmissionCollector("get_risk", repo_root=ctx.path)exclude_spec = _get_exclude_spec(ctx.path)targets = filter_path_list(targets, exclude_spec)if changed_files:@@ -205,6 +214,8 @@ async def get_risk(node_meta,exclude_spec,team_size,+ collector,+ "graph" in include_set,)for t in targets]@@ -220,39 +231,38 @@ async def get_risk(# Churn stays the fallback, so a repo with no fix convention keeps# exactly the list it had. These are full ORM rows, so the fix columns# are already in memory and this adds no query.- target_set = set(targets)- res = await session.execute(- select(GitMetadata)- .where(- GitMetadata.repository_id == repo_id,- (GitMetadata.is_hotspot == True) # noqa: E712- | (GitMetadata.bug_magnet == True), # noqa: E712+ global_hotspots = []+ if len(targets) > 1 and not changed_files:+ target_set = set(targets)+ res = await session.execute(+ select(GitMetadata)+ .where(+ GitMetadata.repository_id == repo_id,+ (GitMetadata.is_hotspot == True) # noqa: E712+ | (GitMetadata.bug_magnet == True), # noqa: E712+ )+ .order_by(+ GitMetadata.bug_magnet.desc(),+ GitMetadata.fix_mass.desc(),+ GitMetadata.churn_percentile.desc(),+ ))- .order_by(- GitMetadata.bug_magnet.desc(),- GitMetadata.fix_mass.desc(),- GitMetadata.churn_percentile.desc(),+ all_hotspots = filter_rows_by_attr(+ list(res.scalars().all()), "file_path", exclude_spec)- .limit(len(targets) + 5)- )- all_hotspots = filter_rows_by_attr(list(res.scalars().all()), "file_path", exclude_spec)- global_hotspots = []- for h in all_hotspots:- if h.file_path in target_set:- continue- entry = {- "file_path": h.file_path,- "hotspot_score": h.churn_percentile,- "is_hotspot": True,- "primary_owner": h.primary_owner_name,- }- # Silent on files with no counted fixes, so a repo without fix- # history pays nothing for this.- fixes = fix_annotation(h)- if fixes is not None:- entry.update(fixes)- global_hotspots.append(entry)- global_hotspots = global_hotspots[:5]+ for h in all_hotspots:+ if h.file_path in target_set:+ continue+ entry = {+ "file_path": h.file_path,+ "hotspot_score": h.churn_percentile,+ "is_hotspot": True,+ "primary_owner": h.primary_owner_name,+ }+ fixes = fix_annotation(h)+ if fixes is not None:+ entry.update(fixes)+ global_hotspots.append(entry)# A. PR blast radius (only when caller passes changed_files)pr_blast_radius: dict | None = None@@ -263,7 +273,9 @@ async def get_risk(pr_blast_radius = await analyzer.analyze_files(changed_files, exclude_spec=exclude_spec)# Cross-repo blast radius enrichment (Phase 3 + 4)- await _enrich_cross_repo(results, ctx.alias)+ await _enrich_cross_repo(+ results, ctx.alias, collector, include_graph="graph" in include_set+ )# ---- Code-health enrichment --------------------------------------------# Attach per-file health_score + top_biomarkers (up to 3) drawn from the@@ -281,7 +293,6 @@ async def get_risk(**({"risk_scales": file_risk_scales()} if "scales" in include_set else {}),}- collector = OmissionCollector("get_risk", repo_root=ctx.path)if pr_blast_radius is not None:assert changed_files is not None# Governance risk — bounded query over changed_files (small set).@@ -304,7 +315,14 @@ async def get_risk(elif len(targets) > 1:# Standard per-file risk request (no diff) — ambient orientation across# a set of targets. On one file the caller already named, it is noise.- response["global_hotspots"] = global_hotspots+ cap_collection(+ response,+ "global_hotspots",+ global_hotspots,+ 5,+ collector,+ label="global_hotspots beyond cap=5",+ )response["_meta"] = _build_meta(repository=repository,diff --git a/packages/server/src/repowise/server/mcp_server/tool_symbol.py b/packages/server/src/repowise/server/mcp_server/tool_symbol.pyindex fc8a6d640..ac3fed62f 100644--- a/packages/server/src/repowise/server/mcp_server/tool_symbol.py+++ b/packages/server/src/repowise/server/mcp_server/tool_symbol.py@@ -43,6 +43,7 @@ Returns a flat dict (not wrapped in `targets`) so the agent can pipe thefrom __future__ import annotationsimport re+import sqlite3import timefrom datetime import UTC, datetimefrom pathlib import Path@@ -295,13 +296,18 @@ def _resolve_omission_ref(record: dict | None = Nonefor db_path in candidates:- if not db_path.exists():- continue- store = OmissionStore(db_path)try:- record = store.get_record(ref, query=query)- finally:- store.close()+ if not db_path.exists():+ continue+ store = OmissionStore(db_path)+ try:+ record = store.get_record(ref, query=query)+ finally:+ store.close()+ except (OSError, sqlite3.Error):+ # An inaccessible fallback store is equivalent to a missing ref.+ # Recovery must never make get_symbol itself fail.+ continueif record is not None:breakdiff --git a/packages/server/src/repowise/server/mcp_server/tool_why.py b/packages/server/src/repowise/server/mcp_server/tool_why.pyindex 3d8554f00..0179b389a 100644--- a/packages/server/src/repowise/server/mcp_server/tool_why.py+++ b/packages/server/src/repowise/server/mcp_server/tool_why.py@@ -14,6 +14,7 @@ from sqlalchemy import selectfrom repowise.core.analysis.decision_semantic_match import DECISION_VECTOR_PREFIXfrom repowise.core.persistence.database import get_sessionfrom repowise.core.persistence.models import (+ DecisionEdge,DecisionEvidence,DecisionRecord,GitMetadata,@@ -24,6 +25,7 @@ from repowise.core.registry import ToolRecipefrom repowise.core.registry import mcp_tool_registry as mcpfrom repowise.server.mcp_server._budget import (OmissionCollector,+ cap_collection,fit_to_budget,over_budget,)@@ -168,13 +170,19 @@ async def _why_workspace_search(query: str) -> dict:# as they do within one repo; alias and id only settle what those three leave# equal, and are here so the answer is the same on two runs.scored.sort(key=lambda t: (t[0], t[1], t[3]))- selected = scored[:_MAX_WORKSPACE_DECISIONS]+ selected = scored+ collector = OmissionCollector(+ "get_why", repo_root=selected[0][2].path if selected else None+ )for selected_ctx in {entry[2].alias: entry[2] for entry in selected}.values():selected_records = [entry[4] for entry in selected if entry[2] is selected_ctx]async with get_session(selected_ctx.session_factory) as session:await _attach_decision_evidence(session, selected_records)decisions: list[dict] = []- for _, alias, selected_ctx, _id, d, folded in selected:+ entries_by_alias: dict[str, list[dict[str, Any]]] = {}+ records_by_alias: dict[str, list[Any]] = {}+ contexts_by_alias = {entry[1]: entry[2] for entry in selected}+ for _, alias, _selected_ctx, _id, d, folded in selected:entry = {"repo": alias,"id": d.id,@@ -187,17 +195,33 @@ async def _why_workspace_search(query: str) -> dict:}if folded:entry["restates"] = folded+ entries_by_alias.setdefault(alias, []).append(entry)+ records_by_alias.setdefault(alias, []).append(d)+ decisions.append(entry)+ for alias, entries in entries_by_alias.items():await annotate_response_evidence_async(- {"decisions": [entry]}, alias, [d], repo_root=selected_ctx.path+ {"decisions": entries},+ alias,+ records_by_alias[alias],+ repo_root=contexts_by_alias[alias].path,)- decisions.append(entry)- return {+ result = {"mode": "search","query": query,"workspace": True,"decisions": decisions,"_meta": _build_meta(),}+ cap_collection(+ result,+ "decisions",+ decisions,+ _MAX_WORKSPACE_DECISIONS,+ collector,+ label=f"workspace decisions beyond cap={_MAX_WORKSPACE_DECISIONS}",+ )+ collector.attach(result)+ return resultasync def _why_health_dashboard(repo: str | None) -> dict:@@ -205,6 +229,7 @@ async def _why_health_dashboard(repo: str | None) -> dict:from repowise.core.persistence.crud import get_decision_health_summaryctx = await _resolve_repo_context(repo)+ collector = OmissionCollector("get_why", repo_root=ctx.path)async with get_session(ctx.session_factory) as session:repository = await _get_repo(session)health = await get_decision_health_summary(session, repository.id)@@ -229,9 +254,9 @@ async def _why_health_dashboard(repo: str | None) -> dict:"staleness_score": d.staleness_score,"affected_files": filter_path_list(json.loads(d.affected_files_json), _get_exclude_spec(ctx.path)- )[:5],+ ),}- for d in stale[:_MAX_HEALTH_STALE]+ for d in stale],"proposed_awaiting_review": [{@@ -240,19 +265,44 @@ async def _why_health_dashboard(repo: str | None) -> dict:"source": d.source,"confidence": d.confidence,}- for d in proposed[:_MAX_HEALTH_PROPOSED]+ for d in proposed],- "ungoverned_hotspots": ungoverned[:_MAX_HEALTH_UNGOVERNED],- "conflicts": health.get("conflicts", [])[:10],+ "ungoverned_hotspots": ungoverned,+ "conflicts": list(health.get("conflicts", [])),"_meta": _build_meta(repository=repository),}+ for entry in result_data["stale_decisions"]:+ cap_collection(+ entry,+ "affected_files",+ entry["affected_files"],+ 5,+ collector,+ label=f"health stale decision {entry['id']} :: affected_files beyond cap=5",+ )await _attach_decision_evidence(session, [*stale, *proposed])- return await annotate_response_evidence_async(+ result_data = await annotate_response_evidence_async(result_data,ctx.alias,[*stale, *proposed],repo_root=ctx.path,)+ for key, cap in (+ ("stale_decisions", _MAX_HEALTH_STALE),+ ("proposed_awaiting_review", _MAX_HEALTH_PROPOSED),+ ("ungoverned_hotspots", _MAX_HEALTH_UNGOVERNED),+ ("conflicts", 10),+ ):+ cap_collection(+ result_data,+ key,+ result_data[key],+ cap,+ collector,+ label=f"health {key} beyond cap={cap}",+ )+ collector.attach(result_data)+ return result_data# --- Path-mode cap and projection -------------------------------------------@@ -355,7 +405,12 @@ def _path_decision_sort_key(d: Any) -> tuple[int, float, float]:)-def _governing_decision_entry(d: Any, affected_files: list, lineage: list[dict]) -> dict:+def _governing_decision_entry(+ d: Any,+ affected_files: list,+ lineage: list[dict],+ collector: OmissionCollector | None = None,+) -> dict:"""Serialize a decision that governs a path, including its lineage chain."""entry = {"id": d.id,@@ -373,7 +428,14 @@ def _governing_decision_entry(d: Any, affected_files: list, lineage: list[dict])"lineage": lineage if len(lineage) > 1 else [],}if len(affected_files) > _MAX_AFFECTED_FILES:- entry["affected_files_total"] = len(affected_files)+ cap_collection(+ entry,+ "affected_files",+ affected_files,+ _MAX_AFFECTED_FILES,+ collector,+ label=f"decision {d.id} :: affected_files beyond cap={_MAX_AFFECTED_FILES}",+ )return entry@@ -403,6 +465,114 @@ def _trim_commit_text(origin_story: dict) -> None:_trim(linked.get("evidence_commits"))+def _cap_origin_story(+ origin_story: dict[str, Any],+ collector: OmissionCollector,+ *,+ label: str,+) -> None:+ """Bound each origin lane independently and bank its exact omitted rows."""+ for key, cap in (+ ("contributors", 5),+ ("key_commits", 5),+ ("linked_decisions", _MAX_PATH_DECISIONS),+ ):+ rows = origin_story.get(key)+ if isinstance(rows, list):+ cap_collection(+ origin_story,+ key,+ rows,+ cap,+ collector,+ label=f"{label} :: origin.{key} beyond cap={cap}",+ )+ for linked in origin_story.get("linked_decisions") or []:+ if not isinstance(linked, dict):+ continue+ commits = linked.get("evidence_commits")+ if isinstance(commits, list):+ cap_collection(+ linked,+ "evidence_commits",+ commits,+ 5,+ collector,+ label=f"{label} :: origin.linked_decisions.evidence_commits beyond cap=5",+ )+++def _cap_archaeology(+ archaeology: dict[str, Any], collector: OmissionCollector, *, label: str+) -> None:+ """Cap fully annotated archaeology lanes without discarding their tails."""+ for key, cap in (("file_commits", 10), ("cross_references", 10), ("git_log", 20)):+ rows = archaeology.get(key)+ if isinstance(rows, list):+ cap_collection(+ archaeology,+ key,+ rows,+ cap,+ collector,+ label=f"{label} :: archaeology.{key} beyond cap={cap}",+ )+++def _cap_supporting_lanes(+ result: dict[str, Any], collector: OmissionCollector, *, label: str+) -> None:+ """Cap supporting Why lanes only after evidence annotation is complete."""+ origin = result.get("origin_story")+ if isinstance(origin, dict):+ _cap_origin_story(origin, collector, label=label)+ archaeology = result.get("git_archaeology")+ if isinstance(archaeology, dict):+ _cap_archaeology(archaeology, collector, label=label)+ rationale = result.get("code_rationale")+ if isinstance(rationale, list):+ cap_collection(+ result,+ "code_rationale",+ rationale,+ 5,+ collector,+ label=f"{label} :: code_rationale beyond cap=5",+ )+ for target, context in (result.get("target_context") or {}).items():+ if not isinstance(context, dict):+ continue+ target_origin = context.get("origin")+ if isinstance(target_origin, dict):+ _cap_origin_story(target_origin, collector, label=target)+ target_archaeology = context.get("git_archaeology")+ if isinstance(target_archaeology, dict):+ _cap_archaeology(target_archaeology, collector, label=target)+++def _prepare_episode_bodies(+ population: list[dict[str, Any]],+ visible_count: int,+ pending: list[tuple[dict, str, str]],+ collector: OmissionCollector,+ repo_root: Path,+) -> OmissionCollector:+ """Inline-bank visible long bodies; keep omitted episode rows byte-complete."""+ visible_ids = {id(entry) for entry in population[:visible_count]}+ visible_pending: list[tuple[dict, str, str]] = []+ for entry, label, body in pending:+ if id(entry) in visible_ids:+ visible_pending.append((entry, label, body))+ else:+ entry["recorded"] = body+ return bank_overflow(+ visible_pending,+ tool="get_why",+ repo_root=repo_root,+ collector=collector,+ ) or collector++def _fit_path_response(result_data: dict, repo_root: Any, collector: OmissionCollector | None = None) -> dict:@@ -450,7 +620,13 @@ def _fit_path_response(collector = OmissionCollector("get_why", repo_root=repo_root)def _shed(*order: str) -> None:- fit_to_budget(result_data, order, collector, headroom=_COLLECTOR_HEADROOM_CHARS)+ fit_to_budget(+ result_data,+ order,+ collector,+ headroom=_COLLECTOR_HEADROOM_CHARS,+ record_counts=True,+ )# Episodes go before the governing records, not after: they are the newest# evidence kind here and must only ever spend slack. Dropping them later in@@ -465,6 +641,17 @@ def _fit_path_response(collector.add(f"dropped governing decision {dropped.get('title', '')}", dropped)result_data["truncated"] = Trueresult_data.setdefault("dropped_decisions", []).append(dropped.get("id", ""))+ if "decisions_total" in result_data:+ result_data["decisions_emitted"] = len(decisions)+ if len(decisions) < result_data["decisions_total"]:+ prior = result_data.get("decisions_reduced_reason")+ result_data["decisions_reduced_reason"] = (+ "construction_cap_and_response_budget"+ if prior == "construction_cap"+ else "response_budget"+ )+ result_data["decisions_truncated"] = True+ result_data["decisions_omitted"] = result_data["decisions_total"] - len(decisions)_shed("code_rationale", "git_archaeology", "origin_story")@@ -475,6 +662,7 @@ def _fit_path_response(async def _why_path(query: str, repo: str | None) -> dict:"""Mode 2: query is a path — governing decisions, origin story, alignment."""ctx = await _resolve_repo_context(repo)+ collector = OmissionCollector("get_why", repo_root=ctx.path)if is_excluded(query, _get_exclude_spec(ctx.path)):return {"query": query, "error": f"'{query}' is excluded by exclude_patterns."}async with get_session(ctx.session_factory) as session:@@ -503,8 +691,6 @@ async def _why_path(query: str, repo: str | None) -> dict:)all_git_meta = all_git_res.scalars().all()- from repowise.core.persistence.decision_graph import build_lineage_chain-matched = [dfor d in all_decisions@@ -514,12 +700,15 @@ async def _why_path(query: str, repo: str | None) -> dict:# Rank before capping, so the 8 that survive are the 8 that govern —# not whichever 8 the table scan happened to yield first.matched.sort(key=_path_decision_sort_key)+ lineage_by_id = await _lineage_for_records(session, matched, all_decisions)governing = []- for rank, d in enumerate(matched[:_MAX_PATH_DECISIONS]):+ for rank, d in enumerate(matched):# Walk supersedes/refines back to roots so the answer is a# lineage chain (sessions → JWT → OAuth2), not a flat list.- lineage = await build_lineage_chain(session, d.id)- entry = _governing_decision_entry(d, json.loads(d.affected_files_json), lineage)+ lineage = lineage_by_id.get(d.id, [])+ entry = _governing_decision_entry(+ d, json.loads(d.affected_files_json), lineage, collector+ )# Ask git whether the top record still holds — and only the top# one. The query is ~60 ms, which is affordable once inside an MCP# call and is not affordable eight times; the record ranked first@@ -537,7 +726,6 @@ async def _why_path(query: str, repo: str | None) -> dict:governing.append(entry)origin_story = _build_origin_story(query, git_meta, governing)- _trim_commit_text(origin_story)result_data: dict[str, Any] = {"mode": "path",@@ -562,9 +750,6 @@ async def _why_path(query: str, repo: str | None) -> dict:all_decisions,),}- if len(matched) > _MAX_PATH_DECISIONS:- result_data["decisions_total"] = len(matched)-# --- Fallback: git archaeology when no decisions found ---if not governing:result_data["git_archaeology"] = await _git_archaeology_fallback(@@ -572,10 +757,13 @@ async def _why_path(query: str, repo: str | None) -> dict:git_meta,all_git_meta,repository,+ collector,)# Decisions and git history both silent → the "why" may live in a# code comment. Mine this file's rationale comments directly.- rationale = _mine_rationale(ctx.path, [query], None)+ rationale = _mine_rationale(+ ctx.path, [query], None, max_results=1000, truncate_blocks=False+ )if rationale:result_data["code_rationale"] = rationale@@ -583,19 +771,42 @@ async def _why_path(query: str, repo: str | None) -> dict:# above. A well-governed file still has a history, and "what happened# here, dated" is the question this mode is asked; gating it on the# absence of decisions would hide it exactly where there is most to say.- episodes, pending = await asyncio.to_thread(episode_evidence, ctx.path, paths=[query])+ episode_population: list[dict] = []+ episodes, pending = await asyncio.to_thread(+ episode_evidence,+ ctx.path,+ paths=[query],+ full_population=episode_population,+ )if episodes:- result_data["episodes"] = episodes- # Banked here, not in the thread above: the omission store is a- # sqlite3 connection bound to its creating thread, and this collector- # is finalised below on this one.- collector = bank_overflow(pending, tool="get_why", repo_root=ctx.path)+ collector = _prepare_episode_bodies(+ episode_population, len(episodes), pending, collector, ctx.path+ )+ result_data["episodes"] = episode_populationresult_data["_meta"] = _build_meta(repository=repository)await _attach_response_decision_evidence(session, result_data, all_decisions)await annotate_response_evidence_async(result_data, ctx.alias, all_decisions, repo_root=ctx.path)+ _cap_supporting_lanes(result_data, collector, label=query)+ if episodes:+ cap_collection(+ result_data,+ "episodes",+ result_data["episodes"],+ len(episodes),+ collector,+ label="episodes beyond construction cap",+ )+ cap_collection(+ result_data,+ "decisions",+ result_data["decisions"],+ _MAX_PATH_DECISIONS,+ collector,+ label=f"path decisions beyond cap={_MAX_PATH_DECISIONS}",+ )return _fit_path_response(result_data, ctx.path, collector=collector)@@ -664,7 +875,7 @@ def _score_keyword_matches())scored_decisions.sort(key=lambda t: (t[0], t[1], t[2]))- return [((t[0], t[1], t[2]), t[3]) for t in scored_decisions[:_KEYWORD_POOL]]+ return [((t[0], t[1], t[2]), t[3]) for t in scored_decisions]def _rank_keyword_matches(all_decisions: list, query: str, target_set: set[str]) -> list:@@ -702,7 +913,7 @@ async def _fts_doc_results(ctx: Any, query: str) -> list:"""doc_results: list = []with contextlib.suppress(Exception):- doc_results = await ctx.fts.search(query, limit=3)+ doc_results = await ctx.fts.search(query, limit=_SEMANTIC_WINDOW)return doc_results@@ -745,21 +956,106 @@ async def _semantic_lanes(ctx: Any, query: str) -> tuple[list, list]:decision_hits.append(r)else:doc_hits.append(r)- return decision_hits[:_MAX_SEARCH_DECISIONS], doc_hits[:3]+ return decision_hits, doc_hits-async def _lineage_for_matches(ctx: Any, keyword_matches: list) -> dict[str, list[dict]]:- """Walk lineage chains for the keyword matches; keep only multi-node chains."""- from repowise.core.persistence.decision_graph import build_lineage_chain+async def _lineage_for_records(+ session: Any, candidates: list[Any], all_decisions: list[Any]+) -> dict[str, list[dict]]:+ """Build every candidate lineage from one edge query and in-memory records."""+ if not candidates:+ return {}+ edges = list(+ (+ await session.execute(+ select(DecisionEdge).where(+ DecisionEdge.repository_id == candidates[0].repository_id,+ DecisionEdge.kind.in_(("supersedes", "refines")),+ )+ )+ )+ .scalars()+ .all()+ )+ outgoing: dict[str, list[Any]] = {}+ for edge in edges:+ outgoing.setdefault(edge.src_decision_id, []).append(edge)+ for rows in outgoing.values():+ rows.sort(+ key=lambda edge: (+ edge.kind == "supersedes",+ edge.confidence or 0.0,+ edge.dst_decision_id,+ ),+ reverse=True,+ )+ records = {record.id: record for record in all_decisions}+ edge_record_ids = {+ decision_id+ for edge in edges+ for decision_id in (edge.src_decision_id, edge.dst_decision_id)+ }+ missing_ids = edge_record_ids - records.keys()+ if missing_ids:+ missing_records = list(+ (+ await session.execute(+ select(DecisionRecord).where(DecisionRecord.id.in_(missing_ids))+ )+ )+ .scalars()+ .all()+ )+ records.update({record.id: record for record in missing_records})+ result: dict[str, list[dict]] = {}+ for candidate in candidates:+ order: list[tuple[str, str | None]] = []+ visited: set[str] = set()+ current = candidate.id+ relation: str | None = None+ while current and current not in visited and len(order) < 50:+ visited.add(current)+ order.append((current, relation))+ edge = next(+ (+ row+ for row in outgoing.get(current, [])+ if row.dst_decision_id not in visited+ ),+ None,+ )+ if edge is None:+ break+ current = edge.dst_decision_id+ relation = edge.kind+ if len(order) <= 1:+ continue+ chain = []+ for decision_id, kind in reversed(order):+ record = records.get(decision_id)+ if record is not None:+ chain.append(+ {+ "id": record.id,+ "title": record.title,+ "status": record.status,+ "source": record.source,+ "relation": kind,+ }+ )+ if len(chain) > 1:+ result[candidate.id] = chain+ return result+- lineage_by_id: dict[str, list[dict]] = {}- if keyword_matches:- async with get_session(ctx.session_factory) as session3:- for d in keyword_matches:- chain = await build_lineage_chain(session3, d.id)- if len(chain) > 1:- lineage_by_id[d.id] = chain- return lineage_by_id+async def _lineage_for_matches(+ ctx: Any, keyword_matches: list, all_decisions: list[Any]+) -> dict[str, list[dict]]:+ """Build all keyword lineages with one bounded edge query."""+ if not keyword_matches:+ return {}+ async with get_session(ctx.session_factory) as session3:+ return await _lineage_for_records(session3, keyword_matches, all_decisions)def _evidence_key(d: Any) -> tuple[object, ...] | None:@@ -810,6 +1106,7 @@ def _merge_decisions(keyword_matches: list[tuple[Any, list[str]]],decision_results: list,lineage_by_id: dict[str, list[dict]],+ collector: OmissionCollector | None = None,) -> list[dict]:"""Project collapsed keyword hits, then append semantic hits not already in.@@ -841,7 +1138,14 @@ def _merge_decisions("lineage": lineage_by_id.get(d.id, []),}if len(affected_files) > _MAX_AFFECTED_FILES:- entry["affected_files_total"] = len(affected_files)+ cap_collection(+ entry,+ "affected_files",+ affected_files,+ _MAX_AFFECTED_FILES,+ collector,+ label=f"decision {d.id} :: affected_files beyond cap={_MAX_AFFECTED_FILES}",+ )if folded:entry["restates"] = foldedmerged_decisions.append(entry)@@ -869,6 +1173,7 @@ async def _build_target_context(all_decisions: list,target_git: dict[str, Any],targets: list[str],+ collector: OmissionCollector | None = None,) -> dict[str, Any]:"""Per-target governing decisions + origin story, with archaeology fallback."""async with get_session(ctx.session_factory) as session2:@@ -896,20 +1201,21 @@ async def _build_target_context("status": d.status,"source": d.source,}- for d in governing_records[:_MAX_PATH_DECISIONS]+ for d in governing_records]git_m = target_git.get(t)- ctx_entry: dict[str, Any] = {- "governing_decisions": t_governing,- "origin": _build_origin_story(t, git_m, t_governing)+ origin = (+ _build_origin_story(t, git_m, t_governing)if git_melse {"available": False,"summary": f"No git history for {t}.",- },+ }+ )+ ctx_entry: dict[str, Any] = {+ "governing_decisions": t_governing,+ "origin": origin,}- if len(governing_records) > _MAX_PATH_DECISIONS:- ctx_entry["governing_decisions_total"] = len(governing_records)# Git archaeology fallback when no decisions foundif not t_governing:ctx_entry["git_archaeology"] = await _git_archaeology_fallback(@@ -917,11 +1223,31 @@ async def _build_target_context(git_m,all_git_meta_list,repository,+ collector,)target_context[t] = ctx_entryreturn target_context+def _cap_target_context(+ target_context: dict[str, Any], collector: OmissionCollector+) -> None:+ """Cap evidence-enriched per-target decision lanes independently."""+ for target, entry in target_context.items():+ decisions = entry.get("governing_decisions")+ if isinstance(decisions, list):+ cap_collection(+ entry,+ "governing_decisions",+ decisions,+ _MAX_PATH_DECISIONS,+ collector,+ label=(+ f"{target} :: governing_decisions beyond cap={_MAX_PATH_DECISIONS}"+ ),+ )++async def _why_no_match(query: str,targets: list[str] | None,@@ -955,18 +1281,27 @@ async def _why_no_match("decisions": [],**redirect_for(query),}+ collector: OmissionCollector | None = Noneif targets:+ collector = OmissionCollector("get_why", repo_root=ctx.path)result["target_context"] = await _build_target_context(- ctx, repository, all_decisions, target_git, targets+ ctx, repository, all_decisions, target_git, targets, collector+ )+ rationale = _mine_rationale(+ ctx.path, targets, query, max_results=1000, truncate_blocks=False)- rationale = _mine_rationale(ctx.path, targets, query)if rationale:result["code_rationale"] = rationaleawait _hydrate_response_decision_evidence(ctx, result, all_decisions)await annotate_response_evidence_async(result, ctx.alias, all_decisions, repo_root=ctx.path)+ if collector is not None:+ _cap_supporting_lanes(result, collector, label=query)+ _cap_target_context(result["target_context"], collector)result["_meta"] = _build_meta(repository=repository, targets=targets if targets else None)+ if collector is not None:+ collector.attach(result)return result@@ -1081,18 +1416,23 @@ async def _why_targets(targets: list[str], repo: str | None) -> dict:return await _why_path(targets[0], repo)ctx, repository, all_decisions, target_git = await _load_corpus(repo, targets)+ collector = OmissionCollector("get_why", repo_root=ctx.path)result_data = {"mode": "path","paths": targets,"target_context": await _build_target_context(- ctx, repository, all_decisions, target_git, targets+ ctx, repository, all_decisions, target_git, targets, collector),"_meta": _build_meta(repository=repository, targets=targets),}await _hydrate_response_decision_evidence(ctx, result_data, all_decisions)- return await annotate_response_evidence_async(+ result_data = await annotate_response_evidence_async(result_data, ctx.alias, all_decisions, repo_root=ctx.path)+ _cap_supporting_lanes(result_data, collector, label="targets")+ _cap_target_context(result_data["target_context"], collector)+ collector.attach(result_data)+ return result_dataasync def _why_search(query: str, targets: list[str] | None, repo: str | None) -> dict:@@ -1105,10 +1445,15 @@ async def _why_search(query: str, targets: list[str] | None, repo: str | None) -ranked = _rank_keyword_matches(all_decisions, query, target_set)if not ranked:return await _why_no_match(query, targets, ctx, repository, all_decisions, target_git)- collapsed = _collapse_restatements(ranked)[:_MAX_SEARCH_DECISIONS]+ collector = OmissionCollector("get_why", repo_root=ctx.path)+ collapsed = _collapse_restatements(ranked)decision_results, doc_results = await _semantic_lanes(ctx, query)- lineage_by_id = await _lineage_for_matches(ctx, [d for d, _ in collapsed])- merged_decisions = _merge_decisions(collapsed, decision_results, lineage_by_id)+ lineage_by_id = await _lineage_for_matches(+ ctx, [d for d, _ in collapsed], all_decisions+ )+ merged_decisions = _merge_decisions(+ collapsed, decision_results, lineage_by_id, collector+ )# No further slice: the cap is on *bodies*, applied to ``collapsed`` above.# Semantic hits append as id-plus-snippet at roughly 200 chars each, so@@ -1126,14 +1471,14 @@ async def _why_search(query: str, targets: list[str] | None, repo: str | None) -"snippet": r.snippet,"relevance_score": r.score,}- for r in doc_results[:3]+ for r in doc_results],}# If targets provided, include target contextif targets:result_data["target_context"] = await _build_target_context(- ctx, repository, all_decisions, target_git, targets+ ctx, repository, all_decisions, target_git, targets, collector)# The comment-mining fallback that used to sit here was gated on# ``not merged_decisions``, which nothing ever reached. It now lives in@@ -1141,27 +1486,60 @@ async def _why_search(query: str, targets: list[str] | None, repo: str | None) -# Targets resolve through the node index; without them the question itself# is the only handle, so it is ranked against the bodies.+ episode_population: list[dict] = []episodes, pending = await asyncio.to_thread(episode_evidence,ctx.path,paths=targets or None,query=None if targets else query,+ full_population=episode_population,)if episodes:- result_data["episodes"] = episodes+ collector = _prepare_episode_bodies(+ episode_population, len(episodes), pending, collector, ctx.path+ )+ result_data["episodes"] = episode_populationawait _hydrate_response_decision_evidence(ctx, result_data, all_decisions)await annotate_response_evidence_async(result_data, ctx.alias, all_decisions, repo_root=ctx.path)+ if targets:+ _cap_supporting_lanes(result_data, collector, label=query)+ _cap_target_context(result_data["target_context"], collector)+ else:+ _cap_supporting_lanes(result_data, collector, label=query)+ if episodes:+ cap_collection(+ result_data,+ "episodes",+ result_data["episodes"],+ len(episodes),+ collector,+ label="episodes beyond construction cap",+ )result_data["_meta"] = _build_meta(repository=repository, targets=targets if targets else None)# Episode overflow is banked here because it is produced before the shared# final budget pass. The middleware owns the complete search-mode shed# order after trust metadata is attached; routing this shape through the# path-only fitter would discard its primary decision lane prematurely.- collector = bank_overflow(pending, tool="get_why", repo_root=ctx.path)- if collector is not None:- collector.attach(result_data)+ cap_collection(+ result_data,+ "decisions",+ result_data["decisions"],+ _MAX_SEARCH_DECISIONS,+ collector,+ label=f"search decisions beyond cap={_MAX_SEARCH_DECISIONS}",+ )+ cap_collection(+ result_data,+ "related_documentation",+ result_data["related_documentation"],+ 3,+ collector,+ label="related_documentation beyond cap=3",+ )+ collector.attach(result_data)return result_data@@ -1231,6 +1609,7 @@ async def _git_archaeology_fallback(git_meta: Any | None,all_git_meta: list,repository: Any,+ collector: OmissionCollector | None = None,) -> dict:"""When no decisions govern a file, mine git history for intent signals."""result: dict[str, Any] = {"triggered": True}@@ -1248,7 +1627,7 @@ async def _git_archaeology_fallback(}for c in commits]- result["file_commits"] = file_commits[:10] # Cap to keep response bounded+ result["file_commits"] = file_commits# --- Layer 2: Cross-file search — other files' commits mentioning this file ---basename = file_path.rsplit("/", 1)[-1] if "/" in file_path else file_path@@ -1267,7 +1646,7 @@ async def _git_archaeology_fallback(for c in commits:msg_lower = c.get("message", "").lower()# Match if the commit message mentions the file basename or 2+ stem terms- matched_terms = [t for t in search_terms if t in msg_lower]+ matched_terms = sorted(t for t in search_terms if t in msg_lower)if basename.lower() in msg_lower or len(matched_terms) >= 2:cross_references.append({@@ -1287,7 +1666,7 @@ async def _git_archaeology_fallback(seen_shas.add(cr["sha"])unique_refs.append(cr)unique_refs.sort(key=lambda x: x.get("date", ""), reverse=True)- result["cross_references"] = unique_refs[:10]+ result["cross_references"] = unique_refs# --- Layer 3: Live git log (when local repo exists) ---git_log_results = []@@ -1400,7 +1779,7 @@ async def _run_git_log()except (subprocess.TimeoutExpired, FileNotFoundError, OSError):pass- return results[:20]+ return resultstry:return await asyncio.wait_for(asyncio.to_thread(_sync_git_log), timeout=15)diff --git a/tests/unit/server/mcp/test_budget.py b/tests/unit/server/mcp/test_budget.pyindex 5ac2d7099..7a71e8142 100644--- a/tests/unit/server/mcp/test_budget.py+++ b/tests/unit/server/mcp/test_budget.py@@ -141,16 +141,17 @@ def test_collector_store_failure_degrades_silently(tmp_path: Path):assert "recovery_unavailable" in response["_meta"]-def test_collector_chunks_large_recovery_documents(repo_root: Path):+def test_collector_keeps_large_recovery_document_in_one_call(repo_root: Path):collector = OmissionCollector("test_tool", repo_root=repo_root)collector.add("large", "x" * 70_000)response: dict = {"_meta": {}}collector.attach(response)refs = response["_meta"]["omitted"]["refs"]- assert len(refs) == 3- assert len(response["omission_markers"]) == 3- assert all(len(_store_get(repo_root, ref) or "") <= 28_000 for ref in refs)+ assert len(refs) == 1+ assert "omission_markers" not in response+ recovered = _store_get(repo_root, refs[0]) or ""+ assert recovered.endswith("x" * 70_000)# ---------------------------------------------------------------------------@@ -368,7 +369,7 @@ def test_fit_to_budget_reports_total_emitted_and_reason(repo_root: Path):assert response["results_omitted"] == 6 - len(response["results"])-def test_fit_to_budget_preserves_projection_reason_and_persisted_omission_count(+def test_fit_to_budget_composes_projection_reason_and_full_omission_count(repo_root: Path,):response = {@@ -392,7 +393,7 @@ def test_fit_to_budget_preserves_projection_reason_and_persisted_omission_count(assert response["results_total"] == 8assert response["results_emitted"] == len(response["results"])assert response["results_reduced_reason"].endswith("_and_response_budget")- assert response["results_omitted"] == 3 - len(response["results"])+ assert response["results_omitted"] == 8 - len(response["results"])def test_fit_to_budget_can_reduce_a_ranked_mapping(repo_root: Path):diff --git a/tests/unit/server/mcp/test_context.py b/tests/unit/server/mcp/test_context.pyindex 5dfd5e655..3d4da5e67 100644--- a/tests/unit/server/mcp/test_context.py+++ b/tests/unit/server/mcp/test_context.py@@ -474,6 +474,56 @@ async def test_file_target_callers_rolls_up_importers(setup_mcp):assert "rollup" in t.get("_call_graph_note", "")+async def test_file_target_callers_bank_the_full_ranked_tail(+ setup_mcp, session, tmp_path, monkeypatch+):+ """File import rollups report and bank every caller beyond the visible 20."""+ from repowise.core.persistence.models import GraphEdge, GraphNode, Repository+ from repowise.server.mcp_server import get_context, get_symbol++ store_path = tmp_path / "omissions.sqlite3"+ monkeypatch.setattr(+ "repowise.server.mcp_server._budget.collector.default_store_path",+ lambda _root: store_path,+ )+ monkeypatch.setattr(+ "repowise.core.distill.store.default_store_path",+ lambda _root=None: store_path,+ )+ repo = (await session.execute(__import__("sqlalchemy").select(Repository))).scalars().first()+ for index in range(25):+ node_id = f"src/generated/importer_{index:02d}.py"+ session.add(+ GraphNode(+ id=f"file_importer_{index}",+ repository_id=repo.id,+ node_id=node_id,+ node_type="file",+ name=f"importer_{index:02d}.py",+ file_path=node_id,+ )+ )+ session.add(+ GraphEdge(+ repository_id=repo.id,+ source_node_id=node_id,+ target_node_id="src/auth/service.py",+ edge_type="imports",+ )+ )+ await session.commit()++ result = await get_context(["src/auth/service.py"], include=["callers"], compact=False)+ card = result["targets"]["src/auth/service.py"]+ assert card["callers_total"] == 27+ assert card["callers_emitted"] == 20+ assert card["callers_reduced_reason"] == "construction_cap"+ [ref] = result["_meta"]["omitted"]["refs"]+ recovered = await get_symbol(f"repowise#{ref}")+ assert "src/generated/importer_24.py" in recovered.get("content", ""), recovered++@pytest.mark.asyncioasync def test_symbol_callers_carry_definition_line(setup_mcp, session):"""Symbol-level callers must carry the caller's definition line so the@@ -616,12 +666,19 @@ async def test_one_caller_joined_by_two_edge_types_is_listed_once(setup_mcp, ses@pytest.mark.asyncio-async def test_high_fan_in_callers_signal_truncation(setup_mcp, session):+async def test_high_fan_in_callers_signal_truncation(+ setup_mcp, session, tmp_path, monkeypatch+):"""A symbol with more callers than the display cap must report the TRUEtotal + a truncation flag, so a find-all-callers sweep is not silentlymisled into thinking the partial list is complete (S2 dogfood bug)."""from repowise.core.persistence.models import GraphEdge, GraphNode, Repositoryfrom repowise.server.mcp_server import get_context+ from repowise.server.mcp_server._budget import collector as collector_mod++ monkeypatch.setattr(+ collector_mod, "default_store_path", lambda start=None: tmp_path / "omissions.db"+ )repo = (await session.execute(__import__("sqlalchemy").select(Repository))).scalars().first()target_id = "src/db/util.py::hot"@@ -675,8 +732,11 @@ async def test_high_fan_in_callers_signal_truncation(setup_mcp, session):t = result["targets"][target_id]assert len(t["callers"]) == 50 # capped displayassert t["callers_total"] == n_callers # true total surfaced+ assert t["callers_emitted"] == 50+ assert t["callers_reduced_reason"] == "construction_cap"assert t["callers_truncated"] is True- assert "grep" in t["_callers_note"]+ assert "get_symbol" in t["_callers_note"]+ assert result["_meta"]["omitted"]["refs"]# --- Structural retrieval: parent page + concept-page tree position ---------diff --git a/tests/unit/server/mcp/test_recoverable_caps_wire_contracts.py b/tests/unit/server/mcp/test_recoverable_caps_wire_contracts.pynew file mode 100644index 000000000..567bbf3cc--- /dev/null+++ b/tests/unit/server/mcp/test_recoverable_caps_wire_contracts.py@@ -0,0 +1,884 @@+"""Sealed final-wire fixtures for recoverable MCP response caps."""++from __future__ import annotations++import json+from datetime import UTC, datetime+from pathlib import Path+from types import SimpleNamespace+from typing import Any++import pytest++from repowise.core.persistence.models import (+ DecisionEdge,+ DecisionRecord,+ GitMetadata,+ GraphEdge,+ GraphNode,+)+from repowise.server.mcp_server import (+ get_context,+ get_risk,+ get_symbol,+ get_why,+ tool_middleware,+)+from repowise.server.mcp_server._budget import (+ DEFAULT_RESPONSE_CHARS,+ EXPANDED_RESPONSE_CHARS,+)++_NOW = datetime(2026, 8, 26, tzinfo=UTC)+++def _configure_omissions(tmp_path: Path) -> None:+ import repowise.server.mcp_server as mcp_mod++ (tmp_path / ".repowise").mkdir(exist_ok=True)+ mcp_mod._repo_path = str(tmp_path)+++def _wire_size(result: dict[str, Any]) -> int:+ return len(json.dumps(result, separators=(",", ":"), default=str))+++def _assert_wire(result: dict[str, Any], first: str, limit: int) -> None:+ assert next(iter(result)) == first+ accounting = result["_meta"]["response_budget"]+ assert accounting["serialized_chars"] == _wire_size(result) <= limit+ assert accounting["limit_chars"] == limit+++async def _recover(result: dict[str, Any]) -> str:+ recovered: list[str] = []+ for ref in result.get("_meta", {}).get("omitted", {}).get("refs", []):+ row = await get_symbol(f"repowise#{ref}")+ assert "error" not in row, row+ recovered.append(row["content"])+ return "\n".join(recovered)+++async def _recover_one(result: dict[str, Any], *sentinels: str) -> str:+ """Prove each named omitted row is contained by one public recovery call."""+ refs = result.get("_meta", {}).get("omitted", {}).get("refs", [])+ assert refs+ contents: list[str] = []+ for ref in refs:+ row = await get_symbol(f"repowise#{ref}")+ assert "error" not in row, row+ contents.append(row["content"])+ for sentinel in sentinels:+ assert any(sentinel in content for content in contents), sentinel+ return "\n".join(contents)+++def _omission_section(recovered: str, label: str) -> str:+ marker = f"==== {label} ===="+ assert marker in recovered, label+ return recovered.split(marker, 1)[1].split("==== ", 1)[0].strip()+++async def _seed_context_fanout(session: Any, rid: str, count: int) -> str:+ target = "src/sealed/hub.py::hub"+ session.add(+ GraphNode(+ id="sealed-hub",+ repository_id=rid,+ node_id=target,+ node_type="symbol",+ name="hub",+ file_path="src/sealed/hub.py",+ kind="function",+ start_line=1,+ end_line=2,+ created_at=_NOW,+ )+ )+ for index in range(count):+ caller = f"src/sealed/caller_{index:03d}.py::call_{index:03d}"+ callee = f"src/sealed/callee_{index:03d}.py::work_{index:03d}"+ session.add_all(+ [+ GraphNode(+ id=f"sealed-caller-{index}",+ repository_id=rid,+ node_id=caller,+ node_type="symbol",+ name=f"call_{index:03d}",+ file_path=caller.split("::", 1)[0],+ kind="function",+ start_line=index + 1,+ end_line=index + 2,+ created_at=_NOW,+ ),+ GraphNode(+ id=f"sealed-callee-{index}",+ repository_id=rid,+ node_id=callee,+ node_type="symbol",+ name=f"work_{index:03d}",+ file_path=callee.split("::", 1)[0],+ kind="function",+ start_line=index + 1,+ end_line=index + 2,+ created_at=_NOW,+ ),+ GraphEdge(+ id=f"sealed-in-{index}",+ repository_id=rid,+ source_node_id=caller,+ target_node_id=target,+ edge_type="calls",+ confidence=0.99,+ created_at=_NOW,+ ),+ GraphEdge(+ id=f"sealed-out-{index}",+ repository_id=rid,+ source_node_id=target,+ target_node_id=callee,+ edge_type="calls",+ confidence=0.99,+ created_at=_NOW,+ ),+ ]+ )+ await session.flush()+ return target+++async def test_context_real_minimum_and_typical_wire_shapes(+ setup_mcp: str, session: Any, tmp_path: Path+) -> None:+ _configure_omissions(tmp_path)+ wrapped = tool_middleware(get_context)++ minimum = await wrapped(["src/auth/service.py"])+ _assert_wire(minimum, "targets", DEFAULT_RESPONSE_CHARS)+ assert "truncated" not in minimum++ target = await _seed_context_fanout(session, setup_mcp, 3)+ typical = await wrapped([target], include=["callers", "callees"])+ _assert_wire(typical, "targets", EXPANDED_RESPONSE_CHARS)+ card = typical["targets"][target]+ assert len(card["callers"]) == len(card["callees"]) == 3+ assert "callers_total" not in card and "callees_total" not in card+++async def test_context_real_adversarial_wire_recovers_independent_tails(+ setup_mcp: str, session: Any, tmp_path: Path+) -> None:+ _configure_omissions(tmp_path)+ target = await _seed_context_fanout(session, setup_mcp, 63)+ result = await tool_middleware(get_context)(+ [target], include=["callers", "callees"]+ )++ _assert_wire(result, "targets", EXPANDED_RESPONSE_CHARS)+ card = result["targets"][target]+ for key in ("callers", "callees"):+ assert card[f"{key}_total"] == 63+ assert card[f"{key}_emitted"] == 50+ assert card[f"{key}_reduced_reason"] == "construction_cap"+ recovered = await _recover_one(result, "caller_062", "callee_062")+ assert "caller_062" in recovered and "callee_062" in recovered+ assert "caller_000" not in recovered and "callee_000" not in recovered+++async def test_context_used_by_and_relations_recover_in_one_bounded_query_shape(+ setup_mcp: str, session: Any, tmp_path: Path+) -> None:+ from sqlalchemy import event++ _configure_omissions(tmp_path)+ target = await _seed_context_fanout(session, setup_mcp, 1)+ for index in range(26):+ file_id = f"src/sealed/user_{index:03d}.py"+ relation_id = f"src/sealed/type_{index:03d}.py::Type{index:03d}"+ session.add_all(+ [+ GraphNode(+ id=f"sealed-user-{index}",+ repository_id=setup_mcp,+ node_id=file_id,+ node_type="file",+ file_path=file_id,+ pagerank=index / 100,+ created_at=_NOW,+ ),+ GraphNode(+ id=f"sealed-type-{index}",+ repository_id=setup_mcp,+ node_id=relation_id,+ node_type="symbol",+ name=f"Type{index:03d}",+ file_path=relation_id.split("::", 1)[0],+ kind="class",+ created_at=_NOW,+ ),+ GraphEdge(+ id=f"sealed-import-{index}",+ repository_id=setup_mcp,+ source_node_id=file_id,+ target_node_id="src/auth/service.py",+ edge_type="imports",+ imported_names_json='["AuthService"]',+ created_at=_NOW,+ ),+ GraphEdge(+ id=f"sealed-extends-{index}",+ repository_id=setup_mcp,+ source_node_id=relation_id,+ target_node_id=target,+ edge_type="extends",+ confidence=0.95,+ created_at=_NOW,+ ),+ ]+ )+ await session.flush()++ statements = 0++ def count_statement(*_args: Any, **_kwargs: Any) -> None:+ nonlocal statements+ statements += 1++ engine = session.bind.sync_engine+ event.listen(engine, "before_cursor_execute", count_statement)+ try:+ relation_result = await tool_middleware(get_context)(+ [target], include=["callers"]+ )+ relation_statements = statements+ statements = 0+ used_by_result = await tool_middleware(get_context)(["AuthService"])+ used_by_statements = statements+ finally:+ event.remove(engine, "before_cursor_execute", count_statement)++ relation = next(+ row+ for row in relation_result["targets"][target]["relations"]+ if row["edge_type"] == "extends"+ )+ assert relation["rows_total"] == 26 and relation["rows_emitted"] == 5+ docs = used_by_result["targets"]["AuthService"]["docs"]+ assert docs["used_by_total"] >= 26 and docs["used_by_emitted"] == 20+ recovered = await _recover_one(used_by_result, "src/sealed/user_000.py")+ assert "src/sealed/user_000.py" in recovered+ assert "src/sealed/user_025.py" not in recovered+ relation_recovered = await _recover_one(relation_result, "Type025")+ assert "Type025" in relation_recovered+ assert "Type000" not in relation_recovered+ assert relation_statements <= 20 and used_by_statements <= 20+++async def test_risk_real_minimum_and_typical_wire_shapes(+ setup_mcp: str, tmp_path: Path+) -> None:+ _configure_omissions(tmp_path)+ wrapped = tool_middleware(get_risk)++ minimum = await wrapped(["src/auth/service.py"])+ _assert_wire(minimum, "targets", DEFAULT_RESPONSE_CHARS)++ typical = await wrapped(+ ["src/auth/service.py"], changed_files=["src/auth/service.py"]+ )+ _assert_wire(typical, "directive", DEFAULT_RESPONSE_CHARS)+ assert next(iter(typical["directive"])) == "may_break"+ for key in ("breaking_changes", "conformance_violations", "dependency_cycles"):+ assert f"{key}_total" not in typical["directive"]+++async def test_risk_multi_target_graph_cards_recover_relationship_tails(+ setup_mcp: str, session: Any, tmp_path: Path+) -> None:+ _configure_omissions(tmp_path)+ for index in range(14):+ file_id = f"src/sealed/risk_consumer_{index:03d}.py"+ session.add_all(+ [+ GraphNode(+ id=f"sealed-risk-file-{index}",+ repository_id=setup_mcp,+ node_id=file_id,+ node_type="file",+ file_path=file_id,+ created_at=_NOW,+ ),+ GraphEdge(+ id=f"sealed-risk-import-{index}",+ repository_id=setup_mcp,+ source_node_id=file_id,+ target_node_id="src/auth/service.py",+ edge_type="imports",+ created_at=_NOW,+ ),+ ]+ )+ await session.flush()++ result = await tool_middleware(get_risk)(+ ["src/auth/service.py", "src/auth/middleware.py"], include=["graph"]+ )+ _assert_wire(result, "targets", EXPANDED_RESPONSE_CHARS)+ card = result["targets"]["src/auth/service.py"]+ assert card["dependents_total"] >= 14+ assert card["dependents_emitted"] < card["dependents_total"]+ recovered = await _recover_one(result, "risk_consumer_013.py")+ assert "risk_consumer_000.py" not in recovered+++async def test_risk_real_adversarial_wire_recovers_each_directive_lane(+ setup_mcp: str, session: Any, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ from repowise.core.analysis.pr_blast import PRBlastRadiusAnalyzer++ _configure_omissions(tmp_path)+ for index in range(8):+ session.add(+ GraphNode(+ id=f"sealed-test-{index}",+ repository_id=setup_mcp,+ node_id=f"tests/sealed_{index}.py",+ node_type="file",+ is_test=True,+ created_at=_NOW,+ )+ )+ await session.flush()++ original = PRBlastRadiusAnalyzer.analyze_files++ async def sealed_analyze(self: Any, changed_files: list[str], **kwargs: Any) -> dict:+ payload = await original(self, changed_files, **kwargs)+ payload["transitive_affected"] = [+ *[f"src/downstream_{i}.py" for i in range(9)],+ *[f"tests/sealed_{i}.py" for i in range(8)],+ ]+ payload["cochange_warnings"] = [f"src/cochange_{i}.py" for i in range(8)]+ payload["guarding_tests"] = {+ "tests_to_run": [f"tests/GUARD_{i}.py::test_it" for i in range(14)],+ "basis": "measured",+ }+ recommendations = [+ {+ "test_id": f"tests/REC_{i}.py::test_it",+ "basis": "measured" if i % 2 == 0 else "inferred",+ "basis_detail": f"REC_DETAIL_{i}_" + "d" * 2000,+ }+ for i in range(15)+ ]+ payload["test_impact"] = {+ "recommendations": recommendations,+ "recommendations_by_primary_basis": {"measured": 8, "inferred": 7},+ "coverage": {"status": "available", "freshness": {"status": "fresh"}},+ "inference": {"status": "available"},+ "analysis": {"status": "available"},+ "files_without_measured_tests": [+ f"src/NO_MEASURED_{i}.py" for i in range(12)+ ],+ "unknown_files": [f"src/UNKNOWN_{i}.py" for i in range(12)],+ }+ payload["test_gaps"] = list(changed_files)+ payload["sealed_support_noise"] = "FINAL_BUDGET_SENTINEL_" + "z" * 30_000+ return payload++ monkeypatch.setattr(PRBlastRadiusAnalyzer, "analyze_files", sealed_analyze)+ changed = [f"src/gap_{i}.py" for i in range(6)]+ result = await tool_middleware(get_risk)(+ ["src/auth/service.py"], changed_files=changed+ )++ _assert_wire(result, "directive", DEFAULT_RESPONSE_CHARS)+ directive = result["directive"]+ expected = {+ "may_break": 9,+ "may_break_tests": 8,+ "missing_cochanges": 8,+ "missing_tests": 6,+ "tests_to_run": 14,+ "test_recommendations": 15,+ "files_without_measured_tests": 12,+ "test_unknown_files": 12,+ }+ for key, total in expected.items():+ assert directive[f"{key}_total"] == total+ assert directive[f"{key}_emitted"] < total+ assert directive[f"{key}_reduced_reason"].startswith("construction_cap")+ assert result["truncated"] is True+ assert "pr_blast_radius" not in result+ assert directive["test_recommendations_reduced_reason"] == (+ "construction_cap_and_response_budget"+ )+ assert directive["test_recommendations_omitted"] == (+ directive["test_recommendations_total"]+ - directive["test_recommendations_emitted"]+ )+ recovered = await _recover_one(+ result,+ "downstream_8",+ "sealed_7",+ "cochange_7",+ "REC_14",+ "GUARD_13",+ "src/gap_5.py",+ "FINAL_BUDGET_SENTINEL",+ "NO_MEASURED_11",+ "UNKNOWN_11",+ )+ assert "downstream_8" in recovered+ assert "sealed_7" in recovered+ assert "cochange_7" in recovered+ assert "REC_14" in recovered and '"basis": "measured"' in recovered+ rec_14_row = recovered.split('"test_id": "tests/REC_14.py::test_it"', 1)[1][+ :5000+ ]+ assert '"basis": "measured"' in rec_14_row+ assert "REC_DETAIL_14" in rec_14_row+ assert "GUARD_13" in recovered+ assert "src/gap_5.py" in recovered+ assert "FINAL_BUDGET_SENTINEL" in recovered+++async def test_risk_breaking_and_conformance_caps_are_counted_and_recoverable(+ setup_mcp: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ import repowise.server.mcp_server.tool_risk.directives as directives_mod+ from repowise.server.mcp_server import _state++ _configure_omissions(tmp_path)+ changes = [+ {+ "contract_id": f"contract-{index}",+ "contract_type": "code",+ "kind": "removed_endpoint",+ "severity": "breaking",+ "detail": f"BREAKING_SENTINEL_{index}",+ "provider_file": f"src/provider_{index}.py",+ "impacted_consumers": [+ {+ "repo": "consumer",+ "service": "api",+ "file": f"src/consumer_{index}_{consumer}.py",+ }+ for consumer in range(7)+ ],+ }+ for index in range(7)+ ]+ violations = [+ {+ "source": "repowise",+ "target": f"forbidden-{index}",+ "rule_source": "repowise",+ "rule_target": f"forbidden-{index}",+ "edge_kind": "imports",+ "rule_description": f"CONFORMANCE_SENTINEL_{index}",+ }+ for index in range(7)+ ]+ cycles = [+ {"nodes": ["repowise", f"cycle-{index}"], "length": 2} for index in range(5)+ ]+ enricher = SimpleNamespace(+ has_breaking_changes=True,+ has_conformance=True,+ get_breaking_changes_for_repo=lambda alias: changes,+ get_conformance_for_repo=lambda alias: {+ "violations": violations,+ "cycles": cycles,+ },+ get_system_graph=lambda: None,+ )+ monkeypatch.setattr(_state, "_cross_repo_enricher", enricher)+ monkeypatch.setattr(directives_mod, "_is_workspace_mode", lambda: True)+ response = await tool_middleware(get_risk)(+ ["src/auth/service.py"], changed_files=["src/auth/service.py"]+ )+ _assert_wire(response, "directive", DEFAULT_RESPONSE_CHARS)++ directive = response["directive"]+ for key, total, emitted in (+ ("breaking_changes", 7, 5),+ ("conformance_violations", 7, 5),+ ("dependency_cycles", 5, 3),+ ):+ assert directive[f"{key}_total"] == total+ assert directive[f"{key}_emitted"] == emitted+ assert directive[f"{key}_reduced_reason"] == "construction_cap"+ assert directive["breaking_changes"][0]["impacted_consumers_total"] == 7+ assert directive["breaking_changes_truncated"] == 2+ recovered = await _recover_one(+ response,+ "BREAKING_SENTINEL_6",+ "CONFORMANCE_SENTINEL_6",+ "cycle-4",+ "src/consumer_0_6.py",+ )+ assert "BREAKING_SENTINEL_6" in recovered+ assert "CONFORMANCE_SENTINEL_6" in recovered+ assert "cycle-4" in recovered+ assert "src/consumer_0_6.py" in recovered+++async def _seed_why_decisions(session: Any, rid: str, count: int) -> None:+ for index in range(count):+ session.add_all(+ [+ DecisionRecord(+ id=f"sealed-why-ancestor-{index}",+ repository_id=rid,+ title=f"Legacy unrelated policy {index}",+ status="superseded",+ decision="Retain the former policy for lineage.",+ affected_files_json="[]",+ affected_modules_json="[]",+ alternatives_json="[]",+ consequences_json="[]",+ tags_json="[]",+ source="git_history",+ created_at=_NOW,+ updated_at=_NOW,+ ),+ DecisionRecord(+ id=f"sealed-why-{index}",+ repository_id=rid,+ title=f"Use sealed response contract {index}",+ status="active" if index == 0 else "proposed",+ context="sealed response context " + "x" * 1200,+ decision="Use sealed response contract for recovery.",+ rationale=f"WHY_SENTINEL_{index}_" + "r" * 800,+ affected_files_json=json.dumps(["src/auth/service.py"]),+ affected_modules_json="[]",+ alternatives_json="[]",+ consequences_json="[]",+ tags_json='["sealed", "response"]',+ source="session",+ evidence_commits_json=json.dumps([f"{index + 1:040x}"]),+ confidence=0.9 - index / 100,+ staleness_score=0.0,+ created_at=_NOW,+ updated_at=_NOW,+ ),+ DecisionEdge(+ id=f"sealed-lineage-{index}",+ repository_id=rid,+ src_decision_id=f"sealed-why-{index}",+ dst_decision_id=f"sealed-why-ancestor-{index}",+ kind="supersedes",+ confidence=1.0,+ created_at=_NOW,+ ),+ ]+ )+ await session.flush()+++async def test_why_real_minimum_and_typical_wire_shapes(+ setup_mcp: str, tmp_path: Path+) -> None:+ _configure_omissions(tmp_path)+ wrapped = tool_middleware(get_why)++ minimum = await wrapped("where is the episode store")+ _assert_wire(minimum, "mode", DEFAULT_RESPONSE_CHARS)+ assert minimum["decisions"] == [] and "truncated" not in minimum++ typical = await wrapped("src/auth/service.py")+ _assert_wire(typical, "mode", DEFAULT_RESPONSE_CHARS)+ assert typical["decisions"]+++async def test_why_real_adversarial_wire_recovers_decisions_docs_and_episodes(+ setup_mcp: str, session: Any, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ import repowise.server.mcp_server.tool_why as why_mod++ _configure_omissions(tmp_path)+ await _seed_why_decisions(session, setup_mcp, 9)++ semantic_decisions: list[Any] = []+ semantic_docs = [+ SimpleNamespace(+ page_id=f"file_page:docs/sealed_{i}.md",+ title=f"Sealed documentation {i}",+ page_type="file_page",+ snippet=f"DOC_SENTINEL_{i}_" + "d" * 400,+ score=0.9 - i / 100,+ )+ for i in range(8)+ ]++ async def sealed_semantic(ctx: Any, query: str) -> tuple[list[Any], list[Any]]:+ return semantic_decisions, semantic_docs++ def sealed_episodes(*args: Any, **kwargs: Any) -> tuple[list[dict], list]:+ population: list[dict[str, Any]] = []+ pending: list[tuple[dict[str, Any], str, str]] = []+ for i in range(8):+ body = f"EPISODE_SENTINEL_{i}_START_" + "e" * 1100 + f"_END_{i}"+ entry = {+ "tier": "git",+ "kind": "sealed",+ "subject": f"Episode {i}",+ "recorded": body[:900],+ "evidence": {"commit": f"{i:040x}"},+ "scope": ["src/auth/service.py"],+ }+ population.append(entry)+ pending.append((entry, f"episode:sealed:{i}", body))+ full = kwargs.get("full_population")+ if isinstance(full, list):+ full.extend(population)+ return population[:3], pending++ monkeypatch.setattr(why_mod, "_semantic_lanes", sealed_semantic)+ monkeypatch.setattr(why_mod, "episode_evidence", sealed_episodes)++ result = await tool_middleware(get_why)(+ "why use sealed response contract",+ targets=["src/auth/service.py"],+ )++ _assert_wire(result, "mode", DEFAULT_RESPONSE_CHARS)+ assert result["decisions_total"] >= 9+ assert result["decisions_emitted"] <= 3+ assert "construction_cap" in result["decisions_reduced_reason"]+ assert result["related_documentation_total"] == 8+ assert result["episodes_total"] == 8+ context = result["target_context"]["src/auth/service.py"]+ assert context["governing_decisions_total"] >= 9++ recovered = await _recover_one(+ result,+ "WHY_SENTINEL_8",+ "DOC_SENTINEL_7",+ "EPISODE_SENTINEL_7_START_",+ "_END_7",+ )+ assert "WHY_SENTINEL_8" in recovered+ assert "DOC_SENTINEL_7" in recovered+ assert "EPISODE_SENTINEL_7" in recovered+ assert '"evidence_refs"' in recovered+ assert "sealed-why-ancestor" in recovered+ omitted_decisions = json.loads(+ _omission_section(recovered, "search decisions beyond cap=3")+ )+ why_8_row = next(row for row in omitted_decisions if row["id"] == "sealed-why-8")+ assert any(+ row["id"] == "sealed-why-ancestor-8" for row in why_8_row["lineage"]+ )+ assert why_8_row["evidence_refs"]+ assert "repowise#" in result["episodes"][0]["recorded"]+ hidden_body_refs = [+ ref+ for ref in result["_meta"]["omitted"]["refs"]+ if "_END_7" in (+ await get_symbol(f"repowise#{ref}")+ ).get("content", "")+ ]+ assert len(hidden_body_refs) == 1+ emitted_ids = {row["id"] for row in result["decisions"] if "id" in row}+ assert all(decision_id not in recovered for decision_id in emitted_ids)+++async def test_why_health_and_targets_only_modes_are_bounded_and_recoverable(+ setup_mcp: str,+ session: Any,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from sqlalchemy import select++ import repowise.core.persistence.crud as crud_mod++ _configure_omissions(tmp_path)+ await _seed_why_decisions(session, setup_mcp, 9)+ records = list(+ (+ await session.execute(+ select(DecisionRecord).where(+ DecisionRecord.id.in_([f"sealed-why-{index}" for index in range(9)])+ )+ )+ )+ .scalars()+ .all()+ )+ records[0].affected_files_json = json.dumps(+ [f"src/HEALTH_AFFECTED_{index}.py" for index in range(8)]+ )++ async def sealed_health(*_args: Any, **_kwargs: Any) -> dict[str, Any]:+ return {+ "summary": {"active": 1, "stale": len(records)},+ "stale_decisions": records,+ "proposed_awaiting_review": records,+ "ungoverned_hotspots": [+ {"file_path": f"src/HEALTH_HOTSPOT_{index}.py"}+ for index in range(12)+ ],+ "conflicts": [+ {"detail": f"HEALTH_CONFLICT_{index}"} for index in range(12)+ ],+ }++ monkeypatch.setattr(crud_mod, "get_decision_health_summary", sealed_health)+ wrapped = tool_middleware(get_why)++ health = await wrapped()+ _assert_wire(health, "mode", DEFAULT_RESPONSE_CHARS)+ assert health["stale_decisions_total"] == 9+ assert health["stale_decisions_emitted"] == 5+ assert health["proposed_awaiting_review_total"] == 9+ assert health["proposed_awaiting_review_emitted"] == 5+ assert health["ungoverned_hotspots_total"] == 12+ assert health["ungoverned_hotspots_emitted"] == 8+ assert health["conflicts_total"] == 12+ assert health["conflicts_emitted"] == 10+ assert health["stale_decisions"][0]["affected_files_total"] == 8+ health_recovered = await _recover_one(+ health,+ "sealed response contract 8",+ "HEALTH_HOTSPOT_11",+ "HEALTH_CONFLICT_11",+ "HEALTH_AFFECTED_7",+ )+ assert "sealed response contract 8" in health_recovered.lower()+ stale_tail = json.loads(+ _omission_section(+ health_recovered, "health stale_decisions beyond cap=5"+ )+ )+ proposed_tail = json.loads(+ _omission_section(+ health_recovered, "health proposed_awaiting_review beyond cap=5"+ )+ )+ assert any(row["id"] == "sealed-why-8" for row in stale_tail)+ assert any(row["id"] == "sealed-why-8" for row in proposed_tail)++ targets_only = await wrapped(+ targets=["src/auth/service.py", "src/auth/middleware.py"]+ )+ _assert_wire(targets_only, "mode", DEFAULT_RESPONSE_CHARS)+ context = targets_only["target_context"]["src/auth/service.py"]+ assert context["governing_decisions_total"] >= 9+ assert context["governing_decisions_emitted"] == 8+ recovered = await _recover_one(targets_only, "sealed-why-8")+ assert "sealed-why-8" in recovered+ assert '"evidence_refs"' in recovered+++async def test_why_fallback_archaeology_and_rationale_wire_recover_annotated_tails(+ setup_mcp: str,+ session: Any,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ import repowise.server.mcp_server.tool_why as why_mod++ _configure_omissions(tmp_path)+ commits = [+ {+ "sha": f"{index + 100:040x}",+ "message": f"ARCHAEOLOGY_SENTINEL_{index}",+ "author": "sealed",+ "date": f"2026-08-{index + 1:02d}",+ }+ for index in range(13)+ ]+ session.add(+ GitMetadata(+ id="sealed-fallback-git",+ repository_id=setup_mcp,+ file_path="src/sealed/fallback.py",+ significant_commits_json=json.dumps(commits),+ )+ )+ for index in range(13):+ session.add(+ GitMetadata(+ id=f"sealed-cross-git-{index}",+ repository_id=setup_mcp,+ file_path=f"src/sealed/cross_{index}.py",+ significant_commits_json=json.dumps(+ [+ {+ "sha": f"{index + 200:040x}",+ "message": (+ f"fallback.py CROSS_REFERENCE_SENTINEL_{index}"+ ),+ "author": "sealed",+ "date": f"2026-07-{index + 1:02d}",+ }+ ]+ ),+ )+ )+ from repowise.core.persistence.models import Repository++ repository = await session.get(Repository, setup_mcp)+ repository.local_path = str(Path.cwd())+ await session.flush()++ async def sealed_git_log(*_args: Any, **_kwargs: Any) -> list[dict[str, Any]]:+ return [+ {+ "sha": f"{index + 300:040x}",+ "message": f"GIT_LOG_SENTINEL_{index}",+ "author": "sealed",+ "date": f"2026-06-{index + 1:02d}",+ "source": "git_log",+ }+ for index in range(23)+ ]++ monkeypatch.setattr(why_mod, "_run_git_log", sealed_git_log)+ monkeypatch.setattr(+ why_mod,+ "_mine_rationale",+ lambda *_args, **_kwargs: [+ {+ "path": "src/sealed/fallback.py",+ "lines": f"{index + 1}-{index + 1}",+ "comment": f"RATIONALE_SENTINEL_{index}",+ }+ for index in range(8)+ ],+ )++ result = await tool_middleware(get_why)("src/sealed/fallback.py")+ _assert_wire(result, "mode", DEFAULT_RESPONSE_CHARS)+ assert result["git_archaeology"]["file_commits_total"] == 13+ assert result["git_archaeology"]["cross_references_total"] == 13+ assert result["git_archaeology"]["git_log_total"] == 23+ assert result["code_rationale_total"] == 8+ recovered = await _recover_one(+ result,+ "ARCHAEOLOGY_SENTINEL_12",+ "CROSS_REFERENCE_SENTINEL_0",+ "GIT_LOG_SENTINEL_22",+ "RATIONALE_SENTINEL_7",+ )+ assert "ARCHAEOLOGY_SENTINEL_12" in recovered+ assert "RATIONALE_SENTINEL_7" in recovered+ assert "CROSS_REFERENCE_SENTINEL_12" not in recovered+ rationale_row = recovered.split("RATIONALE_SENTINEL_7", 1)[1][:2000]+ assert '"provenance": "extracted_rationale"' in rationale_row+ assert '"evidence_refs"' in rationale_rowdiff --git a/tests/unit/server/mcp/test_risk.py b/tests/unit/server/mcp/test_risk.pyindex 122872cc7..603b59e03 100644--- a/tests/unit/server/mcp/test_risk.py+++ b/tests/unit/server/mcp/test_risk.py@@ -505,8 +505,10 @@ async def test_get_risk_directive_points_at_the_full_run_list_when_capped(setup_assert f"Showing {_TESTS_TO_RUN_LIMIT} of {over_cap + 1}" in directive["summary"]assert directive["tests_to_run_total"] == over_capassert directive["tests_to_run_emitted"] == _TESTS_TO_RUN_LIMIT+ assert directive["tests_to_run_reduced_reason"] == "construction_cap"assert directive["tests_to_run_truncated"] is Trueassert directive["test_recommendations_total"] == over_cap + 1+ assert directive["test_recommendations_reduced_reason"] == "construction_cap"assert "response omission marker" in directive["summary"]assert len(result["pr_blast_radius"]["guarding_tests"]["tests_to_run"]) == over_cap@@ -551,5 +553,6 @@ async def test_missing_tests_totals_use_full_precap_changed_file_population(setuassert directive["missing_tests"] == changed[:3]assert directive["missing_tests_total"] == 5assert directive["missing_tests_emitted"] == 3+ assert directive["missing_tests_reduced_reason"] == "construction_cap"assert directive["missing_tests_truncated"] is Trueassert directive["missing_tests_omitted"] == 2diff --git a/tests/unit/server/mcp/test_used_by_ranking.py b/tests/unit/server/mcp/test_used_by_ranking.pyindex c657938a5..a93c84ca6 100644--- a/tests/unit/server/mcp/test_used_by_ranking.py+++ b/tests/unit/server/mcp/test_used_by_ranking.py@@ -108,10 +108,14 @@ async def _card(session, repository, target: str) -> dict:async def test_the_most_central_user_survives_the_cut(session, repository, many_users) -> None:- used_by = (await _card(session, repository, "AuthService"))["docs"]["used_by"]+ docs = (await _card(session, repository, "AuthService"))["docs"]+ used_by = docs["used_by"]assert len(used_by) == _MAX_USED_BYassert used_by[0] == "src/zz_hub.py"+ assert docs["used_by_total"] == _NOISE + 3+ assert docs["used_by_emitted"] == _MAX_USED_BY+ assert docs["used_by_reduced_reason"] == "construction_cap"async def test_used_by_is_ordered_by_centrality(session, repository, many_users) -> None:diff --git a/tests/unit/server/mcp/test_why.py b/tests/unit/server/mcp/test_why.pyindex 96e35cdb7..a92ef9d62 100644--- a/tests/unit/server/mcp/test_why.py+++ b/tests/unit/server/mcp/test_why.py@@ -439,11 +439,53 @@ async def test_get_why_path_fits_a_narrowed_host_cap(session, setup_mcp, monkeypassert len(_json.dumps(result, default=str)) <= effective_char_budget()+def test_path_final_fit_composes_episode_construction_counts(tmp_path, monkeypatch):+ from repowise.server.mcp_server._budget import OmissionCollector+ from repowise.server.mcp_server.tool_why import _fit_path_response++ monkeypatch.setenv("MAX_MCP_OUTPUT_TOKENS", "2000")+ response = {+ "mode": "path",+ "path": "src/large.py",+ "decisions": [],+ "episodes": [+ {"subject": f"episode-{index}", "recorded": "x" * 5000}+ for index in range(3)+ ],+ "episodes_total": 8,+ "episodes_emitted": 3,+ "episodes_reduced_reason": "construction_cap",+ "episodes_truncated": True,+ "episodes_omitted": 5,+ "_meta": {},+ }+ collector = OmissionCollector(+ "get_why", store_path=tmp_path / "omissions.sqlite3"+ )++ result = _fit_path_response(response, tmp_path, collector)++ assert result["episodes_total"] == 8+ assert result["episodes_emitted"] == 0+ assert result["episodes_omitted"] == 8+ assert result["episodes_reduced_reason"] == (+ "construction_cap_and_response_budget"+ )+ assert result["_meta"]["omitted"]["refs"]++@pytest.mark.asyncio-async def test_get_why_path_caps_records_and_keeps_the_active_one_first(session, setup_mcp):+async def test_get_why_path_caps_records_and_keeps_the_active_one_first(+ session, setup_mcp, tmp_path, monkeypatch+):from repowise.server.mcp_server import get_why+ from repowise.server.mcp_server._budget import collector as collector_modfrom repowise.server.mcp_server.tool_why import _MAX_PATH_DECISIONS+ monkeypatch.setattr(+ collector_mod, "default_store_path", lambda start=None: tmp_path / "omissions.db"+ )+await _seed_bulky_decisions(session, setup_mcp, "src/auth/service.py", 30)result = await get_why("src/auth/service.py")@@ -453,6 +495,9 @@ async def test_get_why_path_caps_records_and_keeps_the_active_one_first(session,assert result["decisions"][0]["status"] == "active"# And the count that was capped is still reported honestly.assert result["decisions_total"] == 31+ assert result["decisions_emitted"] == _MAX_PATH_DECISIONS+ assert result["decisions_reduced_reason"] == "construction_cap_and_response_budget"+ assert result["_meta"]["omitted"]["refs"]assert result["alignment"]["governing_count"] == 31diff --git a/tests/unit/server/mcp/test_why_workspace_ranking.py b/tests/unit/server/mcp/test_why_workspace_ranking.pyindex 8ccd308aa..ac2f56a15 100644--- a/tests/unit/server/mcp/test_why_workspace_ranking.py+++ b/tests/unit/server/mcp/test_why_workspace_ranking.py@@ -197,7 +197,7 @@ async def test_a_question_the_workspace_cannot_answer_gets_a_redirect(two_repos)@pytest.mark.asyncio-async def test_workspace_search_serves_five_of_nine_answers(tmp_path):+async def test_workspace_search_serves_five_of_nine_answers(tmp_path, monkeypatch):"""The count is written out rather than read from the constant.Comparing the result against ``_MAX_WORKSPACE_DECISIONS`` would hold for any@@ -205,7 +205,16 @@ async def test_workspace_search_serves_five_of_nine_answers(tmp_path):about an agent's context, which is exactly the kind of thing a test shouldfail on when it changes."""- from repowise.server.mcp_server import get_why+ from repowise.server.mcp_server import get_symbol, get_why, tool_middleware++ monkeypatch.setattr(+ "repowise.server.mcp_server._budget.collector.default_store_path",+ lambda _root: tmp_path / "omissions.sqlite3",+ )+ monkeypatch.setattr(+ "repowise.core.distill.store.default_store_path",+ lambda _root=None: tmp_path / "omissions.sqlite3",+ )ctx = await _store(tmp_path,@@ -229,8 +238,17 @@ async def test_workspace_search_serves_five_of_nine_answers(tmp_path):# and the cap is the only thing deciding the count. A question carrying a# word none of them holds would be refused outright instead, since an unseen# term takes the rarest weight the store can award.- result = await get_why(query="why is Redis the session cache backend", repo="all")+ result = await tool_middleware(get_why)(+ query="why is Redis the session cache backend", repo="all"+ )assert len(result["decisions"]) == 5+ assert result["decisions_total"] == 9+ assert result["decisions_emitted"] == 5+ assert result["decisions_reduced_reason"] == "construction_cap"+ [ref] = result["_meta"]["omitted"]["refs"]+ recovered = await get_symbol(f"repowise#{ref}")+ assert "Redis session cache decision 8" in recovered["content"]+ assert '"evidence_refs"' in recovered["content"]finally:await _uninstall(registry)