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.

refactor(search): move query-shape routing into a module with no database import (#2511)

Raghav Chamadiya770b9612d9a9
diff --git a/packages/server/src/repowise/server/mcp_server/__init__.py b/packages/server/src/repowise/server/mcp_server/__init__.py
index 59b21a4f0..f61e4c1be 100644
--- a/packages/server/src/repowise/server/mcp_server/__init__.py
+++ b/packages/server/src/repowise/server/mcp_server/__init__.py
@@ -78,7 +78,7 @@ _LAZY_ATTRS: dict[str, tuple[str, str]] = {
"_build_visual_context": ("_graph_utils", "build_visual_context"),
"_compute_alignment": ("_helpers", "_compute_alignment"),
"_get_repo": ("_helpers", "_get_repo"),
- "_is_path": ("_helpers", "_is_path"),
+ "_is_path": ("_query_shape", "_is_path"),
"create_mcp_server": ("_server", "create_mcp_server"),
"run_mcp": ("_server", "run_mcp"),
}
diff --git a/packages/server/src/repowise/server/mcp_server/_helpers.py b/packages/server/src/repowise/server/mcp_server/_helpers.py
index 2cf6627bc..ab3627690 100644
--- a/packages/server/src/repowise/server/mcp_server/_helpers.py
+++ b/packages/server/src/repowise/server/mcp_server/_helpers.py
@@ -5,7 +5,6 @@ from __future__ import annotations
import json
import logging
import os
-import os.path
from collections.abc import Collection
from pathlib import Path
from typing import Any
@@ -15,7 +14,6 @@ from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.analysis.decisions.lifecycle import is_governing
from repowise.core.analysis.decisions.scope import binds_to_paths
-from repowise.core.ingestion.languages.registry import REGISTRY as _LANG_REGISTRY
from repowise.core.persistence.models import (
Repository,
)
@@ -28,6 +26,7 @@ from repowise.core.persistence.sql import ( # noqa: F401
is_missing_table,
)
from repowise.server.mcp_server import _state
+from repowise.server.mcp_server._query_shape import _is_path # noqa: F401
_log = logging.getLogger("repowise.mcp")
@@ -35,8 +34,6 @@ _log = logging.getLogger("repowise.mcp")
# Constants
# ---------------------------------------------------------------------------
-_CODE_EXTS = _LANG_REGISTRY.all_code_extensions()
-
# Ceiling on one vector-store query, seconds. The first query in a process pays
# for the store open, the first embed and the first ANN probe; #1678 measured
# 6.3s + 13.4s on a cold Windows index where a warm query takes 0.19s. The old
@@ -107,30 +104,6 @@ def embed_timeout_s() -> float:
return min(seconds, _EMBED_TIMEOUT_MAX_S)
-# Words that mark a string as a natural-language question rather than a path.
-# Keep this small — false positives here send genuine paths to the NL branch,
-# which is harmless (path lookup also runs as a fallback) but slower.
-_NL_QUESTION_TOKENS = frozenset(
- {
- "why",
- "how",
- "what",
- "when",
- "where",
- "who",
- "which",
- "should",
- "can",
- "does",
- "do",
- "is",
- "are",
- "was",
- "were",
- }
-)
-
-
# ---------------------------------------------------------------------------
# Repository resolution
# ---------------------------------------------------------------------------
@@ -168,43 +141,6 @@ async def _get_repo(session: AsyncSession, repo: str | None = None) -> Repositor
# ---------------------------------------------------------------------------
-def _is_path(query: str) -> bool:
- """Heuristic: does this string look like a file or module path?
-
- Natural-language questions take precedence over the slash heuristic
- because phrases like "two-phase plan/apply flow" or "client/server
- boundary" contain a slash without being paths. We treat anything with
- a question mark, that starts with a question word, or that has 4+
- whitespace-separated tokens including a question word, as NL.
- """
- stripped = query.strip()
- if not stripped:
- return False
-
- # Trailing "?" is an unambiguous NL signal.
- if stripped.endswith("?"):
- return False
-
- tokens = stripped.split()
-
- # First token is a question word → NL.
- if tokens and tokens[0].lower().rstrip(",.;:") in _NL_QUESTION_TOKENS:
- return False
-
- # Sentence-shaped input (multiple words including a question word) → NL.
- if len(tokens) >= 4 and any(t.lower().rstrip(",.;:") in _NL_QUESTION_TOKENS for t in tokens):
- return False
-
- # A path can't contain whitespace.
- if any(ch.isspace() for ch in stripped):
- return False
-
- if "/" in stripped or "\\" in stripped:
- return True
- _, ext = os.path.splitext(stripped)
- return ext in _CODE_EXTS
-
-
# ---------------------------------------------------------------------------
# Workspace-aware repo context resolution
# ---------------------------------------------------------------------------
diff --git a/packages/server/src/repowise/server/mcp_server/_query_shape.py b/packages/server/src/repowise/server/mcp_server/_query_shape.py
new file mode 100644
index 000000000..193799c0f
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/_query_shape.py
@@ -0,0 +1,247 @@
+"""How ``search_codebase`` reads a query's shape, and its relevance constants.
+
+Stdlib only at import time: no database session, no MCP tool registry, so a
+caller can reuse the routing without loading either. The language registry is
+imported on the first extension check, not at import.
+"""
+
+from __future__ import annotations
+
+import os.path
+import re
+from functools import cache
+
+
+@cache
+def _code_exts() -> frozenset[str]:
+ from repowise.core.ingestion.languages.registry import REGISTRY
+
+ return REGISTRY.all_code_extensions()
+
+
+# Words that mark a string as a natural-language question rather than a path.
+# Keep this small — false positives here send genuine paths to the NL branch,
+# which is harmless (path lookup also runs as a fallback) but slower.
+_NL_QUESTION_TOKENS = frozenset(
+ {
+ "why",
+ "how",
+ "what",
+ "when",
+ "where",
+ "who",
+ "which",
+ "should",
+ "can",
+ "does",
+ "do",
+ "is",
+ "are",
+ "was",
+ "were",
+ }
+)
+
+
+def _is_path(query: str) -> bool:
+ """Heuristic: does this string look like a file or module path?
+
+ Natural-language questions take precedence over the slash heuristic
+ because phrases like "two-phase plan/apply flow" or "client/server
+ boundary" contain a slash without being paths. We treat anything with
+ a question mark, that starts with a question word, or that has 4+
+ whitespace-separated tokens including a question word, as NL.
+ """
+ stripped = query.strip()
+ if not stripped:
+ return False
+
+ # Trailing "?" is an unambiguous NL signal.
+ if stripped.endswith("?"):
+ return False
+
+ tokens = stripped.split()
+
+ # First token is a question word → NL.
+ if tokens and tokens[0].lower().rstrip(",.;:") in _NL_QUESTION_TOKENS:
+ return False
+
+ # Sentence-shaped input (multiple words including a question word) → NL.
+ if len(tokens) >= 4 and any(t.lower().rstrip(",.;:") in _NL_QUESTION_TOKENS for t in tokens):
+ return False
+
+ # A path can't contain whitespace.
+ if any(ch.isspace() for ch in stripped):
+ return False
+
+ if "/" in stripped or "\\" in stripped:
+ return True
+ _, ext = os.path.splitext(stripped)
+ return ext in _code_exts()
+
+
+def _qual_norm(name: str | None) -> str:
+ """Normalize a qualified name's separators (``::``/``/`` -> ``.``), lowered."""
+ s = name or ""
+ for sep in ("::", "/"):
+ s = s.replace(sep, ".")
+ return s.lower()
+
+
+# Pure-identifier pattern: a single bareword that looks like a code symbol
+# (no spaces, no punctuation other than _/.). These are almost always
+# better handled by Grep than by semantic search — vector embeddings of a
+# bare ``getCurrentUser`` quickly drift to thematically-similar but
+# textually-distant pages, while Grep would have found the literal usage
+# in milliseconds. We hint to Grep but still run the search so callers
+# that genuinely want fuzzy symbol search are not blocked.
+_IDENT_QUERY_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_.]{1,29}$")
+
+
+def _canonical_symbol_query(query: str) -> tuple[str, str] | None:
+ """Return ``(path, symbol)`` for an exact canonical ``path::Symbol`` query."""
+ stripped = query.strip().replace("\\", "/")
+ if "::" not in stripped:
+ return None
+ path, symbol = stripped.rsplit("::", 1)
+ if not path or not symbol or "/" not in path:
+ return None
+ return path, symbol
+
+
+def _looks_like_exact_token(query: str) -> bool:
+ """True when the query is a single identifier-shaped token best served by Grep."""
+ stripped = query.strip()
+ if not stripped or " " in stripped:
+ return False
+ return bool(_IDENT_QUERY_RE.match(stripped))
+
+
+# Identifier-shaped tokens inside a longer query: snake_case of any casing
+# (≥1 underscore, incl. _UPPER_SNAKE constants) or CamelCase (≥2 humps).
+# Plain English words never match.
+_IDENT_TOKEN_RE = re.compile(
+ r"\b(?:_*[A-Za-z0-9]+_[A-Za-z0-9_]+|[A-Z][A-Za-z0-9_]+)"
+ r"(?:\.[A-Za-z_][A-Za-z0-9_]*)+\b"
+ r"|\b(?:_*[A-Za-z0-9]+_[A-Za-z0-9_]+|[A-Z][a-z][a-z0-9]*(?:[A-Z][a-z0-9]+)+)\b"
+)
+
+
+def _embedded_identifiers(query: str) -> list[str]:
+ """Identifier-shaped tokens carried inside a natural-language query."""
+ return _IDENT_TOKEN_RE.findall(query)
+
+
+def _identifier_candidates(query: str, mode: str) -> list[str]:
+ """Identifier tokens the query is asking after, for the exact-match signal.
+
+ A single-token query IS the identifier (symbol mode); a natural-language
+ query carrying identifiers (hybrid mode) exposes them the same way
+ ``_resolve_mode`` used to route here. Concept/path queries name none.
+ """
+ if mode == "symbol":
+ q = query.strip()
+ canonical = _canonical_symbol_query(q)
+ return [q, canonical[1]] if canonical else ([q] if q else [])
+ if mode == "hybrid":
+ return _embedded_identifiers(query)
+ return []
+
+
+def _qualified_name_matches(qn: str, wanted: set[str]) -> bool:
+ if not qn:
+ return False
+ if qn in wanted:
+ return True
+ return any("." in candidate and qn.endswith(f".{candidate}") for candidate in wanted)
+
+
+def _symbol_matches_name(item: dict, wanted: set[str]) -> bool:
+ symbol_id = (item.get("symbol_id") or "").strip().lower().replace("\\", "/")
+ if symbol_id and symbol_id in wanted:
+ return True
+ name = (item.get("name") or "").strip().lower()
+ if name and name in wanted:
+ return True
+ return _qualified_name_matches(_qual_norm(item.get("qualified_name")), wanted)
+
+
+def _has_exact_symbol(candidates: list[str], symbols: list[dict]) -> bool:
+ """True when some returned symbol's name/qualified-name equals a candidate.
+
+ Reuses the scorer's separator-normalisation so an agent's ``Class.method``
+ matches a ``Class::method`` qualified_name in the index. This is the score
+ cliff made explicit: an exact hit and a fuzzy neighbour look identical in
+ the result list otherwise, and the agent anchors on whatever ranks first.
+ """
+ if not candidates or not symbols:
+ return False
+ wanted = {c.strip().lower() for c in candidates if c.strip()}
+ wanted |= {_qual_norm(c) for c in candidates if c.strip()}
+ return any(_symbol_matches_name(symbol, wanted) for symbol in symbols)
+
+
+_VALID_MODES = {"auto", "concept", "symbol", "path", "hybrid"}
+
+
+def _resolve_mode(query: str, mode: str | None) -> str:
+ """Resolve ``mode="auto"`` to a concrete branch from the query shape.
+
+ Explicit modes pass through. ``auto`` routes path-shaped queries to path
+ search, single identifier-shaped tokens to symbol search, and queries that
+ merely *carry* an identifier inside natural language to hybrid; everything
+ else stays concept (the original wiki-semantic path). The routing reuses
+ the exact heuristics that previously only emitted a grep_hint.
+ """
+ m = (mode or "auto").lower()
+ if m not in _VALID_MODES:
+ m = "auto"
+ if m != "auto":
+ return m
+ if _canonical_symbol_query(query):
+ return "symbol"
+ if _is_path(query):
+ return "path"
+ if _looks_like_exact_token(query):
+ return "symbol"
+ if _embedded_identifiers(query):
+ return "hybrid"
+ return "concept"
+
+
+# Minimum relevance score below which results are dropped. Prevents
+# returning semantically unrelated pages when the corpus has no real match.
+_MIN_RELEVANCE_SCORE = 0.03
+
+
+# Decision records are short, dense title-statements; they win cosine
+# similarity against long file-page embeddings on any query containing
+# design nouns ("store", "SQLite", "cap", "prune") and crowd file pages
+# out of the top ranks entirely. Down-weight them unless the query is
+# why-shaped — rationale questions are get_why's territory, but a caller
+# who phrases one here clearly wants the decision pages ranked honestly.
+_DECISION_DOWNWEIGHT = 0.6
+
+
+_WHY_SHAPED_RE = re.compile(
+ r"^\s*(why|when\s+did|when\s+was|who\s+decided|who\s+chose|what\s+was\s+the\s+(reason|rationale))\b"
+ r"|\b(decision|decided|rationale|adr)\b",
+ re.IGNORECASE,
+)
+
+
+def _is_why_shaped(query: str) -> bool:
+ """True when the query asks for rationale, so decision records should rank naturally."""
+ return bool(_WHY_SHAPED_RE.search(query))
+
+
+def _fetch_limit_for(limit: int, kind: str | None) -> int:
+ """Over-fetch headroom for post-filters and decision down-weighting.
+
+ Always over-fetch at least 3x: without headroom the down-weighting can
+ only reorder a window that decision records may already fill, so file
+ pages never surface. ``kind`` trims hardest (decision/module/overview
+ pages all classify as "doc"), so it gets 6x — 3x was measured to leave
+ zero implementation pages in the window on decision-heavy queries.
+ """
+ return limit * (6 if kind else 3)
diff --git a/packages/server/src/repowise/server/mcp_server/tool_search.py b/packages/server/src/repowise/server/mcp_server/tool_search.py
index e541223b0..430998a6a 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_search.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_search.py
@@ -29,7 +29,6 @@ from repowise.server.mcp_server._helpers import (
_VECTOR_TIMEOUT_ENV,
_get_exclude_spec,
_get_repo,
- _is_path,
_resolve_all_contexts,
_resolve_repo_context,
attach_ignored_arguments,
@@ -41,20 +40,30 @@ from repowise.server.mcp_server._meta import EXHAUSTIVE_SWEEP_HINT
from repowise.server.mcp_server._meta import build_meta as _build_meta
from repowise.server.mcp_server._page_paths import file_candidates, hit_file_path
from repowise.server.mcp_server._prose_symbols import symbol_backed_pages
+from repowise.server.mcp_server._query_shape import (
+ _DECISION_DOWNWEIGHT,
+ _MIN_RELEVANCE_SCORE,
+ _VALID_MODES,
+ _canonical_symbol_query,
+ _embedded_identifiers,
+ _fetch_limit_for,
+ _has_exact_symbol,
+ _identifier_candidates,
+ _is_why_shaped,
+ _looks_like_exact_token,
+ _qual_norm,
+ _resolve_mode,
+ _symbol_matches_name,
+)
from repowise.server.mcp_server._references import path_identity, symbol_identity
from repowise.server.mcp_server._retrieval_rank import rerank_by_context_coverage
from repowise.server.mcp_server.tool_search_symbols import (
- _qual_norm,
search_paths_single,
search_symbols_single,
)
_log = logging.getLogger("repowise.mcp.search")
-# Minimum relevance score below which results are dropped. Prevents
-# returning semantically unrelated pages when the corpus has no real match.
-_MIN_RELEVANCE_SCORE = 0.03
-
# Freshness tie-breaker, added (not multiplied) to a hit's fused relevance.
# The RRF-fused score spaces adjacent ranks ~0.05 apart, so this stays under
# one rank step: recency orders otherwise-comparable hits without overriding
@@ -62,98 +71,6 @@ _MIN_RELEVANCE_SCORE = 0.03
# for 30-day).
_FRESHNESS_TIEBREAK = 0.03
-# Pure-identifier pattern: a single bareword that looks like a code symbol
-# (no spaces, no punctuation other than _/.). These are almost always
-# better handled by Grep than by semantic search — vector embeddings of a
-# bare ``getCurrentUser`` quickly drift to thematically-similar but
-# textually-distant pages, while Grep would have found the literal usage
-# in milliseconds. We hint to Grep but still run the search so callers
-# that genuinely want fuzzy symbol search are not blocked.
-_IDENT_QUERY_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_.]{1,29}$")
-
-
-def _canonical_symbol_query(query: str) -> tuple[str, str] | None:
- """Return ``(path, symbol)`` for an exact canonical ``path::Symbol`` query."""
- stripped = query.strip().replace("\\", "/")
- if "::" not in stripped:
- return None
- path, symbol = stripped.rsplit("::", 1)
- if not path or not symbol or "/" not in path:
- return None
- return path, symbol
-
-
-def _looks_like_exact_token(query: str) -> bool:
- """True when the query is a single identifier-shaped token best served by Grep."""
- stripped = query.strip()
- if not stripped or " " in stripped:
- return False
- return bool(_IDENT_QUERY_RE.match(stripped))
-
-
-# Identifier-shaped tokens inside a longer query: snake_case of any casing
-# (≥1 underscore, incl. _UPPER_SNAKE constants) or CamelCase (≥2 humps).
-# Plain English words never match.
-_IDENT_TOKEN_RE = re.compile(
- r"\b(?:_*[A-Za-z0-9]+_[A-Za-z0-9_]+|[A-Z][A-Za-z0-9_]+)"
- r"(?:\.[A-Za-z_][A-Za-z0-9_]*)+\b"
- r"|\b(?:_*[A-Za-z0-9]+_[A-Za-z0-9_]+|[A-Z][a-z][a-z0-9]*(?:[A-Z][a-z0-9]+)+)\b"
-)
-
-
-def _embedded_identifiers(query: str) -> list[str]:
- """Identifier-shaped tokens carried inside a natural-language query."""
- return _IDENT_TOKEN_RE.findall(query)
-
-
-def _identifier_candidates(query: str, mode: str) -> list[str]:
- """Identifier tokens the query is asking after, for the exact-match signal.
-
- A single-token query IS the identifier (symbol mode); a natural-language
- query carrying identifiers (hybrid mode) exposes them the same way
- ``_resolve_mode`` used to route here. Concept/path queries name none.
- """
- if mode == "symbol":
- q = query.strip()
- canonical = _canonical_symbol_query(q)
- return [q, canonical[1]] if canonical else ([q] if q else [])
- if mode == "hybrid":
- return _embedded_identifiers(query)
- return []
-
-
-def _qualified_name_matches(qn: str, wanted: set[str]) -> bool:
- if not qn:
- return False
- if qn in wanted:
- return True
- return any("." in candidate and qn.endswith(f".{candidate}") for candidate in wanted)
-
-
-def _symbol_matches_name(item: dict, wanted: set[str]) -> bool:
- symbol_id = (item.get("symbol_id") or "").strip().lower().replace("\\", "/")
- if symbol_id and symbol_id in wanted:
- return True
- name = (item.get("name") or "").strip().lower()
- if name and name in wanted:
- return True
- return _qualified_name_matches(_qual_norm(item.get("qualified_name")), wanted)
-
-
-def _has_exact_symbol(candidates: list[str], symbols: list[dict]) -> bool:
- """True when some returned symbol's name/qualified-name equals a candidate.
-
- Reuses the scorer's separator-normalisation so an agent's ``Class.method``
- matches a ``Class::method`` qualified_name in the index. This is the score
- cliff made explicit: an exact hit and a fuzzy neighbour look identical in
- the result list otherwise, and the agent anchors on whatever ranks first.
- """
- if not candidates or not symbols:
- return False
- wanted = {c.strip().lower() for c in candidates if c.strip()}
- wanted |= {_qual_norm(c) for c in candidates if c.strip()}
- return any(_symbol_matches_name(symbol, wanted) for symbol in symbols)
-
def _protect_exact_symbols(query: str, symbols: list[dict]) -> list[dict]:
"""Stable-partition an exact identifier or ``path::Symbol`` hit to the head."""
@@ -226,26 +143,6 @@ def _interleave_hybrid(
return (symbols[: max(1, limit - reserved)] + concepts)[:limit]
-# Decision records are short, dense title-statements; they win cosine
-# similarity against long file-page embeddings on any query containing
-# design nouns ("store", "SQLite", "cap", "prune") and crowd file pages
-# out of the top ranks entirely. Down-weight them unless the query is
-# why-shaped — rationale questions are get_why's territory, but a caller
-# who phrases one here clearly wants the decision pages ranked honestly.
-_DECISION_DOWNWEIGHT = 0.6
-
-_WHY_SHAPED_RE = re.compile(
- r"^\s*(why|when\s+did|when\s+was|who\s+decided|who\s+chose|what\s+was\s+the\s+(reason|rationale))\b"
- r"|\b(decision|decided|rationale|adr)\b",
- re.IGNORECASE,
-)
-
-
-def _is_why_shaped(query: str) -> bool:
- """True when the query asks for rationale, so decision records should rank naturally."""
- return bool(_WHY_SHAPED_RE.search(query))
-
-
def _downweight_decisions(output: list[dict], query: str) -> None:
"""Scale decision_record relevance in place unless the query is why-shaped."""
if _is_why_shaped(query):
@@ -465,18 +362,6 @@ async def _append_symbol_backed(
return head + additions + output[len(head) :]
-def _fetch_limit_for(limit: int, kind: str | None) -> int:
- """Over-fetch headroom for post-filters and decision down-weighting.
-
- Always over-fetch at least 3x: without headroom the down-weighting can
- only reorder a window that decision records may already fill, so file
- pages never surface. ``kind`` trims hardest (decision/module/overview
- pages all classify as "doc"), so it gets 6x — 3x was measured to leave
- zero implementation pages in the window on decision-heavy queries.
- """
- return limit * (6 if kind else 3)
-
-
# Path-prefix heuristics for the ``kind`` filter. We classify a hit's
# target_path against these prefixes; if none match, the hit falls into
# ``other`` and is dropped only when the caller asked for a specific kind.
@@ -922,34 +807,6 @@ def _grep_hint_for(query: str) -> str | None:
return None
-_VALID_MODES = {"auto", "concept", "symbol", "path", "hybrid"}
-
-
-def _resolve_mode(query: str, mode: str | None) -> str:
- """Resolve ``mode="auto"`` to a concrete branch from the query shape.
-
- Explicit modes pass through. ``auto`` routes path-shaped queries to path
- search, single identifier-shaped tokens to symbol search, and queries that
- merely *carry* an identifier inside natural language to hybrid; everything
- else stays concept (the original wiki-semantic path). The routing reuses
- the exact heuristics that previously only emitted a grep_hint.
- """
- m = (mode or "auto").lower()
- if m not in _VALID_MODES:
- m = "auto"
- if m != "auto":
- return m
- if _canonical_symbol_query(query):
- return "symbol"
- if _is_path(query):
- return "path"
- if _looks_like_exact_token(query):
- return "symbol"
- if _embedded_identifiers(query):
- return "hybrid"
- return "concept"
-
-
async def _contexts_for(repo: str | None) -> list:
"""The repo contexts a structured search runs over (one, or all in 'all')."""
if repo == "all":
diff --git a/packages/server/src/repowise/server/mcp_server/tool_search_symbols.py b/packages/server/src/repowise/server/mcp_server/tool_search_symbols.py
index a888539e9..5b24478c6 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_search_symbols.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_search_symbols.py
@@ -33,6 +33,7 @@ from repowise.server.mcp_server._helpers import (
escape_like,
is_excluded,
)
+from repowise.server.mcp_server._query_shape import _qual_norm
# Candidate ceiling: scoring/sorting happens in Python, so the SQL pre-filter
# caps how many rows we pull. Generous enough that the true top-`limit` is
@@ -62,14 +63,6 @@ def _tokens(text: str | None) -> set[str]:
return out
-def _qual_norm(name: str | None) -> str:
- """Normalize a qualified name's separators (``::``/``/`` -> ``.``), lowered."""
- s = name or ""
- for sep in ("::", "/"):
- s = s.replace(sep, ".")
- return s.lower()
-
-
def _score_symbol(row: WikiSymbol, gnode: GraphNode | None, qtokens: set[str], qnorm: str) -> float:
"""Rank a candidate symbol against the query (higher = better).
diff --git a/tests/unit/server/mcp/test_search_query_shape.py b/tests/unit/server/mcp/test_search_query_shape.py
new file mode 100644
index 000000000..15060d102
--- /dev/null
+++ b/tests/unit/server/mcp/test_search_query_shape.py
@@ -0,0 +1,78 @@
+"""How search_codebase reads a query's shape, pinned at the tool module."""
+
+from __future__ import annotations
+
+import subprocess
+import sys
+
+import pytest
+
+from repowise.server.mcp_server.tool_search import (
+ _DECISION_DOWNWEIGHT,
+ _MIN_RELEVANCE_SCORE,
+ _canonical_symbol_query,
+ _embedded_identifiers,
+ _fetch_limit_for,
+ _has_exact_symbol,
+ _is_why_shaped,
+ _resolve_mode,
+)
+
+
+ "query, mode, expected",
+ [
+ ("src/app.py::Service", None, "symbol"),
+ ("src\\app.py::Service", "auto", "symbol"),
+ ("app.py::Service", None, "concept"),
+ ("packages/core/src/x.py", None, "path"),
+ ("setup.py", None, "path"),
+ ("main.go", None, "path"),
+ # Not a code extension, so it is not a path; it reads as an identifier.
+ ("README.md", None, "symbol"),
+ ("what does client/server boundary mean", None, "concept"),
+ ("src/app.py?", None, "concept"),
+ ("getCurrentUser", None, "symbol"),
+ ("Foo.bar", None, "symbol"),
+ ("how does parse_file handle errors", None, "hybrid"),
+ ("where is ParserRegistry.resolve used", None, "hybrid"),
+ ("how does caching work", None, "concept"),
+ ("anything", "PATH", "path"),
+ ("how it works", "bogus", "concept"),
+ ("", None, "concept"),
+ ],
+)
+def test_resolve_mode(query: str, mode: str | None, expected: str) -> None:
+ assert _resolve_mode(query, mode) == expected
+
+
+def test_identifier_shapes() -> None:
+ assert _canonical_symbol_query(" src\\a.py::Foo ") == ("src/a.py", "Foo")
+ assert _canonical_symbol_query("a.py::Foo") is None
+ assert _embedded_identifiers("why does ParserRegistry.resolve call load_spec") == [
+ "ParserRegistry.resolve",
+ "load_spec",
+ ]
+ assert _embedded_identifiers("plain english words only") == []
+
+
+def test_exact_symbol_and_relevance_constants() -> None:
+ symbols = [{"name": "method", "qualified_name": "pkg::Class::method"}]
+ assert _has_exact_symbol(["Class.method"], symbols)
+ assert not _has_exact_symbol(["other"], symbols)
+ assert (_MIN_RELEVANCE_SCORE, _DECISION_DOWNWEIGHT) == (0.03, 0.6)
+ assert _fetch_limit_for(10, None) == 30
+ assert _fetch_limit_for(10, "test") == 60
+ assert _is_why_shaped("why is the cache here")
+ assert not _is_why_shaped("cache eviction")
+
+
+def test_the_shape_module_loads_no_registry_or_database() -> None:
+ code = (
+ "import sys; import repowise.server.mcp_server._query_shape; "
+ "print(sorted(m for m in sys.modules if m == 'sqlalchemy' "
+ "or m.startswith(('repowise.core.registry', 'repowise.core.persistence', "
+ "'repowise.core.ingestion'))))"
+ )
+ out = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, check=True)
+ assert out.stdout.strip() == "[]"