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(search): centre a hit's evidence snippet on what the query matched (#1191)
Swati Ahujad9548194b383
diff --git a/packages/core/src/repowise/core/persistence/search.py b/packages/core/src/repowise/core/persistence/search.pyindex de2035c56..dde84117e 100644--- a/packages/core/src/repowise/core/persistence/search.py+++ b/packages/core/src/repowise/core/persistence/search.py@@ -262,8 +262,41 @@ def _build_fts5_query(query: str, document_frequency: Callable[[str], int] | Nonreturn " OR ".join(_match_term(t) for t in kept)-def _snippet(content: str) -> str:- return content[:_SNIPPET_LEN].rstrip()+def snippet_around(content: str, query: str, length: int = _SNIPPET_LEN) -> str:+ """A window of *content* centred on the first term of *query* it carries.++ This string is a hit's evidence: ``search_codebase`` returns it as the+ reason the page is in the list, and the answer tool's coverage re-ranker+ reads it when ordering candidates. Taken from the front of the page it is+ the same ``## Overview`` opener on every generated page — identical across+ thousands of hits, and never the passage that matched.++ Terms are the ones :func:`_meaningful_terms` keeps, so a query made of+ common words cannot steer the window: matching on "the" would centre on+ the opener for almost every query and the window would buy nothing.++ Falls back to the opener when nothing matches, which is the right answer+ for a hit found by its title or its path — those carry no region of the+ content to point at. Never returns empty for a non-empty page.+ """+ if not content:+ return ""++ lowered = content.lower()+ position = -1+ for term in _meaningful_terms(query):+ found = lowered.find(term)+ if found != -1 and (position == -1 or found < position):+ position = found+ if position == -1:+ return content[:length].rstrip()++ # Centre the window, then slide it back inside the page rather than+ # letting it run off an edge: a match in the first or last few characters+ # would otherwise return a window shorter than the budget for no reason.+ start = max(0, position - length // 2)+ start = min(start, max(0, len(content) - length))+ return content[start : start + length].strip()class FullTextSearch:@@ -633,7 +666,7 @@ class FullTextSearch:page_type=page_type,target_path=target_path,score=score,- snippet=_snippet(content_by_id[pid]),+ snippet=snippet_around(content_by_id[pid], query),search_type="fulltext",))@@ -728,7 +761,7 @@ class FullTextSearch:page_type=r[3],target_path=r[4],score=float(r[5]),- snippet=_snippet(r[2]),+ snippet=snippet_around(r[2], query),search_type="fulltext",)for r in rawdiff --git a/packages/core/src/repowise/core/persistence/vector_store/lancedb_store.py b/packages/core/src/repowise/core/persistence/vector_store/lancedb_store.pyindex 609bd17b8..24e354653 100644--- a/packages/core/src/repowise/core/persistence/vector_store/lancedb_store.py+++ b/packages/core/src/repowise/core/persistence/vector_store/lancedb_store.py@@ -4,10 +4,39 @@ from __future__ import annotationsfrom repowise.core.providers.embedding.base import Embedder-from ..search import SearchResult+from ..search import _SNIPPET_LEN, SearchResult, snippet_aroundfrom ._base import VectorStore, iter_embed_chunks-__all__ = ["LanceDBVectorStore"]+__all__ = ["STORED_SNIPPET_CHARS", "LanceDBVectorStore"]++# How much of a page's content each row keeps.+#+# A hit's evidence snippet should show the region the query matched, not the+# page's opening line — on a generated page that opener is the same+# ``## Overview`` paragraph every time. The full-text arm holds the whole page+# at search time and can cut a window from it; this arm cannot, because what a+# search sees was fixed when the row was written. So the row keeps enough+# content for a window to exist inside it.+#+# It is a prefix, not the whole page: this column is read on the hot path and+# duplicated per row, and a match beyond the first few thousand characters is+# rare enough not to be worth the store. A row written before this widening+# holds 200 characters and simply windows to its opener.+STORED_SNIPPET_CHARS = 2_000+++def _evidence(stored: str, query: str | None) -> str:+ """The served snippet, cut from the wider text a row keeps.++ With a query, a window centred on what it matched. Without one — the raw+ vector path, which carries no question — the opener, at the width it had+ before the stored column was widened.+ """+ if not stored:+ return ""+ if query:+ return snippet_around(stored, query)+ return stored[:_SNIPPET_LEN].rstrip()def _paths_in_filter(paths: list[str]) -> str:@@ -137,7 +166,7 @@ class LanceDBVectorStore(VectorStore):"title": str(metadata.get("title", "")),"page_type": str(metadata.get("page_type", "")),"target_path": str(metadata.get("target_path", "")),- "content_snippet": content[:200],+ "content_snippet": content[:STORED_SNIPPET_CHARS],}async def _upsert_rows(self, rows: list[dict]) -> None:@@ -195,7 +224,9 @@ class LanceDBVectorStore(VectorStore):f"embed_batch: {failed}/{len(items)} items failed to embed") from last_exc- async def _search_by_vector(self, q_vec: list[float], limit: int) -> list[SearchResult]:+ async def _search_by_vector(+ self, q_vec: list[float], limit: int, query: str | None = None+ ) -> list[SearchResult]:# Query with explicit cosine distance so ``_distance`` is a cosine# distance (1 - cos); we return ``1 - _distance`` = cosine similarity.# This makes the score semantics match the other backends@@ -206,6 +237,10 @@ class LanceDBVectorStore(VectorStore):query_builder = query_builder.distance_type("cosine")raw = await query_builder.limit(limit).to_list()+ # A caller that came in by raw vector has no query text to centre on,+ # so it gets the opener — at the width it always had. The stored+ # column is now wider than the snippet it serves, and returning it+ # whole would push ten times the text into a prompt.return [SearchResult(page_id=r["page_id"],@@ -213,7 +248,7 @@ class LanceDBVectorStore(VectorStore):page_type=r.get("page_type", ""),target_path=r.get("target_path", ""),score=1.0 - float(r.get("_distance", 1.0)),- snippet=r.get("content_snippet", ""),+ snippet=_evidence(r.get("content_snippet", ""), query),search_type="vector",)for r in raw@@ -237,7 +272,7 @@ class LanceDBVectorStore(VectorStore):return []q_vecs = await self._embedder.embed([query])- return await self._search_by_vector([float(v) for v in q_vecs[0]], limit)+ return await self._search_by_vector([float(v) for v in q_vecs[0]], limit, query=query)async def search_by_vector(self, vector: list[float], limit: int = 10) -> list[SearchResult]:await self._ensure_connected()@@ -254,9 +289,11 @@ class LanceDBVectorStore(VectorStore):return [[] for _ in queries]q_vecs = await self._embedder.embed(list(queries))out: list[list[SearchResult]] = []- for q_vec in q_vecs:+ for query, q_vec in zip(queries, q_vecs, strict=True):try:- out.append(await self._search_by_vector([float(v) for v in q_vec], limit))+ out.append(+ await self._search_by_vector([float(v) for v in q_vec], limit, query=query)+ )except Exception:out.append([])return out@@ -293,9 +330,11 @@ class LanceDBVectorStore(VectorStore):async def get_page_summary_by_path(self, path: str) -> dict | None:"""Return {'summary': str, 'key_exports': list[str]} for a previously-indexed page, or None.- LanceDB stores up to 200 chars of content in 'content_snippet'; we use- that as the summary. 'key_exports' is not stored in the schema, so we- return [] — the caller only uses the text summary for prompt injection.+ The summary is the opening of 'content_snippet'. That column holds more+ than this now, because a search cuts an evidence window out of it, but+ this text goes into a prompt — so it keeps the width it always had+ rather than growing with the store behind it. 'key_exports' is not in+ the schema, so it comes back empty; the caller only uses the summary."""await self._ensure_connected()if self._table is None:@@ -316,8 +355,8 @@ class LanceDBVectorStore(VectorStore):if not rows:return None- summary = rows[0].get("content_snippet") or ""- return {"summary": str(summary), "key_exports": []}+ summary = str(rows[0].get("content_snippet") or "")[:_SNIPPET_LEN]+ return {"summary": summary, "key_exports": []}async def get_page_summaries_by_paths(self, paths: list[str]) -> dict[str, dict]:"""One ``IN``-filtered scan instead of one filtered query per path.@@ -346,7 +385,7 @@ class LanceDBVectorStore(VectorStore):tp = str(r.get("target_path") or "")if not tp or tp in out:continue- summary = r.get("content_snippet") or ""+ summary = str(r.get("content_snippet") or "")[:_SNIPPET_LEN]if summary:- out[tp] = {"summary": str(summary), "key_exports": []}+ out[tp] = {"summary": summary, "key_exports": []}return outdiff --git a/tests/unit/persistence/test_evidence_snippet.py b/tests/unit/persistence/test_evidence_snippet.pynew file mode 100644index 000000000..7d78843f3--- /dev/null+++ b/tests/unit/persistence/test_evidence_snippet.py@@ -0,0 +1,121 @@+"""The evidence snippet shows the part of the page the query matched.++``search_codebase`` puts this string in front of the caller as its reason for+returning a hit, and the answer tool's coverage re-ranker reads it when+ordering candidates. Both were being handed the first 200 characters of the+page, which on a generated page is the same ``## Overview`` opener every time —+identical across thousands of hits, and never the passage that matched.++A window centred on the match says why the page is here. The opener remains+the fallback, because a hit with no matching term still has to show something.+"""++from __future__ import annotations++import pytest++from repowise.core.persistence.search import FullTextSearch, snippet_around++_OPENER = "## Overview\n\nThis module is part of the indexing pipeline. " + "Filler. " * 40+_MATCH = "The walker refuses to descend into a nested git checkout."+_TAIL = " Trailing prose. " * 40+++async def fts(async_engine):+ fs = FullTextSearch(async_engine)+ await fs.ensure_index()+ return fs+++class TestSnippetAround:+ def test_a_matching_term_centres_the_window(self):+ content = _OPENER + _MATCH + _TAIL++ window = snippet_around(content, "nested git checkout")++ assert "nested git checkout" in window+ assert not window.startswith("## Overview")++ def test_no_match_falls_back_to_the_opener(self):+ """A hit with no matching term still has to show something."""+ content = _OPENER + _MATCH++ window = snippet_around(content, "xylophone tuning")++ assert window.startswith("## Overview")++ def test_an_empty_query_falls_back_to_the_opener(self):+ content = _OPENER + _MATCH+ assert snippet_around(content, "").startswith("## Overview")++ def test_the_window_is_capped(self):+ content = _OPENER + _MATCH + _TAIL+ assert len(snippet_around(content, "nested")) <= 200++ def test_a_short_page_is_returned_whole(self):+ assert snippet_around("Tiny page about walkers.", "walkers") == "Tiny page about walkers."++ def test_an_empty_page_returns_empty(self):+ assert snippet_around("", "walkers") == ""++ def test_a_match_near_the_start_does_not_produce_a_short_window(self):+ """Centring must not run off the front and truncate the window."""+ content = "The walker stops here. " + _TAIL++ window = snippet_around(content, "walker")++ assert "walker" in window+ assert len(window) > 150++ def test_a_match_near_the_end_does_not_produce_a_short_window(self):+ content = _TAIL + "The walker stops here."++ window = snippet_around(content, "walker")++ assert "walker" in window+ assert len(window) > 150++ def test_matching_is_case_insensitive(self):+ content = _OPENER + "The WALKER refuses to descend." + _TAIL+ assert "WALKER" in snippet_around(content, "walker")++ def test_a_stop_word_alone_does_not_steer_the_window(self):+ """ "the" appears in the opener; it must not count as a match.++ Otherwise every query containing a common word centres on the opener+ and the change buys nothing.+ """+ content = _OPENER + _MATCH + _TAIL+ assert snippet_around(content, "the").startswith("## Overview")+++class TestFullTextSnippet:+ async def test_a_full_text_hit_shows_the_matching_region(self, fts):+ await fts.index(+ "p1",+ "File: walker.py",+ _OPENER + _MATCH + _TAIL,+ summary="Walks the tree.",+ target_path="src/walker.py",+ )++ results = await fts.search("nested git checkout")++ assert len(results) == 1+ assert "nested git checkout" in results[0].snippet++ async def test_a_hit_matched_only_by_its_path_shows_the_opener(self, fts):+ """The window comes from the content, so a path-only match has none."""+ await fts.index(+ "p1",+ "Walker",+ _OPENER,+ summary="Walks the tree.",+ target_path="src/telemetry/collector.py",+ )++ results = await fts.search("telemetry collector")++ assert len(results) == 1+ assert results[0].snippet.startswith("## Overview")diff --git a/tests/unit/persistence/test_vector_evidence_snippet.py b/tests/unit/persistence/test_vector_evidence_snippet.pynew file mode 100644index 000000000..911903cb1--- /dev/null+++ b/tests/unit/persistence/test_vector_evidence_snippet.py@@ -0,0 +1,116 @@+"""The vector arm's evidence snippet, and the field it is cut from.++The full-text arm holds the page content at search time and can window it. The+vector arm cannot: LanceDB stores a fixed prefix of the content at index time+and that is all a search has to work with. So the stored prefix has to be wide+enough for a window to be cut out of it.++Two other readers of the same column use it as a short prompt summary and must+keep the size they had — widening the store must not widen a prompt.+"""++from __future__ import annotations++import pytest++from repowise.core.persistence.search import _SNIPPET_LEN+from repowise.core.persistence.vector_store.lancedb_store import (+ STORED_SNIPPET_CHARS,+ LanceDBVectorStore,+)+from repowise.core.providers.embedding.base import MockEmbedder++_OPENER = "## Overview\n\nThis module is part of the indexing pipeline. " + "Filler. " * 60+_MATCH = "The walker refuses to descend into a nested git checkout."+++async def store(tmp_path):+ st = LanceDBVectorStore(db_path=str(tmp_path / "lancedb"), embedder=MockEmbedder())+ yield st+++def _page(content: str) -> dict:+ return {+ "title": "File: walker.py",+ "page_type": "file_page",+ "target_path": "src/walker.py",+ "content": content,+ }+++class TestStoredWidth:+ def test_the_stored_prefix_is_wider_than_the_snippet_it_serves(self):+ """A window can only be cut from text the store actually kept."""+ assert STORED_SNIPPET_CHARS > _SNIPPET_LEN++ async def test_a_long_page_is_stored_up_to_the_cap(self, store):+ content = _OPENER + _MATCH + " tail " * 1000++ await store.embed_and_upsert("p1", content, _page(content))+ rows = await store._table.query().select(["content_snippet"]).to_list()++ assert len(rows[0]["content_snippet"]) == STORED_SNIPPET_CHARS++ async def test_a_page_shorter_than_the_cap_is_stored_whole(self, store):+ content = _OPENER + _MATCH+ assert len(content) < STORED_SNIPPET_CHARS++ await store.embed_and_upsert("p1", content, _page(content))+ rows = await store._table.query().select(["content_snippet"]).to_list()++ assert rows[0]["content_snippet"] == content+++class TestSearchSnippet:+ async def test_a_query_carrying_search_centres_the_snippet(self, store):+ content = _OPENER + _MATCH+ await store.embed_and_upsert("p1", content, _page(content))++ results = await store.search("nested git checkout", limit=5)++ assert "nested git checkout" in results[0].snippet+ assert len(results[0].snippet) <= _SNIPPET_LEN++ async def test_no_match_falls_back_to_the_opener(self, store):+ content = _OPENER + _MATCH+ await store.embed_and_upsert("p1", content, _page(content))++ results = await store.search("xylophone tuning", limit=5)++ assert results[0].snippet.startswith("## Overview")++ async def test_searching_by_raw_vector_serves_the_opener_at_the_old_size(self, store):+ """That path has no query text, so there is nothing to centre on.++ It must not start returning the whole stored prefix instead — this is+ what the answer pipeline calls, and the snippet reaches a prompt.+ """+ content = _OPENER + _MATCH+ await store.embed_and_upsert("p1", content, _page(content))+ vector = (await store._embedder.embed(["anything"]))[0]++ results = await store.search_by_vector([float(v) for v in vector], limit=5)++ assert len(results[0].snippet) <= _SNIPPET_LEN+ assert results[0].snippet.startswith("## Overview")+++class TestPromptSummariesKeepTheirSize:+ """The prompt-injection readers of this column must not grow with it."""++ async def test_summary_by_path_stays_at_the_old_width(self, store):+ content = _OPENER + _MATCH+ await store.embed_and_upsert("p1", content, _page(content))++ found = await store.get_page_summary_by_path("src/walker.py")++ assert len(found["summary"]) <= _SNIPPET_LEN++ async def test_summaries_by_paths_stay_at_the_old_width(self, store):+ content = _OPENER + _MATCH+ await store.embed_and_upsert("p1", content, _page(content))++ found = await store.get_page_summaries_by_paths(["src/walker.py"])++ assert len(found["src/walker.py"]["summary"]) <= _SNIPPET_LEN