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
feat(mcp): give the five uncapped tools a shared response ceiling (#1876)
Raghav Chamadiyadc0e4413f143
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.mdindex 3111e8f6a..c103a02e6 100644--- a/docs/agent/MCP_TOOLS.md+++ b/docs/agent/MCP_TOOLS.md@@ -130,6 +130,8 @@ envelope lists how to get it back: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 tool+declares cheapest-loss-first, and reports `truncated: true` alongside the refs.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.diff --git a/packages/server/src/repowise/server/mcp_server/_budget/__init__.py b/packages/server/src/repowise/server/mcp_server/_budget/__init__.pyindex d0e8140da..0b6abf59d 100644--- a/packages/server/src/repowise/server/mcp_server/_budget/__init__.py+++ b/packages/server/src/repowise/server/mcp_server/_budget/__init__.py@@ -1,17 +1,20 @@"""Shared output-budget enforcement for MCP tools.Every MCP tool that trims its response to fit the transport token cap goes-through this package instead of rolling its own silent drop. Two pieces:+through this package instead of rolling its own silent drop. Three pieces:* :func:`truncate_to_budget` — the staged whole-response truncation strategy- (originally built for ``get_context``), now the reference implementation.+ built for (and shaped by) ``get_context``'s targets/docs/symbols payload.+* :func:`fit_to_budget` — the whole-response ceiling for tools whose payload is+ a bag of independent blocks: sheds them in a tool-declared order until the+ response fits.* :class:`OmissionCollector` — captures whatever a tool drops, persists it tothe durable omission store, and stamps the response with a``[repowise#<ref>]`` marker plus ``_meta.omitted`` so the content staysrecoverable via ``repowise expand <ref>`` or ``get_symbol("repowise#<ref>")``.-Tools that don't use the staged truncator (fixed per-list caps) use the-collector directly at their cap sites.+Tools with fixed per-list caps use the collector directly at their cap sites,+under whichever whole-response ceiling they enforce."""from __future__ import annotations@@ -19,12 +22,15 @@ from __future__ import annotationsfrom repowise.server.mcp_server._budget.budgeter import (CHAR_BUDGET,CHARS_PER_TOKEN,+ FIT_HEADROOM_CHARS,HOST_CAP_BUDGET_FRACTION,HOST_MCP_TOKEN_CAP_DEFAULT,TOKEN_BUDGET,effective_char_budget,estimate_response_tokens,+ fit_to_budget,host_token_cap,+ over_budget,truncate_to_budget,)from repowise.server.mcp_server._budget.collector import OmissionCollector@@ -32,12 +38,15 @@ from repowise.server.mcp_server._budget.collector import OmissionCollector__all__ = ["CHARS_PER_TOKEN","CHAR_BUDGET",+ "FIT_HEADROOM_CHARS","HOST_CAP_BUDGET_FRACTION","HOST_MCP_TOKEN_CAP_DEFAULT","TOKEN_BUDGET","OmissionCollector","effective_char_budget","estimate_response_tokens",+ "fit_to_budget","host_token_cap",+ "over_budget","truncate_to_budget",]diff --git a/packages/server/src/repowise/server/mcp_server/_budget/budgeter.py b/packages/server/src/repowise/server/mcp_server/_budget/budgeter.pyindex 41a8f34d6..165d54658 100644--- a/packages/server/src/repowise/server/mcp_server/_budget/budgeter.py+++ b/packages/server/src/repowise/server/mcp_server/_budget/budgeter.py@@ -1,12 +1,17 @@-"""Staged whole-response truncation — the shared budgeter.+"""Whole-response budget enforcement — the shared ceilings.-Ported from ``tool_context/truncation.py`` (which now re-exports from here)-so every tool shares one budget strategy instead of ad-hoc caps. The-keep/drop decisions are byte-identical to the original implementation; the-only additions are (a) an optional :class:`OmissionCollector` that makes-every drop recoverable, and (b) a skeleton-stripping stage for the-``include=["skeleton"]`` blocks that did not exist when the original was-written.+Two strategies, for two payload shapes:++* :func:`truncate_to_budget` — the staged truncator ported from+ ``tool_context/truncation.py`` (which now re-exports from here). Every stage+ walks ``result["targets"][name]["docs"|"skeleton"|"symbols"]``, so it is+ ``get_context``-shaped and has one caller by design. Keep/drop decisions are+ byte-identical to the original; the additions are an optional+ :class:`OmissionCollector` and a skeleton-stripping stage.+* :func:`fit_to_budget` — sheds whole named blocks in a tool-declared order,+ for the tools whose payload is a bag of independent blocks.++``get_health`` keeps a third strategy (trims the longest ranked list by rows).The MCP host caps the size of a tool result. An over-cap result is **spilled toa sidecar file** the agent must Read back, not rejected: it comes back worded as@@ -30,6 +35,7 @@ from __future__ import annotationsimport jsonimport loggingimport os+from collections.abc import Sequencefrom typing import Anyfrom repowise.server.mcp_server._budget.collector import OmissionCollector@@ -91,6 +97,77 @@ def estimate_response_tokens(obj: Any) -> int:return len(json.dumps(obj, separators=(",", ":"), default=str)) // CHARS_PER_TOKEN+# Reserved for what the collector appends after the last fit check: the+# omission marker and ``_meta.omitted``.+FIT_HEADROOM_CHARS = 400+++def response_chars(response: Any) -> int:+ """Serialised size of *response* in the compact JSON the MCP layer emits."""+ return len(json.dumps(response, separators=(",", ":"), default=str))+++def over_budget(response: Any, *, headroom: int = FIT_HEADROOM_CHARS) -> bool:+ """True when *response* would exceed the transport ceiling once markers land."""+ return response_chars(response) > effective_char_budget() - headroom+++def fit_to_budget(+ response: dict[str, Any],+ order: Sequence[str],+ collector: OmissionCollector,+ *,+ headroom: int = FIT_HEADROOM_CHARS,+) -> dict[str, Any]:+ """Shed whole blocks named by *order* until *response* fits the budget.++ *order* is the tool's cheapest-loss-first ranking of the blocks it can live+ without. ``"parent.child"`` sheds a nested block; ``"key[]"`` drops rows+ from the tail of a ranked list instead of the list itself, keeping the+ first. Shedding stops the moment the response fits, so an under-budget+ response — the common case — is untouched.++ Drops go to *collector* as expandable ``[repowise#<ref>]`` markers and set+ ``truncated``. Call before the caller's :meth:`OmissionCollector.attach`,+ which is what ``headroom`` reserves for.+ """+ for key in order:+ if not over_budget(response, headroom=headroom):+ break+ container, _, leaf = key.rpartition(".")+ target: Any = response+ for part in container.split(".") if container else ():+ target = target.get(part) if isinstance(target, dict) else None+ if not isinstance(target, dict):+ continue+ if leaf.endswith("[]"):+ _shed_tail(response, target, leaf[:-2], key[:-2], collector, headroom)+ elif target.get(leaf):+ collector.add(key, target.pop(leaf))+ response["truncated"] = True+ return response+++def _shed_tail(+ response: dict[str, Any],+ container: dict[str, Any],+ leaf: str,+ label: str,+ collector: OmissionCollector,+ headroom: int,+) -> None:+ """Drop ranked rows from the tail of ``container[leaf]`` until it fits."""+ rows = container.get(leaf)+ if not isinstance(rows, list):+ return+ dropped: list[Any] = []+ while len(rows) > 1 and over_budget(response, headroom=headroom):+ dropped.append(rows.pop())+ if dropped:+ collector.add(label, list(reversed(dropped)))+ response["truncated"] = True++# Heavy optional fields we can strip from a target's docs block without losing# its identity. Ordering matters: earlier entries are dropped first because they# carry the most bytes per unit of navigational value.diff --git a/packages/server/src/repowise/server/mcp_server/tool_change_risk.py b/packages/server/src/repowise/server/mcp_server/tool_change_risk.pyindex cfdf0f559..4e89c9b2c 100644--- a/packages/server/src/repowise/server/mcp_server/tool_change_risk.py+++ b/packages/server/src/repowise/server/mcp_server/tool_change_risk.py@@ -21,7 +21,7 @@ from repowise.core.analysis.change_risk import ()from repowise.core.analysis.pr_blast import rank_tests_by_reachfrom 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, fit_to_budgetfrom repowise.server.mcp_server._helpers import (_get_repo,_resolve_repo_context,@@ -38,6 +38,15 @@ _IMPACTED_TESTS_LIMIT = 10#: per-file blocks in this response stay the same size._PRIOR_FIXES_LIMIT = 10+# Cheapest loss first; the score, its drivers and fix_history's numbers are the+# answer and never shed.+_SHED_ORDER: tuple[str, ...] = (+ "exclude_patterns",+ "prior_fixes",+ "impacted_tests",+ "fix_history.files",+)+@mcp.tool()async def get_change_risk(@@ -136,6 +145,7 @@ async def get_change_risk(targets=sorted(changed) or None,extra={"source": "live_git"},)+ fit_to_budget(payload, _SHED_ORDER, collector)collector.attach(payload)return payloaddiff --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 edd0a3cdd..74c53cf03 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+from repowise.server.mcp_server._budget import OmissionCollector, fit_to_budgetfrom repowise.server.mcp_server._helpers import (_get_exclude_spec,_get_repo,@@ -157,6 +157,9 @@ 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@@ -216,6 +219,14 @@ 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."@@ -390,6 +401,7 @@ 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_overview.py b/packages/server/src/repowise/server/mcp_server/tool_overview.pyindex caf923888..aad36d124 100644--- a/packages/server/src/repowise/server/mcp_server/tool_overview.py+++ b/packages/server/src/repowise/server/mcp_server/tool_overview.py@@ -49,7 +49,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+from repowise.server.mcp_server._budget import OmissionCollector, fit_to_budgetfrom repowise.server.mcp_server._helpers import (_get_exclude_spec,_get_repo,@@ -180,6 +180,9 @@ async def _workspace_overview() -> dict:if cross_repo_topology:result["cross_repo_topology"] = cross_repo_topology+ collector = OmissionCollector("get_overview", repo_root=registry.workspace_root if registry else None)+ fit_to_budget(result, _WORKSPACE_SHED_ORDER, collector)+ collector.attach(result)return result@@ -879,6 +882,25 @@ def _build_guided_tour(result.setdefault("architecture", {})["layer_order"] = layer_order+# Cheapest loss first. Everything not listed answers a question that changes an+# agent's next action, so it is never shed.+_WORKSPACE_SHED_ORDER: tuple[str, ...] = ("cross_repo_topology", "repos[]")++_SHED_ORDER: tuple[str, ...] = (+ "tool_guide",+ "guided_tour_hint",+ "guided_tour",+ "reading_order_hint",+ "reading_order",+ "community_summary",+ "knowledge_map",+ "key_decisions",+ "outline_hint",+ "outline",+ "key_modules[]",+)++@mcp.tool()async def get_overview(repo: str | None = None, include: list[str] | None = None) -> dict:"""Architecture map for an unfamiliar repo — first call when you don't know your way around.@@ -1059,6 +1081,7 @@ async def get_overview(repo: str | None = None, include: list[str] | None = None}result["_meta"] = _build_meta(repository=repository)+ fit_to_budget(result, _SHED_ORDER, collector)collector.attach(result)return resultdiff --git a/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py b/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.pyindex 017837d38..4c3902a24 100644--- a/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py+++ b/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py@@ -14,7 +14,7 @@ from repowise.core.persistence.models import (GraphNode,)from 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, fit_to_budgetfrom repowise.server.mcp_server._episodes import enrich_episode_counts as _enrich_episodesfrom repowise.server.mcp_server._helpers import (_get_exclude_spec,@@ -30,6 +30,14 @@ from .assessment import _assess_one_target, _get_active_contributor_count, fix_afrom .directives import _build_pr_directive, _governance_directivefrom .enrichment import _enrich_cross_repo, _enrich_health, _finalize_dep_summaries+# Cheapest loss first; the target cards and the directive are never shed.+# ``guarding_tests`` leads the dossier: _trim_blast_lists leaves it uncapped.+_SHED_ORDER: tuple[str, ...] = (+ "global_hotspots",+ "pr_blast_radius.guarding_tests",+ "pr_blast_radius",+)+@mcp.tool()async def get_risk(@@ -224,5 +232,6 @@ async def get_risk(repository=repository,targets=[*targets, *(changed_files or [])] if targets or changed_files else None,)+ fit_to_budget(response, _SHED_ORDER, collector)collector.attach(response)return responsediff --git a/packages/server/src/repowise/server/mcp_server/tool_search.py b/packages/server/src/repowise/server/mcp_server/tool_search.pyindex 393db7688..6c420a159 100644--- a/packages/server/src/repowise/server/mcp_server/tool_search.py+++ b/packages/server/src/repowise/server/mcp_server/tool_search.py@@ -19,6 +19,7 @@ from repowise.core.providers.embedding import store_has_semantic_vectorsfrom 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_budgetfrom repowise.server.mcp_server._helpers import (_VECTOR_TIMEOUT_ENV,_get_exclude_spec,@@ -773,6 +774,21 @@ 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)+++# 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 _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)+ if response.get("truncated") and isinstance(response.get("_meta"), dict):+ response["_meta"]["targets"] = _result_paths(response.get("results") or [])+ collector.attach(response)return response@@ -976,7 +992,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 response+ return _fit_search_response(response, contexts[0].path if contexts else None)@mcp.tool()@@ -1114,4 +1130,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 response+ return _fit_search_response(response, ctx.path)diff --git a/packages/server/src/repowise/server/mcp_server/tool_why.py b/packages/server/src/repowise/server/mcp_server/tool_why.pyindex 4004766e5..e4580f11a 100644--- a/packages/server/src/repowise/server/mcp_server/tool_why.py+++ b/packages/server/src/repowise/server/mcp_server/tool_why.py@@ -20,7 +20,11 @@ from repowise.core.persistence.models import (from repowise.core.precedent.currency import describe_decision_currencyfrom repowise.core.providers.embedding import store_has_semantic_vectorsfrom repowise.core.registry import mcp_tool_registry as mcp-from repowise.server.mcp_server._budget import OmissionCollector, effective_char_budget+from repowise.server.mcp_server._budget import (+ OmissionCollector,+ fit_to_budget,+ over_budget,+)from repowise.server.mcp_server._code_rationale import mine_rationale as _mine_rationalefrom repowise.server.mcp_server._episodes import bank_overflow, episode_evidencefrom repowise.server.mcp_server._helpers import (@@ -401,12 +405,8 @@ def _fit_path_response(under-budget path still attaches: a response that fits can still carry acapped body whose remainder needs advertising."""- # Reserved so the marker the collector appends after the last check cannot- # itself push the response back over the host cap.- budget = effective_char_budget() - _COLLECTOR_HEADROOM_CHARS-def _over() -> bool:- return len(json.dumps(result_data, separators=(",", ":"), default=str)) > budget+ return over_budget(result_data, headroom=_COLLECTOR_HEADROOM_CHARS)if not _over():if collector is not None:@@ -416,21 +416,15 @@ def _fit_path_response(if collector is None:collector = OmissionCollector("get_why", repo_root=repo_root)- def _drop_block(key: str, container: dict) -> None:- if _over() and container.get(key):- collector.add(key, container.pop(key))- result_data["truncated"] = True-- origin_story = result_data.get("origin_story")- if isinstance(origin_story, dict):- _drop_block("linked_decisions", origin_story)+ def _shed(*order: str) -> None:+ fit_to_budget(result_data, order, collector, headroom=_COLLECTOR_HEADROOM_CHARS)- # Before the governing records, not after them: episodes are the newest+ # Episodes go before the governing records, not after: they are the newest# evidence kind here and must only ever spend slack. Dropping them later in# the sequence meant the decisions loop ran with the episode block still# inflating the response, and a governing record was evicted to make room# for an episode that then survived — measured, not theorised.- _drop_block("episodes", result_data)+ _shed("origin_story.linked_decisions", "episodes")decisions: list = result_data.get("decisions") or []while decisions and _over():@@ -439,8 +433,7 @@ def _fit_path_response(result_data["truncated"] = Trueresult_data.setdefault("dropped_decisions", []).append(dropped.get("id", ""))- for key in ("code_rationale", "git_archaeology", "origin_story"):- _drop_block(key, result_data)+ _shed("code_rationale", "git_archaeology", "origin_story")collector.attach(result_data)return result_datadiff --git a/tests/unit/server/mcp/test_budget.py b/tests/unit/server/mcp/test_budget.pyindex 6c234ff49..2b9a2b465 100644--- a/tests/unit/server/mcp/test_budget.py+++ b/tests/unit/server/mcp/test_budget.py@@ -5,6 +5,8 @@ Covers:and the degrade-to-silent-drop posture on store failure.* truncate_to_budget — dropped symbols / targets / skeleton texts arerecoverable, and keep/drop decisions are unchanged by the collector.+* fit_to_budget — the block-shedding ceiling: a no-op under budget, sheds in+ the tool's declared order over it, and every drop stays expandable.* get_symbol — omission-ref overload (``repowise#<12-hex>``), queryfiltering, and byte-identical normal symbol resolution.* Migrated tools (get_dead_code, get_risk trim helper, get_overview) — no@@ -28,7 +30,9 @@ from repowise.server.mcp_server._budget import (HOST_MCP_TOKEN_CAP_DEFAULT,OmissionCollector,effective_char_budget,+ fit_to_budget,host_token_cap,+ over_budget,truncate_to_budget,)@@ -48,6 +52,11 @@ def _store_get(repo: Path, ref: str, query: str | None = None) -> str | None:store.close()+def _joined(repo: Path, refs: list[str]) -> str:+ """Every omission doc the refs point at, concatenated."""+ return chr(10).join(_store_get(repo, r) or "" for r in refs)++def _store_record(repo: Path, ref: str) -> dict | None:store = OmissionStore(default_store_path(repo))try:@@ -225,6 +234,91 @@ def test_budgeter_decisions_unchanged_by_collector(repo_root: Path):)+# ---------------------------------------------------------------------------+# fit_to_budget — the block-shedding ceiling+# ---------------------------------------------------------------------------+++def _blocks_response(pad: int = 0) -> dict:+ return {+ "title": "repo",+ "keep_me": {"entry_points": ["main.py"]},+ "cheap": "c" * pad,+ "dear": {"rows": ["d" * pad]},+ "nested": {"heavy": "h" * pad, "light": 1},+ "ranked": [{"row": i, "body": "r" * pad} for i in range(6)],+ "_meta": {"timing_ms": 1.0},+ }+++_ORDER = ("cheap", "nested.heavy", "dear", "ranked[]")+++def _narrow_budget(monkeypatch, tokens: int) -> None:+ """Pull the host cap down so a small fixture counts as oversized."""+ monkeypatch.setenv("MAX_MCP_OUTPUT_TOKENS", str(tokens))+++def test_fit_to_budget_is_a_noop_under_budget(repo_root: Path):+ """The common case: a response that fits keeps every block, untouched."""+ response = _blocks_response(pad=50)+ before = json.dumps(response, sort_keys=True, default=str)+ collector = OmissionCollector("get_overview", repo_root=repo_root)++ out = fit_to_budget(response, _ORDER, collector)++ assert json.dumps(out, sort_keys=True, default=str) == before+ assert "truncated" not in out+ assert collector.empty+++def test_fit_to_budget_sheds_in_declared_order(repo_root: Path, monkeypatch):+ _narrow_budget(monkeypatch, 1200)+ response = _blocks_response(pad=1200)+ collector = OmissionCollector("get_overview", repo_root=repo_root)++ out = fit_to_budget(response, _ORDER, collector)+ collector.attach(out)++ assert out["truncated"] is True+ # Cheapest first, and shedding stops as soon as it fits.+ assert "cheap" not in out+ assert out["title"] == "repo"+ assert out["keep_me"] == {"entry_points": ["main.py"]}+ assert not over_budget(out)+ refs = out["_meta"]["omitted"]["refs"]+ stored = _joined(repo_root, refs)+ assert "cccc" in stored+++def test_fit_to_budget_sheds_a_nested_block(repo_root: Path, monkeypatch):+ _narrow_budget(monkeypatch, 900)+ response = _blocks_response(pad=1500)+ collector = OmissionCollector("get_overview", repo_root=repo_root)++ fit_to_budget(response, ("nested.heavy",), collector)++ assert "heavy" not in response["nested"]+ assert response["nested"]["light"] == 1+++def test_fit_to_budget_trims_a_ranked_tail_but_never_empties_it(+ repo_root: Path, monkeypatch+):+ _narrow_budget(monkeypatch, 700)+ response = {"results": [{"row": i, "body": "r" * 900} for i in range(6)]}+ collector = OmissionCollector("search_codebase", repo_root=repo_root)++ fit_to_budget(response, ("results[]",), collector)+ collector.attach(response)++ assert len(response["results"]) == 1+ assert response["results"][0]["row"] == 0 # best-ranked survives+ refs = response["_meta"]["omitted"]["refs"]+ stored = _joined(repo_root, refs)+ assert '"row": 5' in stored++def _skeleton_response(text_chars: int = 12000) -> dict:return {"targets": {@@ -369,6 +463,30 @@ async def test_get_dead_code_truncation_is_expandable(setup_mcp, repo_root: Pathassert rec["source"] == "mcp:get_dead_code"+async def test_get_overview_stays_under_a_narrowed_host_cap(+ setup_mcp, repo_root: Path, monkeypatch+):+ """The ceiling is real end to end: no block of a live tool escapes it."""+ import repowise.server.mcp_server as mcp_mod+ from repowise.server.mcp_server import get_overview++ mcp_mod._repo_path = str(repo_root)+ full = await get_overview()+ assert "truncated" not in full # normal cap: nothing sheds+ assert full["tool_guide"]++ monkeypatch.setenv("MAX_MCP_OUTPUT_TOKENS", "700")+ trimmed = await get_overview()++ assert trimmed["truncated"] is True+ assert "tool_guide" not in trimmed # first in the declared shed order+ assert trimmed["title"] == full["title"]+ assert not over_budget(trimmed)+ stored = _joined(repo_root, trimmed["_meta"]["omitted"]["refs"])+ assert "first_call" in stored++def test_risk_trim_blast_lists_collects_drops(repo_root: Path):from repowise.server.mcp_server.tool_risk import _trim_blast_lists