Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(mcp): read a typed identifier as one name in get_answer retrieval (#2736)
Raghav Chamadiya657153c61d5f
diff --git a/packages/server/src/repowise/server/mcp_server/_answer_pipeline.py b/packages/server/src/repowise/server/mcp_server/_answer_pipeline.pyindex 952acbd4f..566eaccf7 100644--- a/packages/server/src/repowise/server/mcp_server/_answer_pipeline.py+++ b/packages/server/src/repowise/server/mcp_server/_answer_pipeline.py@@ -375,6 +375,7 @@ async def hybrid_retrieve(question: str, ctx: Any) -> list[dict]:entry["score"] = entry.get("score", 0.0) + 1.0 / (rank + _SYMBOL_LEG_RRF_K)entry["_sources"].add("symbol")entry["_sym_rank"] = rank+ entry["_symbol_names"] = h.symbol_names# Scale to BM25-range so downstream confidence/dominance gates (tuned# against the prior single-mode BM25 retrieval) keep behaving sanely.@@ -503,13 +504,16 @@ class _SymbolLegResult:way FTS and the vector store present theirs."""- __slots__ = ("page_id", "page_type", "snippet", "title")+ __slots__ = ("page_id", "page_type", "snippet", "symbol_names", "title")- def __init__(self, page_id: str, title: str, snippet: str, page_type: str) -> None:+ def __init__(+ self, page_id: str, title: str, snippet: str, page_type: str, symbol_names: list[str]+ ) -> None:self.page_id = page_idself.title = titleself.snippet = snippetself.page_type = page_type+ self.symbol_names = symbol_namesasync def _safe_symbol_search(ctx: Any, question: str) -> list[_SymbolLegResult]:@@ -545,7 +549,13 @@ async def _safe_symbol_search(ctx: Any, question: str) -> list[_SymbolLegResult]return []_record_leg("symbol", "ok")return [- _SymbolLegResult(p["page_id"], p["title"], (p.get("summary") or "")[:200], p["page_type"])+ _SymbolLegResult(+ p["page_id"],+ p["title"],+ (p.get("summary") or "")[:200],+ p["page_type"],+ p.get("symbol_names") or [],+ )for p in pages]diff --git a/packages/server/src/repowise/server/mcp_server/_prose_symbols.py b/packages/server/src/repowise/server/mcp_server/_prose_symbols.pyindex b0ae3a717..55fa4ea1f 100644--- a/packages/server/src/repowise/server/mcp_server/_prose_symbols.py+++ b/packages/server/src/repowise/server/mcp_server/_prose_symbols.py@@ -138,6 +138,12 @@ def _score(return score+def _covers(term: str, symbol_tokens: set[str]) -> bool:+ """Whether every word of *term* is a token of the symbol (one word for a plain term)."""+ words = _tokens(term)+ return bool(words) and words <= symbol_tokens++def _corroborated(row: WikiSymbol, covered: dict[str, float], saturated: set[str]) -> bool:"""Whether *row* has enough independent evidence to enter the pool.@@ -156,7 +162,9 @@ def _corroborated(row: WikiSymbol, covered: dict[str, float], saturated: set[strreturn any(term != name for term in informative)if name in informative:return True- return len(informative) >= 2+ # A compound the caller typed (``module_page``) is its words already agreeing+ # in order, so it counts once per word.+ return sum(len(_tokens(term)) for term in informative) >= 2async def search_symbols_by_terms(@@ -216,12 +224,13 @@ async def search_symbols_by_terms(continue# A term counts as covered when it survives tokenisation of the symbol# name, not merely as a substring: ``update`` should match- # ``update_index``, not ``groupdater``.+ # ``update_index``, not ``groupdater``. A compound term is covered when+ # every word of it is, since the window already matched it contiguously.stoks = _tokens(row.name) | _tokens(row.qualified_name) | _tokens(row.file_path)covered = {t: (_SATURATED_TERM_WEIGHT if t in saturated else 1.0)for t in matched.get(symbol_id, ())- if t in stoks+ if _covers(t, stoks)}if not _corroborated(row, covered, saturated):continue@@ -265,12 +274,14 @@ async def symbol_backed_pages(return []paths: list[str] = []- seen: set[str] = set()+ names: dict[str, list[str]] = {}for hit in symbols:path = hit.get("file")- if path and path not in seen:- seen.add(path)+ if not path:+ continue+ if path not in names:paths.append(path)+ names.setdefault(path, []).append(hit.get("name") or "")paths = paths[:max_files]if not paths:return []@@ -290,6 +301,9 @@ async def symbol_backed_pages("title": row[2] or f"File: {row[1]}","summary": row[3] or "","page_type": row[4] or "file_page",+ # The names that earned the page its place, for a ranker that+ # would otherwise judge it on prose that never mentions them.+ "symbol_names": names[row[1]],}for row in res.all()}diff --git a/packages/server/src/repowise/server/mcp_server/_retrieval_rank.py b/packages/server/src/repowise/server/mcp_server/_retrieval_rank.pyindex b6b3122b1..e3e8933d2 100644--- a/packages/server/src/repowise/server/mcp_server/_retrieval_rank.py+++ b/packages/server/src/repowise/server/mcp_server/_retrieval_rank.py@@ -5,7 +5,9 @@ from __future__ import annotationsimport mathimport re-from repowise.server.mcp_server._query_terms import content_terms+from repowise.server.mcp_server._query_terms import content_terms, split_humps++_IDENTIFIER_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")_INFLECTIONS = {"changed": "change",@@ -22,6 +24,39 @@ def _ranking_terms(text: str, *, max_terms: int = 8) -> set[str]:return {_INFLECTIONS.get(term, term) for term in content_terms(text, max_terms=max_terms)}+def _identifier_words(token: str) -> list[str]:+ """``generateModulePage`` / ``generate_module_page`` -> ``[generate, module, page]``."""+ return [w for w in re.split(r"[^a-z0-9]+", split_humps(token).lower()) if w]+++def _typed_compounds(query: str, terms: set[str]) -> dict[str, list[str]]:+ """Ranking terms the query typed as one identifier, with their words.++ A typed compound (``module_page``, ``modulePage``) also counts inside a+ longer name (``generate_module_page``), which word-level tokens never produce.+ """+ compounds: dict[str, list[str]] = {}+ for raw in _IDENTIFIER_RE.findall(query):+ words = _identifier_words(raw)+ if len(words) >= 2 and raw.lower() in terms:+ compounds[raw.lower()] = words+ return compounds+++def _names_compound(text: str, words: list[str]) -> bool:+ """Whether an identifier in *text* holds *words* as consecutive whole words.++ Prose never matches: ``module page`` is two identifiers, and ``this_test``+ does not hold ``is_test``.+ """+ n = len(words)+ for raw in _IDENTIFIER_RE.findall(text):+ parts = _identifier_words(raw)+ if any(parts[i : i + n] == words for i in range(len(parts) - n + 1)):+ return True+ return False++def rerank_by_context_coverage(hits: list[dict],query: str,@@ -48,11 +83,18 @@ def rerank_by_context_coverage(hit.get("snippet", "") or "",hit.get("summary", "") or "",hit.get("target_path", "") or "",+ # A page the symbol leg reached is about the names it matched.+ " ".join(hit.get("_symbol_names") or ()),])for hit in hits]- tokens_by_hit = [_ranking_terms(text, max_terms=128) for text in texts_by_hit]+ compounds = _typed_compounds(query, terms)+ tokens_by_hit = [+ _ranking_terms(text, max_terms=128)+ | {term for term, words in compounds.items() if _names_compound(text, words)}+ for text in texts_by_hit+ ]document_frequency = {term: sum(1 for tokens in tokens_by_hit if term in tokens) for term in terms}diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/retrieval.py b/packages/server/src/repowise/server/mcp_server/tool_answer/retrieval.pyindex 1ead81f11..65bb70134 100644--- a/packages/server/src/repowise/server/mcp_server/tool_answer/retrieval.py+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/retrieval.py@@ -10,6 +10,7 @@ from __future__ import annotationsimport asyncioimport logging+import refrom typing import Anyfrom sqlalchemy import select@@ -247,6 +248,21 @@ async def _attach_page_excerpts(hits: list[dict], ctx: Any = None) -> int:return missing+_DOMAIN_WORD_SUFFIXES = ("", "s", "es", "er", "ers")+++def _names_domain_word(token: str, words: set[str], text: str) -> bool:+ """*token* as a word or with a common suffix, or (6+ chars) a word it begins.++ A hyphenated token (``client-side``) is matched as a phrase in *text*.+ """+ if "-" in token:+ return re.search(rf"\b{re.escape(token)}\b", text) is not None+ if any(f"{token}{suffix}" in words for suffix in _DOMAIN_WORD_SUFFIXES):+ return True+ return len(token) >= 6 and any(word.startswith(token) for word in words)++def _detect_question_domain(question: str) -> str | None:"""Return ``"ui"``, ``"backend"``, or ``None`` when the question is ambiguous.@@ -254,9 +270,12 @@ def _detect_question_domain(question: str) -> str | None:token sets fire, or neither, no penalty applies rather than miscategorise across-cutting question."""- qlow = question.lower()- has_ui = any(tok in qlow for tok in _UI_QUESTION_TOKENS)- has_backend = any(tok in qlow for tok in _BACKEND_QUESTION_TOKENS)+ # Whole words, identifiers kept intact: ``module_page`` names a symbol, not+ # a UI page, and ``client`` is not ``cli``. Hyphens split (``settings-page``).+ text = question.lower()+ words = set(re.findall(r"[a-z0-9_]+", text))+ has_ui = any(_names_domain_word(tok, words, text) for tok in _UI_QUESTION_TOKENS)+ has_backend = any(_names_domain_word(tok, words, text) for tok in _BACKEND_QUESTION_TOKENS)if has_ui and not has_backend:return "ui"if has_backend and not has_ui:diff --git a/tests/unit/server/mcp/test_answer_typed_identifiers.py b/tests/unit/server/mcp/test_answer_typed_identifiers.pynew file mode 100644index 000000000..5f3b6770e--- /dev/null+++ b/tests/unit/server/mcp/test_answer_typed_identifiers.py@@ -0,0 +1,97 @@+"""A typed identifier is one name, not the words it is spelled with.++"How is ``report_card`` built" names symbols such as ``build_report_card``. Read+as the words ``report`` and ``card`` it matched the symbol index too weakly to+enter the pool, ranked below any page whose prose said "report card", and put+the question into the UI domain because ``card`` is a UI word.+"""++from __future__ import annotations++from repowise.server.mcp_server._prose_symbols import _corroborated, _covers+from repowise.server.mcp_server._retrieval_rank import rerank_by_context_coverage+from repowise.server.mcp_server.tool_answer.retrieval import _detect_question_domain+from repowise.server.mcp_server.tool_search_symbols import _tokens+++class _Sym:+ def __init__(self, name: str) -> None:+ self.name = name+++def test_a_typed_compound_is_covered_by_a_longer_name_holding_its_words():+ assert _covers("report_card", _tokens("build_report_card"))+ assert not _covers("report_card", _tokens("build_report"))+++def test_a_term_with_no_words_left_covers_nothing():+ assert not _covers("_x_", _tokens("anything_at_all"))+++def test_a_typed_compound_corroborates_on_its_own_when_its_words_are_common():+ covered = {"report_card": 1.0, "report": 0.25, "card": 0.25}+ assert _corroborated(_Sym("build_report_card"), covered, saturated={"report", "card"})+++def test_a_single_plain_word_still_does_not_corroborate():+ assert not _corroborated(_Sym("build_report"), {"report": 1.0}, saturated=set())+++def _hit(path: str, score: float, summary: str, names: list[str] | None = None) -> dict:+ hit = {"target_path": path, "score": score, "title": path, "summary": summary}+ if names is not None:+ hit["_symbol_names"] = names+ return hit+++def test_the_file_defining_the_named_symbol_outranks_prose_that_spells_its_words():+ prose = _hit("web/report/card.tsx", 1.0, "Renders the report card view.")+ defining = _hit("lib/build.py", 1.0, "Builds documents.", names=["build_report_card"])++ ranked = rerank_by_context_coverage(+ [prose, defining], "how is report_card built", score_key="score", floor=0.5+ )++ assert ranked[0]["target_path"] == "lib/build.py"+++def test_an_identifier_holding_a_ui_word_does_not_make_the_question_a_ui_one():+ assert _detect_question_domain("how is report_page generated") is None+ assert _detect_question_domain("how is the settings page rendered") == "ui"+++def test_domain_words_are_matched_whole():+ # ``client`` is not ``cli``, ``overview`` is not ``view``.+ assert _detect_question_domain("how does the client retry") is None+ assert _detect_question_domain("where is the overview built") is None+ assert _detect_question_domain("how does the orchestration layer start") == "backend"+++def test_a_compound_needs_whole_words_inside_the_longer_name():+ # ``this_test`` does not hold ``is_test``; prose "report card" is not one name.+ wrong = _hit("lib/a.py", 1.0, "Guards this_test and the report card.")+ right = _hit("lib/b.py", 1.0, "Checks flags.", names=["check_is_test"])++ ranked = rerank_by_context_coverage(+ [wrong, right], "where is is_test decided", score_key="score", floor=0.5+ )++ assert ranked[0]["target_path"] == "lib/b.py"+++def test_a_camel_case_compound_matches_the_same_words_in_snake_case():+ prose = _hit("web/report/card.tsx", 1.0, "Renders the report card view.")+ defining = _hit("lib/build.py", 1.0, "Builds documents.", names=["build_report_card"])++ ranked = rerank_by_context_coverage(+ [prose, defining], "how is reportCard built", score_key="score", floor=0.5+ )++ assert ranked[0]["target_path"] == "lib/build.py"+++def test_hyphenated_and_suffixed_domain_words_still_count():+ assert _detect_question_domain("where is the settings-page layout") == "ui"+ assert _detect_question_domain("how is the api-key stored") == "backend"+ assert _detect_question_domain("how does the viewer scroll") == "ui"+ assert _detect_question_domain("how is client-side state kept") == "ui"