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
refactor(mcp): one response-budget contract for every tool (#2051)
Raghav Chamadiya7c65a0449d95
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.mdindex 1875e62f6..3cfd29119 100644--- a/docs/agent/MCP_TOOLS.md+++ b/docs/agent/MCP_TOOLS.md@@ -132,6 +132,12 @@ Truncated skeleton blocks are replaced in place by a `[repowise#<ref>: ...]`marker; everything else is captured into one combined document per response.A response that would still oversize sheds whole blocks, in an order each tooldeclares cheapest-loss-first, and reports `truncated: true` alongside the refs.++Every tool is budgeted. Most declare their own shed order; the rest meet a+final size guard that trims the largest blocks and records what it took. Either+way no response is returned unbounded and unflagged, and+`_meta.response_budget` reports the ceiling that applied and the size delivered+under it.Resolve refs with `repowise expand <ref>` from a shell, or`get_symbol("repowise#<ref>")` from any MCP client. See[DISTILL.md](DISTILL.md) for the full reversibility model.@@ -150,6 +156,8 @@ Resolve refs with `repowise expand <ref>` from a shell, or| `index_behind` | Whenever the live-vs-indexed comparison ran: `true` if HEAD has moved (alongside `stale_warning` when served content actually changed), `false` if the commits match. Absent means the comparison could not run (no git, or a repo-level tool that serves no file content) || `embedder_degraded` | Whenever an embedder is resolved, `true` or `false`. Absent means none was initialised || `embedder`, `embedder_warning` | Only when the embedder fell back to a mock/degraded mode |+| `response_budget` | Always: `limit_chars` (the ceiling that applied), `tier` (`default` or `expanded`, chosen by whether the call passed an expansion argument), `serialized_chars` (the size delivered) |+| `state` | Only when something fired: `degraded` plus `degraded_reasons` mapping each contributing key to its reason (a synthesis reason string, the retrieval legs that broke), `partial`, `truncated`. A coarse roll-up of the response's own flags |Silence on `stale_warning` means the index is current; don't infer staleness from its absence. `list_repos`, `get_architecture`, `get_blast_radius`, and `get_conformance` don't carry a freshness envelope at all.@@ -241,6 +249,12 @@ One-call RAG: retrieves over the wiki, gates synthesis on confidence, and return**Returns:** A synthesized answer with file/symbol citations and a confidence label (`high`, `medium`, `low`). High-confidence answers can be cited directly. Low-confidence answers return ranked wiki candidates instead, with the page excerpt served on the highest-scoring few; the rest carry path, title and summary, and one follow-up call opens any of them.+When synthesis cannot run at all — no provider resolvable, or the call failed —+the response carries a top-level `degraded` naming the reason, and is built from+retrieval and mined rationale with no LLM involved. `confidence` is `low` there+for a different reason than usual, so read `degraded` first. It also raises+`_meta.state.degraded`.+Two path-bearing blocks, with different jobs:| Field | Job | Confidence-gated? |@@ -782,7 +796,10 @@ does not have an error report.`_meta.health_analysis` explicitly labels the result as stored analysis,states that the call did not recompute it, distinguishes index/live-Git factsfrom source-byte verification, and gives the exact commit-then-update refresh-precondition. `_meta.health_analyzed_at` dates the health pass, which is separate from+precondition. Its `status` is `available`, `provenance_unknown` (metrics exist+but no row recorded the commit they were computed against, with `reason:+"analysis_commit_not_recorded"`), or `unavailable` (no stored analysis at all).+`provenance_unknown` is a gap in attribution, not a failed analysis. `_meta.health_analyzed_at` dates the health pass, which is separate fromindexing and can lag it, and `_meta.health_analyzed_commit` says which committhose scores were computed against. The incremental update path rescores onlythe files that changed, so the metrics table can hold rows from several passes@@ -795,10 +812,11 @@ five ranked lists compose: `include=['refactoring']` on a mid-size repo landsnear the host's tool-result cap, past which the host rejects the whole resultand you get nothing. Pair `include` with `only` —`get_health(include=['refactoring'], only=['refactoring_plans'])` is the call-`directive.plan_via` names. Anything that would still overflow is trimmed-longest-ranked-list-first and reported in `_meta.truncated_to_fit`-(`{block: rows_dropped}`), never silently; the `*_total` siblings still describe-what was there, and re-requesting one block with `only` recovers it.+`directive.plan_via` names. Anything that would still overflow is shed in the order this tool declares,+never silently: the response carries `truncated: true`, the `*_total` /+`*_emitted` / `*_reduced_reason` siblings describe what was there, and+`_meta.omitted` names refs that restore the dropped rows. Re-requesting one+block with `only` also recovers it.**Test material is bucketed, not hidden.** Every metric row carries `is_test`(distinct from `has_test_file`: "is this file a test" vs "is this file tested").diff --git a/packages/cli/src/repowise/cli/tool_bridge.py b/packages/cli/src/repowise/cli/tool_bridge.pyindex d06ed4831..0cccca5df 100644--- a/packages/cli/src/repowise/cli/tool_bridge.py+++ b/packages/cli/src/repowise/cli/tool_bridge.py@@ -30,6 +30,7 @@ still MCP-only.from __future__ import annotationsimport contextlib+import inspectfrom collections.abc import Awaitable, Callablefrom pathlib import Pathfrom typing import Any@@ -82,7 +83,7 @@ async def _acall_tool(decision_store=store,repo_path=str(repo_path),)- return await factory()+ return _budgeted(tool_name, await factory())except Exception as exc:return _shape_exception(tool_name, exc)finally:@@ -97,6 +98,30 @@ async def _acall_tool(await engine.dispose()+def _budgeted(tool_name: str, result: dict) -> dict:+ """Apply the tool's response budget, which the MCP middleware would have.++ A CLI command awaits the undecorated tool function, so none of the+ middleware runs. Budgeting is the one layer that has to: ``repowise search+ --format json`` is read by agents, and an unbounded response is the failure+ the shared contract exists to prevent. The expansion tier needs the call's+ own arguments, which the zero-argument factory has already closed over, so+ every bridged call is budgeted at the default tier.+ """+ from repowise.server.mcp_server._budget import enforce_response_budget++ def _call() -> None:+ pass++ return enforce_response_budget(+ tool_name,+ result,+ signature=inspect.signature(_call),+ args=(),+ kwargs={},+ )++async def _open_vector_store(repo_path: Path) -> Any:"""The repo's LanceDB store, or an in-memory one when there is none.diff --git a/packages/core/src/repowise/core/analysis/health/finding_identity.py b/packages/core/src/repowise/core/analysis/health/finding_identity.pyindex fa38d31d8..c0c61ab54 100644--- a/packages/core/src/repowise/core/analysis/health/finding_identity.py+++ b/packages/core/src/repowise/core/analysis/health/finding_identity.py@@ -16,9 +16,10 @@ from __future__ import annotationsimport hashlibimport json-import posixpathfrom typing import Any+from repowise.core.references import path_identity+from .rows import detail_map, fieldFINDING_ID_VERSION = 1@@ -42,12 +43,6 @@ when unrelated code changes."""-def _path_identity(path: str) -> str:- """One repository-relative POSIX form, so a Windows caller matches."""- normalized = posixpath.normpath(str(path).strip().replace("\\", "/"))- return normalized.removeprefix("./")--def finding_public_id(row: Any) -> str:"""The stable public id for one finding row."""details = {@@ -58,7 +53,7 @@ def finding_public_id(row: Any) -> str:kernel = {"kernel_version": FINDING_ID_VERSION,"dimension": field(row, "dimension", None) or "defect",- "path": _path_identity(field(row, "file_path", "") or ""),+ "path": path_identity(field(row, "file_path", "") or ""),"kind": field(row, "biomarker_type", "") or "","symbol": field(row, "function_name", None) or "","line_start": field(row, "line_start", None),diff --git a/packages/core/src/repowise/core/references.py b/packages/core/src/repowise/core/references.pynew file mode 100644index 000000000..6a5753dd2--- /dev/null+++ b/packages/core/src/repowise/core/references.py@@ -0,0 +1,156 @@+"""Public reference and evidence identity.++Every surface that hands an agent a pointer back into the code — an MCP tool+response, a persisted finding, a stored evidence row — has to spell it the same+way, because the pointer is the contract: an id quoted in one response is+passed back verbatim to another tool later. This module knows the spelling.++Two id shapes. :func:`source_reference` composes a readable pointer (``path``,+``path:start-end``, ``path::Symbol``) accepted verbatim by the tool that serves+it. :func:`content_id`, :func:`reference` and :func:`stable_entity_id` mint a+digest: sha256 of canonical JSON truncated to 20 hex characters, behind a+caller-chosen prefix, so an id quoted yesterday still resolves today.++Normalisation is what keeps either shape stable: ``src\\main.py`` from a+Windows caller and ``./src/main.py`` from a POSIX one must produce one id.++Pure and dependency-free — stdlib only, no database or filesystem — so+ingestion, the server and the CLI can all use it.+"""++from __future__ import annotations++import hashlib+import json+import posixpath+import re+from collections.abc import Mapping, Sequence+from typing import Any++#: Length of the truncated sha256 digest behind every ``<prefix>_<digest>`` id.+_DIGEST_LENGTH = 20++#: A ``repowise#<ref>`` omission token, bare or embedded in a distill marker.+#: The 12-hex ref itself is minted by ``core.distill``; this only recognises it.+_OMISSION_REF_RE = re.compile(r"(?:^repowise#|\[repowise#)([0-9a-f]{12})(?:$|:)")+_BARE_OMISSION_REF_RE = re.compile(r"[0-9a-f]{12}")+++def repository_identity(repository: str) -> str:+ """Return the canonical, case-insensitive public repository identity."""++ return repository.strip().replace("\\", "/").strip("/").casefold()+++def path_identity(path: str) -> str:+ """Return one repository-relative POSIX path form."""++ normalized = posixpath.normpath(str(path).strip().replace("\\", "/"))+ return normalized.removeprefix("./")+++def symbol_identity(symbol_id: str) -> str:+ """Return the canonical ``path::Symbol`` public identifier form."""++ path, separator, name = symbol_id.strip().partition("::")+ if not separator:+ return path_identity(path)+ return f"{path_identity(path)}::{name.strip()}"+++def content_id(value: object) -> str:+ """Return the stable compact digest used by public reference identities."""++ raw = json.dumps(value, sort_keys=True, separators=(",", ":"), default=str)+ return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:_DIGEST_LENGTH]+++def reference(kind: str, repository: str, **coordinates: object) -> dict[str, Any]:+ """Build a repository-scoped, deterministic evidence reference."""++ identity = {+ "repository": repository_identity(repository),+ "kind": kind,+ **coordinates,+ }+ return {+ "id": f"ev_{content_id(identity)}",+ **identity,+ }+++def omission_reference(value: str) -> str | None:+ """Return the exact omission token accepted by ``get_symbol``."""++ candidate = value.strip()+ if _BARE_OMISSION_REF_RE.fullmatch(candidate):+ return f"repowise#{candidate}"+ match = _OMISSION_REF_RE.search(candidate)+ return f"repowise#{match.group(1)}" if match else None+++def source_reference(+ repository: str,+ path: str,+ *,+ lines: Sequence[int] | None = None,+ symbol_id: str | None = None,+ verification_basis: str,+ source_kind: str,+ commit: str | None = None,+) -> dict[str, Any]:+ """Build a source pointer whose ``id`` is accepted by its target tool."""++ normalized_path = path_identity(path)+ valid_range = (+ lines+ and len(lines) == 2+ and all(isinstance(line, int) and line > 0 for line in lines)+ and int(lines[1]) >= int(lines[0])+ )+ if symbol_id:+ identifier = symbol_identity(symbol_id)+ if "::" not in identifier:+ raise ValueError("symbol_id must use the canonical 'path::Symbol' form")+ symbol_path, _separator, _name = identifier.partition("::")+ if symbol_path != normalized_path:+ raise ValueError("symbol_id path must match the reference path")+ kind = "symbol"+ elif valid_range:+ identifier = f"{normalized_path}:{int(lines[0])}-{int(lines[1])}"+ kind = "file_range"+ else:+ identifier = normalized_path+ kind = "file"+ result: dict[str, Any] = {+ "id": identifier,+ "repository": repository_identity(repository),+ "kind": kind,+ "path": normalized_path,+ "verification_basis": verification_basis,+ "source_kind": source_kind,+ }+ if valid_range:+ result["range"] = [int(lines[0]), int(lines[1])]+ if commit:+ result["commit"] = commit.strip().lower()+ return result+++def stable_entity_id(prefix: str, repository: str, coordinates: Mapping[str, object]) -> str:+ """Return a stable public ID for replace-on-analysis persisted rows."""++ identity = {"repository": repository_identity(repository), **coordinates}+ return f"{prefix}_{content_id(identity)}"+++__all__ = [+ "content_id",+ "omission_reference",+ "path_identity",+ "reference",+ "repository_identity",+ "source_reference",+ "stable_entity_id",+ "symbol_identity",+]diff --git a/packages/server/src/repowise/server/mcp_server/_budget/__init__.py b/packages/server/src/repowise/server/mcp_server/_budget/__init__.pyindex 681bac84c..14148e6a9 100644--- a/packages/server/src/repowise/server/mcp_server/_budget/__init__.py+++ b/packages/server/src/repowise/server/mcp_server/_budget/__init__.py@@ -15,6 +15,11 @@ through this package instead of rolling its own silent drop. Three pieces:Tools with fixed per-list caps use the collector directly at their cap sites,under whichever whole-response ceiling they enforce.++Every tool is budgeted. A tool that declares no shed order still gets the final+size guard, so nothing reaches an agent unbounded and unflagged. The handful of+tools needing a step of their own once shedding has settled register it through+:mod:`._hooks` rather than being named inside the shared layer."""from __future__ import annotations@@ -41,6 +46,11 @@ from repowise.server.mcp_server._budget.contracts import (enforce_response_budget,resolve_response_budget_repo_root,)+from repowise.server.mcp_server._budget.hooks import (+ register_post_enforce,+ register_post_shed,+ registered_hook_tools,+)__all__ = ["CHARS_PER_TOKEN",@@ -60,6 +70,9 @@ __all__ = ["fit_to_budget","host_token_cap","over_budget",+ "register_post_enforce",+ "register_post_shed",+ "registered_hook_tools","resolve_response_budget_repo_root","truncate_to_budget",]diff --git a/packages/server/src/repowise/server/mcp_server/_budget/contracts.py b/packages/server/src/repowise/server/mcp_server/_budget/contracts.pyindex 30a156ff9..b77ac832d 100644--- a/packages/server/src/repowise/server/mcp_server/_budget/contracts.py+++ b/packages/server/src/repowise/server/mcp_server/_budget/contracts.py@@ -21,11 +21,16 @@ from repowise.server.mcp_server._budget.budgeter import (truncate_to_budget,)from repowise.server.mcp_server._budget.collector import OmissionCollector+from repowise.server.mcp_server._budget.hooks import run_post_enforce, run_post_shedDEFAULT_RESPONSE_CHARS = 24_000EXPANDED_RESPONSE_CHARS = 32_000_FINAL_HEADROOM_CHARS = 1_200+#: Floor for a long text field the guard trims in place. Below this the excerpt+#: stops being worth reading and the omission ref is the whole answer.+_MIN_KEPT_TEXT_CHARS = 800+@dataclass(frozen=True)class ResponseBudgetContract:@@ -37,6 +42,12 @@ class ResponseBudgetContract:protected: tuple[str, ...] = ()+#: What a tool gets when it declares no priority of its own. An empty shed+#: order leaves the ordinary pass a no-op; the final size guard is what this+#: buys. Declining to rank your evidence has the guard rank it, and is never a+#: choice to be delivered unbounded.+_DEFAULT_CONTRACT = ResponseBudgetContract("blocks")+_CONTRACTS: dict[str, ResponseBudgetContract] = {"get_context": ResponseBudgetContract("targets", protected=("targets",)),"get_risk": ResponseBudgetContract(@@ -96,7 +107,7 @@ _CONTRACTS: dict[str, ResponseBudgetContract] = {"fallback_targets",),expansion_argument="include",- protected=("answer", "confidence", "citations", "next_action_hint"),+ protected=("answer", "confidence", "citations", "next_action_hint", "degraded"),),# Whole-block drops served 0 of 50 pages, 0 of 12 episodes and 0 of 58# mined rationale comments across the two modes. Trimming runs to@@ -202,6 +213,109 @@ _CONTRACTS: dict[str, ResponseBudgetContract] = {"gap_analysis",),),+ # The tool caps source at 600 *lines*, and 600 lines of dense code measured+ # 79k chars — far past the ceiling that line cap was sized against. Callee+ # bodies are context for the root symbol, so they go first. ``source`` is+ # protected so the guard trims it to what fits rather than dropping it: a+ # symbol read with no body is a wasted call even with a recoverable ref.+ "get_symbol": ResponseBudgetContract(+ "blocks",+ ("callee_bodies.callees[]", "candidates[]"),+ expansion_argument=None,+ protected=(+ "source",+ "symbol_id",+ "file",+ "name",+ "qualified_name",+ "signature",+ "kind",+ "start_line",+ "end_line",+ "verified",+ "continuation",+ "continuation_reference",+ "error",+ ),+ ),+ # Same order the tool used, enforced where the size is rechecked after the+ # trust envelope: its own pass reserved 400 chars for a collector and the+ # metadata that followed added roughly 2.6k.+ "search_codebase": ResponseBudgetContract(+ "blocks",+ ("candidates", "results[]"),+ expansion_argument=None,+ protected=("results", "mode", "exact_match"),+ ),+ "get_dead_code": ResponseBudgetContract(+ "blocks",+ # Same order the tool used for its own pass, then the ranked tiers+ # themselves, least-confident first.+ (+ "impact",+ "by_directory",+ "by_owner",+ "tiers.low.findings[]",+ "tiers.medium.findings[]",+ "tiers.high.findings[]",+ ),+ expansion_argument=None,+ protected=("summary", "tiers", "workspace", "error", "finding", "resolved"),+ ),+ # One ranked list. ``total_entry_points`` is derived before shedding, so+ # the count stays exact.+ "get_execution_flows": ResponseBudgetContract(+ "blocks",+ ("flows[]",),+ expansion_argument=None,+ protected=("total_entry_points",),+ ),+ "get_dependency_path": ResponseBudgetContract(+ "blocks",+ (+ "visual_context.shared_neighbors",+ "visual_context.bridge_suggestions",+ "visual_context.nearest_common_ancestors",+ "visual_context",+ ),+ expansion_argument=None,+ protected=("distance", "explanation"),+ ),+ # These three cap their one list at 25 rows by construction and measured+ # under 1.4k. They publish integer ``*_truncated`` counts of their own,+ # which a shed order would overwrite with a bool, so they declare none and+ # ride the size guard.+ "get_architecture": ResponseBudgetContract(+ "blocks",+ ("role_breakdown",),+ expansion_argument=None,+ protected=("summary", "architecture_type", "score", "core_members", "error"),+ ),+ "get_conformance": ResponseBudgetContract(+ "blocks",+ expansion_argument=None,+ protected=("summary", "violation_count", "cycle_count", "total_cycles", "error"),+ ),+ "get_blast_radius": ResponseBudgetContract(+ "blocks",+ ("impact_score_semantics",),+ expansion_argument=None,+ protected=("summary", "targets", "total_impacted", "unresolved_targets"),+ ),+ "list_repos": ResponseBudgetContract(+ "blocks",+ ("repos[]",),+ expansion_argument=None,+ protected=("workspace", "workspace_root", "default_repo"),+ ),+ # No shed order: the enabled path returns generated code whose shape we+ # have not measured, and ranking blocks we have not seen would be a guess.+ # It rides the final size guard until someone measures it.+ "generate_refactoring_code": ResponseBudgetContract(+ "blocks",+ expansion_argument=None,+ protected=("suggestion_id", "resolved", "error"),+ ),}@@ -282,8 +396,12 @@ def _emergency_fit(value = result.pop(key)collector.add(f"{key} removed by final budget guard", value)if isinstance(value, list):- result[f"{key}_total"] = len(value)+ # An earlier pass may already have trimmed this list, so its total+ # describes the population, not what is left to drop here.+ total = max(len(value), int(result.get(f"{key}_total") or 0))+ result[f"{key}_total"] = totalresult[f"{key}_emitted"] = 0+ result[f"{key}_omitted"] = totalresult[f"{key}_reduced_reason"] = "response_budget"result["truncated"] = True@@ -347,29 +465,16 @@ def _emergency_fit(else:marker = collector.add_inline(path, value)suffix = f"\n{marker}" if marker else "\n[reduced to fit]"- container[key] = value[: max(0, 800 - len(suffix))] + suffix+ # Keep as much as the budget actually allows rather than a fixed+ # floor: cutting a 33k body to 800 characters costs the caller the+ # whole read to save bytes the budget never asked for.+ room = limit - (before - len(value)) - len(suffix)+ container[key] = value[: max(_MIN_KEPT_TEXT_CHARS, room)] + suffixresult["truncated"] = Trueif response_chars(result) >= before:return-def _reconcile_health_plan_status(result: dict[str, Any]) -> None:- """Keep plan availability honest after the final budget mutates collections."""- status = result.get("refactoring_plans_status")- plans = result.get("refactoring_plans")- if not isinstance(status, dict) or status.get("state") != "available":- return- if plans is not None and (not isinstance(plans, list) or plans):- return- if not result.get("refactoring_plans_total", 0):- return- status.update(- state="available_not_emitted",- reason="response_budget",- message="Plans exist but were removed by the final response budget.",- )--def enforce_response_budget(tool: str,result: Any,@@ -379,10 +484,15 @@ def enforce_response_budget(kwargs: dict[str, Any],repo_root: str | Path | None = None,) -> Any:- """Apply *tool*'s contract to its final, metadata-complete result."""- contract = _CONTRACTS.get(tool)- if contract is None or not isinstance(result, dict):+ """Apply *tool*'s contract to its final, metadata-complete result.++ A tool with no declared contract is budgeted under :data:`_DEFAULT_CONTRACT`+ rather than returned untouched: an undeclared priority is a missing shed+ order, never a claim that the response is small.+ """+ if not isinstance(result, dict):return result+ contract = _CONTRACTS.get(tool, _DEFAULT_CONTRACT)if repo_root is None:from repowise.server.mcp_server import _state@@ -416,33 +526,7 @@ def enforce_response_budget(headroom=0,record_counts=True,)- if tool == "get_why":- # Re-derived after shedding: the basis names a lane, and a lane- # this pass emptied must not leave the claim standing.- from repowise.server.mcp_server.tool_why import _stamp_answer_basis-- _stamp_answer_basis(result)- if tool == "get_health":- plans = result.get("refactoring_plans")- profiles = result.get("validation_profiles")- if isinstance(plans, list) and isinstance(profiles, list):- referenced = {- plan.get("validation_profile_id")- for plan in plans- if isinstance(plan, dict) and plan.get("validation_profile_id")- }- kept_profiles = [- profile- for profile in profiles- if isinstance(profile, dict) and profile.get("id") in referenced- ]- dropped_profiles = [profile for profile in profiles if profile not in kept_profiles]- if dropped_profiles:- collector.add("validation_profiles no longer referenced after response budgeting", dropped_profiles)- result["validation_profiles"] = kept_profiles- result["validation_profiles_emitted"] = len(kept_profiles)- result["validation_profiles_reduced_reason"] = "response_budget"- result["truncated"] = True+ run_post_shed(tool, result, collector)collector.attach(result)if response_chars(result) > limit:@@ -450,8 +534,7 @@ def enforce_response_budget(_emergency_fit(result, contract, emergency, working_limit)emergency.attach(result)- if tool == "get_health":- _reconcile_health_plan_status(result)+ run_post_enforce(tool, result)if result.get("truncated"):result.setdefault("_meta", {}).setdefault("state", {})["truncated"] = Truediff --git a/packages/server/src/repowise/server/mcp_server/_budget/hooks.py b/packages/server/src/repowise/server/mcp_server/_budget/hooks.pynew file mode 100644index 000000000..ef70e9cd8--- /dev/null+++ b/packages/server/src/repowise/server/mcp_server/_budget/hooks.py@@ -0,0 +1,76 @@+"""Per-tool callbacks the shared response budget runs, without naming a tool.++The budgeter owns accounting, tier selection, shedding, and omission storage+for every tool. A few tools need one more step once shedding has decided what+survives: a claim re-derived from the lanes that are left, a cross-reference+pruned to the rows still emitted. Those steps know field names the shared layer+must not, so a tool registers them here at import time instead of the budgeter+importing back into a tool module.++``post_shed`` runs after shedding while the collector is still open, so a hook+may route what it drops into recovery. Only the ``blocks`` strategy has that+window; the ``targets`` strategy attaches inside :func:`truncate_to_budget`.++``post_enforce`` runs on the settled shape, after the final size check, for+claims about what was delivered.+"""++from __future__ import annotations++from collections.abc import Callable+from typing import TYPE_CHECKING, Any++if TYPE_CHECKING:+ from repowise.server.mcp_server._budget.collector import OmissionCollector++PostShedHook = Callable[[dict[str, Any], "OmissionCollector"], None]+PostEnforceHook = Callable[[dict[str, Any]], None]++_POST_SHED: dict[str, list[PostShedHook]] = {}+_POST_ENFORCE: dict[str, list[PostEnforceHook]] = {}+++def register_post_shed(tool: str, hook: PostShedHook) -> None:+ """Register *hook* to run for *tool* while the omission collector is open."""+ _register(_POST_SHED, tool, hook)+++def register_post_enforce(tool: str, hook: PostEnforceHook) -> None:+ """Register *hook* to run for *tool* once the delivered shape is settled."""+ _register(_POST_ENFORCE, tool, hook)+++def _register(registry: dict[str, list[Any]], tool: str, hook: Any) -> None:+ # Idempotent: a tool module re-imported under a test reload would otherwise+ # stack duplicate hooks onto every later response.+ hooks = registry.setdefault(tool, [])+ if hook not in hooks:+ hooks.append(hook)+++def run_post_shed(tool: str, result: dict[str, Any], collector: OmissionCollector) -> None:+ """Run *tool*'s post-shed hooks, in registration order."""+ for hook in _POST_SHED.get(tool, ()):+ hook(result, collector)+++def run_post_enforce(tool: str, result: dict[str, Any]) -> None:+ """Run *tool*'s post-enforce hooks, in registration order."""+ for hook in _POST_ENFORCE.get(tool, ()):+ hook(result)+++def registered_hook_tools() -> frozenset[str]:+ """Tools with at least one hook, for coverage assertions."""+ return frozenset(_POST_SHED) | frozenset(_POST_ENFORCE)+++__all__ = [+ "PostEnforceHook",+ "PostShedHook",+ "register_post_enforce",+ "register_post_shed",+ "registered_hook_tools",+ "run_post_enforce",+ "run_post_shed",+]diff --git a/packages/server/src/repowise/server/mcp_server/_meta.py b/packages/server/src/repowise/server/mcp_server/_meta.pyindex 07b0d36b2..7ec20e79b 100644--- a/packages/server/src/repowise/server/mcp_server/_meta.py+++ b/packages/server/src/repowise/server/mcp_server/_meta.py@@ -381,13 +381,20 @@ def finalize_trust_envelope(result: Any, *, evidence_kind: str | None = None) ->elif evidence_kind == "generated":meta.setdefault("existing_verified_code", False)- state: dict[str, bool] = {}+ state: dict[str, Any] = {}combined = {**result, **meta}- if any(- value and (key == "degraded" or key.endswith("_degraded"))- for key, value in combined.items()- ):+ # The bool is deliberately coarse. Carry the values behind it, not just the+ # key names: the producers already hold the answer -- a synthesis reason+ # string, the list of retrieval legs that broke -- and naming only the key+ # would discard it.+ degraded_by = {+ key: value+ for key, value in sorted(combined.items())+ if value and (key == "degraded" or key.endswith("_degraded"))+ }+ if degraded_by:state["degraded"] = True+ state["degraded_reasons"] = degraded_byif any(value and (key == "partial" or key.endswith("_partial")) for key, value in combined.items()):diff --git a/packages/server/src/repowise/server/mcp_server/_references.py b/packages/server/src/repowise/server/mcp_server/_references.pyindex 87886469e..a0dd9d8f8 100644--- a/packages/server/src/repowise/server/mcp_server/_references.py+++ b/packages/server/src/repowise/server/mcp_server/_references.py@@ -1,128 +1,25 @@-"""Canonical identifiers and evidence references shared by MCP tools.+"""Reference identity as the MCP tools consume it.-The identity helpers in this module are presentation-only. They normalize the-coordinates tools already expose; they do not merge persisted records or-manufacture precision that the underlying source cannot verify.+The identity primitives themselves are portable and live in+:mod:`repowise.core.references`; they are re-exported here so the tool modules+that already import them keep one spelling. What stays server-side is the one+helper that needs the health layer to answer."""from __future__ import annotations-import hashlib-import json-import posixpath-import re-from collections.abc import Mapping, Sequencefrom typing import Any-_OMISSION_REF_RE = re.compile(r"(?:^repowise#|\[repowise#)([0-9a-f]{12})(?:$|:)")---def repository_identity(repository: str) -> str:- """Return the canonical, case-insensitive public repository identity."""-- return repository.strip().replace("\\", "/").strip("/").casefold()---def path_identity(path: str) -> str:- """Return one repository-relative POSIX path form."""-- normalized = posixpath.normpath(path.strip().replace("\\", "/"))- return normalized.removeprefix("./")---def symbol_identity(symbol_id: str) -> str:- """Return the canonical ``path::Symbol`` public identifier form."""-- path, separator, name = symbol_id.strip().partition("::")- if not separator:- return path_identity(path)- return f"{path_identity(path)}::{name.strip()}"---def content_id(value: object) -> str:- """Return the stable compact digest used by public reference identities."""-- raw = json.dumps(value, sort_keys=True, separators=(",", ":"), default=str)- return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:20]---def reference(kind: str, repository: str, **coordinates: object) -> dict[str, Any]:- """Build a repository-scoped, deterministic evidence reference."""-- identity = {- "repository": repository_identity(repository),- "kind": kind,- **coordinates,- }- return {- "id": f"ev_{content_id(identity)}",- **identity,- }---def omission_reference(value: str) -> str | None:- """Return the exact omission token accepted by ``get_symbol``."""-- candidate = value.strip()- if re.fullmatch(r"[0-9a-f]{12}", candidate):- return f"repowise#{candidate}"- match = _OMISSION_REF_RE.search(candidate)- return f"repowise#{match.group(1)}" if match else None---def source_reference(- repository: str,- path: str,- *,- lines: Sequence[int] | None = None,- symbol_id: str | None = None,- verification_basis: str,- source_kind: str,- commit: str | None = None,-) -> dict[str, Any]:- """Build a source pointer whose ``id`` is accepted by its target tool."""-- normalized_path = path_identity(path)- valid_range = (- lines- and len(lines) == 2- and all(isinstance(line, int) and line > 0 for line in lines)- and int(lines[1]) >= int(lines[0])- )- if symbol_id:- identifier = symbol_identity(symbol_id)- if "::" not in identifier:- raise ValueError("symbol_id must use the canonical 'path::Symbol' form")- symbol_path, _separator, _name = identifier.partition("::")- if symbol_path != normalized_path:- raise ValueError("symbol_id path must match the reference path")- kind = "symbol"- elif valid_range:- identifier = f"{normalized_path}:{int(lines[0])}-{int(lines[1])}"- kind = "file_range"- else:- identifier = normalized_path- kind = "file"- result: dict[str, Any] = {- "id": identifier,- "repository": repository_identity(repository),- "kind": kind,- "path": normalized_path,- "verification_basis": verification_basis,- "source_kind": source_kind,- }- if valid_range:- result["range"] = [int(lines[0]), int(lines[1])]- if commit:- result["commit"] = commit.strip().lower()- return result---def stable_entity_id(prefix: str, repository: str, coordinates: Mapping[str, object]) -> str:- """Return a stable public ID for replace-on-analysis persisted rows."""-- identity = {"repository": repository_identity(repository), **coordinates}- return f"{prefix}_{content_id(identity)}"+from repowise.core.references import (+ content_id,+ omission_reference,+ path_identity,+ reference,+ repository_identity,+ source_reference,+ stable_entity_id,+ symbol_identity,+)def refactoring_plan_id(suggestion: Any, repository: str) -> str:@@ -147,7 +44,6 @@ def refactoring_plan_id(suggestion: Any, repository: str) -> str:# Compatibility aliases for the get_why-specific module that originally# owned these primitives. Keeping the private spellings prevents a mechanical# promotion from changing sealed evidence identities or downstream imports.-_repository_identity = repository_identity_path_identity = path_identity_content_id = content_id_reference = referencediff --git a/packages/server/src/repowise/server/mcp_server/tool_dead_code.py b/packages/server/src/repowise/server/mcp_server/tool_dead_code.pyindex a3a45f0b8..0362cdecf 100644--- a/packages/server/src/repowise/server/mcp_server/tool_dead_code.py+++ b/packages/server/src/repowise/server/mcp_server/tool_dead_code.py@@ -22,7 +22,7 @@ from repowise.core.persistence.models import ()from repowise.core.registry import mcp_tool_registry as mcpfrom repowise.server.mcp_server import _state-from repowise.server.mcp_server._budget import OmissionCollector, fit_to_budget+from repowise.server.mcp_server._budget import OmissionCollectorfrom repowise.server.mcp_server._helpers import (_get_exclude_spec,_get_repo,@@ -158,9 +158,6 @@ async def _get_dead_code_all_repos(}apply_limit_note(result_ws)result_ws["_meta"] = _build_meta()- collector = OmissionCollector("get_dead_code")- fit_to_budget(result_ws, _WORKSPACE_SHED_ORDER, collector)- collector.attach(result_ws)return result_ws@@ -220,14 +217,6 @@ async def _load_git_meta_map(session: Any, repository_id: Any, findings: list) -return {g.file_path: g for g in git_res.scalars().all()}-# Cheapest loss first; all three are re-derivable from the findings. ``impact``-# leads because the rollups were explicitly asked for via group_by.-_SHED_ORDER: tuple[str, ...] = ("impact", "by_directory", "by_owner")--# The workspace shape has no rollups; past the impact estimate only the tiers-# themselves are left.-_WORKSPACE_SHED_ORDER: tuple[str, ...] = ("impact",)-_TIER_DESC_HIGH = ("High confidence (>=0.8): No references found in the codebase. ""Strong cleanup candidates — review (especially runtime-loaded files) before deleting."@@ -459,7 +448,6 @@ async def get_dead_code(result["_meta"] = _build_meta(repository=repository)attach_ignored_arguments(result, ignored)- fit_to_budget(result, _SHED_ORDER, collector)collector.attach(result)return resultdiff --git a/packages/server/src/repowise/server/mcp_server/tool_health.py b/packages/server/src/repowise/server/mcp_server/tool_health.pyindex e08eff78f..39653f7af 100644--- a/packages/server/src/repowise/server/mcp_server/tool_health.py+++ b/packages/server/src/repowise/server/mcp_server/tool_health.py@@ -55,7 +55,11 @@ 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,+ register_post_enforce,+ register_post_shed,+)from repowise.server.mcp_server._helpers import (_get_exclude_spec,_get_repo,@@ -1041,6 +1045,60 @@ def _refactoring_plans_status(}+def _prune_orphaned_validation_profiles(+ result: dict[str, Any], collector: OmissionCollector+) -> None:+ """Drop profiles whose plan the response budget removed.++ A validation profile only means anything next to the plan referencing it,+ so leaving one behind after its plan is shed hands the agent an id that+ resolves to nothing.+ """+ plans = result.get("refactoring_plans")+ profiles = result.get("validation_profiles")+ if not isinstance(plans, list) or not isinstance(profiles, list):+ return+ referenced = {+ plan.get("validation_profile_id")+ for plan in plans+ if isinstance(plan, dict) and plan.get("validation_profile_id")+ }+ kept = [+ profile+ for profile in profiles+ if isinstance(profile, dict) and profile.get("id") in referenced+ ]+ dropped = [profile for profile in profiles if profile not in kept]+ if not dropped:+ return+ collector.add("validation_profiles no longer referenced after response budgeting", dropped)+ result["validation_profiles"] = kept+ result["validation_profiles_emitted"] = len(kept)+ result["validation_profiles_reduced_reason"] = "response_budget"+ result["truncated"] = True+++def _reconcile_plan_status(result: dict[str, Any]) -> None:+ """Keep plan availability honest after the final budget mutates collections."""+ status = result.get("refactoring_plans_status")+ plans = result.get("refactoring_plans")+ if not isinstance(status, dict) or status.get("state") != "available":+ return+ if plans is not None and (not isinstance(plans, list) or plans):+ return+ if not result.get("refactoring_plans_total", 0):+ return+ status.update(+ state="available_not_emitted",+ reason="response_budget",+ message="Plans exist but were removed by the final response budget.",+ )+++register_post_shed("get_health", _prune_orphaned_validation_profiles)+register_post_enforce("get_health", _reconcile_plan_status)++def _attach_health_analysis_meta(meta: dict[str, Any], metrics: list[HealthFileMetric]) -> None:@@ -1065,7 +1123,7 @@ async def _attach_repository_analysis_meta(the analysis, but every detail mode used to answer it from the rows ithappened to be reporting on. A ``plan_id`` call scoped to a file whose rowcarries a commit said ``available`` at the same instant the dashboard said- ``degraded (analysis_commit_not_recorded)`` from the repo-wide latest row,+ ``provenance_unknown (analysis_commit_not_recorded)`` from the repo-wide row,and the reverse when the scoped file was the one missing it. Three boundedaggregates, so agreeing costs no scan."""@@ -1110,7 +1168,12 @@ def _write_health_analysis_meta(metrics = has_metricsanalyzed = latest_at is not Nonecommits_count = distinct_commits- status = "available" if latest_commit else "degraded" if metrics else "unavailable"+ # Metrics without a recorded commit are usable but unattributable: a+ # provenance gap, not degradation. ``degraded`` is reserved tool-wide for a+ # capability that failed or was unavailable.+ status = (+ "available" if latest_commit else "provenance_unknown" if metrics else "unavailable"+ )analysis: dict[str, Any] = {"status": status,"source": "stored_health_analysis",@@ -2829,8 +2892,8 @@ async def get_health(analyzed_source = metric_rows if scoped else all_metricsif scoped:# Scoped calls used to answer repository freshness from the caller's own- # files, which is how the same repo read ``available`` and ``degraded``- # in the same second depending on which mode answered.+ # files, so one repo read two different statuses in the same second+ # depending on which mode answered.await _attach_repository_analysis_meta(session, repository, result["_meta"])else:_attach_health_analysis_meta(result["_meta"], analyzed_source)diff --git a/packages/server/src/repowise/server/mcp_server/tool_search.py b/packages/server/src/repowise/server/mcp_server/tool_search.pyindex 845cfe2fa..2f3343cb9 100644--- a/packages/server/src/repowise/server/mcp_server/tool_search.py+++ b/packages/server/src/repowise/server/mcp_server/tool_search.py@@ -20,7 +20,11 @@ from repowise.core.registry import ToolRecipefrom repowise.core.registry import mcp_tool_registry as mcpfrom repowise.core.test_paths import is_test_path, is_test_related_pathfrom repowise.server.mcp_server._answer_pipeline import _RRF_K, _RRF_SCORE_SCALE-from repowise.server.mcp_server._budget import OmissionCollector, fit_to_budget+from repowise.server.mcp_server._budget import (+ OmissionCollector,+ register_post_enforce,+ register_post_shed,+)from repowise.server.mcp_server._helpers import (_VECTOR_TIMEOUT_ENV,_get_exclude_spec,@@ -850,22 +854,27 @@ async def _federated_search(response["candidates"] = candidates# Last, so nothing above has to know the field is on its way out._drop_derivable_page_ids(output)- return _fit_search_response(response, contexts[0].path if contexts else None)-+ return response-# A search response is one ranked list, so past the derived ``candidates`` there-# is nothing to shed but the weakest hits.-_SHED_ORDER: tuple[str, ...] = ("candidates", "results[]")+def _refresh_served_targets(response: dict, _collector: OmissionCollector | None) -> None:+ """Re-derive target-scoped freshness from the hits that survived shedding.-def _fit_search_response(response: dict, repo_root: Any) -> dict:- """Bring a search response under the transport ceiling, recoverably."""- collector = OmissionCollector("search_codebase", repo_root=repo_root)- fit_to_budget(response, _SHED_ORDER, collector)+ ``_meta.targets`` claims which files the response served. Shedding decides+ that, so this has to run after it or the claim names rows the caller never+ received.+ """if response.get("truncated") and isinstance(response.get("_meta"), dict):response["_meta"]["targets"] = _result_paths(response.get("results") or [])- collector.attach(response)- return response+++def _refresh_served_targets_final(response: dict) -> None:+ """Same claim, re-derived after the final size guard may have cut again."""+ _refresh_served_targets(response, None)+++register_post_shed("search_codebase", _refresh_served_targets)+register_post_enforce("search_codebase", _refresh_served_targets_final)def _result_paths(results: list[dict]) -> list[str]:@@ -1079,7 +1088,7 @@ async def _structured_search(response["grep_hint"] = grep_hint# Last, so nothing above has to know the field is on its way out._drop_derivable_page_ids(results)- return _fit_search_response(response, contexts[0].path if contexts else None)+ return response@mcp.tool(@@ -1236,4 +1245,4 @@ async def search_codebase(attach_ignored_arguments(response, ignored)# Last, so nothing above has to know the field is on its way out._drop_derivable_page_ids(output)- return _fit_search_response(response, ctx.path)+ return responsediff --git a/packages/server/src/repowise/server/mcp_server/tool_symbol.py b/packages/server/src/repowise/server/mcp_server/tool_symbol.pyindex 01664bff2..458e3aeea 100644--- a/packages/server/src/repowise/server/mcp_server/tool_symbol.py+++ b/packages/server/src/repowise/server/mcp_server/tool_symbol.py@@ -54,6 +54,7 @@ from sqlalchemy import selectfrom repowise.core.persistence.database import get_sessionfrom repowise.core.persistence.models import WikiSymbolfrom repowise.core.registry import mcp_tool_registry as mcp+from repowise.server.mcp_server._budget import register_post_shedfrom repowise.server.mcp_server._helpers import (_get_exclude_spec,_get_repo,@@ -656,6 +657,29 @@ async def _render_ambiguous(return response+def _correct_ambiguity_note(result: dict[str, Any], _collector: Any) -> None:+ """Stop promising every candidate body once the budget has cut some.++ The ambiguous shape exists so a wrong pick is never made silently, and says+ so in ``note``. A shed that leaves the note standing makes exactly the+ claim the shape was built to avoid.+ """+ if not result.get("ambiguous"):+ return+ emitted = result.get("candidates_emitted")+ if emitted is None or emitted >= (result.get("match_count") or 0):+ return+ result["note"] = (+ f"{result.get('match_count')} symbols match this id (overloads, "+ f"re-exports, or conditional definitions). {emitted} candidate bodies "+ "fit this response; the rest are recoverable from the omission ref, or "+ "fetch one directly with its file range."+ )+++register_post_shed("get_symbol", _correct_ambiguity_note)++@mcp.tool(surface_order=30, artifact_type="source", presentation="source", evidence_basis="measured")async def get_symbol(symbol_id: str | None = None,diff --git a/packages/server/src/repowise/server/mcp_server/tool_why.py b/packages/server/src/repowise/server/mcp_server/tool_why.pyindex 4c6bfdc32..468392d43 100644--- a/packages/server/src/repowise/server/mcp_server/tool_why.py+++ b/packages/server/src/repowise/server/mcp_server/tool_why.py@@ -28,6 +28,7 @@ from repowise.server.mcp_server._budget import (cap_collection,fit_to_budget,over_budget,+ register_post_shed,)from repowise.server.mcp_server._code_rationale import mine_rationale as _mine_rationalefrom repowise.server.mcp_server._episodes import bank_overflow, episode_evidence@@ -104,6 +105,18 @@ def _stamp_answer_basis(result: dict) -> dict:return result+def _restamp_answer_basis(result: dict, _collector: OmissionCollector) -> None:+ """Re-derive the basis after shedding.++ The basis names a lane, and a lane the budget pass emptied must not leave+ the claim standing.+ """+ _stamp_answer_basis(result)+++register_post_shed("get_why", _restamp_answer_basis)++@mcp.tool(surface_order=70,artifact_type="decisions",diff --git a/scripts/measure_mcp_response_sizes.py b/scripts/measure_mcp_response_sizes.pynew file mode 100644index 000000000..3125cd70a--- /dev/null+++ b/scripts/measure_mcp_response_sizes.py@@ -0,0 +1,231 @@+"""Measure the serialized size of every MCP tool response against a real index.++The response budget is declared in characters, so this reports characters, using+the budgeter's own serialization. Two numbers per case: the raw handler result,+and the same call through the production middleware stack, which is where+budgeting happens. Raw over the ceiling with wrapped under it means the budget+did its job; both over means the tool is delivering unbounded.++Synthetic payloads cannot answer this — a tool is only as big as the repository+it is reading — so this needs a real indexed repo and does not run in CI. The+CI-side guarantee is `tests/unit/server/mcp/test_response_budget_contracts.py`,+which pins that every tool has a contract and that the floor truncates and+flags. Use this when changing a shed order, adding a tool, or checking whether a+cap still holds on a large repository.++ python scripts/measure_mcp_response_sizes.py --repo /path/to/indexed/repo++Workspace-only tools (`get_architecture`, `get_conformance`, `get_blast_radius`)+need `--repo` inside a workspace; elsewhere they return an error payload, which+is reported as `not measured` rather than as a bound.+"""++from __future__ import annotations++import argparse+import asyncio+import contextlib+import importlib+import json+import os+import sqlite3+import sys+import traceback+from typing import Any++#: Representative worst cases. Paths are resolved against the target repo and a+#: case whose target is missing is reported, never silently skipped.+CASES: list[tuple[str, str, dict[str, Any]]] = [+ ("get_overview", "default", {}),+ ("get_overview", "all-includes", {"include": ["modules", "entry_points", "hotspots"]}),+ ("get_context", "one-file", {"targets": ["{file}"]}),+ ("get_context", "many-targets", {"targets": ["{file}", "{file2}"], "include": ["skeleton", "callers"]}),+ ("get_symbol", "largest-symbol", {"symbol_id": "{symbol}"}),+ ("get_symbol", "largest-depth-3", {"symbol_id": "{symbol}", "depth": 3, "context_lines": 50}),+ ("search_codebase", "limit-5", {"query": "{query}"}),+ ("search_codebase", "limit-50", {"query": "{query}", "limit": 50}),+ ("get_health", "default", {}),+ ("get_health", "limit-100", {"limit": 100}),+ ("get_health", "all-includes", {"include": ["files", "refactoring", "performance"], "limit": 100}),+ ("get_risk", "one-target", {"targets": ["{file}"]}),+ ("get_change_risk", "head", {"revspec": "HEAD"}),+ ("get_why", "targets", {"targets": ["{file}"]}),+ ("get_dead_code", "default", {}),+ ("get_dead_code", "limit-200", {"limit": 200, "min_confidence": 0.0, "include_internals": True}),+ ("get_execution_flows", "default", {}),+ ("get_execution_flows", "top-100-depth-20", {"top_n": 100, "max_depth": 20}),+ ("get_dependency_path", "two-files", {"source": "{file}", "target": "{file2}"}),+ ("get_architecture", "default", {}),+ ("get_conformance", "default", {}),+ ("get_blast_radius", "one-target", {"targets": ["{file}"]}),+ ("list_repos", "default", {}),+ ("get_answer", "how-question", {"question": "How does {query} work?"}),+]+++def _size(payload: object) -> int:+ """Exactly what ``_budget.budgeter.response_chars`` measures."""+ return len(json.dumps(payload, separators=(",", ":"), default=str))+++def _pick_targets(repo: str) -> dict[str, str]:+ """Choose the largest indexed symbol and its file, so cases are worst case."""+ db = os.path.join(repo, ".repowise", "wiki.db")+ if not os.path.exists(db):+ raise SystemExit(f"no index at {db}; run 'repowise init' in that repo first")+ connection = sqlite3.connect(db)+ try:+ rows = list(+ connection.execute(+ "SELECT symbol_id, file_path FROM wiki_symbols "+ "ORDER BY end_line - start_line DESC LIMIT 2"+ )+ )+ finally:+ connection.close()+ if not rows:+ raise SystemExit(f"index at {db} has no symbols")+ return {+ "symbol": rows[0][0],+ "file": rows[0][1],+ "file2": rows[1][1] if len(rows) > 1 else rows[0][1],+ "query": "index the repository",+ }+++def _skeleton(payload: Any) -> Any:+ """The nested key shape of a response, with every value discarded.++ A declared shed path that does not resolve against this is a silent no-op,+ which the size columns cannot reveal: the final guard brings the response+ under the ceiling either way.+ """+ if isinstance(payload, dict):+ # A map keyed by repository path is one shape under many names, and+ # those names differ per repo. Collapse it so the fixture describes the+ # shape rather than the checkout it was recorded against.+ if len(payload) > 1 and all("/" in key for key in payload):+ return {"<path>": _skeleton(next(iter(payload.values())))}+ return {key: _skeleton(value) for key, value in payload.items()}+ if isinstance(payload, list):+ return [_skeleton(payload[0])] if payload else []+ return None+++def _merge_skeleton(into: Any, new: Any) -> Any:+ """Union two shapes, so several cases together describe one tool."""+ if isinstance(into, dict) and isinstance(new, dict):+ for key, value in new.items():+ into[key] = _merge_skeleton(into.get(key), value) if key in into else value+ return into+ if isinstance(into, list) and isinstance(new, list):+ if new and not into:+ return new+ if into and new:+ into[0] = _merge_skeleton(into[0], new[0])+ return into+ return new if into is None else into+++def _bind(kwargs: dict[str, Any], targets: dict[str, str]) -> dict[str, Any]:+ def sub(value: Any) -> Any:+ if isinstance(value, str):+ return value.format(**targets)+ if isinstance(value, list):+ return [sub(item) for item in value]+ return value++ return {key: sub(value) for key, value in kwargs.items()}+++async def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--repo", required=True, help="path to an indexed repository")+ parser.add_argument("--json", help="also write the full rows here")+ parser.add_argument("--only", help="comma-separated tool names")+ parser.add_argument(+ "--skeletons",+ help="write each tool's nested key shape here, for the shed-path fixture",+ )+ options = parser.parse_args()++ os.environ.setdefault("REPOWISE_TELEMETRY_DISABLED", "1")++ from repowise.server.mcp_server import _TOOL_MODULES, _server, _state, tool_middleware+ from repowise.server.mcp_server._budget import (+ DEFAULT_RESPONSE_CHARS,+ EXPANDED_RESPONSE_CHARS,+ )++ _state._repo_path = options.repo+ only = set(options.only.split(",")) if options.only else None+ targets = _pick_targets(options.repo)++ handlers: dict[str, tuple[Any, Any]] = {}+ for name, module in _TOOL_MODULES.items():+ if only and name not in only:+ continue+ function = getattr(importlib.import_module(f"repowise.server.mcp_server.{module}"), name)+ handlers[name] = (function, tool_middleware(function))++ rows: list[dict[str, Any]] = []+ skeletons: dict[str, Any] = {}+ async with _server._lifespan(None):+ ready = getattr(_state, "_vector_store_ready", None)+ if ready is not None:+ # The vector arm loads in the background; measuring before it lands+ # would understate every search-backed response.+ with contextlib.suppress(TimeoutError):+ await asyncio.wait_for(ready.wait(), timeout=60)++ for tool, case, raw_kwargs in CASES:+ if only and tool not in only:+ continue+ if tool not in handlers:+ continue+ kwargs = _bind(raw_kwargs, targets)+ row: dict[str, Any] = {"tool": tool, "case": case, "args": kwargs}+ for label, handler in (("raw", handlers[tool][0]), ("wrapped", handlers[tool][1])):+ try:+ payload = await handler(**kwargs)+ except Exception as exc:+ row[f"{label}_error"] = f"{type(exc).__name__}: {exc}"+ row[f"{label}_trace"] = traceback.format_exc()[-1200:]+ continue+ row[f"{label}_chars"] = _size(payload)+ if label == "raw" and isinstance(payload, dict):+ if "error" in payload:+ row["unexercised"] = payload["error"]+ else:+ skeletons[tool] = _merge_skeleton(+ skeletons.get(tool), _skeleton(payload)+ )+ rows.append(row)++ print(f"{'tool':<26} {'case':<20} {'raw':>9} {'wrapped':>9} verdict")+ for row in rows:+ wrapped = row.get("wrapped_chars")+ if row.get("unexercised") or wrapped is None:+ verdict = "not measured"+ elif wrapped > EXPANDED_RESPONSE_CHARS:+ verdict = f"OVER expanded ({EXPANDED_RESPONSE_CHARS})"+ elif wrapped > DEFAULT_RESPONSE_CHARS:+ verdict = f"over default ({DEFAULT_RESPONSE_CHARS})"+ else:+ verdict = "within budget"+ print(+ f"{row['tool']:<26} {row['case']:<20} "+ f"{row.get('raw_chars', '-'):>9} {wrapped if wrapped is not None else '-':>9} {verdict}"+ )++ if options.json:+ with open(options.json, "w", encoding="utf-8") as handle:+ json.dump(rows, handle, indent=2, default=str)+ if options.skeletons:+ with open(options.skeletons, "w", encoding="utf-8") as handle:+ json.dump(skeletons, handle, indent=2, sort_keys=True)+ return 0+++if __name__ == "__main__":+ sys.exit(asyncio.run(main()))diff --git a/tests/fixtures/mcp/retrieval_precision_corpus.json b/tests/fixtures/mcp/retrieval_precision_corpus.jsonindex 6576b967b..b202359de 100644--- a/tests/fixtures/mcp/retrieval_precision_corpus.json+++ b/tests/fixtures/mcp/retrieval_precision_corpus.json@@ -1,9 +1,9 @@{- "schema_version": 1,+ "schema_version": 2,"sealed_at_commit": "c2f915d07c11ca3f451309054dfb610e75b8ae26","window_size": 5,- "modes": ["full", "degraded"],- "degraded_mode": {+ "modes": ["full", "keyless"],+ "keyless_mode": {"embedder": "keyless","llm": "absent","retained_legs": ["path", "symbol", "fts", "history"]@@ -24,12 +24,12 @@"supported_generic_targets": [],"oracle_basis": "Exact seeded WikiSymbol.name and canonical path::Symbol identity.","candidates": [- {"target": "packages/server/src/repowise/server/mcp_server/tool_search.py::search_codebase", "kind": "symbol", "member_name": "search_codebase", "path": "packages/server/src/repowise/server/mcp_server/tool_search.py", "owner": "", "context": ["search", "codebase", "mcp"], "legs": {"full": ["symbol", "semantic"], "degraded": ["symbol", "fts"]}},- {"target": "packages/cli/src/repowise/cli/commands/search_cmd.py::search", "kind": "symbol", "member_name": "search", "path": "packages/cli/src/repowise/cli/commands/search_cmd.py", "owner": "", "context": ["search", "cli"], "legs": {"full": ["semantic"], "degraded": ["fts"]}},- {"target": "packages/core/src/repowise/core/workspace/registry.py::WorkspaceRegistry.get", "kind": "symbol", "member_name": "get", "path": "packages/core/src/repowise/core/workspace/registry.py", "owner": "WorkspaceRegistry", "context": ["workspace", "registry"], "legs": {"full": ["symbol"], "degraded": ["symbol"]}},- {"target": "packages/cli/src/repowise/cli/main.py::main", "kind": "symbol", "member_name": "main", "path": "packages/cli/src/repowise/cli/main.py", "owner": "", "context": ["cli", "entrypoint"], "legs": {"full": ["symbol"], "degraded": ["symbol"]}},- {"target": "packages/server/src/repowise/server/mcp_server/tool_context/__init__.py", "kind": "page", "member_name": "", "path": "packages/server/src/repowise/server/mcp_server/tool_context/__init__.py", "owner": "", "context": ["mcp", "context"], "legs": {"full": ["semantic"], "degraded": ["fts"]}},- {"target": "packages/core/src/repowise/core/distill/runner.py::run", "kind": "symbol", "member_name": "run", "path": "packages/core/src/repowise/core/distill/runner.py", "owner": "", "context": ["distill", "command"], "legs": {"full": ["symbol"], "degraded": ["symbol"]}}+ {"target": "packages/server/src/repowise/server/mcp_server/tool_search.py::search_codebase", "kind": "symbol", "member_name": "search_codebase", "path": "packages/server/src/repowise/server/mcp_server/tool_search.py", "owner": "", "context": ["search", "codebase", "mcp"], "legs": {"full": ["symbol", "semantic"], "keyless": ["symbol", "fts"]}},+ {"target": "packages/cli/src/repowise/cli/commands/search_cmd.py::search", "kind": "symbol", "member_name": "search", "path": "packages/cli/src/repowise/cli/commands/search_cmd.py", "owner": "", "context": ["search", "cli"], "legs": {"full": ["semantic"], "keyless": ["fts"]}},+ {"target": "packages/core/src/repowise/core/workspace/registry.py::WorkspaceRegistry.get", "kind": "symbol", "member_name": "get", "path": "packages/core/src/repowise/core/workspace/registry.py", "owner": "WorkspaceRegistry", "context": ["workspace", "registry"], "legs": {"full": ["symbol"], "keyless": ["symbol"]}},+ {"target": "packages/cli/src/repowise/cli/main.py::main", "kind": "symbol", "member_name": "main", "path": "packages/cli/src/repowise/cli/main.py", "owner": "", "context": ["cli", "entrypoint"], "legs": {"full": ["symbol"], "keyless": ["symbol"]}},+ {"target": "packages/server/src/repowise/server/mcp_server/tool_context/__init__.py", "kind": "page", "member_name": "", "path": "packages/server/src/repowise/server/mcp_server/tool_context/__init__.py", "owner": "", "context": ["mcp", "context"], "legs": {"full": ["semantic"], "keyless": ["fts"]}},+ {"target": "packages/core/src/repowise/core/distill/runner.py::run", "kind": "symbol", "member_name": "run", "path": "packages/core/src/repowise/core/distill/runner.py", "owner": "", "context": ["distill", "command"], "legs": {"full": ["symbol"], "keyless": ["symbol"]}}]},{@@ -46,12 +46,12 @@"supported_generic_targets": [],"oracle_basis": "Exact seeded Page.target_path equality.","candidates": [- {"target": "packages/core/src/repowise/core/analysis/test_impact.py", "kind": "page", "member_name": "", "path": "packages/core/src/repowise/core/analysis/test_impact.py", "owner": "", "context": ["analysis", "test", "impact"], "legs": {"full": ["path", "semantic"], "degraded": ["path", "fts"]}},- {"target": "tests/unit/server/mcp/test_pr_test_impact_semantics.py", "kind": "page", "member_name": "", "path": "tests/unit/server/mcp/test_pr_test_impact_semantics.py", "owner": "", "context": ["test", "impact", "semantics"], "legs": {"full": ["path", "semantic"], "degraded": ["path", "fts"]}},- {"target": "packages/core/src/repowise/core/analysis/pr_blast.py", "kind": "page", "member_name": "", "path": "packages/core/src/repowise/core/analysis/pr_blast.py", "owner": "", "context": ["analysis", "pr", "blast"], "legs": {"full": ["semantic"], "degraded": ["fts"]}},- {"target": "packages/core/src/repowise/core/workspace/repo_index.py::RepoIndex.get", "kind": "symbol", "member_name": "get", "path": "packages/core/src/repowise/core/workspace/repo_index.py", "owner": "RepoIndex", "context": ["workspace", "repository"], "legs": {"full": ["symbol"], "degraded": ["symbol"]}},- {"target": "packages/cli/src/repowise/cli/main.py::main", "kind": "symbol", "member_name": "main", "path": "packages/cli/src/repowise/cli/main.py", "owner": "", "context": ["cli"], "legs": {"full": ["symbol"], "degraded": ["symbol"]}},- {"target": "packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py", "kind": "page", "member_name": "", "path": "packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py", "owner": "", "context": ["risk", "impact"], "legs": {"full": ["semantic"], "degraded": ["fts"]}}+ {"target": "packages/core/src/repowise/core/analysis/test_impact.py", "kind": "page", "member_name": "", "path": "packages/core/src/repowise/core/analysis/test_impact.py", "owner": "", "context": ["analysis", "test", "impact"], "legs": {"full": ["path", "semantic"], "keyless": ["path", "fts"]}},+ {"target": "tests/unit/server/mcp/test_pr_test_impact_semantics.py", "kind": "page", "member_name": "", "path": "tests/unit/server/mcp/test_pr_test_impact_semantics.py", "owner": "", "context": ["test", "impact", "semantics"], "legs": {"full": ["path", "semantic"], "keyless": ["path", "fts"]}},+ {"target": "packages/core/src/repowise/core/analysis/pr_blast.py", "kind": "page", "member_name": "", "path": "packages/core/src/repowise/core/analysis/pr_blast.py", "owner": "", "context": ["analysis", "pr", "blast"], "legs": {"full": ["semantic"], "keyless": ["fts"]}},+ {"target": "packages/core/src/repowise/core/workspace/repo_index.py::RepoIndex.get", "kind": "symbol", "member_name": "get", "path": "packages/core/src/repowise/core/workspace/repo_index.py", "owner": "RepoIndex", "context": ["workspace", "repository"], "legs": {"full": ["symbol"], "keyless": ["symbol"]}},+ {"target": "packages/cli/src/repowise/cli/main.py::main", "kind": "symbol", "member_name": "main", "path": "packages/cli/src/repowise/cli/main.py", "owner": "", "context": ["cli"], "legs": {"full": ["symbol"], "keyless": ["symbol"]}},+ {"target": "packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py", "kind": "page", "member_name": "", "path": "packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py", "owner": "", "context": ["risk", "impact"], "legs": {"full": ["semantic"], "keyless": ["fts"]}}]},{@@ -68,13 +68,13 @@"supported_generic_targets": [],"oracle_basis": "analyze_test_impact owns measured/inferred recommendations and coverage-backed tests_to_run; pr_blast consumes it.","candidates": [- {"target": "packages/core/src/repowise/core/analysis/health/perf/coverage.py", "kind": "page", "member_name": "", "path": "packages/core/src/repowise/core/analysis/health/perf/coverage.py", "owner": "", "context": ["performance", "coverage", "health"], "legs": {"full": ["fts"], "degraded": ["fts"]}},- {"target": "packages/core/src/repowise/core/analysis/test_impact.py", "kind": "page", "member_name": "", "path": "packages/core/src/repowise/core/analysis/test_impact.py", "owner": "", "context": ["pr", "test", "impact", "coverage", "changed", "files", "tests", "run"], "legs": {"full": ["semantic", "fts", "symbol"], "degraded": ["fts", "symbol"]}},- {"target": "packages/core/src/repowise/core/analysis/pr_blast.py", "kind": "page", "member_name": "", "path": "packages/core/src/repowise/core/analysis/pr_blast.py", "owner": "", "context": ["pr", "changed", "files", "test", "impact"], "legs": {"full": ["semantic", "fts"], "degraded": ["fts"]}},- {"target": "packages/server/src/repowise/server/mcp_server/tool_risk/directives.py", "kind": "page", "member_name": "", "path": "packages/server/src/repowise/server/mcp_server/tool_risk/directives.py", "owner": "", "context": ["tests", "run", "basis", "risk", "directive"], "legs": {"full": ["semantic"], "degraded": ["fts"]}},- {"target": "packages/core/src/repowise/core/workspace/registry.py::WorkspaceRegistry.get", "kind": "symbol", "member_name": "get", "path": "packages/core/src/repowise/core/workspace/registry.py", "owner": "WorkspaceRegistry", "context": ["workspace"], "legs": {"full": ["symbol"], "degraded": ["symbol"]}},- {"target": "packages/core/src/repowise/core/distill/runner.py::run", "kind": "symbol", "member_name": "run", "path": "packages/core/src/repowise/core/distill/runner.py", "owner": "", "context": ["distill"], "legs": {"full": ["symbol"], "degraded": ["symbol"]}},- {"target": "packages/cli/src/repowise/cli/main.py::main", "kind": "symbol", "member_name": "main", "path": "packages/cli/src/repowise/cli/main.py", "owner": "", "context": ["cli"], "legs": {"full": ["symbol"], "degraded": ["symbol"]}}+ {"target": "packages/core/src/repowise/core/analysis/health/perf/coverage.py", "kind": "page", "member_name": "", "path": "packages/core/src/repowise/core/analysis/health/perf/coverage.py", "owner": "", "context": ["performance", "coverage", "health"], "legs": {"full": ["fts"], "keyless": ["fts"]}},+ {"target": "packages/core/src/repowise/core/analysis/test_impact.py", "kind": "page", "member_name": "", "path": "packages/core/src/repowise/core/analysis/test_impact.py", "owner": "", "context": ["pr", "test", "impact", "coverage", "changed", "files", "tests", "run"], "legs": {"full": ["semantic", "fts", "symbol"], "keyless": ["fts", "symbol"]}},+ {"target": "packages/core/src/repowise/core/analysis/pr_blast.py", "kind": "page", "member_name": "", "path": "packages/core/src/repowise/core/analysis/pr_blast.py", "owner": "", "context": ["pr", "changed", "files", "test", "impact"], "legs": {"full": ["semantic", "fts"], "keyless": ["fts"]}},+ {"target": "packages/server/src/repowise/server/mcp_server/tool_risk/directives.py", "kind": "page", "member_name": "", "path": "packages/server/src/repowise/server/mcp_server/tool_risk/directives.py", "owner": "", "context": ["tests", "run", "basis", "risk", "directive"], "legs": {"full": ["semantic"], "keyless": ["fts"]}},+ {"target": "packages/core/src/repowise/core/workspace/registry.py::WorkspaceRegistry.get", "kind": "symbol", "member_name": "get", "path": "packages/core/src/repowise/core/workspace/registry.py", "owner": "WorkspaceRegistry", "context": ["workspace"], "legs": {"full": ["symbol"], "keyless": ["symbol"]}},+ {"target": "packages/core/src/repowise/core/distill/runner.py::run", "kind": "symbol", "member_name": "run", "path": "packages/core/src/repowise/core/distill/runner.py", "owner": "", "context": ["distill"], "legs": {"full": ["symbol"], "keyless": ["symbol"]}},+ {"target": "packages/cli/src/repowise/cli/main.py::main", "kind": "symbol", "member_name": "main", "path": "packages/cli/src/repowise/cli/main.py", "owner": "", "context": ["cli"], "legs": {"full": ["symbol"], "keyless": ["symbol"]}}]},{@@ -91,12 +91,12 @@"supported_generic_targets": [],"oracle_basis": "answer.py invokes the retrieval pipeline; _answer_pipeline.py owns hybrid page/symbol retrieval across module boundaries.","candidates": [- {"target": "packages/server/src/repowise/server/mcp_server/tool_answer/answer.py", "kind": "page", "member_name": "", "path": "packages/server/src/repowise/server/mcp_server/tool_answer/answer.py", "owner": "", "context": ["mcp", "question", "answer", "orchestration", "retrieval"], "legs": {"full": ["semantic", "fts"], "degraded": ["fts"]}},- {"target": "packages/server/src/repowise/server/mcp_server/_answer_pipeline.py", "kind": "page", "member_name": "", "path": "packages/server/src/repowise/server/mcp_server/_answer_pipeline.py", "owner": "", "context": ["answer", "pipeline", "hybrid", "page", "symbol", "retrieval"], "legs": {"full": ["semantic", "fts", "symbol"], "degraded": ["fts", "symbol"]}},- {"target": "packages/server/src/repowise/server/mcp_server/tool_answer/retrieval.py", "kind": "page", "member_name": "", "path": "packages/server/src/repowise/server/mcp_server/tool_answer/retrieval.py", "owner": "", "context": ["answer", "retrieval"], "legs": {"full": ["semantic"], "degraded": ["fts"]}},- {"target": "packages/core/src/repowise/core/workspace/registry.py::WorkspaceRegistry.get", "kind": "symbol", "member_name": "get", "path": "packages/core/src/repowise/core/workspace/registry.py", "owner": "WorkspaceRegistry", "context": ["workspace"], "legs": {"full": ["symbol"], "degraded": ["symbol"]}},- {"target": "packages/core/src/repowise/core/distill/runner.py::run", "kind": "symbol", "member_name": "run", "path": "packages/core/src/repowise/core/distill/runner.py", "owner": "", "context": ["distill"], "legs": {"full": ["symbol"], "degraded": ["symbol"]}},- {"target": "packages/cli/src/repowise/cli/main.py::main", "kind": "symbol", "member_name": "main", "path": "packages/cli/src/repowise/cli/main.py", "owner": "", "context": ["cli"], "legs": {"full": ["symbol"], "degraded": ["symbol"]}}+ {"target": "packages/server/src/repowise/server/mcp_server/tool_answer/answer.py", "kind": "page", "member_name": "", "path": "packages/server/src/repowise/server/mcp_server/tool_answer/answer.py", "owner": "", "context": ["mcp", "question", "answer", "orchestration", "retrieval"], "legs": {"full": ["semantic", "fts"], "keyless": ["fts"]}},+ {"target": "packages/server/src/repowise/server/mcp_server/_answer_pipeline.py", "kind": "page", "member_name": "", "path": "packages/server/src/repowise/server/mcp_server/_answer_pipeline.py", "owner": "", "context": ["answer", "pipeline", "hybrid", "page", "symbol", "retrieval"], "legs": {"full": ["semantic", "fts", "symbol"], "keyless": ["fts", "symbol"]}},+ {"target": "packages/server/src/repowise/server/mcp_server/tool_answer/retrieval.py", "kind": "page", "member_name": "", "path": "packages/server/src/repowise/server/mcp_server/tool_answer/retrieval.py", "owner": "", "context": ["answer", "retrieval"], "legs": {"full": ["semantic"], "keyless": ["fts"]}},+ {"target": "packages/core/src/repowise/core/workspace/registry.py::WorkspaceRegistry.get", "kind": "symbol", "member_name": "get", "path": "packages/core/src/repowise/core/workspace/registry.py", "owner": "WorkspaceRegistry", "context": ["workspace"], "legs": {"full": ["symbol"], "keyless": ["symbol"]}},+ {"target": "packages/core/src/repowise/core/distill/runner.py::run", "kind": "symbol", "member_name": "run", "path": "packages/core/src/repowise/core/distill/runner.py", "owner": "", "context": ["distill"], "legs": {"full": ["symbol"], "keyless": ["symbol"]}},+ {"target": "packages/cli/src/repowise/cli/main.py::main", "kind": "symbol", "member_name": "main", "path": "packages/cli/src/repowise/cli/main.py", "owner": "", "context": ["cli"], "legs": {"full": ["symbol"], "keyless": ["symbol"]}}]},{@@ -111,12 +111,12 @@"supported_generic_targets": [],"oracle_basis": "Standing decision: embed_batch raises on failure so indexed/failed counters stay honest; affected source is decision_extractor.py.","candidates": [- {"target": "dec_embed_batch_counters", "kind": "decision", "member_name": "", "path": "packages/core/src/repowise/core/analysis/decision_extractor.py", "owner": "", "context": ["decision", "indexing", "embed", "batch", "counters", "failure"], "legs": {"full": ["history", "semantic"], "degraded": ["history", "fts"]}},- {"target": "packages/core/src/repowise/core/analysis/decision_extractor.py", "kind": "page", "member_name": "", "path": "packages/core/src/repowise/core/analysis/decision_extractor.py", "owner": "", "context": ["decision", "extractor", "indexing", "embed", "batch"], "legs": {"full": ["semantic", "fts"], "degraded": ["fts"]}},- {"target": "dec_generic_branch_names", "kind": "decision", "member_name": "", "path": "", "owner": "", "context": ["branch", "names"], "legs": {"full": ["history"], "degraded": ["history"]}},- {"target": "packages/core/src/repowise/core/workspace/registry.py::WorkspaceRegistry.get", "kind": "symbol", "member_name": "get", "path": "packages/core/src/repowise/core/workspace/registry.py", "owner": "WorkspaceRegistry", "context": ["workspace"], "legs": {"full": ["symbol"], "degraded": ["symbol"]}},- {"target": "packages/core/src/repowise/core/distill/runner.py::run", "kind": "symbol", "member_name": "run", "path": "packages/core/src/repowise/core/distill/runner.py", "owner": "", "context": ["distill"], "legs": {"full": ["symbol"], "degraded": ["symbol"]}},- {"target": "packages/cli/src/repowise/cli/main.py::main", "kind": "symbol", "member_name": "main", "path": "packages/cli/src/repowise/cli/main.py", "owner": "", "context": ["cli"], "legs": {"full": ["symbol"], "degraded": ["symbol"]}}+ {"target": "dec_embed_batch_counters", "kind": "decision", "member_name": "", "path": "packages/core/src/repowise/core/analysis/decision_extractor.py", "owner": "", "context": ["decision", "indexing", "embed", "batch", "counters", "failure"], "legs": {"full": ["history", "semantic"], "keyless": ["history", "fts"]}},+ {"target": "packages/core/src/repowise/core/analysis/decision_extractor.py", "kind": "page", "member_name": "", "path": "packages/core/src/repowise/core/analysis/decision_extractor.py", "owner": "", "context": ["decision", "extractor", "indexing", "embed", "batch"], "legs": {"full": ["semantic", "fts"], "keyless": ["fts"]}},+ {"target": "dec_generic_branch_names", "kind": "decision", "member_name": "", "path": "", "owner": "", "context": ["branch", "names"], "legs": {"full": ["history"], "keyless": ["history"]}},+ {"target": "packages/core/src/repowise/core/workspace/registry.py::WorkspaceRegistry.get", "kind": "symbol", "member_name": "get", "path": "packages/core/src/repowise/core/workspace/registry.py", "owner": "WorkspaceRegistry", "context": ["workspace"], "legs": {"full": ["symbol"], "keyless": ["symbol"]}},+ {"target": "packages/core/src/repowise/core/distill/runner.py::run", "kind": "symbol", "member_name": "run", "path": "packages/core/src/repowise/core/distill/runner.py", "owner": "", "context": ["distill"], "legs": {"full": ["symbol"], "keyless": ["symbol"]}},+ {"target": "packages/cli/src/repowise/cli/main.py::main", "kind": "symbol", "member_name": "main", "path": "packages/cli/src/repowise/cli/main.py", "owner": "", "context": ["cli"], "legs": {"full": ["symbol"], "keyless": ["symbol"]}}]},{@@ -135,13 +135,13 @@],"oracle_basis": "The generic leaf is supported by exact owner, module/path, and omission-reference query context; every other generic member is manually labelled unsupported.","candidates": [- {"target": "packages/core/src/repowise/core/workspace/registry.py::WorkspaceRegistry.get", "kind": "symbol", "member_name": "get", "path": "packages/core/src/repowise/core/workspace/registry.py", "owner": "WorkspaceRegistry", "context": ["workspace", "alias"], "legs": {"full": ["symbol"], "degraded": ["symbol"]}},- {"target": "packages/core/src/repowise/core/distill/store.py::OmissionStore.get", "kind": "symbol", "member_name": "get", "path": "packages/core/src/repowise/core/distill/store.py", "owner": "OmissionStore", "context": ["omission", "store", "saved", "reference", "expand"], "legs": {"full": ["symbol", "semantic", "fts"], "degraded": ["symbol", "fts"]}},- {"target": "packages/core/src/repowise/core/ingestion/languages/registry.py::LanguageRegistry.get", "kind": "symbol", "member_name": "get", "path": "packages/core/src/repowise/core/ingestion/languages/registry.py", "owner": "LanguageRegistry", "context": ["language", "tag"], "legs": {"full": ["symbol"], "degraded": ["symbol"]}},- {"target": "packages/core/src/repowise/core/sessions/cursor.py::SessionCursor.get", "kind": "symbol", "member_name": "get", "path": "packages/core/src/repowise/core/sessions/cursor.py", "owner": "SessionCursor", "context": ["session", "cursor", "file"], "legs": {"full": ["symbol"], "degraded": ["symbol"]}},- {"target": "packages/core/src/repowise/core/distill/runner.py::run", "kind": "symbol", "member_name": "run", "path": "packages/core/src/repowise/core/distill/runner.py", "owner": "", "context": ["distill", "command"], "legs": {"full": ["symbol"], "degraded": ["symbol"]}},- {"target": "packages/cli/src/repowise/cli/main.py::main", "kind": "symbol", "member_name": "main", "path": "packages/cli/src/repowise/cli/main.py", "owner": "", "context": ["cli", "entrypoint"], "legs": {"full": ["symbol"], "degraded": ["symbol"]}},- {"target": "packages/core/src/repowise/core/distill/store.py", "kind": "page", "member_name": "", "path": "packages/core/src/repowise/core/distill/store.py", "owner": "", "context": ["omission", "store", "saved", "reference", "expand"], "legs": {"full": ["semantic", "fts"], "degraded": ["fts"]}}+ {"target": "packages/core/src/repowise/core/workspace/registry.py::WorkspaceRegistry.get", "kind": "symbol", "member_name": "get", "path": "packages/core/src/repowise/core/workspace/registry.py", "owner": "WorkspaceRegistry", "context": ["workspace", "alias"], "legs": {"full": ["symbol"], "keyless": ["symbol"]}},+ {"target": "packages/core/src/repowise/core/distill/store.py::OmissionStore.get", "kind": "symbol", "member_name": "get", "path": "packages/core/src/repowise/core/distill/store.py", "owner": "OmissionStore", "context": ["omission", "store", "saved", "reference", "expand"], "legs": {"full": ["symbol", "semantic", "fts"], "keyless": ["symbol", "fts"]}},+ {"target": "packages/core/src/repowise/core/ingestion/languages/registry.py::LanguageRegistry.get", "kind": "symbol", "member_name": "get", "path": "packages/core/src/repowise/core/ingestion/languages/registry.py", "owner": "LanguageRegistry", "context": ["language", "tag"], "legs": {"full": ["symbol"], "keyless": ["symbol"]}},+ {"target": "packages/core/src/repowise/core/sessions/cursor.py::SessionCursor.get", "kind": "symbol", "member_name": "get", "path": "packages/core/src/repowise/core/sessions/cursor.py", "owner": "SessionCursor", "context": ["session", "cursor", "file"], "legs": {"full": ["symbol"], "keyless": ["symbol"]}},+ {"target": "packages/core/src/repowise/core/distill/runner.py::run", "kind": "symbol", "member_name": "run", "path": "packages/core/src/repowise/core/distill/runner.py", "owner": "", "context": ["distill", "command"], "legs": {"full": ["symbol"], "keyless": ["symbol"]}},+ {"target": "packages/cli/src/repowise/cli/main.py::main", "kind": "symbol", "member_name": "main", "path": "packages/cli/src/repowise/cli/main.py", "owner": "", "context": ["cli", "entrypoint"], "legs": {"full": ["symbol"], "keyless": ["symbol"]}},+ {"target": "packages/core/src/repowise/core/distill/store.py", "kind": "page", "member_name": "", "path": "packages/core/src/repowise/core/distill/store.py", "owner": "", "context": ["omission", "store", "saved", "reference", "expand"], "legs": {"full": ["semantic", "fts"], "keyless": ["fts"]}}]}]diff --git a/tests/fixtures/mcp/tool_response_shapes.json b/tests/fixtures/mcp/tool_response_shapes.jsonnew file mode 100644index 000000000..3333ebd56--- /dev/null+++ b/tests/fixtures/mcp/tool_response_shapes.json@@ -0,0 +1,1706 @@+{+ "get_answer": {+ "_meta": {+ "cached": null,+ "contract_version": null,+ "embedder_degraded": null,+ "index_age_days": null,+ "indexed_commit": null,+ "projection": {+ "recovery": {+ "arguments": {+ "include": [+ null+ ],+ "question": null+ },+ "tool": null+ }+ },+ "timing_ms": null+ },+ "answer": null,+ "candidates_emitted": null,+ "candidates_reduced_reason": null,+ "candidates_total": null,+ "citations": [+ null+ ],+ "confidence": null,+ "fallback_targets_emitted": null,+ "fallback_targets_reduced_reason": null,+ "fallback_targets_total": null,+ "flow_path": [+ null+ ],+ "next_action_hint": null,+ "note": null,+ "quotes": [+ {+ "lines": [+ null+ ],+ "path": null,+ "quote": null+ }+ ],+ "quotes_emitted": null,+ "quotes_reduced_reason": null,+ "quotes_total": null,+ "retrieval_quality": null+ },+ "get_architecture": {+ "_meta": {+ "analysis_commits": {+ "backend": null,+ "frontend": null,+ "repowise": null+ },+ "analysis_timestamp": null,+ "contract_version": null,+ "embedder_degraded": null+ },+ "architecture_type": null,+ "conformance_violations": null,+ "core_members": [+ null+ ],+ "core_members_truncated": null,+ "core_ratio": null,+ "core_size": null,+ "cycle_count": null,+ "node_count": null,+ "propagation_cost_pct": null,+ "role_breakdown": {+ "control": null,+ "core": null,+ "peripheral": null,+ "shared": null+ },+ "score": null,+ "summary": null+ },+ "get_blast_radius": {+ "_meta": {+ "analysis_commits": {+ "backend": null,+ "frontend": null,+ "repowise": null+ },+ "analysis_timestamp": null,+ "contract_version": null,+ "embedder_degraded": null+ },+ "behavioral_count": null,+ "impact_score_semantics": {+ "authoritative_for_change_review": null,+ "calibration": {+ "status": null+ },+ "field": null,+ "kind": null,+ "measures": null,+ "range": {+ "maximum": null,+ "minimum": null+ },+ "runtime_breakage_probability": null,+ "unit": null+ },+ "impacted": [],+ "impacted_repos": [],+ "impacted_truncated": null,+ "max_distance": null,+ "structural_count": null,+ "summary": null,+ "target_repos": [],+ "targets": [],+ "total_impacted": null,+ "unresolved_targets": [+ null+ ]+ },+ "get_change_risk": {+ "_meta": {+ "contract_version": null,+ "embedder_degraded": null,+ "index_age_days": null,+ "indexed_commit": null,+ "omitted": {+ "refs": [+ null+ ],+ "restore": null,+ "tokens": null+ },+ "source": null,+ "timing_ms": null+ },+ "change_shape": {+ "classification": null,+ "diagnostics_via": null,+ "fallback_band": null,+ "is_fix": null,+ "measures": null,+ "review_priority": null,+ "risk_percentile": null,+ "score": null+ },+ "classification": null,+ "directive": {+ "headline": null,+ "next_actions": [+ null+ ],+ "reasons": [+ null+ ],+ "status": null+ },+ "exclude_patterns": [],+ "fallback_band": null,+ "fix_history": {+ "available": null,+ "density": null,+ "files": [+ {+ "churn": null,+ "fix_pressure": null,+ "path": null+ }+ ],+ "percentile": null+ },+ "health_delta": {+ "analyzer": {+ "analyzer_version": null,+ "performance_model_version": null,+ "rules_fingerprint": null+ },+ "base": {+ "kind": null,+ "ref": null,+ "sha": null+ },+ "basis": null,+ "by_dimension": {},+ "by_severity": {},+ "explanation": null,+ "findings_emitted": null,+ "findings_total": null,+ "head": {+ "kind": null,+ "ref": null,+ "sha": null+ },+ "introduced": null,+ "limits": [+ null+ ],+ "resolved": null,+ "scope": {+ "analyzed": null,+ "changed": null,+ "eligible": null,+ "failed": null,+ "skipped": null+ },+ "skipped": {+ "by_reason": {+ "not_health_analyzable": null+ },+ "total": null+ },+ "status": null,+ "top_findings": [],+ "worsened": null+ },+ "impacted_tests": {+ "basis": null,+ "line_coverage": {+ "covered": [],+ "no_coverage_data": [],+ "stale_test_candidates": [],+ "untested_changes": []+ },+ "map_present": null,+ "status": null,+ "summary": null,+ "tests_to_run": [+ null+ ],+ "total": null,+ "truncated": null+ },+ "is_fix": null,+ "omission_marker": null,+ "prior_fixes": {+ "changed_lines_in_fixed_files": null,+ "files": [+ {+ "changed_lines": null,+ "file_path": null,+ "fix_count": null,+ "last_fix_days_ago": null,+ "overlapping_lines": null,+ "share_of_change": null+ }+ ],+ "files_with_fixes": null,+ "line_overlap": null,+ "summary": null,+ "total_fixes": null,+ "truncated": null+ },+ "ref": null,+ "review_priority": null,+ "risk_percentile": null,+ "score": null,+ "working_tree": null+ },+ "get_conformance": {+ "_meta": {+ "analysis_commits": {+ "backend": null,+ "frontend": null,+ "repowise": null+ },+ "analysis_timestamp": null,+ "contract_version": null,+ "embedder_degraded": null+ },+ "checked_at": null,+ "cycle_count": null,+ "cycles": [+ {+ "edge_ids": [+ null+ ],+ "length": null,+ "nodes": [+ null+ ]+ }+ ],+ "cycles_truncated": null,+ "rules_evaluated": null,+ "summary": null,+ "total_cycles": null,+ "violation_count": null,+ "violations": [],+ "violations_truncated": null+ },+ "get_context": {+ "_meta": {+ "contract_version": null,+ "embedder_degraded": null,+ "index_age_days": null,+ "indexed_commit": null,+ "timing_ms": null+ },+ "targets": {+ "<path>": {+ "_call_graph_note": null,+ "architectural_layer": {+ "description": null,+ "name": null,+ "role": null+ },+ "callers": [+ {+ "file": null,+ "imports": null,+ "inbound_calls": null+ }+ ],+ "docs": {+ "summary": null,+ "symbols": [+ {+ "kind": null,+ "line": null,+ "name": null,+ "signature": null,+ "symbol_id": null+ }+ ],+ "symbols_truncated": {+ "hint": null,+ "shown": null,+ "total": null+ },+ "title": null+ },+ "episodes": null,+ "fix_history": {+ "bug_magnet": null,+ "fix_count": null,+ "last_fix_days_ago": null+ },+ "freshness": {+ "confidence_score": null,+ "freshness_status": null,+ "is_stale": null+ },+ "hotspot": null,+ "parent_page": {+ "section": null,+ "target_path": null,+ "title": null+ },+ "path": null,+ "skeleton": {+ "bodies_kept": [],+ "full_tokens": null,+ "mode": null,+ "pct_of_full": null,+ "text": null,+ "tokens": null,+ "verified": null+ },+ "target": null,+ "type": null+ }+ }+ },+ "get_dead_code": {+ "_meta": {+ "contract_version": null,+ "embedder_degraded": null,+ "index_age_days": null,+ "indexed_commit": null,+ "omitted": {+ "refs": [+ null+ ],+ "restore": null,+ "tokens": null+ }+ },+ "impact": {+ "recommendation": null,+ "safe_lines_reclaimable": null,+ "total_lines_reclaimable": null+ },+ "limit_note": null,+ "omission_marker": null,+ "summary": {+ "by_kind": {+ "unreachable_file": null,+ "unused_export": null,+ "unused_internal": null,+ "zombie_package": null+ },+ "deletable_lines": null,+ "filtered_findings": null,+ "safe_to_delete_count": null,+ "total_findings": null+ },+ "tiers": {+ "high": {+ "count": null,+ "description": null,+ "findings": [+ {+ "age_days": null,+ "commit_count_90d": null,+ "confidence": null,+ "end_line": null,+ "file_path": null,+ "id": null,+ "kind": null,+ "last_commit_at": null,+ "last_meaningful_change": null,+ "lines": null,+ "primary_owner": null,+ "reason": null,+ "repository": null,+ "risk_factors": [],+ "safe_to_delete": null,+ "start_line": null,+ "symbol_kind": null,+ "symbol_name": null+ }+ ],+ "lines": null,+ "safe_count": null,+ "truncated": null+ },+ "low": {+ "count": null,+ "description": null,+ "findings": [+ {+ "age_days": null,+ "commit_count_90d": null,+ "confidence": null,+ "end_line": null,+ "file_path": null,+ "id": null,+ "kind": null,+ "last_commit_at": null,+ "last_meaningful_change": null,+ "lines": null,+ "primary_owner": null,+ "reason": null,+ "repository": null,+ "risk_factors": [+ null+ ],+ "safe_to_delete": null,+ "start_line": null,+ "symbol_kind": null,+ "symbol_name": null+ }+ ],+ "lines": null,+ "safe_count": null,+ "truncated": null+ },+ "medium": {+ "count": null,+ "description": null,+ "findings": [+ {+ "age_days": null,+ "commit_count_90d": null,+ "confidence": null,+ "end_line": null,+ "file_path": null,+ "id": null,+ "kind": null,+ "last_commit_at": null,+ "last_meaningful_change": null,+ "lines": null,+ "primary_owner": null,+ "reason": null,+ "repository": null,+ "risk_factors": [+ null+ ],+ "safe_to_delete": null,+ "start_line": null,+ "symbol_kind": null,+ "symbol_name": null+ }+ ],+ "lines": null,+ "safe_count": null,+ "truncated": null+ }+ }+ },+ "get_dependency_path": {+ "distance": null,+ "explanation": null,+ "path": [],+ "visual_context": {+ "bridge_suggestions": [+ {+ "node": null,+ "pagerank": null+ }+ ],+ "community": {+ "same_community": null,+ "source_community": null,+ "target_community": null+ },+ "disconnected": null,+ "nearest_common_ancestors": [+ {+ "distance_from_source": null,+ "distance_from_target": null,+ "node": null+ }+ ],+ "reverse_path": {+ "distance": null,+ "exists": null,+ "note": null,+ "path": [+ null+ ]+ },+ "shared_neighbors": [+ null+ ],+ "suggestion": null+ }+ },+ "get_execution_flows": {+ "_meta": {+ "contract_version": null,+ "embedder_degraded": null,+ "hint": null,+ "timing_ms": null+ },+ "flows": [+ {+ "communities_visited": [+ null+ ],+ "crosses_community": null,+ "depth": null,+ "entry_point": null,+ "entry_point_name": null,+ "entry_point_score": null,+ "termination": null,+ "trace": [+ null+ ],+ "trace_via": [+ null+ ]+ }+ ],+ "total_entry_points": null+ },+ "get_health": {+ "_meta": {+ "contract_version": null,+ "embedder_degraded": null,+ "health_analysis": {+ "analyzed_at": null,+ "analyzed_commit": null,+ "analyzed_commits_distinct": null,+ "live_verification": {+ "basis": null,+ "source_bytes_verified": null+ },+ "recomputed_this_call": null,+ "refresh": {+ "command": null,+ "precondition": null,+ "required_before_comparison": null+ },+ "source": null,+ "status": null+ },+ "health_analyzed_at": null,+ "health_analyzed_commit": null,+ "health_analyzed_commits_distinct": null,+ "health_semantics": {+ "percentiles": {+ "direction": null,+ "freshness": null,+ "population": null,+ "public_raw_scale": null,+ "stored_scale": null+ },+ "weighted_deficit_points": {+ "denominator": null,+ "direction": null,+ "interpretation": null,+ "numerator": null,+ "scale": {+ "maximum": null,+ "minimum": null,+ "normalized": null+ },+ "unit": null+ }+ },+ "index_age_days": null,+ "indexed_commit": null,+ "timing_ms": null+ },+ "directive": {+ "fix_first": null,+ "next_action": null,+ "plan_addresses_reason": null,+ "plan_note": null,+ "plan_via": null,+ "reason": null,+ "recovers_points": null,+ "recovers_points_compatibility": {+ "deprecated": null,+ "equivalent_value": null,+ "replacement": null+ },+ "recovers_weighted_deficit_points": null,+ "share_of_repo_gap_pct": null,+ "then": [+ null+ ],+ "then_emitted": null,+ "then_total": null+ },+ "distribution": {+ "bands": {+ "alert": {+ "files": null,+ "nloc": null,+ "pct": null+ },+ "healthy": {+ "files": null,+ "nloc": null,+ "pct": null+ },+ "warning": {+ "files": null,+ "nloc": null,+ "pct": null+ }+ },+ "total_files": null,+ "total_nloc": null+ },+ "gap_analysis": {+ "files_below_target": null,+ "files_for_half_gap": null,+ "files_to_reach_target": null,+ "target_score": null,+ "weighted_gap_points": null,+ "weighted_gross_gap_points": null+ },+ "high_leverage_files": [+ {+ "branch_coverage_pct": null,+ "file_path": null,+ "has_test_file": null,+ "is_test": null,+ "line_coverage_pct": null,+ "maintainability_score": null,+ "max_ccn": null,+ "max_nesting": null,+ "module": null,+ "nloc": null,+ "performance_score": null,+ "primary_biomarker": null,+ "primary_reason": null,+ "score": null,+ "share_of_repo_gap_pct": null,+ "total_deduction": null,+ "weighted_deficit": null+ }+ ],+ "high_leverage_files_emitted": null,+ "high_leverage_files_reduced_reason": null,+ "high_leverage_files_total": null,+ "kpis": {+ "average_health": null,+ "average_health_code_only": null,+ "average_health_unweighted": null,+ "average_health_weighting": null,+ "band": null,+ "file_count": null,+ "hotspot_health": null,+ "maintainability_average": null,+ "non_code_files": null,+ "performance_analyzed_files": null,+ "performance_average": null,+ "performance_coverage_pct": null,+ "performance_covered_files": null,+ "performance_findings": null,+ "performance_findings_density_per_10k_loc": null,+ "performance_skipped_files": null,+ "performance_unsupported_languages": [+ null+ ],+ "performance_unsupported_languages_emitted": null,+ "performance_unsupported_languages_total": null,+ "worst_performer_path": null,+ "worst_performer_score": null+ },+ "mode": null,+ "performance_directive": {+ "advisory_total": null,+ "affected_call_sites_total": null,+ "boundary_kind": null,+ "execution_context": null,+ "file_path": null,+ "investigate_total": null,+ "next_action": {+ "arguments": {+ "opportunity_id": null+ },+ "tool": null+ },+ "observations_total": null,+ "opportunities_total": null,+ "opportunity_id": null,+ "performance_model_version": null,+ "plan_ready_total": null,+ "plan_reason": null,+ "plan_state": null,+ "prerequisites": [],+ "prerequisites_emitted": null,+ "prerequisites_total": null,+ "status": null,+ "title": null,+ "why_ranked": [+ {+ "factor": null,+ "points": null,+ "value": null+ }+ ],+ "why_ranked_emitted": null,+ "why_ranked_total": null+ },+ "performance_opportunities": [+ {+ "actionability_reason": null,+ "actionability_state": null,+ "affected_call_sites_total": null,+ "affected_files_total": null,+ "biomarker_type": null,+ "biomarker_types": [+ null+ ],+ "biomarker_types_emitted": null,+ "biomarker_types_total": null,+ "boundary_kind": null,+ "confidence": null,+ "evidence": [+ {+ "biomarker_type": null,+ "file_path": null,+ "finding_id": null,+ "function_name": null,+ "line_end": null,+ "line_start": null,+ "path": [],+ "path_emitted": null,+ "path_total": null,+ "provenance": null,+ "reason": null+ }+ ],+ "evidence_emitted": null,+ "evidence_total": null,+ "evidence_truncated": null,+ "execution_context": null,+ "facets": {+ "actionability_confidence": null,+ "amplification": null,+ "change_risk": null,+ "exposure": null,+ "leverage": null+ },+ "file_path": null,+ "fix": {+ "rationale": null,+ "safety": null,+ "strategy": null+ },+ "intervention_symbol": null,+ "observations_total": null,+ "opportunity_id": null,+ "performance_model_version": null,+ "plan_id": null,+ "plan_reason": null,+ "plan_reference": null,+ "plan_status": null,+ "prerequisites": [],+ "prerequisites_emitted": null,+ "prerequisites_total": null,+ "provenance": null,+ "rank_factors": {+ "affected_call_sites": null,+ "boundary_kind": null,+ "entry_reachability": null,+ "execution_context": null,+ "multiplier_shape": null,+ "provenance": null+ },+ "rank_position": null,+ "rank_score": null,+ "reliable_entry_reachability": null,+ "resource_fingerprints": [],+ "resource_fingerprints_emitted": null,+ "resource_fingerprints_total": null,+ "shared_path_suffix": [],+ "shared_path_suffix_emitted": null,+ "shared_path_suffix_total": null,+ "terminal_sink": null,+ "why_ranked": [+ {+ "factor": null,+ "points": null,+ "value": null+ }+ ],+ "why_ranked_emitted": null,+ "why_ranked_total": null+ }+ ],+ "performance_opportunities_emitted": null,+ "performance_opportunities_reduced_reason": null,+ "performance_opportunities_total": null,+ "performance_summary": {+ "actionability": {+ "advisory": null,+ "investigate": null,+ "plan_ready": null+ },+ "analyzed_commit": null,+ "boundary": {+ "db": null,+ "filesystem": null,+ "network": null,+ "none": null,+ "subprocess": null+ },+ "context": {+ "production": null+ },+ "facets": {+ "actionability": [+ {+ "total": null,+ "value": null+ }+ ],+ "actionability_emitted": null,+ "actionability_total": null,+ "boundary": [+ {+ "total": null,+ "value": null+ }+ ],+ "boundary_emitted": null,+ "boundary_total": null,+ "confidence": [+ {+ "total": null,+ "value": null+ }+ ],+ "confidence_emitted": null,+ "confidence_total": null,+ "context": [+ {+ "total": null,+ "value": null+ }+ ],+ "context_emitted": null,+ "context_total": null,+ "plan_state": [+ {+ "total": null,+ "value": null+ }+ ],+ "plan_state_emitted": null,+ "plan_state_total": null+ },+ "materialized_model_version": null,+ "next_call": null,+ "performance_model_version": null,+ "repository_total": null,+ "status": null,+ "total": null,+ "with_plan_total": null+ },+ "recommendation_lede": {+ "next_call": null,+ "performance_lead": {+ "affected_call_sites_total": null,+ "boundary_kind": null,+ "execution_context": null,+ "intervention_symbol": null,+ "opportunity_id": null,+ "rank_score": null+ },+ "performance_opportunities_total": null,+ "performance_plan_id": null,+ "performance_plan_reason": null,+ "recommendation_lead": {+ "benefit": null,+ "cost": null,+ "file_path": null,+ "id": null,+ "leverage": null,+ "rank_score": null,+ "refactoring_type": null,+ "risk": null,+ "target_symbol": null+ },+ "refactoring_plans_total": null+ },+ "recovery": {+ "high_leverage_files": {+ "call": null,+ "remaining": null+ },+ "performance_opportunities": {+ "call": null,+ "remaining": null+ },+ "refactoring_opportunities": {+ "call": null,+ "remaining": null+ },+ "refactoring_plans": {+ "call": null,+ "remaining": null+ }+ },+ "refactoring_directive": {+ "addresses_primary_problem": null,+ "confidence": null,+ "effort_bucket": null,+ "fix_first": null,+ "judgment_steps": null,+ "lead_refactoring_type": null,+ "mechanical_steps": null,+ "next_action": {+ "arguments": {+ "opportunity_id": null+ },+ "tool": null+ },+ "opportunities_total": null,+ "opportunity_id": null,+ "reason": null,+ "recovers_health_points": null,+ "status": null,+ "steps": null+ },+ "refactoring_opportunities": [+ {+ "addresses_primary_problem": null,+ "affected_files_total": null,+ "confidence": null,+ "dependents": null,+ "effort_bucket": null,+ "evidence_total": null,+ "file_nloc": null,+ "file_path": null,+ "judgment_steps": null,+ "lead_biomarker": null,+ "lead_refactoring_type": null,+ "mechanical_steps": null,+ "opportunity_id": null,+ "queue_position": null,+ "rank_factors": {+ "benefit": null,+ "cost": null,+ "mechanical_share": null,+ "primary_problem": null,+ "risk": null+ },+ "rank_position": null,+ "rank_score": null,+ "recoverable_health": null,+ "refactoring_model_version": null,+ "status": null,+ "step_count": null,+ "steps": [+ {+ "applicability": {+ "classification": null,+ "facts": {+ "affected_file_count": null,+ "blast_size": null,+ "callers": null,+ "confidence": null,+ "cross_file": null,+ "framework_registration": null+ },+ "reasons": [+ null+ ],+ "reasons_emitted": null,+ "reasons_total": null,+ "unknowns": [+ null+ ],+ "unknowns_emitted": null,+ "unknowns_total": null+ },+ "confidence": null,+ "effort_bucket": null,+ "file_path": null,+ "finding_ids": [],+ "finding_ids_emitted": null,+ "finding_ids_total": null,+ "impact_delta": null,+ "line_end": null,+ "line_start": null,+ "plan_id": null,+ "refactoring_type": null,+ "relocated_by": null,+ "source_biomarker": null,+ "target_symbol": null,+ "validation_profile_id": null+ }+ ],+ "steps_emitted": null,+ "steps_reduced_reason": null,+ "steps_total": null,+ "why_ranked": [+ {+ "factor": null,+ "value": null+ }+ ],+ "why_ranked_emitted": null,+ "why_ranked_total": null+ }+ ],+ "refactoring_opportunities_emitted": null,+ "refactoring_opportunities_reduced_reason": null,+ "refactoring_opportunities_total": null,+ "refactoring_plans": [+ {+ "benefit": null,+ "blast_radius": {+ "scope": null+ },+ "confidence": null,+ "cost": null,+ "dependents": null,+ "effort_bucket": null,+ "evidence": {+ "ccn_removed": null,+ "slice_nloc": null+ },+ "file_nloc": null,+ "file_path": null,+ "file_weighted_deficit": null,+ "id": null,+ "impact_delta": null,+ "leverage": null,+ "line_end": null,+ "line_start": null,+ "plan": {+ "params": [+ null+ ],+ "params_emitted": null,+ "params_total": null,+ "returns": [],+ "returns_emitted": null,+ "returns_total": null,+ "span": {+ "end": null,+ "start": null+ },+ "suggested_name": null+ },+ "rank_score": null,+ "refactoring_type": null,+ "repository": null,+ "risk": null,+ "source_biomarker": null,+ "target_symbol": null,+ "validation_profile_id": null+ }+ ],+ "refactoring_plans_emitted": null,+ "refactoring_plans_reduced_reason": null,+ "refactoring_plans_status": {+ "reason": null,+ "state": null+ },+ "refactoring_plans_total": null,+ "refactoring_summary": {+ "addresses_primary_problem": {+ "no": null,+ "unknown": null,+ "yes": null+ },+ "analyzed_commit": null,+ "by_confidence": {+ "high": null,+ "medium": null+ },+ "by_effort": {+ "L": null,+ "M": null,+ "S": null,+ "XL": null+ },+ "by_lead_type": {+ "break_cycle": null,+ "extract_class": null,+ "extract_helper": null,+ "extract_method": null,+ "move_method": null,+ "split_file": null+ },+ "by_status": {+ "open": null+ },+ "facets": {+ "confidence": {+ "high": null,+ "medium": null+ },+ "effort": {+ "L": null,+ "M": null,+ "S": null,+ "XL": null+ },+ "lead_type": {+ "break_cycle": null,+ "extract_class": null,+ "extract_helper": null,+ "extract_method": null,+ "move_method": null,+ "split_file": null+ }+ },+ "files_total": null,+ "judgment_steps_total": null,+ "lead": {+ "addresses_primary_problem": null,+ "confidence": null,+ "effort_bucket": null,+ "file_path": null,+ "judgment_steps": null,+ "lead_biomarker": null,+ "lead_refactoring_type": null,+ "mechanical_steps": null,+ "opportunity_id": null,+ "recoverable_health": null,+ "status": null,+ "step_count": null+ },+ "mechanical_steps_total": null,+ "next_call": null,+ "opportunities_total": null,+ "refactoring_model_version": null,+ "status": null,+ "steps_total": null,+ "view": null+ },+ "secondary_rankings": {+ "modules": {+ "call": null,+ "total": null+ },+ "test_findings": {+ "call": null,+ "total": null+ },+ "top_findings": {+ "call": null,+ "total": null+ },+ "worst_files": {+ "call": null,+ "total": null+ }+ },+ "suggestion_legend": {+ "hot_path_sync_io": null,+ "io_in_loop": null,+ "nested_loop_with_io": null,+ "serial_await_in_loop": null+ },+ "unknown_include_keys": [+ null+ ],+ "unknown_include_keys_emitted": null,+ "unknown_include_keys_total": null,+ "validation_profiles": [+ {+ "affected_files": [+ null+ ],+ "affected_files_emitted": null,+ "affected_files_total": null,+ "affected_symbols": [+ null+ ],+ "affected_symbols_emitted": null,+ "affected_symbols_total": null,+ "basis": null,+ "commands": [+ null+ ],+ "commands_emitted": null,+ "commands_total": null,+ "id": null,+ "targets": [+ {+ "basis": null,+ "file_path": null,+ "tests": [+ null+ ],+ "tests_emitted": null,+ "tests_total": null,+ "total": null,+ "truncated": null,+ "via": null+ }+ ],+ "targets_emitted": null,+ "targets_total": null,+ "tests": [+ null+ ],+ "tests_emitted": null,+ "tests_reduced_reason": null,+ "tests_total": null,+ "total": null,+ "via": null+ }+ ],+ "validation_profiles_emitted": null,+ "validation_profiles_total": null+ },+ "get_overview": {+ "_meta": {+ "contract_version": null,+ "embedder_degraded": null,+ "index_age_days": null,+ "indexed_commit": null,+ "omitted": {+ "refs": [+ null+ ],+ "restore": null,+ "tokens": null+ }+ },+ "architecture": {+ "layer_order": [+ null+ ],+ "layers": [+ {+ "file_count": null,+ "name": null+ }+ ],+ "tour_available": null,+ "tour_step_count": null+ },+ "code_health": {+ "average_health": null,+ "band": null,+ "distribution": {+ "bands": {+ "alert": {+ "files": null,+ "nloc": null,+ "pct": null+ },+ "healthy": {+ "files": null,+ "nloc": null,+ "pct": null+ },+ "warning": {+ "files": null,+ "nloc": null,+ "pct": null+ }+ },+ "total_files": null,+ "total_nloc": null+ },+ "file_count": null,+ "hotspot_health": null,+ "open_findings": null,+ "worst_performer_path": null,+ "worst_performer_score": null+ },+ "content_hint": null,+ "content_md": null,+ "entry_points": [+ null+ ],+ "git_health": {+ "avg_bus_factor": null,+ "churn_trend": null,+ "files_git_attributed": null,+ "files_with_bus_factor_1": null,+ "hotspot_count": null,+ "top_churn_modules": [+ null+ ]+ },+ "key_modules": [+ {+ "name": null,+ "path": null,+ "section": null+ }+ ],+ "more": null,+ "omission_marker": null,+ "title": null,+ "tool_surface": {+ "counts": {+ "default": null,+ "eligible": null,+ "enabled": null,+ "opt_in_available": null,+ "tiers": {+ "canonical": null+ }+ },+ "enabled": [+ null+ ],+ "mode": null,+ "opt_in": [+ {+ "description": null,+ "enabled": null,+ "name": null+ }+ ],+ "recipes": [+ {+ "call": null,+ "name": null+ }+ ],+ "tools": [+ {+ "default": null,+ "description": null,+ "name": null,+ "tier": null+ }+ ]+ }+ },+ "get_risk": {+ "_meta": {+ "contract_version": null,+ "embedder_degraded": null,+ "index_age_days": null,+ "indexed_commit": null,+ "omitted": {+ "refs": [+ null+ ],+ "restore": null,+ "tokens": null+ }+ },+ "omission_marker": null,+ "targets": {+ "packages/core/src/repowise/core/ingestion/call_resolver.py": {+ "bus_factor": null,+ "co_change_partners": [+ {+ "direction": null,+ "evidence_kind": null,+ "file_path": null,+ "has_import_link": null,+ "has_structural_link": null,+ "last_co_change": null,+ "provenance": null,+ "relationship_type": null,+ "structural_relationship_types": [+ null+ ],+ "support": null,+ "weight": null+ }+ ],+ "co_change_partners_emitted": null,+ "co_change_partners_omitted": null,+ "co_change_partners_reduced_reason": null,+ "co_change_partners_total": null,+ "co_change_partners_truncated": null,+ "commit_count_capped": null,+ "contributor_count": null,+ "coverage_pct": null,+ "defect_profile": {+ "bug_magnet": null,+ "fix_count": null,+ "last_fix_days_ago": null,+ "top_symbols": {+ "_link_declarations": null,+ "_merged_symbols_for": null,+ "_published": null+ },+ "window": null+ },+ "dependents_count": null,+ "episodes": null,+ "health_score": null,+ "hotspot_score": null,+ "is_hotspot": null,+ "owner_pct": null,+ "primary_owner": null,+ "recent_owner": null,+ "recent_owner_pct": null,+ "risk_summary": null,+ "security_signals": [],+ "target": null,+ "test_gap": null,+ "top_biomarkers": [+ {+ "biomarker_type": null,+ "function_name": null,+ "impact": null,+ "severity": null+ }+ ],+ "trend": null+ }+ }+ },+ "get_symbol": {+ "_meta": {+ "contract_version": null,+ "embedder_degraded": null,+ "index_age_days": null,+ "indexed_commit": null,+ "replaced_tokens": null,+ "timing_ms": null+ },+ "continuation": null,+ "continuation_reference": {+ "id": null,+ "kind": null,+ "path": null,+ "range": [+ null+ ],+ "repository": null,+ "source_kind": null,+ "verification_basis": null+ },+ "end_line": null,+ "file": null,+ "kind": null,+ "language": null,+ "name": null,+ "note": null,+ "qualified_name": null,+ "signature": null,+ "source": null,+ "start_line": null,+ "symbol_end_line": null,+ "symbol_id": null,+ "symbol_start_line": null,+ "truncated": null,+ "verified": null+ },+ "get_why": {+ "_meta": {+ "contract_version": null,+ "embedder_degraded": null,+ "index_age_days": null,+ "indexed_commit": null,+ "omitted": {+ "refs": [+ null+ ],+ "restore": null,+ "tokens": null+ }+ },+ "alignment": {+ "active_count": null,+ "deprecated_count": null,+ "explanation": null,+ "governing_count": null,+ "score": null,+ "sibling_coverage": null,+ "stale_count": null+ },+ "answer_basis": null,+ "code_rationale": [+ {+ "comment": null,+ "evidence_refs": [+ {+ "content_id": null,+ "id": null,+ "kind": null,+ "line": null,+ "path": null,+ "provenance": null,+ "range": [+ null+ ],+ "repository": null,+ "source": null,+ "source_kind": null,+ "verification": null,+ "verification_basis": null+ }+ ],+ "lines": [+ null+ ],+ "matched_terms": [],+ "path": null,+ "provenance": null+ }+ ],+ "code_rationale_emitted": null,+ "code_rationale_omitted": null,+ "code_rationale_reduced_reason": null,+ "code_rationale_total": null,+ "code_rationale_truncated": null,+ "decisions": [],+ "episodes": [+ {+ "evidence": null,+ "evidence_refs": [+ {+ "commit": null,+ "id": null,+ "kind": null,+ "provenance": null,+ "repository": null,+ "source": null,+ "source_kind": null,+ "verification_basis": null+ }+ ],+ "kind": null,+ "provenance": null,+ "recorded": null,+ "scope": [+ null+ ],+ "still_true": null,+ "subject": null,+ "tier": null+ }+ ],+ "episodes_emitted": null,+ "episodes_omitted": null,+ "episodes_reduced_reason": null,+ "episodes_total": null,+ "episodes_truncated": null,+ "git_archaeology": {+ "cross_references": [],+ "file_commits": [+ {+ "author": null,+ "date": null,+ "evidence_refs": [+ {+ "commit": null,+ "id": null,+ "kind": null,+ "provenance": null,+ "repository": null,+ "source": null,+ "source_kind": null,+ "verification_basis": null+ }+ ],+ "message": null,+ "provenance": null,+ "sha": null+ }+ ],+ "file_commits_emitted": null,+ "file_commits_omitted": null,+ "file_commits_reduced_reason": null,+ "file_commits_total": null,+ "file_commits_truncated": null,+ "git_log": [],+ "provenance": null,+ "summary": null,+ "triggered": null+ },+ "mode": null,+ "omission_marker": null,+ "origin_story": {+ "age_days": null,+ "author_commit_pct": null,+ "available": null,+ "contributors": [+ {+ "commit_count": null,+ "email": null,+ "first_commit_ts": null,+ "last_commit_ts": null,+ "name": null+ }+ ],+ "first_commit": null,+ "key_commits": [+ {+ "author": null,+ "date": null,+ "evidence_refs": [+ {+ "commit": null,+ "id": null,+ "kind": null,+ "provenance": null,+ "repository": null,+ "source": null,+ "source_kind": null,+ "verification_basis": null+ }+ ],+ "message": null,+ "pr_number": null,+ "provenance": null,+ "sha": null+ }+ ],+ "key_commits_emitted": null,+ "key_commits_omitted": null,+ "key_commits_reduced_reason": null,+ "key_commits_total": null,+ "key_commits_truncated": null,+ "last_commit": null,+ "linked_decisions": [],+ "primary_author": null,+ "provenance": null,+ "summary": null,+ "total_commits": null+ },+ "path": null+ },+ "list_repos": {+ "_meta": {+ "contract_version": null,+ "embedder_degraded": null+ },+ "default_repo": null,+ "hint": null,+ "repos": [+ {+ "absolute_path": null,+ "alias": null,+ "is_default": null,+ "path": null+ }+ ],+ "workspace": null,+ "workspace_root": null+ },+ "search_codebase": {+ "_meta": {+ "contract_version": null,+ "embedder_degraded": null,+ "index_age_days": null,+ "indexed_commit": null+ },+ "candidates": [+ {+ "path": null+ }+ ],+ "results": [+ {+ "confidence_score": null,+ "page_type": null,+ "relevance_score": null,+ "snippet": null,+ "sources": [+ null+ ],+ "target_path": null,+ "title": null+ }+ ]+ }+}diff --git a/tests/unit/cli/test_tool_bridge.py b/tests/unit/cli/test_tool_bridge.pyindex 1ae945fb5..ff2e1d900 100644--- a/tests/unit/cli/test_tool_bridge.py+++ b/tests/unit/cli/test_tool_bridge.py@@ -72,13 +72,27 @@ def wired(monkeypatch, tmp_path):return engine, store, published, tmp_path+def _answer_only(result: dict) -> dict:+ """The tool's own payload, minus the budget envelope the bridge stamps.++ A bridged call is budgeted the way the MCP middleware budgets an MCP call,+ so every response gains ``_meta.response_budget``. What must not change is+ the answer the tool returned.+ """+ meta = {k: v for k, v in (result.get("_meta") or {}).items() if k != "response_budget"}+ answer = {k: v for k, v in result.items() if k != "_meta"}+ if meta:+ answer["_meta"] = meta+ return answer++def test_it_publishes_this_repos_resources_and_tears_them_down(wired):engine, store, published, repo = wiredasync def _tool():return {"ok": True}- assert tool_bridge.call_tool(repo, _tool, "get_symbol") == {"ok": True}+ assert _answer_only(tool_bridge.call_tool(repo, _tool, "get_symbol")) == {"ok": True}# The session factory is the object that decides *which repo's database*# answers, so it is the one most worth pinning.assert published["session_factory"].kw["bind"] is engine@@ -150,7 +164,7 @@ def test_a_store_that_fails_to_close_does_not_lose_the_answer(wired, monkeypatchasync def _tool():return {"ok": True}- assert tool_bridge.call_tool(repo, _tool, "get_symbol") == {"ok": True}+ assert _answer_only(tool_bridge.call_tool(repo, _tool, "get_symbol")) == {"ok": True}assert engine.disposed@@ -274,7 +288,7 @@ def test_a_store_one_repowise_older_than_the_models_is_still_readable(monkeypatcawait session.execute(select(Repository).limit(1))return {"ok": True}- assert tool_bridge.call_tool(tmp_path, _tool, "get_answer") == {"ok": True}+ assert _answer_only(tool_bridge.call_tool(tmp_path, _tool, "get_answer")) == {"ok": True}conn = sqlite3.connect(db_file)healed = {r[1] for r in conn.execute("pragma table_info(repositories)")}@@ -385,3 +399,26 @@ def test_a_repo_that_asked_for_keyless_is_not_reported_as_degraded(asyncio.run(tool_bridge._open_vector_store(tmp_path))assert restore_embedder_status._embedder_status["degraded"] is False+++def test_a_bridged_call_is_bounded_like_an_mcp_one(wired):+ """The CLI awaits tool functions directly, so no middleware runs.++ Budgeting has to happen here or ``repowise search --format json``, which+ agents read, returns whatever the tool built.+ """+ _engine, _store, _published, repo = wired++ async def _tool():+ return {+ "results": [{"path": f"src/f{i}.py", "excerpt": "x" * 900} for i in range(80)],+ "_meta": {},+ }++ result = tool_bridge.call_tool(repo, _tool, "search_codebase")++ budget = result["_meta"]["response_budget"]+ assert budget["serialized_chars"] <= budget["limit_chars"]+ assert result["truncated"] is True+ assert len(result["results"]) < 80+ assert result["_meta"]["omitted"]["refs"]diff --git a/tests/unit/server/mcp/test_health.py b/tests/unit/server/mcp/test_health.pyindex 712e98f5b..85174d161 100644--- a/tests/unit/server/mcp/test_health.py+++ b/tests/unit/server/mcp/test_health.py@@ -2049,7 +2049,9 @@ async def test_meta_omits_the_commit_when_no_row_records_one(setup_mcp, health_d"source_bytes_verified": False,}analysis = meta["health_analysis"]- assert analysis["status"] == "degraded"+ # Usable metrics with no recorded commit: a provenance gap, not a failed+ # capability, which is what ``degraded`` means everywhere else on the wire.+ assert analysis["status"] == "provenance_unknown"assert analysis["reason"] == "analysis_commit_not_recorded"assert analysis["refresh"] == {"command": "repowise update",diff --git a/tests/unit/server/mcp/test_response_budget_contracts.py b/tests/unit/server/mcp/test_response_budget_contracts.pyindex 261338dce..8faa84a52 100644--- a/tests/unit/server/mcp/test_response_budget_contracts.py+++ b/tests/unit/server/mcp/test_response_budget_contracts.py@@ -111,6 +111,12 @@ def _signature() -> inspect.Signature:def _enforce(tool: str, payload: dict[str, Any], include: list[str] | None = None) -> dict:+ # A tool registers its budget hooks when its module loads, which in+ # production has always happened by the time the middleware calls through.+ # Loading the surface is what makes a direct call mirror that.+ from repowise.server.mcp_server import ensure_full_surface++ ensure_full_surface()kwargs = {"include": include} if include is not None else {}return enforce_response_budget(tool,@@ -397,3 +403,180 @@ async def test_budget_repo_root_follows_workspace_alias(signature = inspect.signature(call)assert await resolve_response_budget_repo_root(signature, (), {"repo": "other"}) == selected+++def test_every_registered_tool_declares_a_contract() -> None:+ """No tool may fall through the shared layer and be delivered unbounded."""+ from repowise.server.mcp_server import _TOOL_MODULES+ from repowise.server.mcp_server._budget import budgeted_tool_names++ assert set(_TOOL_MODULES) == set(budgeted_tool_names())+++def test_no_contract_sheds_a_block_it_also_protects() -> None:+ """Removing a whole top-level block the guard protects is a contradiction.++ Trimming a protected block's tail (``targets[]`` under ``targets``) is not:+ ``fit_to_budget`` ranks rows, ``protected`` only stops wholesale removal.+ """+ from repowise.server.mcp_server._budget.contracts import _CONTRACTS++ for tool, contract in _CONTRACTS.items():+ whole_blocks = {+ key for key in contract.shed_order if "." not in key and not key.endswith("[]")+ }+ assert not whole_blocks & set(contract.protected), tool+++def test_every_hook_owner_registers_on_tool_import() -> None:+ """A hook lost at import is a silent correctness bug, so pin the owners."""+ from repowise.server.mcp_server import ensure_full_surface+ from repowise.server.mcp_server._budget import registered_hook_tools++ ensure_full_surface()+ assert {"get_health", "get_why", "search_codebase"} <= registered_hook_tools()+++def test_an_undeclared_tool_is_still_bounded_and_says_so(setup_mcp: str) -> None:+ """The floor, for a name the registry does not know."""+ payload = {"body": "x" * 60_000, "_meta": {"contract_version": 1}}++ result = _enforce("not_a_registered_tool", payload)++ assert len(json.dumps(result, separators=(",", ":"), default=str)) <= (+ result["_meta"]["response_budget"]["limit_chars"]+ )+ assert result["truncated"] is True+ assert result["_meta"]["omitted"]["refs"]+ assert "repowise expand" in result["_meta"]["omitted"]["restore"]+++def test_oversized_symbol_read_sheds_callees_before_the_body(setup_mcp: str) -> None:+ """get_symbol's measured worst case: callee context goes before the subject."""+ payload = {+ "symbol_id": "src/hub.py::Hub",+ "file": "src/hub.py",+ "name": "Hub",+ "verified": True,+ "continuation": "src/hub.py:601-1200",+ "source": "BODY" * 4_000,+ "callee_bodies": [{"symbol_id": f"src/c.py::c{i}", "source": "C" * 4_000} for i in range(8)],+ "_meta": {"contract_version": 1},+ }++ result = _enforce("get_symbol", payload)++ assert result["symbol_id"] == "src/hub.py::Hub"+ assert result["continuation"] == "src/hub.py:601-1200"+ assert len(result.get("callee_bodies") or []) < 8+ assert result["truncated"] is True+ assert result["_meta"]["omitted"]["refs"]+++def test_an_oversized_body_is_trimmed_to_fit_not_deleted(setup_mcp: str) -> None:+ """A symbol read with no body is a wasted call, even with a recoverable ref."""+ payload = {+ "symbol_id": "src/hub.py::Hub",+ "file": "src/hub.py",+ "continuation": "src/hub.py:601-1200",+ "source": "BODY" * 9_000,+ "_meta": {"contract_version": 1},+ }++ result = _enforce("get_symbol", payload)++ limit = result["_meta"]["response_budget"]["limit_chars"]+ assert len(json.dumps(result, separators=(",", ":"), default=str)) <= limit+ # Most of the budget goes to the body rather than to a bare pointer.+ assert len(result["source"]) > limit // 2+ assert result["truncated"] is True+ assert result["_meta"]["omitted"]["refs"]+++def test_budget_hooks_run_for_the_tool_that_registered_them() -> None:+ """A hook is keyed by tool, so it must not fire for another tool's response."""+ from repowise.server.mcp_server._budget import hooks++ seen: list[str] = []++ def hook(result: dict[str, Any]) -> None:+ seen.append(result["tool"])++ hooks.register_post_enforce("tool_a", hook)+ try:+ hooks.run_post_enforce("tool_a", {"tool": "tool_a"})+ hooks.run_post_enforce("tool_b", {"tool": "tool_b"})+ finally:+ hooks._POST_ENFORCE.pop("tool_a", None)++ assert seen == ["tool_a"]+++#: Real response shapes, recorded by ``scripts/measure_mcp_response_sizes.py``+#: against an indexed repository. Regenerate with ``--skeletons`` when a tool's+#: payload changes shape.+_SHAPES_FIXTURE = (+ Path(__file__).resolve().parents[3] / "fixtures" / "mcp" / "tool_response_shapes.json"+)+++def _resolve_shed_path(shape: dict[str, Any], key: str) -> str | None:+ """Return why *key* fails to name a real block, or None when it resolves.++ A block absent from the recording is not a failure: several are conditional+ on arguments the recording did not pass. A block whose *parent* is present+ while the leaf is not is a typo, and a silent no-op in ``fit_to_budget``.+ """+ leaf, tail = (key[:-2], True) if key.endswith("[]") else (key, False)+ *parents, name = leaf.split(".")+ node: Any = shape+ for parent in parents:+ if not isinstance(node, dict) or parent not in node:+ return None+ node = node[parent]+ if not isinstance(node, dict):+ return f"{'.'.join(parents)} is not a block"+ if name not in node:+ if not parents:+ return None+ return f"{leaf} does not exist; {'.'.join(parents)} has {sorted(node)}"+ if tail and not isinstance(node[name], (list, dict)):+ return f"{leaf} is not a collection, so a tail trim cannot apply"+ return None+++def test_every_shed_path_names_a_real_block() -> None:+ """A shed path that does not resolve sheds nothing, silently.++ The size columns cannot catch this: the final guard brings the response+ under the ceiling either way, so a dead order measures as a working one.++ Bound worth knowing: this catches a leaf misspelled under a parent the+ recording contains. A top-level block the recording never exercised is+ skipped, because most tools have blocks conditional on arguments the sweep+ does not pass, and failing on those would be noise rather than signal.+ """+ from repowise.server.mcp_server._budget.contracts import _CONTRACTS++ shapes = json.loads(_SHAPES_FIXTURE.read_text(encoding="utf-8"))+ problems: list[str] = []+ for tool, contract in _CONTRACTS.items():+ shape = shapes.get(tool)+ if shape is None:+ continue+ problems += [+ f"{tool}: {key} -- {reason}"+ for key in contract.shed_order+ if (reason := _resolve_shed_path(shape, key))+ ]+ assert not problems, "\n".join(problems)+++def test_recorded_shapes_cover_the_tools_that_can_be_exercised() -> None:+ """Guard the fixture itself: a shrinking recording weakens the check above."""+ from repowise.server.mcp_server import _TOOL_MODULES++ shapes = json.loads(_SHAPES_FIXTURE.read_text(encoding="utf-8"))+ # generate_refactoring_code needs a stored plan, which the recorded index+ # had none of. Reported as not measured rather than assumed bounded.+ assert set(shapes) == set(_TOOL_MODULES) - {"generate_refactoring_code"}diff --git a/tests/unit/server/mcp/test_retrieval_precision_corpus.py b/tests/unit/server/mcp/test_retrieval_precision_corpus.pyindex e8df0f4a5..92a241f67 100644--- a/tests/unit/server/mcp/test_retrieval_precision_corpus.py+++ b/tests/unit/server/mcp/test_retrieval_precision_corpus.py@@ -34,7 +34,7 @@ def test_sealed_corpus_has_six_independent_query_shapes() -> None:assert corpus["sealed_at_commit"] == "c2f915d07c11ca3f451309054dfb610e75b8ae26"assert corpus["window_size"] == 5- assert corpus["modes"] == ["full", "degraded"]+ assert corpus["modes"] == ["full", "keyless"]assert {case["shape"] for case in cases} == EXPECTED_SHAPESassert len(cases) == len(EXPECTED_SHAPES)@@ -50,7 +50,7 @@ def test_sealed_corpus_has_six_independent_query_shapes() -> None:assert set(case["supported_generic_targets"]) <= candidate_targetsfor candidate in case["candidates"]:assert set(candidate["legs"]) == set(corpus["modes"])- assert candidate["legs"]["degraded"], "keyless candidates must retain a local leg"+ assert candidate["legs"]["keyless"], "keyless candidates must retain a local leg"def test_generic_support_labels_are_fixture_owned_and_include_positive_controls() -> None:@@ -73,17 +73,17 @@ def test_generic_support_labels_are_fixture_owned_and_include_positive_controls()-def test_full_and_degraded_arms_share_queries_windows_and_oracles() -> None:+def test_full_and_keyless_arms_share_queries_windows_and_oracles() -> None:corpus = load_retrieval_precision_corpus()- assert corpus["degraded_mode"] == {+ assert corpus["keyless_mode"] == {"embedder": "keyless","llm": "absent","retained_legs": ["path", "symbol", "fts", "history"],}for case in corpus["cases"]:assert all(candidate["legs"]["full"] for candidate in case["candidates"])- assert all(candidate["legs"]["degraded"] for candidate in case["candidates"])+ assert all(candidate["legs"]["keyless"] for candidate in case["candidates"])def _rank_case(case: dict, mode: str, window_size: int) -> list[dict]:@@ -158,7 +158,7 @@ def _case_metrics(corpus: dict, case: dict, mode: str) -> dict:}-def test_sealed_ranking_corpus_in_full_and_degraded_modes() -> None:+def test_sealed_ranking_corpus_in_full_and_keyless_modes() -> None:corpus = load_retrieval_precision_corpus()for mode in corpus["modes"]:@@ -171,5 +171,5 @@ def test_sealed_ranking_corpus_in_full_and_degraded_modes() -> None:assert metrics["protected"], (case["shape"], mode, metrics)for required in case["required_targets"]:assert required in metrics["targets"], (case["shape"], mode, metrics)- if mode == "degraded":+ if mode == "keyless":assert all("semantic" not in sources for sources in metrics["sources"])diff --git a/tests/unit/server/mcp/test_trust_contract.py b/tests/unit/server/mcp/test_trust_contract.pyindex 7daa52d52..504100d83 100644--- a/tests/unit/server/mcp/test_trust_contract.py+++ b/tests/unit/server/mcp/test_trust_contract.py@@ -38,11 +38,24 @@ def test_shared_boundary_surfaces_degraded_partial_and_truncated_states():assert result["_meta"]["state"] == {"degraded": True,+ # The umbrella bool cannot say which capability failed, so the reasons+ # behind it travel with it: the synthesis reason and the broken legs,+ # not just the names of the keys holding them.+ "degraded_reasons": {+ "degraded": "no-provider",+ "retrieval_degraded": ["vector"],+ },"partial": True,"truncated": True,}+def test_degraded_reasons_are_absent_when_nothing_degraded():+ result = _meta.finalize_trust_envelope({"_meta": {"members_truncated": 2}})++ assert result["_meta"]["state"] == {"truncated": True}++def test_persisted_analysis_metadata_omits_unknowns_and_preserves_commits():assert _meta.persisted_analysis_meta(None, {}) == {}assert _meta.persisted_analysis_meta("2026-08-24T00:00:00Z", {"api": "abc"}) == {