Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(mcp): restore an oversized omission ref in pages that make progress (#3899)

Raghav Chamadiyab516b33063ed
diff --git a/packages/server/src/repowise/server/mcp_server/_budget/contracts.py b/packages/server/src/repowise/server/mcp_server/_budget/contracts.py
index 0a4342589..6787ecb32 100644
--- a/packages/server/src/repowise/server/mcp_server/_budget/contracts.py
+++ b/packages/server/src/repowise/server/mcp_server/_budget/contracts.py
@@ -33,6 +33,8 @@ _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
+#: Room left for the omission marker that replaces a trimmed text tail.
+_MARKER_RESERVE_CHARS = 200
@dataclass(frozen=True)
@@ -363,12 +365,14 @@ _CONTRACTS: dict[str, ResponseBudgetContract] = {
# 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.
+ # ``content`` is an omission restore's body, protected for the same reason.
"get_symbol": ResponseBudgetContract(
"blocks",
("callee_bodies.callees[]", "candidates[]"),
expansion_argument=None,
protected=(
"source",
+ "content",
"symbol_id",
"file",
"name",
@@ -773,13 +777,20 @@ def _emergency_fit(
container[f"{key}_emitted"] = len(kept)
container[f"{key}_reduced_reason"] = "response_budget"
else:
- marker = collector.add_inline(path, value)
- suffix = f"\n{marker}" if marker else "\n[reduced to fit]"
# 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)] + suffix
+ keep = max(
+ _MIN_KEPT_TEXT_CHARS, limit - (before - len(value)) - _MARKER_RESERVE_CHARS
+ )
+ cut = value.rfind("\n", 0, keep)
+ if cut >= _MIN_KEPT_TEXT_CHARS:
+ keep = cut + 1
+ # The ref holds only the cut tail, so restoring it makes progress
+ # instead of serving the kept head again.
+ marker = collector.add_inline(path, value[keep:])
+ suffix = f"\n{marker}" if marker else "\n[reduced to fit]"
+ container[key] = value[:keep].rstrip("\n") + suffix
result["truncated"] = True
if response_chars(result) >= before:
return
diff --git a/tests/unit/server/mcp/test_response_budget_contracts.py b/tests/unit/server/mcp/test_response_budget_contracts.py
index bbf5d1b66..7f167fb93 100644
--- a/tests/unit/server/mcp/test_response_budget_contracts.py
+++ b/tests/unit/server/mcp/test_response_budget_contracts.py
@@ -288,7 +288,7 @@ def test_oversized_protected_answer_is_reduced_and_recoverable(
(tmp_path / ".repowise").mkdir()
monkeypatch.setattr(mcp_mod, "_repo_path", str(tmp_path))
payload = _payload("get_answer", 0)
- payload["answer"] = "PROTECTED_ANSWER_" + "z" * 50_000
+ answer = payload["answer"] = "PROTECTED_ANSWER_" + "z" * 50_000
result = _enforce("get_answer", payload)
accounting = result["_meta"]["response_budget"]
@@ -299,9 +299,44 @@ def test_oversized_protected_answer_is_reduced_and_recoverable(
refs = result["_meta"]["omitted"]["refs"]
store = OmissionStore(default_store_path(tmp_path))
try:
- assert any("PROTECTED_ANSWER_" in (store.get(ref) or "") for ref in refs)
+ stored = [store.get(ref) or "" for ref in refs]
finally:
store.close()
+ # A ref holds the cut tail, never the head the response already serves.
+ assert any(tail and answer.endswith(tail) for tail in stored)
+ assert not any(tail.startswith("PROTECTED_ANSWER_") for tail in stored)
+
+
+def test_an_oversized_omission_restore_serves_its_head_and_stores_only_the_tail(
+ setup_mcp: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Restoring a ref bigger than the budget must make progress, not loop."""
+ import repowise.server.mcp_server as mcp_mod
+
+ (tmp_path / ".repowise").mkdir()
+ monkeypatch.setattr(mcp_mod, "_repo_path", str(tmp_path))
+ lines = [f"line {i:05d} " + "x" * 40 for i in range(1500)]
+ payload = {
+ "symbol_id": "repowise#0123456789ab",
+ "ref": "repowise#0123456789ab",
+ "kind": "omission",
+ "source": "mcp:get_symbol",
+ "content": "\n".join(lines),
+ "_meta": {"contract_version": 1},
+ }
+
+ result = _enforce("get_symbol", payload)
+
+ head, marker = result["content"].rsplit("\n", 1)
+ shown = head.count("\n") + 1
+ assert head.startswith("line 00000") and shown > 200
+ assert f"{len(lines) - shown} lines omitted" in marker
+ store = OmissionStore(default_store_path(tmp_path))
+ try:
+ tails = [store.get(ref) or "" for ref in result["_meta"]["omitted"]["refs"]]
+ finally:
+ store.close()
+ assert "\n".join(lines[shown:]) in tails
@pytest.mark.asyncio