Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(mcp): share get_context's budget across targets instead of dropping one (#2727)
Raghav Chamadiya262eea5b2bb0
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.mdindex 5e219bdbf..0f2a263c5 100644--- a/docs/agent/MCP_TOOLS.md+++ b/docs/agent/MCP_TOOLS.md@@ -342,6 +342,16 @@ half does, the reply is that file's card with `resolved_to` naming the file anda `note` saying which symbol was not found. The file's symbol list is where thecorrect id is, so this is a partial answer rather than a dead end.+**Several targets under one budget:** each target gets an equal share of the+response budget, and a small target's unused share passes to the others. A+target over its share degrades in place: symbols first, then its optional+blocks, largest first (named per target in `dropped_blocks`), then symbols down+to one. A miss's `suggestions` and a symbol's ambiguity `candidates` are never+shed. When even the identity cards cannot all fit, whole targets are dropped+first so the rest keep their detail; the response then leads with+`dropped_targets` and, when it fits, a `recovery` call: the same call narrowed+to the dropped targets.+**When to use:** Before reading or modifying code. Pass all relevant targets in one call to minimize round-trips. In workspace mode, enriched with cross-repo co-change and contract data.**Example calls:**diff --git a/packages/cli/src/repowise/cli/commands/context_cmd.py b/packages/cli/src/repowise/cli/commands/context_cmd.pyindex 58d458a68..50c8a5874 100644--- a/packages/cli/src/repowise/cli/commands/context_cmd.py+++ b/packages/cli/src/repowise/cli/commands/context_cmd.py@@ -134,9 +134,10 @@ def project(payload: dict, targets: tuple[str, ...]) -> dict:A target the tool could not resolve gets a card carrying only ``error``,and that key survives the trim. Top-level ``truncated`` /- ``dropped_targets`` / ``dropped_symbols`` are kept whenever they say- something — a silently dropped target is exactly the thing a caller must- not have to diff two payloads to notice.+ ``dropped_targets`` / ``dropped_symbols`` / ``dropped_blocks`` and the+ ``recovery`` call are kept whenever they say something: a silently+ dropped target is exactly the thing a caller must not have to diff two+ payloads to notice."""cards = payload.get("targets") or {}out: dict = {@@ -144,7 +145,7 @@ def project(payload: dict, targets: tuple[str, ...]) -> dict:}if payload.get("truncated"):out["truncated"] = True- for key in ("dropped_targets", "dropped_symbols", "omission_marker"):+ for key in ("dropped_targets", "recovery", "dropped_symbols", "dropped_blocks", "omission_marker"):# omission_marker is the only handle on what truncation banked, so a# `truncated: true` without it says content went missing and offers no# way to get it back.diff --git a/packages/server/src/repowise/server/mcp_server/_budget/budgeter.py b/packages/server/src/repowise/server/mcp_server/_budget/budgeter.pyindex d9c1cafc4..22f464dfe 100644--- a/packages/server/src/repowise/server/mcp_server/_budget/budgeter.py+++ b/packages/server/src/repowise/server/mcp_server/_budget/budgeter.py@@ -4,10 +4,9 @@ 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.+ walks ``result["targets"][name]``, so it is ``get_context``-shaped and has+ one caller by design. Each target gets a fair share of the budget and+ degrades inside it; a whole target is dropped only as a last resort.* :func:`fit_to_budget` — sheds whole named blocks in a tool-declared order,for the tools whose payload is a bag of independent blocks.@@ -398,6 +397,155 @@ def query_terms_for(target: str) -> set[str]:return {t for t in (tail, target.lower()) if t}+#: Keys a degraded target always keeps: what it is, whether it resolved, and+#: the did-you-mean list or ambiguity candidates that answer a miss.+_TARGET_IDENTITY_KEYS = frozenset(+ {+ "target",+ "type",+ "path",+ "error",+ "suggestions",+ "docs",+ "parent_page",+ "freshness",+ "fix_history",+ }+)+_DOCS_IDENTITY_KEYS = frozenset({"title", "summary", "symbols", "candidates"})+++def _identity_card(tgt: dict[str, Any]) -> dict[str, Any]:+ """What :func:`_fit_target` can reduce *tgt* to at most: identity and one symbol."""+ card = {+ key: value+ for key, value in tgt.items()+ if key in _TARGET_IDENTITY_KEYS or not isinstance(value, (list, dict))+ }+ docs = tgt.get("docs")+ if isinstance(docs, dict):+ card["docs"] = {+ key: value[:1] if key == "symbols" and isinstance(value, list) else value+ for key, value in docs.items()+ if key in _DOCS_IDENTITY_KEYS or not isinstance(value, (list, dict))+ }+ return card+++def _symbols_trimmed(tgt: dict[str, Any]) -> dict[str, Any]:+ """*tgt* with its symbols cut to their entitled floor, for sizing only."""+ docs = tgt.get("docs")+ symbols = docs.get("symbols") if isinstance(docs, dict) else None+ if not isinstance(symbols, list):+ return tgt+ floor = entitled_floor(max(len(symbols), int(docs.get("symbols_total") or 0)))+ return {**tgt, "docs": {**docs, "symbols": symbols[:floor]}}+++def _fit_target(+ result: dict[str, Any],+ name: str,+ tgt: dict[str, Any],+ share: int,+ collector: OmissionCollector | None,+ record_counts: bool,+) -> None:+ """Degrade one target toward *share* chars.++ Symbols trim to their entitled floor, then optional blocks go largest+ first, then symbols trim to one. A target that still exceeds its share+ after that is only its identity card, and stage 3 decides.+ """+ docs = tgt.get("docs") if isinstance(tgt.get("docs"), dict) else None+ symbols = docs.get("symbols") if docs is not None else None+ if isinstance(symbols, list) and symbols:+ query_terms = query_terms_for(name)+ ordered = sorted(symbols, key=lambda s: symbol_priority(s, query_terms), reverse=True)+ # The floor is the whole list's, so a later pass cannot erode it.+ floor = entitled_floor(max(len(ordered), int(docs.get("symbols_total") or 0)))+ _trim_symbols(result, name, tgt, ordered, share, floor, collector, record_counts)++ def cost() -> int:+ return len(json.dumps(tgt, separators=(",", ":"), default=str))++ # (container, key, label): the target's own blocks and those nested in docs.+ sources = ((tgt, _TARGET_IDENTITY_KEYS, ""), (docs or {}, _DOCS_IDENTITY_KEYS, "docs."))+ blocks = [+ (container, key, prefix + key)+ for container, keep, prefix in sources+ for key, value in container.items()+ if key not in keep and isinstance(value, (list, dict))+ ]+ blocks.sort(key=lambda block: len(json.dumps(block[0][block[1]], default=str)), reverse=True)+ for container, key, label in blocks:+ if cost() <= share:+ return+ value = container.pop(key)+ if collector is not None and value:+ collector.add(f"{name} :: {label}", value)+ result.setdefault("dropped_blocks", {}).setdefault(name, []).append(label)+ result["truncated"] = True+ if record_counts and isinstance(value, list):+ # Keeps a capped list's *_total / *_emitted beside it truthful.+ _record_reduction(result, container, f"targets.{name}.{label}", key, value, emitted=0)++ if cost() > share and isinstance(symbols, list) and symbols:+ _trim_symbols(result, name, tgt, list(docs["symbols"]), share, 1, collector, record_counts)+ head = docs["symbols"][0]+ docstring = head.get("docstring")+ if cost() > share and isinstance(docstring, str) and len(docstring) > 200:+ # One symbol alone over the share: keep it, cut its docstring.+ if collector is not None:+ collector.add(f"{name} :: {head.get('name')} docstring", docstring)+ docs["symbols"][0] = {**head, "docstring": docstring[:200]}+ result["truncated"] = True+++def _trim_symbols(+ result: dict[str, Any],+ name: str,+ tgt: dict[str, Any],+ ordered: list[dict[str, Any]],+ share: int,+ floor: int,+ collector: OmissionCollector | None,+ record_counts: bool,+) -> None:+ """Keep the highest-priority symbols that fit *share*, never fewer than *floor*.++ Compact JSON is additive, so the target's size with a symbol list ``S`` is+ its size with no symbols plus each kept symbol's cost plus the commas.+ """+ docs = tgt["docs"]+ costs = [len(json.dumps(s, separators=(",", ":"), default=str)) for s in ordered]+ docs["symbols"] = []+ base = len(json.dumps(tgt, separators=(",", ":"), default=str))+ kept: list[dict[str, Any]] = []+ used = 0+ for sym, sym_cost in zip(ordered, costs, strict=True):+ if len(kept) < floor or base + used + sym_cost + len(kept) <= share:+ kept.append(sym)+ used += sym_cost+ docs["symbols"] = kept+ if len(kept) == len(ordered):+ return+ kept_ids = {id(sym) for sym in kept}+ dropped = [sym for sym in ordered if id(sym) not in kept_ids]+ result["dropped_symbols"].setdefault(name, []).extend(+ sym.get("name") or "<anonymous>" for sym in dropped+ )+ result["truncated"] = True+ if record_counts:+ docs["symbols_total"] = max(len(ordered), int(docs.get("symbols_total") or 0))+ docs["symbols_emitted"] = len(kept)+ docs["symbols_reduced_reason"] = "response_budget"+ if collector is not None:+ collector.add(+ f"{name} :: symbols dropped from response",+ "\n".join(json.dumps(s, separators=(",", ":"), default=str) for s in dropped),+ )++def truncate_to_budget(result: dict[str, Any],char_budget: int | None = None,@@ -420,23 +568,25 @@ def truncate_to_budget(1.5. **Strip skeleton texts**, largest first. A skeleton block can be ~2ktokens per target; its text is replaced in-place by an omissionmarker (when a collector is present) so it stays one call away.- 2. **Shrink symbol lists within each target**, keeping the highest-priority- symbols per ``symbol_priority``. This preserves the navigational index- (names, signatures, line numbers) while dropping bulk docstrings.- 3. **Drop whole targets** from the tail of the list. Per spec we prefer- keeping fewer full-fidelity targets over many stubs, so once symbols- can't shrink further we evict entire targets rather than gutting them.-- Adds ``truncated: bool``, ``dropped_targets: list[str]``, and- ``dropped_symbols: dict[target, list[name]]`` top-level fields — additive- only, existing callers are unaffected.+ 2. **Fair share per target.** Each target gets an equal share of the+ room the envelope leaves, with a small target's slack passed on. A+ target over its share degrades in place (see :func:`_fit_target`):+ symbols to their entitled floor, optional blocks largest first, then+ symbols to one. Every target the caller named stays visible.+ When the identity cards alone cannot fit (many targets on a narrow+ budget), whole targets are evicted first, so the survivors keep+ their detail.+ 3. **Drop whole targets**, largest first, as the backstop.++ Adds ``truncated: bool``, ``dropped_targets: list[str]``,+ ``dropped_symbols: dict[target, list[name]]`` and+ ``dropped_blocks: dict[target, list[key]]`` top-level fields.With a *collector*, every dropped piece of content is also captured andpersisted, and the response gains ``omission_marker`` + ``_meta.omitted``(see :class:`OmissionCollector`). ``record_counts`` adds the shared``*_total`` / emitted / reason fields for final-delivery accounting. With- neither option, behaviour is byte-identical to the original silent-drop- implementation.+ neither option, drops are silent.Edge cases:* Empty ``targets`` → returns unchanged with ``truncated=False``.@@ -463,6 +613,7 @@ def truncate_to_budget("final_chars": len(json.dumps(result, separators=(",", ":"), default=str)),"dropped_targets": result["dropped_targets"],"dropped_symbol_counts": {k: len(v) for k, v in result["dropped_symbols"].items()},+ "dropped_blocks": result.get("dropped_blocks", {}),},)else:@@ -471,7 +622,7 @@ def truncate_to_budget(# "nothing happened" on every untruncated response — and every response# is untruncated in the common case. Absent reads the same as empty to# a ``.get()``, which is how both projections already test them.- for key in ("truncated", "dropped_targets", "dropped_symbols"):+ for key in ("truncated", "dropped_targets", "dropped_symbols", "dropped_blocks"):if not result.get(key):result.pop(key, None)return result@@ -542,83 +693,79 @@ def _run_stages(if _size() <= char_budget:return result- # Stage 2: prioritise symbols within each target. We iterate from the- # largest target down so the biggest offenders shrink first.- def _target_cost(item: tuple[str, Any]) -> int:- return len(json.dumps(item[1], default=str))+ def _cost(value: Any) -> int:+ return len(json.dumps(value, separators=(",", ":"), default=str))- for tgt_name, tgt in sorted(targets.items(), key=_target_cost, reverse=True):- docs = tgt.get("docs") if isinstance(tgt, dict) else None- if not isinstance(docs, dict):- continue- symbols = docs.get("symbols")- if not isinstance(symbols, list) or not symbols:- continue- query_terms = query_terms_for(tgt_name)- ordered = sorted(symbols, key=lambda s: symbol_priority(s, query_terms), reverse=True)+ # Largest first; error cards last, since they are small and say "not found".+ def _evictable_order() -> list[str]:+ items = list(targets.items())+ items.sort(+ key=lambda kv: (+ 0 if isinstance(kv[1], dict) and "error" in kv[1] else 1,+ len(json.dumps(kv[1], default=str)),+ ),+ reverse=True,+ )+ return [k for k, _ in items]- # Per-symbol greedy fit. The cost of the whole response with a symbol- # list ``S`` is exactly:- # base + sum(cost(s) for s in S) + max(0, len(S) - 1)- # where ``base`` is the response size with this target's ``symbols``- # emptied and ``cost(s)`` is the symbol's compact-JSON length. Both are- # context-independent under the compact separators we serialise with,- # so we precompute each symbol's cost ONCE and track a running sum- # instead of re-serialising the entire response per candidate symbol- # (the old O(targets x symbols^2) behaviour). The keep/drop decision is- # byte-for-byte identical to the previous ``_size()``-per-symbol loop.- costs = [len(json.dumps(s, separators=(",", ":"), default=str)) for s in ordered]- docs["symbols"] = []- base = _size()- kept: list[dict[str, Any]] = []- dropped: list[str] = []- dropped_syms: list[dict[str, Any]] = []- sum_kept = 0- for sym, cost in zip(ordered, costs, strict=True):- # Tentative size if we add this symbol to the current kept set:- # the +len(kept) term is the comma separators for kept+1 entries.- tentative = base + sum_kept + cost + len(kept)- if tentative <= char_budget:- kept.append(sym)- sum_kept += cost- else:- dropped.append(sym.get("name") or "<anonymous>")- dropped_syms.append(sym)- symbol_content_reduced = False- if not kept and ordered:- # Edge case: a single symbol is larger than the budget. Keep one- # (truncating its docstring) rather than returning zero symbols —- # the caller at least learns the target resolved.- head = dict(ordered[0])- if isinstance(head.get("docstring"), str):- symbol_content_reduced = len(head["docstring"]) > 200- head["docstring"] = head["docstring"][:200]- kept = [head]- dropped = [s.get("name") or "<anonymous>" for s in ordered[1:]]- # The kept head lost its docstring tail too — capture the full- # original alongside the genuinely dropped tail.- dropped_syms = list(ordered)- docs["symbols"] = kept- if dropped or symbol_content_reduced:- if record_counts:- docs["symbols_total"] = max(- len(ordered), int(docs.get("symbols_total") or 0)- )- docs["symbols_emitted"] = len(kept)- docs["symbols_reduced_reason"] = "response_budget"- if dropped:- result["dropped_symbols"][tgt_name] = dropped- result["truncated"] = True- if collector is not None and dropped_syms:- collector.add(- f"{tgt_name} :: symbols dropped from response",- "\n".join(- json.dumps(s, separators=(",", ":"), default=str) for s in dropped_syms- ),- )+ def _evict(name: str) -> None:+ evicted = targets.pop(name, None)+ if collector is not None and evicted is not None:+ collector.add(f"dropped target {name}", evicted)+ result["dropped_targets"].append(name)+ result["truncated"] = True+ if record_counts:+ result["targets_total"] = max(+ targets_total, int(result.get("targets_total") or 0)+ )+ result["targets_emitted"] = len(targets)+ result["targets_reduced_reason"] = "response_budget"++ # Stage 2a: when even the identity cards cannot all fit, some targets must+ # go anyway. Evict until the rest fit with only their symbols trimmed, so+ # the survivors keep their blocks instead of every target being gutted.+ def _size_with(card: Any) -> int:+ envelope = _size() - sum(_cost(t) for t in targets.values())+ return envelope + sum(+ _cost(card(t)) if isinstance(t, dict) else _cost(t) for t in targets.values()+ )++ if _size_with(_identity_card) > char_budget:+ for name in _evictable_order():+ if len(targets) <= 1 or _size_with(_symbols_trimmed) <= char_budget:+ break+ _evict(name)+ if _size() <= char_budget:+ return result++ # Stage 2b: every target gets a fair share of what the envelope leaves.+ # Water-filling, smallest first: a target under its share keeps everything+ # and its slack passes to the rest; one over it degrades in place. Each+ # pass sees the dropped_* bookkeeping the previous one added to the+ # envelope; stage 3 stays the backstop if that still does not settle.+ for _ in range(3):+ costs = {name: _cost(tgt) for name, tgt in targets.items()}+ room = char_budget - (_size() - sum(costs.values()))+ by_cost = sorted(targets, key=lambda name: costs[name])+ for index, tgt_name in enumerate(by_cost):+ share = room // (len(by_cost) - index)+ tgt = targets[tgt_name]+ if costs[tgt_name] > share and isinstance(tgt, dict):+ _fit_target(result, tgt_name, tgt, share, collector, record_counts)+ room -= _cost(tgt)if _size() <= char_budget:return result+ # Stage 3: drop whole targets, largest first, until we fit.+ for name in _evictable_order():+ if len(targets) <= 1:+ break+ _evict(name)+ if _size() <= char_budget:+ break++ return result+# Stage 3: drop whole targets, largest first, until we fit. Prefer to keep# error-only targets (they're tiny and signal "not found" to the caller).def _evictable_order() -> list[str]:diff --git a/packages/server/src/repowise/server/mcp_server/_budget/contracts.py b/packages/server/src/repowise/server/mcp_server/_budget/contracts.pyindex da482367a..4ddfd9ac1 100644--- a/packages/server/src/repowise/server/mcp_server/_budget/contracts.py+++ b/packages/server/src/repowise/server/mcp_server/_budget/contracts.py@@ -15,6 +15,7 @@ from pathlib import Pathfrom typing import Any, Literalfrom repowise.server.mcp_server._budget.budgeter import (+ FIT_HEADROOM_CHARS,effective_char_budget,fit_to_budget,response_chars,@@ -754,6 +755,43 @@ def _emergency_fit(return+def _lead_with_dropped_targets(+ tool: str,+ result: dict[str, Any],+ signature: inspect.Signature,+ args: tuple[Any, ...],+ kwargs: dict[str, Any],+ limit: int,+) -> None:+ """Put any target the budget dropped first, with the call that fetches it.++ The recovery is the same call narrowed to the dropped targets. It repeats+ their names, so it rides along only while the response stays under *limit*.+ """+ dropped = result.get("dropped_targets")+ if not dropped:+ return+ try:+ bound = dict(signature.bind_partial(*args, **kwargs).arguments)+ except TypeError:+ bound = dict(kwargs)+ params = signature.parameters+ arguments = {+ name: value+ for name, value in bound.items()+ if value is not None and (name not in params or value != params[name].default)+ }+ arguments["targets"] = list(dropped)+ lead: dict[str, Any] = {"dropped_targets": dropped}+ recovery = {"tool": tool, "arguments": arguments}+ if response_chars(result) + response_chars({"recovery": recovery}) <= limit:+ lead["recovery"] = recovery+ rest = {key: value for key, value in result.items() if key not in lead}+ result.clear()+ result.update(lead)+ result.update(rest)++def enforce_response_budget(tool: str,result: Any,@@ -797,6 +835,9 @@ def enforce_response_budget(collector=collector,record_counts=True,)+ _lead_with_dropped_targets(+ tool, result, signature, args, kwargs, limit - FIT_HEADROOM_CHARS+ )else:fit_to_budget(result,diff --git a/tests/unit/cli/test_tool_adapter_commands.py b/tests/unit/cli/test_tool_adapter_commands.pyindex 71b0a4664..b6a0dd475 100644--- a/tests/unit/cli/test_tool_adapter_commands.py+++ b/tests/unit/cli/test_tool_adapter_commands.py@@ -428,6 +428,20 @@ def test_context_projection_reports_a_target_the_tool_never_mentioned():assert out["not_found"] == ["typo.py"]+def test_context_projection_keeps_per_target_reductions_and_recovery():+ """A block dropped from one target must be as visible as a dropped target."""+ recovery = {"tool": "get_context", "arguments": {"targets": ["b.py"]}}+ payload = {+ **CONTEXT_PAYLOAD,+ "truncated": True,+ "dropped_blocks": {"a.py": ["callers"]},+ "recovery": recovery,+ }+ out = project_context(payload, ("a.py", "b.py"))+ assert out["dropped_blocks"] == {"a.py": ["callers"]}+ assert out["recovery"] == recovery++def test_symbol_projection_keeps_the_body_and_the_continuation():"""``symbol``'s payload *is* its answer, so only the envelope is dropped."""out = project_symbol(SYMBOL_PAYLOAD)diff --git a/tests/unit/server/mcp/test_context.py b/tests/unit/server/mcp/test_context.pyindex 083a1e3ab..b87e17069 100644--- a/tests/unit/server/mcp/test_context.py+++ b/tests/unit/server/mcp/test_context.py@@ -866,3 +866,150 @@ async def test_get_context_meta_envelope(setup_mcp):# hint was dead/always None and has been removed; no empty or spurious hint fieldassert "hint" not in meta+++def _card(name: str, *, symbols: int, callers: int, pad: int = 120) -> dict:+ return {+ "target": name,+ "type": "file",+ "docs": {+ "title": name,+ "summary": "s" * 80,+ "symbols": [+ {"name": f"f{j}", "kind": "function", "signature": "x" * pad, "line": j}+ for j in range(symbols)+ ],+ },+ "callers": [{"file": f"caller_{j}.py", "note": "c" * pad} for j in range(callers)],+ }+++def test_two_targets_share_the_budget_instead_of_one_being_dropped():+ from repowise.server.mcp_server.tool_context import _truncate_to_budget++ result = {+ "targets": {+ "a.py": _card("a.py", symbols=40, callers=40),+ "b.py": _card("b.py", symbols=40, callers=40),+ },+ "_meta": {},+ }+ out = _truncate_to_budget(result, char_budget=9000)++ assert len(json.dumps(out, separators=(",", ":"), default=str)) <= 9000+ assert set(out["targets"]) == {"a.py", "b.py"}+ assert not out.get("dropped_targets")+ for name, tgt in out["targets"].items():+ assert tgt["docs"]["title"] == name+ assert tgt["docs"]["symbols"]+ assert "callers" in out["dropped_blocks"][name]+++def test_a_small_target_keeps_everything_while_a_large_one_degrades():+ from repowise.server.mcp_server.tool_context import _truncate_to_budget++ small = _card("small.py", symbols=2, callers=2)+ result = {+ "targets": {+ "small.py": json.loads(json.dumps(small)),+ "large.py": _card("large.py", symbols=80, callers=80),+ },+ "_meta": {},+ }+ out = _truncate_to_budget(result, char_budget=9000)++ assert out["targets"]["small.py"] == small+ assert "small.py" not in out.get("dropped_blocks", {})+ assert "large.py" in out["dropped_symbols"]+++def test_a_dropped_target_leads_the_response_with_its_recovery_call():+ import inspect++ from repowise.server.mcp_server._budget import enforce_response_budget++ def get_context(targets, include=None, compact=True, repo=None):+ pass++ # Identity cards alone overflow: every summary is long and cannot shrink.+ names = [f"src/m{i}.py" for i in range(60)]+ cards = {name: _card(name, symbols=1, callers=0, pad=10) for name in names}+ for card in cards.values():+ card["docs"]["summary"] = "s" * 900+ payload = {"targets": cards, "_meta": {}}+ out = enforce_response_budget(+ "get_context",+ payload,+ signature=inspect.signature(get_context),+ args=(),+ kwargs={"targets": names, "include": ["callers"]},+ )++ dropped = out["dropped_targets"]+ assert dropped and not set(dropped) & set(out["targets"])+ assert list(out)[:2] == ["dropped_targets", "recovery"]+ assert out["recovery"] == {+ "tool": "get_context",+ "arguments": {"targets": dropped, "include": ["callers"]},+ }+++def _crowd(n: int) -> dict:+ """*n* ordinary cards plus a miss with suggestions and an ambiguous symbol."""+ targets = {f"src/m{i}.py": _card(f"src/m{i}.py", symbols=6, callers=4, pad=40) for i in range(n)}+ targets["src/missing.py"] = {+ "target": "src/missing.py",+ "error": "Target not found: 'src/missing.py'",+ "suggestions": ["src/m1.py", "src/m2.py"],+ }+ targets["src/amb.py::run"] = {+ "target": "src/amb.py::run",+ "type": "symbol",+ "docs": {+ "title": "run",+ "candidates": [{"symbol_id": "src/amb.py::A::run"}, {"symbol_id": "src/amb.py::B::run"}],+ },+ }+ return {"targets": targets, "_meta": {}}+++def test_suggestions_and_candidates_survive_budget_pressure():+ from repowise.server.mcp_server.tool_context import _truncate_to_budget++ for n, budget in ((30, 6000), (60, 12000), (80, 12000)):+ out = _truncate_to_budget(_crowd(n), char_budget=budget)+ missing = out["targets"].get("src/missing.py")+ assert missing is not None and missing["suggestions"] == ["src/m1.py", "src/m2.py"]+ amb = out["targets"].get("src/amb.py::run")+ if amb is not None:+ assert len(amb["docs"]["candidates"]) == 2+ for labels in out.get("dropped_blocks", {}).values():+ assert "suggestions" not in labels and "docs.candidates" not in labels+++def test_a_capped_list_dropped_whole_reports_zero_emitted():+ from repowise.server.mcp_server._budget import truncate_to_budget++ card = _card("a.py", symbols=2, callers=20, pad=200)+ card.update(callers_total=50, callers_emitted=20)+ other = _card("b.py", symbols=2, callers=0)+ out = truncate_to_budget(+ {"targets": {"a.py": card, "b.py": other}, "_meta": {}},+ char_budget=2500,+ record_counts=True,+ )+ kept = out["targets"]["a.py"]+ assert "callers" not in kept+ assert kept["callers_emitted"] == 0+ assert kept["callers_total"] == 50+++def test_survivors_keep_their_detail_when_identity_cards_overflow():+ from repowise.server.mcp_server.tool_context import _truncate_to_budget++ out = _truncate_to_budget(_crowd(30), char_budget=6000)++ assert out["dropped_targets"]+ # Eviction came first, so the fair share had room: no survivor lost a block.+ assert not out.get("dropped_blocks")+ assert len(json.dumps(out, separators=(",", ":"), default=str)) <= 6000diff --git a/tests/unit/server/test_truncate_budget_equivalence.py b/tests/unit/server/test_truncate_budget_equivalence.pydeleted file mode 100644index 8222eec67..000000000--- a/tests/unit/server/test_truncate_budget_equivalence.py+++ /dev/null@@ -1,167 +0,0 @@-"""Characterisation test for the _truncate_to_budget O(n^2) -> O(n) optimisation.--The split of ``tool_context.py`` replaced the per-symbol full-response-re-serialisation in stage 2 of ``_truncate_to_budget`` with a precomputed-per-symbol cost + running sum. This test pins that the optimised implementation-produces a **byte-identical** result to the original implementation (embedded-here verbatim as ``_reference_truncate``) across a range of over-budget fixtures.-"""--from __future__ import annotations--import copy-import json--import pytest--from repowise.server.mcp_server.tool_context.truncation import (- _HEAVY_DOC_FIELDS,- _query_terms_for,- _symbol_priority,- _truncate_to_budget,-)---def _reference_truncate(result: dict, char_budget: int) -> dict:- """Verbatim copy of the original (pre-optimisation) _truncate_to_budget.-- Stage 2 re-serialises the whole response once per candidate symbol — the- O(targets x symbols^2) behaviour the optimisation removes. Kept here purely- as the oracle the optimised implementation must match exactly.- """- result.setdefault("truncated", False)- result.setdefault("dropped_targets", [])- result.setdefault("dropped_symbols", {})-- targets = result.get("targets") or {}- if not targets:- return result-- def _size() -> int:- return len(json.dumps(result, separators=(",", ":"), default=str))-- if _size() <= char_budget:- return result-- for _name, tgt in targets.items():- docs = tgt.get("docs") if isinstance(tgt, dict) else None- if not isinstance(docs, dict):- continue- for field in _HEAVY_DOC_FIELDS:- if field in docs:- docs.pop(field, None)- result["truncated"] = True- if _size() <= char_budget:- return result-- def _target_cost(item):- return len(json.dumps(item[1], default=str))-- for tgt_name, tgt in sorted(targets.items(), key=_target_cost, reverse=True):- docs = tgt.get("docs") if isinstance(tgt, dict) else None- if not isinstance(docs, dict):- continue- symbols = docs.get("symbols")- if not isinstance(symbols, list) or not symbols:- continue- query_terms = _query_terms_for(tgt_name)- ordered = sorted(symbols, key=lambda s: _symbol_priority(s, query_terms), reverse=True)- kept: list[dict] = []- dropped: list[str] = []- for sym in ordered:- docs["symbols"] = [*kept, sym]- if _size() <= char_budget:- kept.append(sym)- else:- dropped.append(sym.get("name") or "<anonymous>")- if not kept and ordered:- head = dict(ordered[0])- if isinstance(head.get("docstring"), str):- head["docstring"] = head["docstring"][:200]- kept = [head]- dropped = [s.get("name") or "<anonymous>" for s in ordered[1:]]- docs["symbols"] = kept- if dropped:- result["dropped_symbols"][tgt_name] = dropped- result["truncated"] = True- if _size() <= char_budget:- return result-- def _evictable_order():- items = list(targets.items())- items.sort(- key=lambda kv: (- 0 if isinstance(kv[1], dict) and "error" in kv[1] else 1,- len(json.dumps(kv[1], default=str)),- ),- reverse=True,- )- return [k for k, _ in items]-- for name in _evictable_order():- if len(targets) <= 1:- break- targets.pop(name, None)- result["dropped_targets"].append(name)- result["truncated"] = True- if _size() <= char_budget:- break-- return result---def _make_response(n_targets: int, n_symbols: int, body_chars: int, docstring_chars: int) -> dict:- """Build a synthetic get_context response large enough to exceed a budget."""- targets: dict[str, dict] = {}- for ti in range(n_targets):- path = f"src/pkg{ti}/module_{ti}.py"- symbols = [- {- "name": f"sym_{ti}_{si}",- "kind": ["class", "function", "method", "helper"][si % 4],- "signature": f"def sym_{ti}_{si}(arg0, arg1, arg2) -> None",- "start_line": si * 5 + 1,- "end_line": si * 5 + 4,- "docstring": ("d" * docstring_chars),- }- for si in range(n_symbols)- ]- targets[path] = {- "target": path,- "type": "file",- "docs": {- "title": f"Module {ti}",- "summary": "s" * 80,- "content_md": "m" * body_chars,- "symbols": symbols,- },- "hotspot": ti % 2 == 0,- }- return {"targets": targets, "_meta": {"timing_ms": 1.0}}--- ("n_targets", "n_symbols", "body_chars", "docstring_chars", "budget"),- [- (4, 30, 4000, 120, 8000),- (6, 60, 5000, 200, 8000),- (1, 200, 0, 300, 8000), # single dense target, busts on symbols alone- (3, 10, 0, 50, 2000), # tiny budget forces target eviction- (10, 5, 1500, 40, 6000),- (2, 1, 0, 50000, 4000), # single symbol larger than budget- ],-)-def test_optimised_matches_reference(n_targets, n_symbols, body_chars, docstring_chars, budget):- fixture = _make_response(n_targets, n_symbols, body_chars, docstring_chars)-- optimised = _truncate_to_budget(copy.deepcopy(fixture), char_budget=budget)- reference = _reference_truncate(copy.deepcopy(fixture), char_budget=budget)-- # Byte-identical serialisation is the strongest possible equality check.- assert json.dumps(optimised, sort_keys=True, default=str) == json.dumps(- reference, sort_keys=True, default=str- )- # And the structural bookkeeping fields match exactly.- assert optimised["truncated"] == reference["truncated"]- assert optimised["dropped_targets"] == reference["dropped_targets"]- assert optimised["dropped_symbols"] == reference["dropped_symbols"]