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.

feat(why): anchor a question on the indexed file it names (#4203)

Raghav Chamadiya682a00be64bd
diff --git a/packages/server/src/repowise/server/mcp_server/_query_shape.py b/packages/server/src/repowise/server/mcp_server/_query_shape.py
index cef008817..e91aba234 100644
--- a/packages/server/src/repowise/server/mcp_server/_query_shape.py
+++ b/packages/server/src/repowise/server/mcp_server/_query_shape.py
@@ -105,7 +105,7 @@ def _is_path(query: str) -> bool:
return ext in _code_exts()
-_TOKEN_EDGE_CHARS = "`'\"()[]{},;"
+_TOKEN_EDGE_CHARS = "`'\"()[]{},;?!"
_LINE_SUFFIX_RE = re.compile(r":\d+(?:-\d+)?$")
diff --git a/packages/server/src/repowise/server/mcp_server/tool_why/loading.py b/packages/server/src/repowise/server/mcp_server/tool_why/loading.py
index e7c0f5ac0..be5322736 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_why/loading.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_why/loading.py
@@ -4,17 +4,21 @@ from __future__ import annotations
from typing import Any
-from sqlalchemy import select
+from sqlalchemy import func, or_, select
from repowise.core.persistence.crud.authority import accepted_decision_ids
from repowise.core.persistence.database import get_session
-from repowise.core.persistence.models import DecisionEvidence, GitMetadata
+from repowise.core.persistence.models import DecisionEvidence, GitMetadata, GraphNode
from repowise.server.mcp_server._helpers import (
+ LIKE_ESCAPE,
_get_exclude_spec,
_get_repo,
_resolve_repo_context,
decision_is_excluded,
+ escape_like,
+ is_excluded,
)
+from repowise.server.mcp_server._query_shape import path_tokens
from repowise.server.mcp_server.tool_why.caps import _DECISION_CORPUS_LIMIT
@@ -29,6 +33,37 @@ async def _git_metadata_for(session: Any, repository_id: Any, file_path: str) ->
return git_res.scalar_one_or_none()
+async def _named_file(query: str, repo: str | None) -> str | None:
+ """The one indexed file a question names, by path or file name, or ``None``.
+
+ An exact path wins; the first token naming one file wins. A name several
+ files end with anchors nothing (ceiling: the question's words could pick one).
+ """
+ tokens = [t.replace("\\", "/").removeprefix("./") for t in path_tokens(query)]
+ if not tokens:
+ return None
+ ctx = await _resolve_repo_context(repo)
+ spec = _get_exclude_spec(ctx.path)
+ async with get_session(ctx.session_factory) as session:
+ repository = await _get_repo(session)
+ for token in tokens:
+ node = func.lower(GraphNode.node_id)
+ low = token.lower()
+ res = await session.execute(
+ select(GraphNode.node_id).where(
+ GraphNode.repository_id == repository.id,
+ GraphNode.node_type == "file",
+ or_(node == low, node.like(f"%/{escape_like(low)}", escape=LIKE_ESCAPE)),
+ )
+ )
+ found = [p for (p,) in res.all() if not is_excluded(p, spec)]
+ if token in found:
+ return token
+ if len(found) == 1:
+ return found[0]
+ return None
+
+
async def _all_git_metadata(session: Any, repository_id: Any) -> list:
"""Every file's git metadata, for the archaeology cross-file search."""
all_git_res = await session.execute(
diff --git a/packages/server/src/repowise/server/mcp_server/tool_why/tool.py b/packages/server/src/repowise/server/mcp_server/tool_why/tool.py
index f1c3a99a8..bbb5debdb 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_why/tool.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_why/tool.py
@@ -13,6 +13,7 @@ from repowise.server.mcp_server._helpers import (
)
from repowise.server.mcp_server.tool_why.basis import _stamp_answer_basis
from repowise.server.mcp_server.tool_why.dashboard import _why_health_dashboard
+from repowise.server.mcp_server.tool_why.loading import _named_file
from repowise.server.mcp_server.tool_why.path_mode import _why_path, _why_targets
from repowise.server.mcp_server.tool_why.reference import _why_reference
from repowise.server.mcp_server.tool_why.search import _why_search
@@ -91,7 +92,17 @@ async def get_why(
return _stamp_answer_basis(await _why_path(query, repo))
# --- Mode 3: Natural language → target-aware search ---
- return _stamp_answer_basis(await _why_search(query, targets, repo))
+ # A named file anchors as ``targets`` would; a failed lookup anchors nothing.
+ named = None
+ if not targets:
+ try:
+ named = await _named_file(query, repo)
+ except Exception:
+ named = None
+ result = await _why_search(query, [named] if named else targets, repo)
+ if named:
+ result["anchored_on"] = named
+ return _stamp_answer_basis(result)
def _reference_coordinates(
diff --git a/tests/unit/server/mcp/test_why.py b/tests/unit/server/mcp/test_why.py
index 1e2cdcd08..f68f20340 100644
--- a/tests/unit/server/mcp/test_why.py
+++ b/tests/unit/server/mcp/test_why.py
@@ -861,3 +861,45 @@ async def test_get_why_governed_target_reason_agrees_with_the_basis(session, set
assert "No decision record covers" not in result["reason"]
assert "binds it whatever the question" in result["reason"]
assert "try_instead" not in result
+
+
+async def test_a_question_naming_one_file_anchors_on_it(setup_mcp):
+ from repowise.server.mcp_server import get_why
+
+ result = await get_why("why is Service.py shaped this way?")
+ assert result["mode"] == "search"
+ assert list(result["target_context"]) == ["src/auth/service.py"]
+ assert result["anchored_on"] == "src/auth/service.py"
+ # Passed targets are the caller's own: nothing is inferred over them.
+ passed = await get_why("why is service.py shaped this way?", targets=["src/db/models.py"])
+ assert list(passed["target_context"]) == ["src/db/models.py"]
+ assert "anchored_on" not in passed
+
+
+async def test_a_file_name_two_indexed_files_carry_anchors_nothing(setup_mcp, factory):
+ from repowise.core.persistence.models import GraphNode
+ from repowise.server.mcp_server import get_why
+
+ async with factory() as session:
+ session.add(
+ GraphNode(
+ id="gn-dup",
+ repository_id=setup_mcp,
+ node_id="src/billing/models.py",
+ node_type="file",
+ language="python",
+ )
+ )
+ await session.commit()
+ assert "target_context" not in await get_why("why is models.py shaped this way?")
+ exact = await get_why("why is src/db/models.py shaped this way?")
+ assert list(exact["target_context"]) == ["src/db/models.py"]
+
+
+async def test_a_question_naming_no_indexed_file_stays_unanchored(setup_mcp):
+ from repowise.server.mcp_server import get_why
+
+ assert "target_context" not in await get_why("why is nowhere.py shaped this way?")