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(answer): trim keyless medium answers on large repos (#3186)

Raghav Chamadiya7a184948c76d
diff --git a/packages/core/src/repowise/core/index_scope.py b/packages/core/src/repowise/core/index_scope.py
index 282ccc2ff..696eec9b4 100644
--- a/packages/core/src/repowise/core/index_scope.py
+++ b/packages/core/src/repowise/core/index_scope.py
@@ -10,6 +10,7 @@ from __future__ import annotations
import hashlib
import json
+import re
from collections.abc import Mapping
from copy import deepcopy
from pathlib import Path
@@ -225,6 +226,17 @@ def resolve_index_scope(
COMPACT_INDEX_SCOPE_PROJECTION = "compact"
CANONICAL_INDEX_SCOPE_PROJECTION = "full"
+#: Degraded-analysis entries the compact scope names; the count stays exact and
+#: the full list rides on the canonical scope.
+_DEGRADED_ANALYSES_SHOWN = 3
+
+_ANALYSIS_ID_RE = re.compile(r"[a-z][a-z0-9_]*")
+
+
+def _free_text_last(entry: str) -> bool:
+ """Sort key putting bare analysis ids (``health``) ahead of free-text run warnings."""
+ return _ANALYSIS_ID_RE.fullmatch(entry) is None
+
#: Set to ``full`` to serve the canonical scope everywhere, as builds before
#: the compact projection did. The compatibility window for a reader that
#: parses the whole object and cannot yet ask for it by name.
@@ -332,7 +344,8 @@ def compact_index_scope(
The one exception is ``degraded_analyses``, carried only when non-empty:
which analysis is missing changes what an answer means, and "health failed"
- and "the graph failed" are not the same warning.
+ and "the graph failed" are not the same warning. A long list is sampled,
+ with its exact count.
"""
if not isinstance(scope, Mapping):
return None
@@ -348,7 +361,15 @@ def compact_index_scope(
}
unavailable = _section(scope, "analysis").get("unavailable")
if unavailable:
- compact["degraded_analyses"] = list(unavailable)
+ entries = list(unavailable)
+ if len(entries) > _DEGRADED_ANALYSES_SHOWN:
+ entries.sort(key=_free_text_last)
+ shown = entries[:_DEGRADED_ANALYSES_SHOWN]
+ compact["degraded_analyses"] = shown
+ if len(unavailable) > len(shown):
+ compact["degraded_analyses_total"] = len(unavailable)
+ compact["degraded_analyses_emitted"] = len(shown)
+ compact["degraded_analyses_reduced_reason"] = "compact_projection"
return compact
diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/projection.py b/packages/server/src/repowise/server/mcp_server/tool_answer/projection.py
index 2621a8877..1945435a7 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_answer/projection.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/projection.py
@@ -14,6 +14,8 @@ from repowise.server.mcp_server.tool_answer.config import (
_CANDIDATE_FILES_MAX,
_LARGE_FILE_BYTES,
)
+from repowise.server.mcp_server.tool_answer.symbols import attach_truncation_contract
+from repowise.server.mcp_server.tool_answer.withheld import _parse_continuation
_COLLECTIONS = (
"citations",
@@ -494,11 +496,106 @@ def _serve_ranked_list(payload: dict[str, Any]) -> None:
)
+# Keyless replies serve source in place of prose. Past this many chars across
+# symbol_bodies, a body keeps its leading lines and a continuation to Read.
+_KEYLESS_BODY_CHARS = 2_000
+_KEYLESS_BODY_REASON = "keyless_body_budget"
+_BODY_NOTE_TAIL = "answer from that rather than re-reading the file."
+_CUT_BODY_NOTE_TAIL = "answer from that, and Read a body's continuation where it was cut."
+
+
+def _cut_body(entry: dict[str, Any], chars: int, root: Path | None) -> int:
+ """Cut one body to whole lines within *chars* (at least its first line).
+
+ Re-derives the truncation contract over everything now unserved and records
+ the line counts beside it. Returns the chars still served.
+ """
+ # Not splitlines(): a form feed or U+2028 inside a line would shift the range.
+ lines = entry["source"].split("\n")
+ kept, used = 0, 0
+ for line in lines:
+ cost = len(line) + (1 if kept else 0)
+ if kept and used + cost > chars:
+ break
+ kept, used = kept + 1, used + cost
+ start, end = entry["lines"]
+ span = _parse_continuation(entry.get("continuation"))
+ indexed_end = span[2] if span else end
+ new_end = start + kept - 1
+ entry["source"] = "\n".join(lines[:kept])
+ entry["lines"] = [start, new_end]
+ for key in ("truncated", "continuation"):
+ entry.pop(key, None)
+ prior_withheld = entry.pop("withheld_symbols", None)
+ attach_truncation_contract(entry, indexed_end=indexed_end, end_served=new_end, repo_root=root)
+ # Without a readable root the prior list is still true: it covers a suffix of the new range.
+ if prior_withheld and "withheld_symbols" not in entry:
+ entry["withheld_symbols"] = prior_withheld
+ # Not the *_total/*_emitted stem: completeness sums those as rows.
+ entry["source_lines"] = len(lines)
+ entry["source_lines_served"] = kept
+ entry["source_lines_cut_reason"] = _KEYLESS_BODY_REASON
+ return used
+
+
+def _point_guidance_at_cuts(payload: dict[str, Any], cuts: list[tuple[dict, str, str]]) -> None:
+ """Keep the note and hint true for bodies this projection cut.
+
+ ``cuts`` holds ``(body, served-through phrase, continuation)`` from before the cut.
+ """
+ note = payload.get("note")
+ if isinstance(note, str):
+ payload["note"] = note.replace(_BODY_NOTE_TAIL, _CUT_BODY_NOTE_TAIL)
+ hint = payload.get("next_action_hint")
+ if not isinstance(hint, str):
+ return
+ for row, served, continuation in cuts:
+ hint = hint.replace(served, f"{row['name']} was served through line {row['lines'][1]};")
+ if continuation and row.get("continuation"):
+ hint = hint.replace(f"'{continuation}'", f"'{row['continuation']}'")
+ payload["next_action_hint"] = hint
+
+
+def _budget_keyless_bodies(payload: dict[str, Any], root: Path | None) -> bool:
+ """Bound a keyless reply's symbol_bodies to :data:`_KEYLESS_BODY_CHARS`.
+
+ The top-ranked file's body goes first and keeps the most; the rest shrink
+ to their signature line. Returns whether any body was cut.
+ """
+ if payload.get("degraded") != "no-llm-provider":
+ return False
+ bodies = payload.get("symbol_bodies")
+ if not isinstance(bodies, list) or not all(
+ isinstance(row, dict) and isinstance(row.get("source"), str)
+ and isinstance(row.get("lines"), list) and len(row["lines"]) == 2
+ for row in bodies
+ ):
+ return False
+ if sum(len(row["source"]) for row in bodies) <= _KEYLESS_BODY_CHARS:
+ return False
+ guess = _first_guess(payload)
+ citations = payload.get("citations") or []
+ top = _nav_path(guess) if guess else (_nav_path(citations[0]) if citations else None)
+ bodies.sort(key=lambda row: _nav_path(row) != top)
+ budget = _KEYLESS_BODY_CHARS
+ cuts: list[tuple[dict, str, str]] = []
+ for row in bodies:
+ if len(row["source"]) <= budget:
+ budget -= len(row["source"])
+ continue
+ served = f"{row.get('name')} was served through line {row['lines'][1]};"
+ continuation = row.get("continuation") or ""
+ budget = max(0, budget - _cut_body(row, budget, root))
+ cuts.append((row, served, continuation))
+ _point_guidance_at_cuts(payload, cuts)
+ return True
+
+
def _record_reductions(
payload: dict[str, Any], totals: dict[str, int], *, scope: str | None, repo: str | None,
- expanded: bool, ranked: bool = False
+ expanded: bool, ranked: bool = False, bodies_cut: bool = False
) -> None:
- reduced = False
+ reduced = bodies_cut
reason = "deduplicated" if expanded else "confidence_projection_and_deduplication"
# Ranked shape only: rows summed across every reduced collection.
shown = hidden = 0
@@ -543,15 +640,18 @@ def _record_reductions(
def project_answer_payload(
raw: dict[str, Any], *, question: str, scope: str | None = None,
- repo: str | None = None, include: list[str] | None = None
+ repo: str | None = None, include: list[str] | None = None,
+ repo_root: Path | None = None,
) -> dict[str, Any]:
"""Return the cache-independent, confidence-specific external response."""
- return _project(raw, question=question, scope=scope, repo=repo, include=include)[0]
+ return _project(
+ raw, question=question, scope=scope, repo=repo, include=include, repo_root=repo_root
+ )[0]
def _project(
raw: dict[str, Any], *, question: str, scope: str | None,
- repo: str | None, include: list[str] | None
+ repo: str | None, include: list[str] | None, repo_root: Path | None = None
) -> tuple[dict[str, Any], bool, bool]:
"""The projection, whether it slimmed ``best_guesses``, and whether it is the ranked list."""
payload = copy.deepcopy(raw)
@@ -567,6 +667,7 @@ def _project(
_default_shape(payload, question)
if _shape_confidence(payload) == "low":
slimmed = _slim_best_guesses(payload, facts if isinstance(facts, dict) else {})
+ bodies_cut = not expanded and _budget_keyless_bodies(payload, repo_root)
_shape_candidate_files(payload, expanded=expanded)
_rewrite_degraded_answer(payload)
ranked = not expanded and _ranked_list_only(payload)
@@ -576,7 +677,8 @@ def _project(
if not payload.get(key):
payload.pop(key, None)
_record_reductions(
- payload, totals, scope=scope, repo=repo, expanded=expanded, ranked=ranked
+ payload, totals, scope=scope, repo=repo, expanded=expanded, ranked=ranked,
+ bodies_cut=bodies_cut,
)
unknown = sorted(set(include or []) - {"evidence"})
if unknown:
@@ -719,20 +821,24 @@ def _add_file_sizes(payload: dict[str, Any], root: Path | None, *, ranked: bool
payload[key] = f"{hint.rstrip()} {cue}" if isinstance(hint, str) else cue
-async def _refresh_file_sizes(
- payload: dict[str, Any], repo: str | None, *, ranked: bool = False
-) -> None:
- """Size the slimmed guesses. Best-effort: a sync stat and bounded read of <= 3 files."""
+async def _resolve_root(repo: str | None) -> Path | None:
+ """The checkout root for serve-time reads, or None. Best-effort."""
if repo == "all":
- return
+ return None
try:
from repowise.server.mcp_server._helpers import _resolve_repo_context
from repowise.server.mcp_server.tool_answer.evidence import _repo_root
- root = _repo_root(await _resolve_repo_context(repo))
+ return _repo_root(await _resolve_repo_context(repo))
except Exception:
- return
- _add_file_sizes(payload, root, ranked=ranked)
+ return None
+
+
+async def _refresh_file_sizes(
+ payload: dict[str, Any], repo: str | None, *, ranked: bool = False
+) -> None:
+ """Size the slimmed guesses. Best-effort: a sync stat and bounded read of <= 3 files."""
+ _add_file_sizes(payload, await _resolve_root(repo), ranked=ranked)
def _whole_bodies(payload: dict[str, Any]) -> int:
@@ -778,8 +884,14 @@ def projected_answer(fn: Callable[..., Any]) -> Callable[..., Any]:
include: list[str] | None = None,
) -> dict[str, Any]:
raw = await fn(question=question, scope=scope, repo=repo, include=include)
+ # Only a keyless reply with bodies reads source at projection time.
+ root = (
+ await _resolve_root(repo)
+ if raw.get("degraded") == "no-llm-provider" and raw.get("symbol_bodies")
+ else None
+ )
payload, slimmed, ranked = _project(
- raw, question=question, scope=scope, repo=repo, include=include
+ raw, question=question, scope=scope, repo=repo, include=include, repo_root=root
)
await _refresh_freshness(payload, repo)
if slimmed:
diff --git a/tests/unit/server/mcp/test_answer_keyless_body_budget.py b/tests/unit/server/mcp/test_answer_keyless_body_budget.py
new file mode 100644
index 000000000..8ed9d7233
--- /dev/null
+++ b/tests/unit/server/mcp/test_answer_keyless_body_budget.py
@@ -0,0 +1,178 @@
+"""A keyless get_answer bounds its symbol_bodies source; keyed and small replies keep theirs."""
+
+from __future__ import annotations
+
+import copy
+import json
+from pathlib import Path
+
+import pytest
+
+from repowise.server.mcp_server.tool_answer import projection
+from repowise.server.mcp_server.tool_answer.projection import project_answer_payload
+
+_BUDGET = projection._KEYLESS_BODY_CHARS
+
+# (path, name, head line, filler line pattern, a definition inside the body)
+_SHAPES = [
+ ("pkg/codec.py", "Codec", "class Codec:", " TABLE_{i} = 0x{i:08x} # table row", " def decode(self, data):"),
+ ("src/router.ts", "Router", "export class Router {", " private r{i}: number = {i}; // route slot", " resolve(path: string) {"),
+ ("Lib/Huffman.cs", "Huffman", "internal static class Huffman {", " 0b1111_{i:04}, // code", " public static int Decode(byte[] src) {"),
+]
+
+
+def _write_body(root: Path, path: str, head: str, filler: str, inner: str) -> tuple[str, int]:
+ """A 120-line body (head, filler, an inner definition at line 100) inside a 200-line file."""
+ lines = [head]
+ for i in range(1, 199):
+ lines.append(inner if i == 99 else filler.format(i=i))
+ lines.append("}")
+ target = root / path
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text("\n".join(lines) + "\n", encoding="utf-8")
+ return "\n".join(lines[:120]), len(lines)
+
+
+def _raw(root: Path, *, degraded: str | None = "no-llm-provider", top: int = 1) -> dict:
+ bodies = []
+ # The top file's body comes second, so ordering by rank has work to do.
+ others = [shape for i, shape in enumerate(_SHAPES) if i != top]
+ for path, name, head, filler, inner in [others[0], _SHAPES[top], *others[1:]]:
+ source, end = _write_body(root, path, head, filler, inner)
+ bodies.append(
+ {
+ "path": path,
+ "name": name,
+ "lines": [1, 120],
+ "source": source,
+ "verified": True,
+ "truncated": True,
+ "continuation": f"{path}:121-{end}",
+ }
+ )
+ raw = {
+ "answer": "evidence below",
+ "citations": [row["path"] for row in bodies],
+ "confidence": "medium",
+ "retrieval_quality": "high",
+ "best_guesses": [{"file": _SHAPES[top][0], "why_relevant": "named"}],
+ "symbol_bodies": bodies,
+ "_meta": {},
+ }
+ if degraded:
+ raw["degraded"] = degraded
+ return raw
+
+
+def test_many_large_bodies_are_bounded_with_the_top_file_first(tmp_path: Path) -> None:
+ out = project_answer_payload(
+ _raw(tmp_path, top=2), question="which file decodes", repo_root=tmp_path
+ )
+ bodies = out["symbol_bodies"]
+
+ assert bodies[0]["path"] == "Lib/Huffman.cs"
+ assert sum(len(row["source"]) for row in bodies) <= _BUDGET + 200
+ assert len(bodies[0]["source"].splitlines()) > 1
+ for row in bodies:
+ start, end = row["lines"]
+ assert end - start + 1 == len(row["source"].splitlines())
+ assert row["truncated"] is True
+ assert row["continuation"] == f"{row['path']}:{end + 1}-200"
+ assert row["source_lines"] == 120
+ assert row["source_lines_served"] == end - start + 1
+ assert row["source_lines_cut_reason"] == "keyless_body_budget"
+ assert not any(key.endswith(("_total", "_emitted")) for key in row)
+ # The rest shrink to their signature line once the budget is spent.
+ assert [len(row["source"].splitlines()) for row in bodies[1:]] == [1]
+ assert out["_meta"]["projection"]["recovery"]["arguments"] == {"include": ["evidence"]}
+
+
[email protected]("index", range(len(_SHAPES)))
+def test_a_definition_in_the_cut_range_is_named(tmp_path: Path, index: int) -> None:
+ out = project_answer_payload(
+ _raw(tmp_path, top=index), question="which file decodes", repo_root=tmp_path
+ )
+ top = out["symbol_bodies"][0]
+ inner = _SHAPES[index][4]
+
+ assert top["path"] == _SHAPES[index][0]
+ assert inner not in top["source"]
+ assert any(row["line"] == 100 for row in top.get("withheld_symbols") or [])
+
+
+def test_without_a_root_the_cut_still_points_at_the_rest(tmp_path: Path) -> None:
+ raw = _raw(tmp_path)
+ raw["symbol_bodies"][1]["withheld_symbols"] = [{"name": "tail", "line": 150}]
+
+ top = project_answer_payload(raw, question="which file")["symbol_bodies"][0]
+
+ assert top["path"] == _SHAPES[1][0]
+ assert top["continuation"] == f"src/router.ts:{top['lines'][1] + 1}-200"
+ assert top["withheld_symbols"] == [{"name": "tail", "line": 150}]
+
+
+def test_a_small_keyless_payload_is_byte_identical(tmp_path: Path, monkeypatch) -> None:
+ raw = _raw(tmp_path)
+ for row in raw["symbol_bodies"]:
+ row["source"] = "\n".join(row["source"].splitlines()[:3])
+ row["lines"] = [1, 3]
+
+ served = project_answer_payload(copy.deepcopy(raw), question="q", repo_root=tmp_path)
+ monkeypatch.setattr(projection, "_budget_keyless_bodies", lambda payload, root: False)
+ unbudgeted = project_answer_payload(copy.deepcopy(raw), question="q", repo_root=tmp_path)
+
+ assert json.dumps(served, sort_keys=True) == json.dumps(unbudgeted, sort_keys=True)
+
+
+ ("degraded", "include"),
+ [(None, None), ("synthesis-failed", None), ("no-llm-provider", ["evidence"])],
+)
+def test_keyed_and_expanded_bodies_are_untouched(
+ tmp_path: Path, monkeypatch, degraded: str | None, include: list[str] | None
+) -> None:
+ raw = _raw(tmp_path, degraded=degraded)
+
+ served = project_answer_payload(
+ copy.deepcopy(raw), question="q", include=include, repo_root=tmp_path
+ )
+ monkeypatch.setattr(projection, "_budget_keyless_bodies", lambda payload, root: False)
+ unbudgeted = project_answer_payload(
+ copy.deepcopy(raw), question="q", include=include, repo_root=tmp_path
+ )
+
+ assert json.dumps(served, sort_keys=True) == json.dumps(unbudgeted, sort_keys=True)
+ assert all("source_lines" not in row for row in served.get("symbol_bodies") or [])
+
+
+def test_a_form_feed_inside_a_body_does_not_shift_its_lines(tmp_path: Path) -> None:
+ raw = _raw(tmp_path)
+ top = raw["symbol_bodies"][1]
+ top["source"] = "\n".join(f"x{i}\fy = {i} # padding padding padding" for i in range(120))
+
+ cut = project_answer_payload(raw, question="q", repo_root=tmp_path)["symbol_bodies"][0]
+
+ assert cut["path"] == top["path"]
+ served = cut["source"].split("\n")
+ assert cut["lines"] == [1, len(served)]
+ assert served[-1].startswith(f"x{len(served) - 1}\f")
+ assert cut["continuation"].endswith(f":{len(served) + 1}-200")
+
+
+def test_the_note_and_hint_point_at_the_new_continuation(tmp_path: Path) -> None:
+ raw = _raw(tmp_path)
+ raw["note"] = (
+ "Synthesis is unavailable. symbol_bodies carries the live body of the symbol(s) "
+ "you named, so answer from that rather than re-reading the file."
+ )
+ raw["next_action_hint"] = (
+ "Router was served through line 120; call get_symbol id='src/router.ts:121-200' "
+ "for the rest of it."
+ )
+
+ out = project_answer_payload(raw, question="q", repo_root=tmp_path)
+ top = out["symbol_bodies"][0]
+
+ assert "continuation" in out["note"] and "rather than re-reading" not in out["note"]
+ assert f"served through line {top['lines'][1]};" in out["next_action_hint"]
+ assert f"id='{top['continuation']}'" in out["next_action_hint"]
diff --git a/tests/unit/server/mcp/test_index_scope_projection.py b/tests/unit/server/mcp/test_index_scope_projection.py
index d85db8415..5efb99c8e 100644
--- a/tests/unit/server/mcp/test_index_scope_projection.py
+++ b/tests/unit/server/mcp/test_index_scope_projection.py
@@ -263,6 +263,32 @@ def test_a_degraded_index_names_what_degraded() -> None:
assert compact["status"] == "degraded"
assert compact["degraded_analyses"] == ["health"]
+ assert "degraded_analyses_total" not in compact
+
+
+def test_a_long_degraded_list_is_sampled_with_its_count() -> None:
+ """The canonical scope keeps every entry; the compact one names a few and counts all."""
+ names = [f"skipped file {i}" for i in range(17)]
+ scope = resolve_index_scope({**_FULL_STATE, "degraded": names})
+
+ compact = compact_index_scope(scope)
+
+ assert compact["degraded_analyses"] == sorted(names)[:3]
+ assert compact["degraded_analyses_total"] == 17
+ assert compact["degraded_analyses_emitted"] == 3
+ assert compact["degraded_analyses_reduced_reason"] == "compact_projection"
+ assert len(scope["analysis"]["unavailable"]) == 17
+
+
+def test_a_real_analysis_id_survives_a_flood_of_run_warnings() -> None:
+ """Warnings with a leading space sort first alphabetically; the id still shows."""
+ warnings = [f" Not indexed: big/file_{i}.cs (3,000 KB, over the limit)" for i in range(16)]
+ scope = resolve_index_scope({**_FULL_STATE, "degraded": [*warnings, "dead_code"]})
+
+ compact = compact_index_scope(scope)
+
+ assert compact["degraded_analyses"][0] == "dead_code"
+ assert compact["degraded_analyses_total"] == 17
def test_a_sound_index_carries_no_degraded_names() -> None: