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): trim get_why lanes before dropping them, and name what the answer rests on (#1963)

Raghav Chamadiya67ef51842964
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.md
index 1ecb08981..cf32e590b 100644
--- a/docs/agent/MCP_TOOLS.md
+++ b/docs/agent/MCP_TOOLS.md
@@ -624,6 +624,8 @@ Architectural decision intelligence. Falls back to git archaeology when no decis
**Returns:** Matching decision records with title, rationale, alternatives considered, affected files, staleness score. Health mode returns stale decisions, conflicts, and ungoverned hotspots.
+`answer_basis` names the strongest lane the response rests on: `decision`, `episode`, `rationale`, `archaeology`, or `documentation`. Only `decision` is a ruling; the rest are evidence to weigh. Absent when no lane was served, and on the health dashboard.
+
**When to use:** Before architectural changes, understand existing intent and constraints. After changes, record new decisions.
**Example calls:**
diff --git a/packages/cli/src/repowise/cli/commands/why_cmd.py b/packages/cli/src/repowise/cli/commands/why_cmd.py
index a4bb65c9a..7598220ff 100644
--- a/packages/cli/src/repowise/cli/commands/why_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/why_cmd.py
@@ -158,6 +158,9 @@ def project(payload: dict) -> dict:
out["counts"] = payload["counts"]
if payload.get("alignment"):
out["alignment"] = payload["alignment"]
+ # Which lane the answer rests on. Only "decision" is a ruling.
+ if payload.get("answer_basis"):
+ out["answer_basis"] = payload["answer_basis"]
decisions = payload.get("decisions")
if decisions is not None:
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 58d8b3a78..e82d799c9 100644
--- a/packages/server/src/repowise/server/mcp_server/_budget/contracts.py
+++ b/packages/server/src/repowise/server/mcp_server/_budget/contracts.py
@@ -85,34 +85,45 @@ _CONTRACTS: dict[str, ResponseBudgetContract] = {
expansion_argument="include",
protected=("answer", "confidence", "citations", "next_action_hint"),
),
- # Dropping docs and episodes whole, and first, served 0 of 50 pages and 0 of
- # 12 episodes on a file whose decision lane was 40 near-duplicates. They are
- # ranked tails now, so a squeeze costs rows rather than the lane, and the
- # decision lane pays before the lanes that answer.
+ # 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
+ # exhaustion before anything is dropped.
#
- # Search mode has no top-level origin_story or git_archaeology (its origin
- # lives under the protected target_context), so for that shape the fix is
- # the tail entries alone; the block entries only bite in path mode.
+ # origin_story and git_archaeology are path mode's; related_documentation is
+ # search mode's; code_rationale is set by both.
"get_why": ResponseBudgetContract(
"blocks",
(
# Titles the decisions lane already carries.
"origin_story.linked_decisions",
+ # Every tail trimmed before any lane is dropped, cheapest loss
+ # first. Episodes last here; the path fitter sheds them first for a
+ # different reason, documented on _fit_path_response.
"decisions[]",
- "code_rationale",
+ "git_archaeology.file_commits[]",
+ "git_archaeology.cross_references[]",
+ "git_archaeology.git_log[]",
+ "related_documentation[]",
+ "code_rationale[]",
+ "episodes[]",
+ # Whole-block drops, only once trimming has run out.
"git_archaeology.file_commits",
"git_archaeology.cross_references",
"git_archaeology.git_log",
- # Ranked tails, moved here from the front of this tuple. Episodes
- # last: they answer "what constrains changing this" when no decision
- # governs the file.
- "related_documentation[]",
- "episodes[]",
"related_documentation",
+ "code_rationale",
"origin_story",
),
expansion_argument=None,
- protected=("mode", "query", "path", "paths", "target_context", "alignment"),
+ protected=(
+ "mode",
+ "query",
+ "path",
+ "paths",
+ "target_context",
+ "alignment",
+ "answer_basis",
+ ),
),
"get_overview": ResponseBudgetContract(
"blocks",
@@ -382,6 +393,12 @@ 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")
diff --git a/packages/server/src/repowise/server/mcp_server/tool_why.py b/packages/server/src/repowise/server/mcp_server/tool_why.py
index dbbcc04bc..051f1c07f 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_why.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_why.py
@@ -60,6 +60,50 @@ from repowise.server.mcp_server._why_relevance import (
)
+def _has_archaeology(archaeology: Any) -> bool:
+ """Whether an archaeology block found anything.
+
+ ``_git_archaeology_fallback`` always returns a dict, carrying ``triggered``
+ and a summary that may say it found nothing, so the block's presence proves
+ only that it ran.
+ """
+ return isinstance(archaeology, dict) and any(
+ archaeology.get(lane)
+ for lane in ("file_commits", "cross_references", "git_log")
+ )
+
+
+def _stamp_answer_basis(result: dict) -> dict:
+ """Name the strongest lane the response actually rests on.
+
+ This tool serves commit messages and mined comments beside decision
+ records. Only a decision is a ruling; the rest are evidence a reader has to
+ weigh. Per-row ``provenance`` answers that one row at a time, which is no
+ help in deciding how much of the whole response to trust.
+
+ Absent when nothing was served, so a refusal cannot read as an answer.
+ Re-derived after the budget pass has shed, so the claim cannot outlive the
+ lane it names; clears first to stay correct on that second call.
+ """
+ result.pop("answer_basis", None)
+ entries = [
+ e for e in (result.get("target_context") or {}).values() if isinstance(e, dict)
+ ]
+ if result.get("decisions") or any(e.get("governing_decisions") for e in entries):
+ result["answer_basis"] = "decision"
+ elif result.get("episodes"):
+ result["answer_basis"] = "episode"
+ elif result.get("code_rationale"):
+ result["answer_basis"] = "rationale"
+ elif _has_archaeology(result.get("git_archaeology")) or any(
+ _has_archaeology(e.get("git_archaeology")) for e in entries
+ ):
+ result["answer_basis"] = "archaeology"
+ elif result.get("related_documentation"):
+ result["answer_basis"] = "documentation"
+ return result
+
+
@mcp.tool(
surface_order=70,
recipes=(
@@ -85,7 +129,10 @@ async def get_why(
(decision health dashboard). Falls back to git archaeology when no
decisions exist for a path — never empty. Evidence-bearing rows carry an
explicit ``provenance`` and self-contained ``evidence_refs``; matching ids
- mean shared evidence, not independent corroboration.
+ mean shared evidence, not independent corroboration. ``answer_basis`` names
+ the strongest lane the response rests on (decision, episode, rationale,
+ archaeology, documentation); only a decision is a ruling, the rest are
+ evidence to weigh.
Args:
query: question, file/module path, or omit for the dashboard.
@@ -108,13 +155,13 @@ async def get_why(
if id:
if repo == "all":
return _unsupported_repo_all("get_why (reference lookup)")
- return await _why_reference(id, repo, reference=reference)
+ return _stamp_answer_basis(await _why_reference(id, repo, reference=reference))
# --- repo="all": search decisions across ALL repos ---
if repo == "all":
if not query:
return _unsupported_repo_all("get_why (health dashboard)")
- return await _why_workspace_search(query)
+ return _stamp_answer_basis(await _why_workspace_search(query))
# --- Mode 1: No query → the targets, or the health dashboard ---
# Targets first: a caller who named files and asked nothing has asked about
@@ -123,15 +170,17 @@ async def get_why(
# what was asked about.
if not query:
if targets:
- return await _why_targets(list(targets), repo)
+ return _stamp_answer_basis(await _why_targets(list(targets), repo))
+ # The dashboard is an orientation call, not an answer, so it carries no
+ # basis to name.
return await _why_health_dashboard(repo)
# --- Mode 2: Path → decisions, origin story, alignment ---
if _is_path(query):
- return await _why_path(query, repo)
+ return _stamp_answer_basis(await _why_path(query, repo))
# --- Mode 3: Natural language → target-aware search ---
- return await _why_search(query, targets, repo)
+ return _stamp_answer_basis(await _why_search(query, targets, repo))
async def _why_reference(
@@ -721,9 +770,10 @@ def _fit_path_response(
2. Drop governing records from the tail, all the way to none if it comes
to that. They are sorted best-first, so the tail is review-queue noise,
and an empty list plus a marker beats a rejected response.
- 3. Drop the fallback blocks the ungoverned branch adds
- (``code_rationale``, then ``git_archaeology``), then ``origin_story``
- whole. What survives — mode, path, alignment, ``_meta`` — is bounded.
+ 3. Trim the fallback blocks the ungoverned branch adds (``code_rationale``,
+ then ``git_archaeology``) to a tail, dropping them whole only if that is
+ not enough, then ``origin_story``. What survives — mode, path,
+ alignment, ``_meta`` — is bounded.
Every drop goes to the omission store, so the agent gets a
``[repowise#<ref>]`` marker it can expand rather than a silently shortened
@@ -763,7 +813,10 @@ def _fit_path_response(
# 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.
- _shed("origin_story.linked_decisions", "episodes")
+ # ``episodes[]`` floors at one row, so the whole-block entry behind it is
+ # what still empties the lane before the decisions loop below. Trimming
+ # first is why mild pressure costs rows: this served 0 of 20.
+ _shed("origin_story.linked_decisions", "episodes[]", "episodes")
decisions: list = result_data.get("decisions") or []
while decisions and _over():
@@ -783,7 +836,13 @@ def _fit_path_response(
result_data["decisions_truncated"] = True
result_data["decisions_omitted"] = result_data["decisions_total"] - len(decisions)
+ # The ungoverned branch's whole answer, and it served 0 of 58 mined
+ # rationale comments on a file with no governing record at all.
_shed(
+ "code_rationale[]",
+ "git_archaeology.file_commits[]",
+ "git_archaeology.cross_references[]",
+ "git_archaeology.git_log[]",
"code_rationale",
"git_archaeology.file_commits",
"git_archaeology.cross_references",