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
feat(mcp): demote decision records and test pages in retrieval (#1040)
Raghav Chamadiya93a47ce63378
diff --git a/packages/server/src/repowise/server/mcp_server/_answer_pipeline.py b/packages/server/src/repowise/server/mcp_server/_answer_pipeline.pyindex b90c7a42a..1a4dab571 100644--- a/packages/server/src/repowise/server/mcp_server/_answer_pipeline.py+++ b/packages/server/src/repowise/server/mcp_server/_answer_pipeline.py@@ -37,6 +37,7 @@ from __future__ import annotationsimport asyncioimport contextlib+import refrom typing import Anyfrom sqlalchemy import select@@ -182,6 +183,54 @@ def _hit_dict_from_result(result: Any) -> dict:}+# ---------------------------------------------------------------------------+# Noise demotion (decision records + test file pages)+# ---------------------------------------------------------------------------++# Retrieval noise that should not occupy get_answer's top-5 on a plain question.+# Mirrors search_codebase's demotion (tool_search._sort_demoting_noise) on the+# answer pipeline's hit shape. Kept local so the answer pipeline does not import+# the search tool; the token lists are intentionally the same.+_TEST_PATH_TOKENS = ("/test/", "/tests/", "/__tests__/", "test_", "_test.", ".spec.", ".test.")+_TEST_QUERY_RE = re.compile(+ r"\b(test|tests|testing|tested|unit[\s-]?test|integration[\s-]?test|pytest|fixture|mock|spec)\b",+ re.IGNORECASE,+)+++def _is_test_path(target_path: str) -> bool:+ tp = (target_path or "").lower()+ return any(tok in tp for tok in _TEST_PATH_TOKENS)+++def demote_noise_hits(hits: list[dict], question: str, *, is_why: bool) -> list[dict]:+ """Stable-partition retrieval noise below real pages before the top-5 cap.++ get_answer applies no demotion of its own — decision records (short dense+ titles) and test file pages win RRF against the implementation a plain+ question is about and take top-5 slots that then feed synthesis. Decision+ records demote unless the question is why-shaped (decisions are the answer+ then, folded into the prelude); test file pages demote unless the question is+ explicitly about tests. Stable: real hits keep their order, and noise keeps+ its relative order at the tail (never dropped — an agent may still want it).+ """+ if not hits:+ return hits+ test_focused = bool(_TEST_QUERY_RE.search(question))++ def _is_noise(h: dict) -> bool:+ pt = h.get("page_type")+ return (pt == "decision_record" and not is_why) or (+ pt == "file_page"+ and not test_focused+ and _is_test_path(h.get("target_path", ""))+ )++ real = [h for h in hits if not _is_noise(h)]+ noise = [h for h in hits if _is_noise(h)]+ return real + noise++# ---------------------------------------------------------------------------# Stage 2: Hydrate hits with Page metadata (target_path, summary)# ---------------------------------------------------------------------------diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/answer.py b/packages/server/src/repowise/server/mcp_server/tool_answer/answer.pyindex 6e4bfa872..a90a03986 100644--- a/packages/server/src/repowise/server/mcp_server/tool_answer/answer.py+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/answer.py@@ -69,6 +69,9 @@ from repowise.server.mcp_server._answer_context import (from repowise.server.mcp_server._answer_pipeline import (apply_pagerank_bias as _apply_pagerank_bias,)+from repowise.server.mcp_server._answer_pipeline import (+ demote_noise_hits as _demote_noise_hits,+)from repowise.server.mcp_server._answer_pipeline import (expand_via_graph as _expand_via_graph,)@@ -804,6 +807,12 @@ async def get_answer(with contextlib.suppress(Exception):async with get_session(ctx.session_factory) as session:hits = await _expand_via_neighbor_rerank(session, repo_id, hits, question, ctx)+ # Demote retrieval noise (decision records on non-why questions, test file+ # pages on non-test questions) below real pages before the cap, so it can't+ # occupy a top-5 slot and feed synthesis. Stable and non-dropping; runs after+ # all anchoring/expansion (which inject file/symbol pages, never noise) so it+ # only reorders what those stages left in place.+ hits = _demote_noise_hits(hits, question, is_why=_is_why_question(question))# Always cap retrieval hits at 5 for the response payload.hits = hits[:5]diff --git a/packages/server/src/repowise/server/mcp_server/tool_search.py b/packages/server/src/repowise/server/mcp_server/tool_search.pyindex 426a10b56..5ba71a1e5 100644--- a/packages/server/src/repowise/server/mcp_server/tool_search.py+++ b/packages/server/src/repowise/server/mcp_server/tool_search.py@@ -163,26 +163,91 @@ def _downweight_decisions(output: list[dict], query: str) -> None:item["relevance_score"] = round(item["relevance_score"] * _DECISION_DOWNWEIGHT, 4)-def _sort_demoting_decisions(output: list[dict], query: str) -> None:- """Sort by relevance, ranking decision records below every file-backed- page on non-why queries.-- The multiplicative down-weight alone is washed out when decision scores- dominate (short dense titles win cosine similarity by a margin > the- 0.6 factor) — observed live as 5/5 irrelevant decisions for a plain- implementation query. For non-why queries a decision record is never a- better first Read than a file page, so the demotion is absolute; the- down-weighted score still orders decisions among themselves.+# Test file pages compete against the implementation they exercise and win+# retrieval on any shared vocabulary ("conftest" for a fixtures question,+# "decision" for a downweight question) — observed live as a test file ranking+# #1 for a plain implementation query. A test is rarely a better first Read than+# the code under test, so demote it, unless the query is explicitly about tests.+_TEST_DOWNWEIGHT = 0.6++_TEST_QUERY_RE = re.compile(+ r"\b(test|tests|testing|tested|unit[\s-]?test|integration[\s-]?test|pytest|fixture|mock|spec)\b",+ re.IGNORECASE,+)+++def _is_test_query(query: str) -> bool:+ """True when the query is explicitly about tests, so test pages rank naturally."""+ return bool(_TEST_QUERY_RE.search(query))+++def _is_test_page(item: dict) -> bool:+ """True when a hit is a file_page documenting a test file."""+ return item.get("page_type") == "file_page" and (+ _classify_hit_kind(item.get("target_path") or "", "file_page") == "test"+ )+++def _downweight_test_pages(output: list[dict], query: str) -> None:+ """Scale test file_page relevance in place unless the query is about tests."""+ if _is_test_query(query):+ return+ for item in output:+ if item.get("relevance_score") and _is_test_page(item):+ item["relevance_score"] = round(item["relevance_score"] * _TEST_DOWNWEIGHT, 4)+++def _sort_demoting_noise(output: list[dict], query: str) -> None:+ """Sort by relevance, ranking retrieval noise below every real page.++ Two classes crowd the top ranks on a plain implementation query and are+ demoted absolutely for their query class (the relevance score still orders+ each class among itself):++ - decision records — short dense titles win cosine similarity by a margin+ wider than the multiplicative down-weight (observed live as 5/5 irrelevant+ decisions for one query). Rationale questions are get_why's territory, so+ a why-shaped query ranks them naturally instead.+ - test file pages — a test is rarely a better first Read than the code it+ exercises. A query explicitly about tests ranks them naturally instead."""why = _is_why_shaped(query)+ test_focused = _is_test_query(query)def key(item: dict) -> tuple:- demoted = (not why) and item.get("page_type") == "decision_record"- return (1 if demoted else 0, -(item.get("relevance_score") or 0.0))+ pt = item.get("page_type")+ is_decision = (not why) and pt == "decision_record"+ is_test = (not test_focused) and _is_test_page(item)+ return (1 if (is_decision or is_test) else 0, -(item.get("relevance_score") or 0.0))output.sort(key=key)+def _norm_decision_title(title: str) -> str:+ """Normalize a decision title to collapse near-duplicate phrasings."""+ return re.sub(r"[^a-z0-9]+", " ", (title or "").lower()).strip()+++def _dedup_decisions(output: list[dict]) -> list[dict]:+ """Collapse near-duplicate decision records by normalized title (order-preserving).++ Live search returned five near-identical "CLI incremental update regenerates+ only affected pages" variants filling positions 3-8. Callers dedup AFTER the+ score sort, so the surviving variant is the highest-scored one; non-decision+ pages always pass through untouched.+ """+ seen: set[str] = set()+ out: list[dict] = []+ for item in output:+ if item.get("page_type") == "decision_record":+ key = _norm_decision_title(item.get("title", ""))+ if key and key in seen:+ continue+ seen.add(key)+ out.append(item)+ return out++async def _non_decision_fallback(ctx, query: str, fetch_limit: int) -> list[dict]:"""Wider re-fetch keeping only non-decision pages.@@ -441,11 +506,11 @@ async def _search_single_repo(_downweight_decisions(output, query)output = await _rescue_all_decision_window(ctx, output, query, fetch_limit)- # Attach target_path + deterministic markers and drop excluded hits per- # repo (so federated search honours each repo's own exclude_patterns)- # before ranking. Runs on the over-fetched list so the kind filter below- # has real headroom. Load precedes the sort so the decision demotion sees- # the page metadata it keys on.+ # Attach target_path and drop excluded hits per repo (so federated search+ # honours each repo's own exclude_patterns) before ranking. Runs on the+ # over-fetched list so the kind filter below has real headroom. Load+ # precedes the sort/demotion so they see the page metadata they key on+ # (test demotion needs target_path to classify a test file page).if output:async with get_session(ctx.session_factory) as session:page_info, tombstoned, _ = await _load_page_info(session, output)@@ -454,7 +519,9 @@ async def _search_single_repo(item["target_path"] = page_info.get(item["page_id"], "")output = filter_dicts_by_key(output, "target_path", _get_exclude_spec(ctx.path))- _sort_demoting_decisions(output, query)+ _downweight_test_pages(output, query)+ _sort_demoting_noise(output, query)+ output = _dedup_decisions(output)output = _filter_by_kind(output, kind)return output[:limit], method@@ -773,9 +840,12 @@ async def search_codebase(gm = git_map.get(target_path) if target_path else None_apply_freshness_boost(item, gm)- # Re-sort by adjusted relevance with decisions hard-demoted on non-why- # queries.- _sort_demoting_decisions(output, query)+ # Re-sort by adjusted relevance with retrieval noise (decisions on+ # non-why queries, test pages on non-test queries) hard-demoted, then+ # collapse near-duplicate decisions to one.+ _downweight_test_pages(output, query)+ _sort_demoting_noise(output, query)+ output = _dedup_decisions(output)output = _filter_by_kind(output, kind)output = output[:limit]diff --git a/tests/unit/server/mcp/test_answer_noise_demotion.py b/tests/unit/server/mcp/test_answer_noise_demotion.pynew file mode 100644index 000000000..ec6a8c090--- /dev/null+++ b/tests/unit/server/mcp/test_answer_noise_demotion.py@@ -0,0 +1,69 @@+"""Unit tests for get_answer's retrieval-noise demotion (_answer_pipeline).++get_answer historically applied no decision/test demotion of its own, so+decision records and test file pages could win RRF and occupy top-5 slots that+feed synthesis. ``demote_noise_hits`` stable-partitions that noise below real+pages before the cap. These are pure-function tests (no fixture, no DB).+"""++from __future__ import annotations++from repowise.server.mcp_server._answer_pipeline import demote_noise_hits+++def _hit(page_type, target_path, title="t"):+ return {"page_type": page_type, "target_path": target_path, "title": title}+++def test_decision_demoted_on_non_why_question():+ hits = [+ _hit("decision_record", ""),+ _hit("file_page", "src/pipeline/incremental.py"),+ ]+ out = demote_noise_hits(hits, "how does incremental update work", is_why=False)+ assert out[0]["target_path"] == "src/pipeline/incremental.py"+ assert out[1]["page_type"] == "decision_record" # demoted, not dropped+++def test_decision_kept_on_why_question():+ hits = [+ _hit("decision_record", ""),+ _hit("file_page", "src/pipeline/incremental.py"),+ ]+ out = demote_noise_hits(hits, "why does update only regenerate affected pages", is_why=True)+ assert out[0]["page_type"] == "decision_record" # ranked naturally on a why question+++def test_test_page_demoted_on_impl_question():+ hits = [+ _hit("file_page", "tests/unit/test_incremental.py"),+ _hit("file_page", "src/pipeline/incremental.py"),+ ]+ out = demote_noise_hits(hits, "how does incremental update work", is_why=False)+ assert out[0]["target_path"] == "src/pipeline/incremental.py"+ assert out[1]["target_path"] == "tests/unit/test_incremental.py" # demoted, not dropped+++def test_test_page_kept_on_test_question():+ hits = [+ _hit("file_page", "tests/unit/test_incremental.py"),+ _hit("file_page", "src/pipeline/incremental.py"),+ ]+ out = demote_noise_hits(hits, "how is incremental update tested", is_why=False)+ assert out[0]["target_path"] == "tests/unit/test_incremental.py" # test-focused: no demotion+++def test_stable_order_preserved_among_real_hits():+ hits = [+ _hit("file_page", "src/a.py"),+ _hit("decision_record", ""),+ _hit("file_page", "src/b.py"),+ _hit("module_page", "src/pkg"),+ ]+ out = demote_noise_hits(hits, "how does a work", is_why=False)+ # Real hits keep their relative order; the decision falls to the tail.+ assert [h.get("target_path") for h in out] == ["src/a.py", "src/b.py", "src/pkg", ""]+++def test_empty_hits_noop():+ assert demote_noise_hits([], "anything", is_why=False) == []diff --git a/tests/unit/server/mcp/test_search.py b/tests/unit/server/mcp/test_search.pyindex 7da3e167b..fca289c82 100644--- a/tests/unit/server/mcp/test_search.py+++ b/tests/unit/server/mcp/test_search.py@@ -45,6 +45,42 @@ def _mk_result(page_id, title, page_type, target_path, score):)+async def _seed_page(page_id, target_path, page_type="file_page"):+ """Insert a Page row into the setup_mcp DB so _load_page_info resolves its+ target_path. Reuses the seeded repository_id so the row is valid."""+ from datetime import UTC, datetime++ from sqlalchemy import select++ import repowise.server.mcp_server as mcp_mod+ from repowise.core.persistence.database import get_session+ from repowise.core.persistence.models import Page++ now = datetime(2026, 1, 1, tzinfo=UTC)+ async with get_session(mcp_mod._session_factory) as session:+ rid = (await session.execute(select(Page.repository_id).limit(1))).scalar()+ session.add(+ Page(+ id=page_id,+ repository_id=rid,+ page_type=page_type,+ title="Test Service",+ content="tests",+ target_path=target_path,+ source_hash="seed",+ model_name="mock",+ provider_name="mock",+ generation_level=2,+ confidence=0.5,+ freshness_status="fresh",+ metadata_json="{}",+ created_at=now,+ updated_at=now,+ )+ )+ await session.commit()++class TestDecisionDownweight:"""Decision records must not crowd file pages out of the top ranks."""@@ -182,6 +218,146 @@ class TestDecisionDownweight:assert [r["target_path"] for r in results] == ["src/auth/service.py"]+class TestNoiseDemotion:+ """Test file pages and near-duplicate decisions must not crowd the top ranks."""++ def test_is_test_query(self):+ from repowise.server.mcp_server.tool_search import _is_test_query++ assert _is_test_query("how is the auth service tested")+ assert _is_test_query("unit test for the parser")+ assert _is_test_query("where are the pytest fixtures")+ assert not _is_test_query("how does the auth service authenticate")+ assert not _is_test_query("where is the SQLite store")++ def test_is_test_page(self):+ from repowise.server.mcp_server.tool_search import _is_test_page++ assert _is_test_page({"page_type": "file_page", "target_path": "tests/unit/test_auth.py"})+ assert _is_test_page({"page_type": "file_page", "target_path": "src/auth/service_test.py"})+ assert not _is_test_page({"page_type": "file_page", "target_path": "src/auth/service.py"})+ # Only file pages classify as test pages, never decision/concept pages.+ assert not _is_test_page({"page_type": "decision_record", "target_path": ""})++ def test_downweight_test_pages_scales_unless_test_query(self):+ from repowise.server.mcp_server.tool_search import _downweight_test_pages++ rows = [+ {"page_type": "file_page", "target_path": "tests/test_x.py", "relevance_score": 1.0},+ {"page_type": "file_page", "target_path": "src/x.py", "relevance_score": 1.0},+ ]+ _downweight_test_pages(rows, "how does x work")+ assert rows[0]["relevance_score"] < 1.0 # test page scaled down+ assert rows[1]["relevance_score"] == 1.0 # impl page untouched++ rows2 = [+ {"page_type": "file_page", "target_path": "tests/test_x.py", "relevance_score": 1.0},+ ]+ _downweight_test_pages(rows2, "how is x tested")+ assert rows2[0]["relevance_score"] == 1.0 # test-focused query: no scaling++ def test_sort_demoting_noise_ranks_impl_over_test(self):+ from repowise.server.mcp_server.tool_search import _sort_demoting_noise++ rows = [+ {"page_type": "file_page", "target_path": "tests/test_x.py", "relevance_score": 0.9},+ {"page_type": "file_page", "target_path": "src/x.py", "relevance_score": 0.4},+ ]+ _sort_demoting_noise(rows, "how does x work")+ assert rows[0]["target_path"] == "src/x.py" # impl promoted over higher-scored test+ assert rows[1]["target_path"] == "tests/test_x.py"++ def test_dedup_decisions_collapses_near_duplicates(self):+ from repowise.server.mcp_server.tool_search import _dedup_decisions++ rows = [+ {+ "page_type": "decision_record",+ "title": "CLI incremental update regenerates only affected pages",+ "page_id": "d1",+ },+ {+ "page_type": "decision_record",+ "title": "CLI incremental update regenerates only affected pages.",+ "page_id": "d2",+ },+ {+ "page_type": "decision_record",+ "title": "CLI incremental-update regenerates only affected pages",+ "page_id": "d3",+ },+ {"page_type": "file_page", "title": "x", "page_id": "f1"},+ {"page_type": "decision_record", "title": "Use repo-local SQLite", "page_id": "d4"},+ ]+ out = _dedup_decisions(rows)+ ids = [r["page_id"] for r in out]+ assert ids == ["d1", "f1", "d4"] # three near-dups -> one; file + distinct decision kept++ @pytest.mark.asyncio+ async def test_impl_page_outranks_its_test_page(self, setup_mcp):+ # Wiring check: demotion runs AFTER target_path is attached, so a+ # higher-scored test page still falls below the impl file page. Uses the+ # pre-seeded src/auth/service.py plus a seeded test page so both page_ids+ # resolve a target_path in _load_page_info.+ import repowise.server.mcp_server as mcp_mod+ from repowise.server.mcp_server import search_codebase++ await _seed_page("file_page:tests/unit/test_service.py", "tests/unit/test_service.py")++ async def fake_search(query, limit=10):+ return [+ _mk_result(+ "file_page:tests/unit/test_service.py",+ "Test Service",+ "file_page",+ "tests/unit/test_service.py",+ 0.62,+ ),+ _mk_result(+ "file_page:src/auth/service.py",+ "Auth Service",+ "file_page",+ "src/auth/service.py",+ 0.41,+ ),+ ]++ mcp_mod._vector_store.search = fake_search+ result = await search_codebase("how does the auth service work")+ paths = [r["target_path"] for r in result["results"]]+ assert paths[0] == "src/auth/service.py"+ assert "tests/unit/test_service.py" in paths # demoted, not dropped++ @pytest.mark.asyncio+ async def test_test_query_keeps_test_page_ranking(self, setup_mcp):+ import repowise.server.mcp_server as mcp_mod+ from repowise.server.mcp_server import search_codebase++ await _seed_page("file_page:tests/unit/test_service.py", "tests/unit/test_service.py")++ async def fake_search(query, limit=10):+ return [+ _mk_result(+ "file_page:tests/unit/test_service.py",+ "Test Service",+ "file_page",+ "tests/unit/test_service.py",+ 0.62,+ ),+ _mk_result(+ "file_page:src/auth/service.py",+ "Auth Service",+ "file_page",+ "src/auth/service.py",+ 0.41,+ ),+ ]++ mcp_mod._vector_store.search = fake_search+ result = await search_codebase("how is the auth service tested")+ assert result["results"][0]["target_path"] == "tests/unit/test_service.py"++class TestClassifyHitKind:"""The ``kind`` filter's path heuristic."""@@ -489,12 +665,14 @@ class TestHybridInterleave:def test_no_exact_prose_query_leads_with_concepts(self):from repowise.server.mcp_server.tool_search import _interleave_hybrid- symbols = [self._sym("get", "a/registry.py", 43.8),- self._sym("get", "b/store.py", 43.7)]+ symbols = [self._sym("get", "a/registry.py", 43.8), self._sym("get", "b/store.py", 43.7)]concepts = [self._page("mcp/answer.py", 0.47)]out = _interleave_hybrid("how does retrieval feed synthesis in get_answer",- symbols, concepts, limit=5, exact=False,+ symbols,+ concepts,+ limit=5,+ exact=False,)assert out[0]["type"] == "page", "the answer.py page must lead, not fuzzy .get"# Nothing dropped - the fuzzy symbols still ride along at the tail.@@ -505,8 +683,9 @@ class TestHybridInterleave:symbols = [self._sym("get_answer", "mcp/answer.py", 143.0)]concepts = [self._page("mcp/other.py", 0.5)]- out = _interleave_hybrid("where is get_answer defined", symbols, concepts,- limit=5, exact=True)+ out = _interleave_hybrid(+ "where is get_answer defined", symbols, concepts, limit=5, exact=True+ )assert out[0]["type"] == "symbol"def test_symbol_heavy_query_keeps_symbols_first(self):@@ -515,16 +694,16 @@ class TestHybridInterleave:# Not prose-dominant, so default ordering even without an exact match.symbols = [self._sym("FooBar", "x.py", 40.0)]concepts = [self._page("y.py", 0.3)]- out = _interleave_hybrid("compare FooBar BazQux", symbols, concepts,- limit=5, exact=False)+ out = _interleave_hybrid("compare FooBar BazQux", symbols, concepts, limit=5, exact=False)assert out[0]["type"] == "symbol"def test_no_concepts_returns_symbols(self):from repowise.server.mcp_server.tool_search import _interleave_hybridsymbols = [self._sym("get", "a.py", 43.0)]- out = _interleave_hybrid("how does retrieval feed synthesis in get_answer",- symbols, [], limit=5, exact=False)+ out = _interleave_hybrid(+ "how does retrieval feed synthesis in get_answer", symbols, [], limit=5, exact=False+ )assert out == symbols