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): rank get_why by question vocabulary, and redirect when nothing matches (#1558)
Raghav Chamadiya2764ecadb75d
diff --git a/packages/core/src/repowise/core/exclusion.py b/packages/core/src/repowise/core/exclusion.pyindex e4c83e972..779df9a9f 100644--- a/packages/core/src/repowise/core/exclusion.py+++ b/packages/core/src/repowise/core/exclusion.py@@ -139,9 +139,21 @@ def decision_is_excluded(decision_row: Any, spec: Any) -> bool:one with no affected files at all is kept (nothing to judge it by).Paths are normalized to forward slashes — ``affected_files_json`` storesOS-native separators.++ Confirmed records are exempt. The file list is where an extractor *read* a+ decision, not what makes it true, and once a human has marked one ``active``+ that provenance has been superseded by their judgement. Measured on this+ repo: all 18 records this rule dropped were ``active``, a quarter of the+ confirmed corpus, and they included both records answering "why ruff check+ and not ruff format" — a rule so plainly repo-wide that it had been written+ into CLAUDE.md by hand while the store already held it. What the rule is+ aimed at is unreviewed machine output from a tree the user said to ignore,+ and that is exactly what ``proposed`` marks."""if spec is None:return False+ if getattr(decision_row, "status", None) == "active":+ return Falsetry:affected = json.loads(getattr(decision_row, "affected_files_json", None) or "[]")except (ValueError, TypeError):diff --git a/packages/server/src/repowise/server/mcp_server/_why_relevance.py b/packages/server/src/repowise/server/mcp_server/_why_relevance.pynew file mode 100644index 000000000..20377a118--- /dev/null+++ b/packages/server/src/repowise/server/mcp_server/_why_relevance.py@@ -0,0 +1,198 @@+"""How relevant a decision record is to a question, and what to say when none is.++Split out of ``tool_why`` because these are the two halves of one judgement —+what to rank first, and when to serve nothing — and both are worth testing+without standing up a repo context.++The scoring problem this solves is specific. ``_score_decision`` adds a weight+per (field, word) hit, so a record is rewarded for saying an ordinary word in+many fields and for being long enough to contain many ordinary words. Measured+on this repo's 614 records: the question "why do we use ruff check instead of+ruff format" is answered by two ``active`` records titled "Never run ruff+format" and "Avoid formatting with ruff", and both lost to records matching+"use", "check", "format" and "instead" while containing no "ruff" at all. One of+the two answers is 48 characters long; under an occurrence count it cannot win+anything.+"""++from __future__ import annotations++import math+from typing import Any++from repowise.server.mcp_server._query_terms import content_terms++#: Weighted share of a question's vocabulary a record must carry to be served.+#:+#: Calibrated on a twenty-question set built before this constant existed, half+#: of it questions this store cannot answer, and swept rather than fitted. Every+#: value from 0.55 to 0.65 served the right record for all twelve answerable+#: questions; the first correct answer is suppressed at 0.70, and by 0.85 five+#: of the twelve are. Refusals move the other way — five of eight unanswerable+#: questions at 0.60, six at 0.65, seven at 0.75.+#:+#: This is the middle of the range where nothing correct is lost, rather than+#: its top. The top would score one refusal better and sit 0.03 from the lowest+#: real answer measured, which is a boundary fitted to one question rather than+#: a threshold. The two errors are not symmetric either: an over-served response+#: costs an agent one padded read, while a suppressed answer costs it the tool.+RELEVANCE_FLOOR = 0.6+++def question_terms(query: str) -> list[str]:+ """Content words of *query*, singularised and deduplicated, longest first."""+ seen: dict[str, None] = {}+ for t in content_terms(query):+ seen.setdefault(stem(t), None)+ return list(seen)+++def stem(term: str) -> str:+ """``comments`` -> ``comment``. A trailing plural and nothing more.++ Deliberately the crudest rule that fixes the case it was written for. The+ question "why must issue comments avoid em dashes" is answered by a record+ titled "Close issues and comment with short, simple text (no em dashes)",+ and it was refused because ``comments`` — the rarest word in the question,+ so the one carrying most of its weight — does not occur in a record that+ writes ``comment``.++ Applied to the question and to nothing else, which is why over-stripping is+ the safe direction and under-stripping is not: presence is a substring test,+ so a record writing ``comments`` still contains ``comment``, and ``status``+ reduced to ``statu`` still matches both ``status`` and ``statuses``. Words+ ending ``-ies`` are left whole for the same reason — turning ``queries``+ into ``query`` would stop it matching a record that writes ``queries``.++ Ceiling: English regular plurals. The upgrade path is a real stemmer, which+ is a dependency this earns only once misses appear that a trailing ``s``+ does not explain.+ """+ if term.endswith(("ies", "ss")):+ return term+ # ``-es`` only after the letters that require it: dashes -> dash, boxes ->+ # box, classes -> class. Stripping it unconditionally turned ``files`` into+ # ``fil``, which then matched ``filter`` and ``profile`` and made the+ # question's most ordinary word look like its rarest.+ if len(term) > 4 and term.endswith(("ches", "shes", "sses", "xes", "zes", "ses")):+ return term[:-2]+ if len(term) > 3 and term.endswith("s"):+ return term[:-1]+ return term+++def term_idf(terms: list[str], corpus: list[str]) -> dict[str, float]:+ """``{term: weight}``, rarer terms weighing more, from *corpus* itself.++ A count of distinct terms present is the shape the sibling episode ranker+ established (see ``precedent.store.search``), and there BM25 supplies the+ rarity half. There is no BM25 here — the decision table is not an FTS index+ — so the weight is computed directly, over the records being ranked.++ This is not the document-frequency *ceiling* that was tried on session+ bodies and measured worse. That one dropped a term outright once it appeared+ in enough documents, which is a threshold fitted to a corpus's vocabulary.+ This is the continuous weight BM25 already applies, derived per call from+ the records in hand, and it fits no constant to anything.++ The expression is BM25's own, ``1 +`` included, and that guard is load+ bearing at the small end rather than the large one: plain ``log(N/df)``+ gives a term appearing in every record a weight of exactly zero, so on a+ store of three records all about one subsystem a question naming that+ subsystem would score its own answer at nothing and the tool would refuse+ itself. A gentler smoothing was tried first and compressed the range too+ far — on a seven-record store the word appearing once outweighed the word+ appearing seven times by only two to one, which was not enough for a terse+ record carrying the rare word to beat a long one carrying four ordinary+ ones.++ A word no record contains is weighted as if exactly one did. Absence is the+ strongest refusal signal there is — "vue", "candidacy" and "episode" are+ what make three of this store's unanswerable questions unanswerable — so+ dropping such words costs most of it: measured, refusals fell from five of+ eight to two of eight. But an unearnable weight left uncapped can put the+ floor out of reach of every record, and did: on a two-record store, "why is+ JWT used for authentication" scored the record titled "Use JWT for+ authentication" at 0.44, because "used" appears in neither record and, being+ unseen, outweighed both words that identify the answer. Capping at the+ rarest weight the store could actually award says what absence knows without+ claiming more than the corpus can support.+ """+ n = len(corpus)+ idf: dict[str, float] = {}+ for t in terms:+ df = sum(1 for text in corpus if t in text) or 1+ idf[t] = math.log(1 + (n - df + 0.5) / (df + 0.5))+ return idf+++def relevance(text: str, idf: dict[str, float]) -> float:+ """Share of the question's *weight* that *text* carries, 0.0 to 1.0.++ Distinct terms only: a record repeating one word forty times is not more+ relevant than one answering the whole question, which is the failure the+ occurrence count had.+ """+ total = sum(idf.values())+ if total <= 0:+ return 0.0+ return sum(w for t, w in idf.items() if t in text) / total+++def clears_floor(score: float) -> bool:+ """Whether a record is relevant enough to serve.++ One threshold and nothing beside it. A rescue for records carrying the+ question's rarest word alone was written first, for the case of a+ 48-character record too terse to cover anything else — and then measured+ inert: presence is a substring test, so ``break`` is carried by+ "KV-cache-breaking" and the rescue admitted whatever the floor rejected,+ flat across every threshold from 0.55 to 0.85. Singularising the question+ (:func:`stem`) turned out to be what those cases actually needed.+ """+ return score >= RELEVANCE_FLOOR+++# --- Redirect ---------------------------------------------------------------+#+# What to return when nothing clears the floor. The premise of the whole tool is+# that a long low-relevance answer is worse than no answer: an agent that reads+# three unrelated records concludes the tool is not worth calling and greps for+# the rest of the session. So this names the tool that *can* answer, and says in+# one sentence why this one did not.+#+# It fires only when the floor is missed. Stapling it to a good answer as a+# hedge trains the same distrust from the other direction.++_RISK_MARKERS = ("break", "impact of changing", "safe to change", "blast radius")+_CONTEXT_MARKERS = ("file", "module", "package", "class", "function", "directory")+++def redirect_for(query: str) -> dict[str, Any]:+ """``{"try_instead": [...], "reason": ...}`` for a question with no record.++ Routed on the question's shape rather than its subject, because the subject+ is exactly what this store was just found to know nothing about.+ """+ q = query.lower().strip()++ if any(m in q for m in _RISK_MARKERS):+ tools = ["get_risk"]+ elif q.startswith(("what is", "what are", "what does", "what's")) and any(+ m in q for m in _CONTEXT_MARKERS+ ):+ tools = ["get_context"]+ elif q.startswith(("how ", "where ")):+ tools = ["get_answer", "search_codebase"]+ else:+ # A "why" with no record behind it is still a question about the code,+ # and get_answer reads the code rather than the decision store.+ tools = ["get_answer"]++ return {+ "try_instead": tools,+ "reason": (+ "No decision record covers this question. The store holds none "+ "carrying its terms, and the closest ones would be noise."+ ),+ }diff --git a/packages/server/src/repowise/server/mcp_server/tool_why.py b/packages/server/src/repowise/server/mcp_server/tool_why.pyindex 5f111f6dc..4bb4cd4e4 100644--- a/packages/server/src/repowise/server/mcp_server/tool_why.py+++ b/packages/server/src/repowise/server/mcp_server/tool_why.py@@ -38,6 +38,13 @@ from repowise.server.mcp_server._helpers import (is_excluded,)from repowise.server.mcp_server._meta import build_meta as _build_meta+from repowise.server.mcp_server._why_relevance import (+ clears_floor,+ question_terms,+ redirect_for,+ relevance,+ term_idf,+)@mcp.tool()@@ -222,6 +229,16 @@ _MAX_SEARCH_DECISIONS = 3#: so the depth is the old decision lane's rather than the sum of the two._SEMANTIC_WINDOW = 50+#: Records search mode ranks over. It used to be 200, against a store holding+#: 614: ``list_decisions`` sorts confirmed-then-confident, so the 414 records+#: below the cut were unreachable by any question, and the cap was a silent+#: recall ceiling rather than a cost control. It is not a cost control either —+#: ranking is a substring scan over short fields, measured at 2 ms for 182+#: records here, so the whole store costs single-digit milliseconds. Kept+#: bounded only so an unattended extractor cannot turn one call into an+#: unbounded scan.+_DECISION_CORPUS_LIMIT = 2000+#: Keyword candidates scored before restatements are collapsed. Wider than the#: serving cap on purpose: the worst cluster here is fourteen phrasings of one#: decision, so a pool cut to three first would serve one decision three times.@@ -487,29 +504,6 @@ async def _why_path(query: str, repo: str | None) -> dict:return _fit_path_response(result_data, ctx.path, collector=collector)-# Stop words removed before keyword matching for better signal.-_QUERY_STOP_WORDS = {- "why",- "was",- "is",- "the",- "a",- "an",- "this",- "that",- "how",- "what",- "when",- "where",- "for",- "to",- "of",- "in",- "it",- "be",-}--async def _load_target_git(session: Any, repository_id: Any, targets: list[str] | None) -> dict[str, Any]:@@ -530,29 +524,62 @@ async def _load_target_git(return target_git+def _governs_any(d: Any, targets: set[str]) -> bool:+ """Whether *d* names any of *targets* among its files or modules."""+ if not targets:+ return False+ affected = set(json.loads(d.affected_files_json))+ modules = json.loads(d.affected_modules_json)+ return any(t in affected or any(t.startswith(m + "/") for m in modules) for t in targets)++def _rank_keyword_matches(all_decisions: list, query: str, target_set: set[str]) -> list:- """Score decisions by weighted keyword overlap, best-first.-- Score first, then status: a record someone confirmed wins a tie against one- an extractor proposed, but never outranks a better-matching record. Ordering- by status *first* was tried and measured worse, and the reason generalises —- only 69 of this repo's 614 records are active, so a hard status gate serves- three weakly-matching confirmed records ahead of the only relevant ones. The- four records that answer "why is entry-point candidacy decided at ingestion"- are all proposed, and status-first ordering made them unreachable.-- Returns a pool wider than the serving cap because restatements are collapsed- downstream, and a pool cut to the cap first would let three phrasings of one- decision fill every slot.+ """Records relevant enough to serve, best-first. Empty when none are.++ Ranks by how much of the question's *vocabulary* a record carries, rarer+ words weighing more, with the older occurrence count breaking ties and+ status breaking the ties after that. Ordering by the occurrence count alone+ scored by length and by how ordinary a word is: measured here, "why do we+ use ruff check instead of ruff format" was won by records matching "use",+ "check", "format" and "instead" while the two ``active`` records that answer+ it — one of them 48 characters long — did not place at all.++ Status stays a tie-break and never a gate. Ordering by it *first* was tried+ and measured worse, and the reason generalises: only 69 of this repo's 614+ records are active, so a hard status gate serves three weakly-matching+ confirmed records ahead of the only relevant ones. The four records that+ answer "why is entry-point candidacy decided at ingestion" are all proposed,+ and status-first ordering made them unreachable.++ Records below the floor are dropped rather than ranked last, so an empty+ return is the honest answer and the caller turns it into a redirect. The+ surviving pool is wider than the serving cap because restatements are+ collapsed downstream, and a pool cut to the cap first would let three+ phrasings of one decision fill every slot."""- query_words = set(query.lower().split()) - _QUERY_STOP_WORDS- scored_decisions: list[tuple[float, int, Any]] = []+ terms = question_terms(query)+ texts = {id(d): _record_text(d) for d in all_decisions}+ idf = term_idf(terms, list(texts.values()))++ scored_decisions: list[tuple[float, float, int, Any]] = []for d in all_decisions:- score = _score_decision(d, query_words, target_set)- if score > 0:- scored_decisions.append((-score, _PATH_STATUS_ORDER.get(d.status, 4), d))- scored_decisions.sort(key=lambda t: (t[0], t[1]))- return [d for _, _, d in scored_decisions[:_KEYWORD_POOL]]+ # A record governing a file the caller named is relevant by+ # construction: they pointed at it instead of describing it, so it owes+ # the question no vocabulary.+ governs = _governs_any(d, target_set)+ score = 1.0 if governs else relevance(texts[id(d)], idf)+ if not clears_floor(score):+ continue+ scored_decisions.append(+ (+ -score,+ -_score_decision(d, set(terms), target_set),+ _PATH_STATUS_ORDER.get(d.status, 4),+ d,+ )+ )+ scored_decisions.sort(key=lambda t: (t[0], t[1], t[2]))+ return [t[3] for t in scored_decisions[:_KEYWORD_POOL]]async def _fts_doc_results(ctx: Any, query: str) -> list:@@ -773,6 +800,50 @@ async def _build_target_context(return target_context+async def _why_no_match(+ query: str,+ targets: list[str] | None,+ ctx: Any,+ repository: Any,+ all_decisions: list,+ target_git: dict[str, Any],+) -> dict[str, Any]:+ """The whole response when no record clears the relevance floor.++ Returns early rather than serving the closest three anyway, and returns+ *before* the semantic lookup: a nearest-neighbour search over a 614-record+ store always returns three records, and on the questions this store cannot+ answer those were "14-language AST support" for "where is the episode store"+ and "Escape LIKE patterns" for "why is entry-point candidacy decided at+ ingestion". Serving them beside a redirect would be the padding the redirect+ exists to stop, and skipping the lookup is also the latency this branch+ saves. Episodes are held back for the same reason — they are what made the+ unanswerable questions the *largest* responses in the measured set.++ Named targets are the exception, and both blocks they carry are kept. A+ caller who passes them has handed over a concrete handle, so this file's+ git archaeology and this file's rationale comments are evidence about the+ thing asked rather than the nearest guess at it — the same reason path mode+ serves them. That is also the branch the redirect is *least* useful on,+ since `get_why` on a path is the tool the caller already reached for.+ """+ result: dict[str, Any] = {+ "mode": "search",+ "query": query,+ "decisions": [],+ **redirect_for(query),+ }+ if targets:+ result["target_context"] = await _build_target_context(+ ctx, repository, all_decisions, target_git, targets+ )+ rationale = _mine_rationale(ctx.path, targets, query)+ if rationale:+ result["code_rationale"] = rationale+ result["_meta"] = _build_meta(repository=repository, targets=targets if targets else None)+ return result++async def _why_search(query: str, targets: list[str] | None, repo: str | None) -> dict:"""Mode 3: natural-language, target-aware decision + documentation search."""from repowise.core.persistence.crud import list_decisions as _list_decisions@@ -781,7 +852,7 @@ async def _why_search(query: str, targets: list[str] | None, repo: str | None) -async with get_session(ctx.session_factory) as session:repository = await _get_repo(session)all_decisions = await _list_decisions(- session, repository.id, include_proposed=True, limit=200+ session, repository.id, include_proposed=True, limit=_DECISION_CORPUS_LIMIT)# Records anchored entirely in excluded paths (vendored venvs mined# before exclude rules changed) are noise for every mode downstream.@@ -794,6 +865,10 @@ async def _why_search(query: str, targets: list[str] | None, repo: str | None) -# Rank wide, collapse restatements, then cap — so the cap spends its slots on# distinct decisions — and only walk lineage for what survives.ranked = _rank_keyword_matches(all_decisions, query, target_set)+ if not ranked:+ return await _why_no_match(+ query, targets, ctx, repository, all_decisions, target_git+ )collapsed = _collapse_restatements(ranked)[:_MAX_SEARCH_DECISIONS]decision_results, doc_results = await _semantic_lanes(ctx, query)lineage_by_id = await _lineage_for_matches(ctx, [d for d, _ in collapsed])@@ -824,12 +899,9 @@ async def _why_search(query: str, targets: list[str] | None, repo: str | None) -result_data["target_context"] = await _build_target_context(ctx, repository, all_decisions, target_git, targets)- # When the decision corpus is thin, the rationale for the anchored- # files may be in their comments — mine them against the question.- if not merged_decisions:- rationale = _mine_rationale(ctx.path, targets, query)- if rationale:- result_data["code_rationale"] = rationale+ # The comment-mining fallback that used to sit here was gated on+ # ``not merged_decisions``, which nothing ever reached. It now lives in+ # ``_why_no_match``, behind the floor — the condition it always meant.# Targets resolve through the node index; without them the question itself# is the only handle, so it is ranked against the bodies.@@ -860,26 +932,20 @@ async def _why_search(query: str, targets: list[str] | None, repo: str | None) -return result_data-def _score_decision(- d: Any,- query_words: set[str],- target_files: set[str],-) -> float:- """Score a decision against query words with field weighting and target boosting."""- if not query_words:- return 1.0 if target_files else 0.0+def _weighted_fields(d: Any) -> list[tuple[float, str]]:+ """The searchable text of a record, lowercased, by field weight.- # Build weighted text fields.- #- # ``affected_files`` is deliberately absent. Joining a record's whole path- # list into one haystack and substring-matching a question against it scores- # by *breadth*: the record here governing 83 files matched almost every- # question asked, because ordinary query words ("index", "page", "format")- # occur somewhere in 83 paths, and it became the top hit for three of five- # probe questions including one about ruff. A scope is not question text.- # The legitimate use of that field — does this record govern the file the- # caller named — is the exact set membership in the target boost below.- fields = [+ ``affected_files`` is deliberately absent. Joining a record's whole path+ list into one haystack and substring-matching a question against it scores+ by *breadth*: the record here governing 83 files matched almost every+ question asked, because ordinary query words ("index", "page", "format")+ occur somewhere in 83 paths, and it became the top hit for three of five+ probe questions including one about ruff. A scope is not question text.+ The legitimate use of that field — does this record govern the file the+ caller named — is the exact set membership in :func:`_governs_any` and in+ the target boost inside :func:`_score_decision`.+ """+ return [(3.0, d.title.lower()),(2.0, d.decision.lower()),(2.0, d.rationale.lower()),@@ -889,8 +955,27 @@ def _score_decision((1.0, (d.evidence_file or "").lower()),]++def _record_text(d: Any) -> str:+ """The same text, unweighted, for term coverage and the relevance floor.++ Built from :func:`_weighted_fields` so a record cannot clear the floor on a+ field the tie-break cannot see, or the reverse.+ """+ return " ".join(text for _, text in _weighted_fields(d))+++def _score_decision(+ d: Any,+ query_words: set[str],+ target_files: set[str],+) -> float:+ """Score a decision against query words with field weighting and target boosting."""+ if not query_words:+ return 1.0 if target_files else 0.0+score = 0.0- for weight, text in fields:+ for weight, text in _weighted_fields(d):for word in query_words:if word in text:score += weightdiff --git a/tests/unit/server/mcp/test_decision_hygiene.py b/tests/unit/server/mcp/test_decision_hygiene.pyindex 2c2817ee4..b366346aa 100644--- a/tests/unit/server/mcp/test_decision_hygiene.py+++ b/tests/unit/server/mcp/test_decision_hygiene.py@@ -17,12 +17,29 @@ from repowise.server.mcp_server._helpers import decision_is_excluded_SPEC = pathspec.PathSpec.from_lines("gitwildmatch", ["research/", "*.lock"])-def _decision(affected: list[str] | None):+def _decision(affected: list[str] | None, status: str = "proposed"):return types.SimpleNamespace(- affected_files_json=json.dumps(affected) if affected is not None else None+ affected_files_json=json.dumps(affected) if affected is not None else None,+ status=status,)+def test_a_confirmed_record_is_never_junk():+ """The file list says where a decision was read, not what makes it true.++ Measured on the dogfooded repo: all 18 records this rule dropped were+ ``active``, a quarter of the confirmed corpus, and among them were both+ records answering "why ruff check and not ruff format" — mined from a+ local-only notes tree, and so plainly repo-wide that the same rule had been+ written into CLAUDE.md by hand. What the rule is aimed at is unreviewed+ machine output from a tree the user said to ignore, and ``proposed`` is+ what marks that.+ """+ files = ["research/.pbvenv/Lib/site-packages/charset_normalizer/api.py"]+ assert decision_is_excluded(_decision(files, status="active"), _SPEC) is False+ assert decision_is_excluded(_decision(files, status="proposed"), _SPEC) is True++def test_all_affected_files_excluded_is_junk():d = _decision(["research/.pbvenv/Lib/site-packages/charset_normalizer/api.py"])assert decision_is_excluded(d, _SPEC) is Truediff --git a/tests/unit/server/mcp/test_why.py b/tests/unit/server/mcp/test_why.pyindex 80defb7da..526cfba2d 100644--- a/tests/unit/server/mcp/test_why.py+++ b/tests/unit/server/mcp/test_why.py@@ -240,18 +240,44 @@ async def test_get_why_targets_surfaces_code_rationale(setup_mcp, tmp_path):@pytest.mark.asyncio-async def test_get_why_semantic_decision_namespace_filtering(setup_mcp):+async def test_get_why_semantic_decision_namespace_filtering(session, setup_mcp):"""Mode 3 semantic path: over-fetch from page store, keep only decision: hits.Upserts a decision vector under the 'decision:' prefix and a noise pagewithout the prefix into the shared vector store. Confirms that get_whysurfaces the decision hit with the prefix stripped, and excludes the noisepage from the decisions list.++ A stored record is seeded alongside them because the semantic lanes now run+ only once something has cleared the relevance floor: a question no stored+ record answers returns before embedding anything, rather than serving the+ three nearest vectors to a store that has nothing to say."""+ import json+import repowise.server.mcp_server as mcp_modfrom repowise.core.analysis.decision_semantic_match import DECISION_VECTOR_PREFIX+ from repowise.core.persistence.models import DecisionRecordfrom repowise.server.mcp_server import get_why+ session.add(+ DecisionRecord(+ id="dec-redis",+ repository_id=setup_mcp,+ title="Redis for caching",+ status="proposed",+ context="caching",+ decision="Use Redis for caching",+ rationale="Redis caching reduces latency",+ affected_files_json=json.dumps([]),+ affected_modules_json=json.dumps([]),+ source="pr",+ confidence=0.8,+ staleness_score=0.0,+ )+ )+ await session.flush()+vs = mcp_mod._vector_store# Insert a decision under the decision: namespacediff --git a/tests/unit/server/mcp/test_why_relevance_floor.py b/tests/unit/server/mcp/test_why_relevance_floor.pynew file mode 100644index 000000000..bb5a6c100--- /dev/null+++ b/tests/unit/server/mcp/test_why_relevance_floor.py@@ -0,0 +1,315 @@+"""Search mode ranks by question vocabulary, and refuses when nothing carries it.++Search mode used to answer everything. Its fallback was gated on+``not merged_decisions``, which nothing reached: with 614 records and a scorer+that always found token overlap, the list was never empty, so a question the+store knew nothing about got the three closest records anyway. Measured on that+store, eight of eight such questions were answered — at 11 700 to 14 700 chars+each — and the ranking that chose them scored by length and by how ordinary a+word is, so the two ``active`` records answering "why ruff check and not ruff+format" placed nowhere.++These pin both halves: what gets ranked first, and what happens when nothing+deserves to be.+"""++from __future__ import annotations++import json++import pytest+++async def _seed(+ session,+ rid: str,+ *,+ id_: str,+ title: str,+ status: str = "proposed",+ decision: str = "dec",+ rationale: str = "why",+ context: str = "ctx",+ files: list[str] | None = None,+ commits: list[str] | None = None,+ confidence: float = 0.8,+) -> None:+ from repowise.core.persistence.models import DecisionRecord++ session.add(+ DecisionRecord(+ id=id_,+ repository_id=rid,+ title=title,+ status=status,+ context=context,+ decision=decision,+ rationale=rationale,+ affected_files_json=json.dumps(files or []),+ affected_modules_json=json.dumps([]),+ evidence_commits_json=json.dumps(commits or [id_]),+ evidence_file=None,+ source="pr",+ confidence=confidence,+ staleness_score=0.0,+ )+ )+ await session.flush()+++# --- Ranking ---------------------------------------------------------------+++async def test_a_terse_record_with_the_rare_word_beats_a_long_one_without_it(+ session, setup_mcp+):+ """The ruff case, reduced to its shape.++ "Never run ruff format" is 48 characters and matches two words of the+ question. It lost to records matching "use", "check", "format" and+ "instead" while containing no "ruff" at all, because an occurrence count+ rewards saying an ordinary word in many fields.+ """+ for n in range(6):+ await _seed(+ session,+ setup_mcp,+ id_=f"common{n}",+ title=f"Formatting check {n}",+ decision="use the formatting check instead",+ rationale="use the formatting check instead",+ context="use the formatting check instead",+ )+ await _seed(session, setup_mcp, id_="terse", title="Never run zebrafish format")++ result = await get_why_search("why do we use zebrafish check instead of format")+ ids = [d["id"] for d in result["decisions"]]++ assert ids and ids[0] == "terse", ids+++async def test_a_plural_in_the_question_matches_a_singular_record(session, setup_mcp):+ """"why must issue comments avoid em dashes" is answered by a record that+ writes "comment" and "dashes", and ``comments`` is the word carrying most of+ that question's weight."""+ for n in range(6):+ await _seed(session, setup_mcp, id_=f"noise{n}", title=f"Unrelated matter {n}")+ await _seed(+ session,+ setup_mcp,+ id_="singular",+ title="Close issues and comment with short text",+ decision="Write a short comment; avoid the em dash",+ rationale="a long comment reads as noise",+ context="issue comment",+ )++ result = await get_why_search("why must issue comments avoid em dashes")++ assert [d["id"] for d in result["decisions"]] == ["singular"]+++def test_a_word_in_every_record_still_carries_weight():+ """A small store where one term is universal must not score its own answer at zero.++ Textbook ``log(N/df)`` weighs a term appearing in every record at exactly+ nothing, so on a store of three records about one subsystem a question+ naming that subsystem would be refused by the tool holding its answer.+ Asserted directly rather than through ``get_why`` because the fixture store+ always carries a record that does not mention the term, which is the one+ arrangement that hides this.+ """+ from repowise.server.mcp_server._why_relevance import relevance, term_idf++ corpus = ["zebrafish one", "zebrafish two", "zebrafish three"]+ idf = term_idf(["zebrafish"], corpus)++ assert idf["zebrafish"] > 0+ assert relevance(corpus[0], idf) == 1.0+++async def test_the_answer_is_found_below_the_old_two_hundred_record_cut(+ session, setup_mcp+):+ """Search ranked over 200 records against a store of 614.++ ``list_decisions`` sorts confirmed-then-confident, so the records below the+ cut were unreachable by any question — a silent recall ceiling rather than a+ cost control. The answer here is seeded last and at the lowest confidence,+ which is exactly where that sort puts it.+ """+ for n in range(240):+ await _seed(+ session,+ setup_mcp,+ id_=f"bulk{n}",+ title=f"Routine maintenance note {n}",+ confidence=0.9,+ )+ await _seed(+ session,+ setup_mcp,+ id_="buried",+ title="Zebrafish caching strategy",+ decision="Use zebrafish caching",+ rationale="zebrafish caching is faster",+ context="zebrafish caching",+ confidence=0.1,+ )++ result = await get_why_search("why zebrafish caching strategy")++ assert "buried" in [d["id"] for d in result["decisions"]]+++# --- The floor and the redirect --------------------------------------------+++async def test_a_question_the_store_cannot_answer_gets_no_records(session, setup_mcp):+ """The fallback was gated on an empty list, which 614 records never produced."""+ # These share vocabulary with the question — "ingestion", "decided",+ # "pipeline" — so a rule that only drops records matching *nothing* would+ # serve them. What they do not carry is what the question is about.+ for n in range(8):+ await _seed(+ session,+ setup_mcp,+ id_=f"other{n}",+ title=f"Ingestion pipeline note {n}",+ decision="the ingestion pipeline is decided by the deployment order",+ rationale="ingestion decided at deployment",+ context="ingestion pipeline decided",+ )++ result = await get_why_search("why is entry-point candidacy decided at ingestion")++ assert result["decisions"] == []+ assert result["try_instead"]+ assert result["reason"]+++async def test_a_refusal_carries_no_semantic_or_episode_padding(session, setup_mcp):+ """A nearest-neighbour search over any store returns three records.++ So the refusal returns before the lookup runs, rather than stapling its+ three nearest guesses to the redirect — that would be the padding the+ redirect exists to stop.+ """+ for n in range(8):+ await _seed(+ session,+ setup_mcp,+ id_=f"other{n}",+ title=f"Ingestion pipeline note {n}",+ decision="the ingestion pipeline is decided by the deployment order",+ rationale="ingestion decided at deployment",+ )++ result = await get_why_search("why is entry-point candidacy decided at ingestion")++ assert "related_documentation" not in result+ assert "episodes" not in result+ assert len(json.dumps(result, default=str)) < 2000, result+++async def test_a_good_answer_is_not_hedged_with_a_redirect(session, setup_mcp):+ """The redirect fires only when the floor is missed.++ Stapled to an answer as a hedge it teaches the same distrust from the other+ direction: an agent that sees "try get_answer instead" beside a correct+ record stops reading either.++ A guard rather than a proof: it passes against the code before the redirect+ existed, because nothing could hedge when nothing could redirect. It is here+ to fail on the change that turns the redirect into a default.+ """+ await _seed(+ session,+ setup_mcp,+ id_="answered",+ title="Zebrafish caching strategy",+ decision="Use zebrafish caching",+ rationale="zebrafish caching is faster",+ context="zebrafish caching strategy",+ )++ result = await get_why_search("why zebrafish caching strategy")++ assert result["decisions"]+ assert "try_instead" not in result+ assert "reason" not in result+++ ("query", "expected"),+ [+ ("what breaks if I change the persist pipeline", "get_risk"),+ ("what is the knowledge graph module responsible for", "get_context"),+ ("where is the episode store implemented", "search_codebase"),+ ("how does the ingestion pipeline project single file components", "get_answer"),+ ("why is entry-point candidacy decided at ingestion", "get_answer"),+ ],+)+async def test_the_redirect_names_a_tool_that_fits_the_question(+ session, setup_mcp, query, expected+):+ """Routed on the question's shape, because its subject is what the store+ was just found to know nothing about."""+ # Carries a word from every one of the queries below, so reaching the+ # redirect depends on the floor rather than on matching nothing at all.+ for n in range(6):+ await _seed(+ session,+ setup_mcp,+ id_=f"partial{n}",+ title=f"Pipeline change note {n}",+ decision="the pipeline module is implemented by the ingestion component",+ rationale="pipeline change persists the graph store",+ context="pipeline module component",+ )++ result = await get_why_search(query)++ assert expected in result["try_instead"], result+++async def test_a_record_governing_a_named_target_is_served_without_matching_words(+ session, setup_mcp+):+ """Naming a file is a stronger handle than describing it.++ A caller who passes ``targets`` has pointed at the thing, so a record+ governing it owes the question no vocabulary and must not be refused for+ sharing none.+ """+ await _seed(+ session,+ setup_mcp,+ id_="governs",+ title="Unrelated wording entirely",+ decision="unrelated",+ rationale="unrelated",+ context="unrelated",+ files=["src/app/handler.py"],+ )++ result = await get_why_search(+ "why is entry-point candidacy decided at ingestion",+ targets=["src/app/handler.py"],+ )++ assert "governs" in [d["id"] for d in result["decisions"]]+++async def get_why_search(query: str, targets: list[str] | None = None) -> dict:+ from repowise.server.mcp_server import get_why++ return await get_why(query, targets=targets)diff --git a/tests/unit/server/mcp/test_why_search_payload.py b/tests/unit/server/mcp/test_why_search_payload.pyindex 8a63ec332..ab836c860 100644--- a/tests/unit/server/mcp/test_why_search_payload.py+++ b/tests/unit/server/mcp/test_why_search_payload.py@@ -147,11 +147,24 @@ async def test_search_caps_full_bodies(session, setup_mcp):@pytest.mark.asyncio-async def test_search_embeds_the_query_once(setup_mcp, monkeypatch):+async def test_search_embeds_the_query_once(session, setup_mcp, monkeypatch):"""Two awaits embedded the same string back to back, one question, two trips."""import repowise.server.mcp_server as mcp_modfrom repowise.server.mcp_server import get_why+ # Seeded because the semantic lanes now run only once some record has+ # cleared the relevance floor: a question with no answer behind it returns+ # before embedding anything, which is its own test below.+ await _seed(+ session,+ setup_mcp,+ id_="jwt",+ title="JWT used for authentication",+ decision="JWT is used for authentication",+ rationale="JWT authentication is stateless",+ context="authentication",+ )+vs = mcp_mod._vector_storecalls: list[str] = []@@ -176,7 +189,7 @@ async def test_search_embeds_the_query_once(setup_mcp, monkeypatch):@pytest.mark.asyncio-async def test_related_documentation_excludes_decision_pages(setup_mcp):+async def test_related_documentation_excludes_decision_pages(session, setup_mcp):"""The doc lane took the nearest pages of any kind, decisions included.So a decision record came back as "related documentation" beside the@@ -187,6 +200,17 @@ async def test_related_documentation_excludes_decision_pages(setup_mcp):from repowise.core.analysis.decision_semantic_match import DECISION_VECTOR_PREFIXfrom repowise.server.mcp_server import get_why+ # Seeded so the question clears the relevance floor and the lanes run at+ # all; the assertion is about which lane a decision page lands in.+ await _seed(+ session,+ setup_mcp,+ id_="zebra-latency",+ title="Zebrafish caching keeps latency down",+ decision="Zebrafish caching keeps latency down",+ rationale="zebrafish caching latency",+ )+vs = mcp_mod._vector_storeawait vs.embed_and_upsert(f"{DECISION_VECTOR_PREFIX}dec-doc-lane",@@ -258,15 +282,31 @@ async def test_status_breaks_ties_without_gating(session, setup_mcp):"""from repowise.server.mcp_server import get_why+ # Both candidates now have to clear the relevance floor before ordering is+ # observable at all, so the weaker one is weaker rather than unrelated: it+ # carries "zebrafish caching" and not "strategy". The three fillers exist to+ # make "strategy" an ordinary word in this store, which is what leaves the+ # weaker record enough of the question's weight to be served.+ for n in range(3):+ await _seed(+ session,+ setup_mcp,+ id_=f"filler{n}",+ title=f"Deployment strategy {n}",+ decision="strategy",+ rationale="strategy",+ context="strategy",+ commits=[f"fill{n}"],+ )await _seed(session,setup_mcp,id_="weak-active",status="active",- title="Zebrafish unrelated",- decision="unrelated",- rationale="unrelated",- context="unrelated",+ title="Zebrafish caching",+ decision="zebrafish caching",+ rationale="zebrafish caching",+ context="zebrafish caching",commits=["aaa"],)await _seed(