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(why): govern a target only by exact scope, and word the reason from the basis (#3769)

Swati Ahujaeadf7e2aa17c
diff --git a/packages/server/src/repowise/server/mcp_server/_why_relevance.py b/packages/server/src/repowise/server/mcp_server/_why_relevance.py
index f07855c66..e910b07df 100644
--- a/packages/server/src/repowise/server/mcp_server/_why_relevance.py
+++ b/packages/server/src/repowise/server/mcp_server/_why_relevance.py
@@ -303,3 +303,19 @@ def redirect_when_served(lanes: list[str], recall: str | None) -> dict[str, Any]
f"unfiltered by the question: {recall}."
)
}
+
+
+def redirect_when_governed() -> dict[str, Any]:
+ """The reason for a call that missed on its terms but names a governed file.
+
+ An accepted rule binds its files whatever the question, so the target card
+ serves it and ``answer_basis`` is ``decision``. Saying no record covers the
+ call beside it would contradict both.
+ """
+ return {
+ "reason": (
+ "No decision record carries this question's terms. The accepted "
+ "decision governing a named file binds it whatever the question; "
+ "anything else served is evidence, not a ruling."
+ )
+ }
diff --git a/packages/server/src/repowise/server/mcp_server/tool_why/basis.py b/packages/server/src/repowise/server/mcp_server/tool_why/basis.py
index f0f420339..bdaa28d02 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_why/basis.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_why/basis.py
@@ -33,6 +33,28 @@ def _is_accepted_row(row: Any) -> bool:
return isinstance(row, dict) and row.get("authority") == "accepted"
+def _decision_rows(result: dict) -> list:
+ """Every decision row served: the top-level lane and each card's rules."""
+ return [
+ *(result.get("decisions") or []),
+ *(
+ r
+ for e in (result.get("target_context") or {}).values()
+ if isinstance(e, dict)
+ for r in (e.get("governing_decisions") or [])
+ ),
+ ]
+
+
+def rests_on_decision(result: dict) -> bool:
+ """Whether *result* serves an accepted decision.
+
+ The one fact behind ``answer_basis: "decision"`` and behind any prose that
+ says no record covers the call, so the two cannot disagree.
+ """
+ return any(_is_accepted_row(r) for r in _decision_rows(result))
+
+
def _stamp_answer_basis(result: dict) -> dict:
"""Name the strongest lane the response actually rests on.
@@ -49,15 +71,11 @@ def _stamp_answer_basis(result: dict) -> dict:
entries = [
e for e in (result.get("target_context") or {}).values() if isinstance(e, dict)
]
- decision_rows = [
- *(result.get("decisions") or []),
- *(r for e in entries for r in (e.get("governing_decisions") or [])),
- ]
candidate_rows = [
*(r for e in entries for r in (e.get("candidate_decisions") or [])),
- *(r for r in decision_rows if not _is_accepted_row(r)),
+ *(r for r in _decision_rows(result) if not _is_accepted_row(r)),
]
- if any(_is_accepted_row(r) for r in decision_rows):
+ if rests_on_decision(result):
result["answer_basis"] = "decision"
elif result.get("episodes"):
result["answer_basis"] = "episode"
diff --git a/packages/server/src/repowise/server/mcp_server/tool_why/path_mode.py b/packages/server/src/repowise/server/mcp_server/tool_why/path_mode.py
index 57df7b2f8..7ce0b085a 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_why/path_mode.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_why/path_mode.py
@@ -315,16 +315,13 @@ async def _build_target_context(
def _records_governing_target(all_decisions: list, target: str) -> list:
- """Records naming *target*, or a module it sits under, best-first."""
- governing_records = []
- for d in all_decisions:
- # Same gate as ``_why_path``, which one target routes to.
- if not binds_to_paths(d.scope_basis):
- continue
- affected = json.loads(d.affected_files_json)
- affected_mods = json.loads(d.affected_modules_json)
- if target in affected or any(target.startswith(m + "/") for m in affected_mods):
- governing_records.append(d)
+ """Records naming *target*, best-first, by the same rule as ``_why_path``.
+
+ A record's modules are mostly its files' folders, so a file merely under
+ one shares a folder with the decision, not its subject. Path mode and the
+ decision graph match a module only as itself, and so does this.
+ """
+ governing_records = _records_naming_path(all_decisions, target)
governing_records.sort(key=_path_decision_sort_key)
return governing_records
diff --git a/packages/server/src/repowise/server/mcp_server/tool_why/search.py b/packages/server/src/repowise/server/mcp_server/tool_why/search.py
index 23bd9a632..3f4422e61 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_why/search.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_why/search.py
@@ -23,13 +23,14 @@ from repowise.server.mcp_server._why_relevance import (
question_terms,
recovery_note,
redirect_for,
+ redirect_when_governed,
redirect_when_served,
relevance,
term_idf,
word_set,
)
from repowise.server.mcp_server.tool_why.archaeology import question_commits
-from repowise.server.mcp_server.tool_why.basis import _has_archaeology
+from repowise.server.mcp_server.tool_why.basis import _has_archaeology, rests_on_decision
from repowise.server.mcp_server.tool_why.caps import (
_MAX_SEARCH_DECISIONS,
_SEMANTIC_WINDOW,
@@ -316,9 +317,13 @@ async def _why_no_match(
)
_cap_supporting_lanes(result, collector, label=query)
_cap_target_context(result["target_context"], collector)
- # Don't redirect away from evidence this response is already serving.
+ # Don't redirect away from evidence this response is already serving, and
+ # read the ruling from the fact ``answer_basis`` reads, so they agree.
served = _served_lanes(result)
- if served:
+ if rests_on_decision(result):
+ result.pop("try_instead", None)
+ result.update(redirect_when_governed())
+ elif served:
result.pop("try_instead", None)
recall = f"get_why(targets={json.dumps(targets)})" if targets else None
result.update(redirect_when_served(served, recall))
diff --git a/tests/unit/server/mcp/test_why.py b/tests/unit/server/mcp/test_why.py
index 95e65973f..1e2cdcd08 100644
--- a/tests/unit/server/mcp/test_why.py
+++ b/tests/unit/server/mcp/test_why.py
@@ -808,3 +808,56 @@ async def test_get_why_targets_do_not_bind_a_record_whose_files_are_gone(session
governing = result["target_context"][path]["governing_decisions"]
assert [d["id"] for d in governing] == ["goneFalse"]
+
+
+_OFF_TOPIC = "why does the connection pool retry on timeout"
+
+
+async def _accept_dec2(session) -> None:
+ from repowise.core.persistence.crud.authority import accept_decision
+ from repowise.core.persistence.models import DecisionRecord
+
+ await accept_decision(
+ session, await session.get(DecisionRecord, "dec2"), accepter="test", evidence=["pr#1"]
+ )
+ await session.flush()
+
+
+async def test_get_why_target_under_a_records_module_is_not_governed(session, setup_mcp):
+ """dec2 names src/db/models.py; its module is only that file's folder.
+
+ A sibling shares the folder, not the decision, and path mode agrees.
+ """
+ from repowise.server.mcp_server import get_why
+
+ await _accept_dec2(session)
+ sibling = "src/db/session.py"
+
+ result = await get_why(_OFF_TOPIC, targets=[sibling])
+
+ assert result["target_context"][sibling]["governing_decisions"] == []
+ assert result.get("answer_basis") != "decision"
+ path_result = await get_why(sibling)
+ assert not path_result.get("decisions")
+
+
+async def test_get_why_governed_target_reason_agrees_with_the_basis(session, setup_mcp):
+ """An off-topic question on a governed file still serves its rule.
+
+ The reason must then say so, not that no record covers the call.
+ """
+ from repowise.server.mcp_server import get_why
+
+ await _accept_dec2(session)
+ path = "src/db/models.py"
+
+ result = await get_why(_OFF_TOPIC, targets=[path])
+
+ governing = result["target_context"][path]["governing_decisions"]
+ assert [d["id"] for d in governing] == ["dec2"]
+ assert result["answer_basis"] == "decision"
+ assert "No decision record covers" not in result["reason"]
+ assert "binds it whatever the question" in result["reason"]
+ assert "try_instead" not in result