Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix: rank the decision lists that agent-facing surfaces truncate (#1598)

Raghav Chamadiyaeee2d7ef5bb4
diff --git a/packages/core/src/repowise/core/persistence/crud/decisions.py b/packages/core/src/repowise/core/persistence/crud/decisions.py
index 9c3d4666b..c220a72dc 100644
--- a/packages/core/src/repowise/core/persistence/crud/decisions.py
+++ b/packages/core/src/repowise/core/persistence/crud/decisions.py
@@ -1172,7 +1172,13 @@ async def get_decision_health_summary(
session: AsyncSession,
repository_id: str,
) -> dict:
- """Return decision health: counts by status, stale decisions, ungoverned hotspots."""
+ """Return decision health: counts by status, stale decisions, ungoverned hotspots.
+
+ The three list fields are returned ranked worst-first: stale by staleness,
+ proposed by confidence, ungoverned hotspots by temporal hotspot score. A
+ caller that shows only the first few shows the few that matter.
+ Callers may truncate; they must not re-order.
+ """
result = await session.execute(
select(DecisionRecord).where(
DecisionRecord.repository_id == repository_id,
@@ -1212,15 +1218,44 @@ async def get_decision_health_summary(
elif d.status == "proposed":
proposed_decisions.append(d)
- # Find ungoverned hotspots
+ # Find ungoverned hotspots, hottest first. Sorting these by path put the file
+ # most in need of a decision behind whatever sorts alphabetically first,
+ # with the score that answers the question sitting unread one column over.
+ # The key is the one ``routers/overview.py`` already applies to these same
+ # rows in SQL (score descending with NULLs last, then churn) rather than a
+ # second answer to "which hotspot matters most". A NULL score is genuinely
+ # unknown and is not the same as a measured zero.
hotspot_result = await session.execute(
- select(GitMetadata.file_path).where(
+ select(
+ GitMetadata.file_path,
+ GitMetadata.temporal_hotspot_score,
+ GitMetadata.churn_percentile,
+ ).where(
GitMetadata.repository_id == repository_id,
GitMetadata.is_hotspot == True, # noqa: E712
)
)
- hotspot_files = {row[0] for row in hotspot_result.all()}
- ungoverned = sorted(hotspot_files - governed_files)
+ hotspot_rows = {row[0]: (row[1], row[2]) for row in hotspot_result.all()}
+
+ def _hotspot_rank(file_path: str) -> tuple[bool, float, float, str]:
+ score, churn = hotspot_rows[file_path]
+ return (score is None, -(score or 0.0), -(churn or 0.0), file_path)
+
+ ungoverned = sorted(hotspot_rows.keys() - governed_files, key=_hotspot_rank)
+
+ # Rank here rather than at the five call sites, none of which does. The MCP
+ # health dashboard and ``repowise decision health`` cut all three lists; the
+ # overview attention panel cuts the hotspots and renders the other two in the
+ # order it is handed; the decisions route serves them whole in that order;
+ # and ``health/governance.py`` walks them to *write* one finding row per
+ # entry. So the callers that truncate were showing whichever rows the scan
+ # returned first, and the ones that do not were still listing them by it,
+ # while the score answering "which of these first" rides on every record,
+ # unread. The ``or 0.0`` guards match how every other reader of these two
+ # fields spells it rather than trusting a column default to have been
+ # back-filled; the id tiebreak makes the key total, so two runs agree.
+ stale_decisions.sort(key=lambda d: (-(d.staleness_score or 0.0), d.id))
+ proposed_decisions.sort(key=lambda d: (-(d.confidence or 0.0), d.id))
# Phase 3B: surface contradictory active decisions (conflicts_with edges).
from ..decision_graph import list_conflict_edges
diff --git a/packages/server/src/repowise/server/mcp_server/tool_why.py b/packages/server/src/repowise/server/mcp_server/tool_why.py
index afecb1da8..4004766e5 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_why.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_why.py
@@ -92,38 +92,81 @@ async def get_why(
async def _why_workspace_search(query: str) -> dict:
- """repo="all": keyword-search decisions across every repo in the workspace."""
+ """repo="all": the question single-repo search answers, across the workspace.
+
+ This used to be the whole tool as it stood before the relevance work: match
+ any query word as a substring, append in whatever order the workspace
+ resolved its stores, serve fifteen whole records. That is the shape the
+ single-repo mode was rebuilt away from, still reachable one argument away and
+ over several stores at once. It now loads its corpus the way ``_load_corpus``
+ does, so dismissed tombstones and records anchored entirely in excluded
+ paths stop being served here alone, and it ranks with the shared machinery, so
+ a question the workspace cannot answer gets the redirect rather than fifteen
+ records that happen to contain "the".
+
+ **Each store is scored against its own corpus, never a pooled one**, and the
+ consequence is asymmetric. The floor keeps the meaning it was swept for:
+ ``relevance`` is a normalised share of the question's weight, so it survives
+ a uniform rescale of the idf vector untouched. What a pooled corpus moves is
+ the *ratio* between term weights, and with it which records clear 0.6.
+ Scoring each store on its own statistics keeps that filter the one that was
+ calibrated. The merge is where the cost lands, and it is a real one: the cut
+ below is decided across stores whose scores come from different
+ distributions, since a large store polarises toward 0 and 1 while a small one
+ lands mid-range. So which store loses a slot is settled approximately, and
+ that is a *selection*, not merely an order. It is the price of not silently
+ re-scaling a constant nobody re-swept. The upgrade path, if workspace
+ ranking ever needs to be exact, is to sweep a floor against a pooled corpus,
+ not to pool the statistics underneath the floor that exists.
+ """
contexts = await _resolve_all_contexts()
- merged: list[dict] = []
- query_words = query.lower().split()
+ scored: list[tuple[tuple[float, float, int], str, str, Any, list[str]]] = []
for ctx in contexts:
async with get_session(ctx.session_factory) as session:
repository = await _get_repo(session)
- res = await session.execute(
- select(DecisionRecord).where(
- DecisionRecord.repository_id == repository.id,
- )
- )
- for d in res.scalars().all():
- text = f"{d.title} {d.decision} {d.rationale} {d.context}".lower()
- if any(w in text for w in query_words):
- merged.append(
- {
- "repo": ctx.alias,
- "id": d.id,
- "title": d.title,
- "status": d.status,
- "decision": _decision_body(d),
- "rationale": d.rationale,
- "source": d.source,
- "confidence": d.confidence,
- }
- )
+ records = await _decision_corpus(session, repository.id, _get_exclude_spec(ctx.path))
+ ranked = _score_keyword_matches(records, query, set())
+ # Collapsed per store, not across the merge: ``_evidence_key`` is a
+ # (source, commit) pair carrying no repo, so two stores sharing a commit
+ # sha would fold into one and a repo would lose its record.
+ key_by_id = {d.id: key for key, d in ranked}
+ for d, folded in _collapse_restatements([d for _, d in ranked]):
+ scored.append((key_by_id[d.id], ctx.alias, d.id, d, folded))
+
+ if not scored:
+ return {
+ "mode": "search",
+ "query": query,
+ "workspace": True,
+ "decisions": [],
+ **redirect_for(query),
+ "_meta": _build_meta(),
+ }
+
+ # The store's own key first, so relevance, occurrence count and status decide
+ # as they do within one repo; alias and id only settle what those three leave
+ # equal, and are here so the answer is the same on two runs.
+ scored.sort(key=lambda t: (t[0], t[1], t[2]))
+ decisions: list[dict] = []
+ for _, alias, _id, d, folded in scored[:_MAX_WORKSPACE_DECISIONS]:
+ entry = {
+ "repo": alias,
+ "id": d.id,
+ "title": d.title,
+ "status": d.status,
+ "decision": _decision_body(d),
+ "rationale": d.rationale,
+ "source": d.source,
+ "confidence": d.confidence,
+ }
+ if folded:
+ entry["restates"] = folded
+ decisions.append(entry)
return {
"mode": "search",
"query": query,
"workspace": True,
- "decisions": merged[:15],
+ "decisions": decisions,
"_meta": _build_meta(),
}
@@ -159,7 +202,7 @@ async def _why_health_dashboard(repo: str | None) -> dict:
json.loads(d.affected_files_json), _get_exclude_spec(ctx.path)
)[:5],
}
- for d in stale[:10]
+ for d in stale[:_MAX_HEALTH_STALE]
],
"proposed_awaiting_review": [
{
@@ -168,9 +211,9 @@ async def _why_health_dashboard(repo: str | None) -> dict:
"source": d.source,
"confidence": d.confidence,
}
- for d in proposed[:10]
+ for d in proposed[:_MAX_HEALTH_PROPOSED]
],
- "ungoverned_hotspots": ungoverned[:15],
+ "ungoverned_hotspots": ungoverned[:_MAX_HEALTH_UNGOVERNED],
"conflicts": health.get("conflicts", [])[:10],
"_meta": _build_meta(repository=repository),
}
@@ -231,6 +274,11 @@ _PATH_STATUS_ORDER = {"active": 0, "proposed": 1, "deprecated": 2, "superseded":
#: hit the ranking is not trustworthy enough to spend an agent's context on.
_MAX_SEARCH_DECISIONS = 3
+#: Records kept by workspace search. Above the single-repo three because the
+#: answer can genuinely live in more than one store and the repo is part of it;
+#: nowhere near the fifteen whole records this path served before it was ranked.
+_MAX_WORKSPACE_DECISIONS = 5
+
#: Nearest pages pulled for the *one* semantic lookup search mode makes. Both
#: lanes (decisions, documentation) are partitioned out of this single window,
#: so the depth is the old decision lane's rather than the sum of the two.
@@ -252,6 +300,16 @@ _DECISION_CORPUS_LIMIT = 2000
#: Bounded because the lineage walk after the collapse costs a query per record.
_KEYWORD_POOL = 24
+#: Items per list in the health dashboard. This mode is an orientation call:
+#: asked once, skimmed, acted on twice. It served 45 items to be read as a
+#: verdict. Halved now that ``get_decision_health_summary`` ranks what it
+#: returns: cutting an unranked list only makes a list nobody reads shorter,
+#: cutting a ranked one keeps the part that is worth reading. The full sizes stay
+#: legible in ``counts`` and in the summary line, so nothing is silently dropped.
+_MAX_HEALTH_STALE = 5
+_MAX_HEALTH_PROPOSED = 5
+_MAX_HEALTH_UNGOVERNED = 8
+
def _path_decision_sort_key(d: Any) -> tuple[int, float, float]:
return (
@@ -540,29 +598,19 @@ def _governs_any(d: Any, targets: set[str]) -> bool:
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:
- """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.
+def _score_keyword_matches(
+ all_decisions: list, query: str, target_set: set[str]
+) -> list[tuple[tuple[float, float, int], Any]]:
+ """``_rank_keyword_matches`` with each record's whole sort key kept beside it.
- 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.
+ Split out for workspace search, which ranks one store at a time and then has
+ to merge the survivors. It is the *whole* key rather than the score because a
+ merge that kept only the score would silently drop the other two rules: the
+ occurrence-count tie-break and the status tie-break both exist because
+ ``relevance`` is a share of one idf vector, so any two records covering the
+ same set of question terms score bit-identically and something has to
+ separate them. The floor and the ordering rules are documented on
+ ``_rank_keyword_matches``; this returns the key that implements them.
"""
terms = question_terms(query)
texts = {id(d): _record_text(d) for d in all_decisions}
@@ -586,7 +634,34 @@ def _rank_keyword_matches(all_decisions: list, query: str, target_set: set[str])
)
)
scored_decisions.sort(key=lambda t: (t[0], t[1], t[2]))
- return [t[3] for t in scored_decisions[:_KEYWORD_POOL]]
+ return [((t[0], t[1], t[2]), t[3]) for t in scored_decisions[:_KEYWORD_POOL]]
+
+
+def _rank_keyword_matches(all_decisions: list, query: str, target_set: set[str]) -> list:
+ """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.
+ """
+ return [d for _, d in _score_keyword_matches(all_decisions, query, target_set)]
async def _fts_doc_results(ctx: Any, query: str) -> list:
@@ -851,6 +926,24 @@ async def _why_no_match(
return result
+async def _decision_corpus(session: Any, repository_id: str, exclude_spec: Any) -> list:
+ """The rankable decision records of one repository.
+
+ A record anchored entirely in excluded paths is noise for every mode, and a
+ dismissed one is a tombstone, so both filters belong wherever a corpus is
+ built. Takes a session rather than a context so the caller that also needs a
+ repository row and git metadata still opens one. Shared with workspace search
+ precisely because that path used to build its own corpus and got neither
+ filter.
+ """
+ from repowise.core.persistence.crud import list_decisions as _list_decisions
+
+ records = await _list_decisions(
+ session, repository_id, include_proposed=True, limit=_DECISION_CORPUS_LIMIT
+ )
+ return [d for d in records if not decision_is_excluded(d, exclude_spec)]
+
+
async def _load_corpus(repo: str | None, targets: list[str] | None) -> tuple:
"""Repo context, the rankable decision corpus, and git metadata for targets.
@@ -859,16 +952,10 @@ async def _load_corpus(repo: str | None, targets: list[str] | None) -> tuple:
every mode downstream, and a mode that skipped the filter would answer from
a different store than its neighbour.
"""
- from repowise.core.persistence.crud import list_decisions as _list_decisions
-
ctx = await _resolve_repo_context(repo)
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=_DECISION_CORPUS_LIMIT
- )
- _spec = _get_exclude_spec(ctx.path)
- all_decisions = [d for d in all_decisions if not decision_is_excluded(d, _spec)]
+ all_decisions = await _decision_corpus(session, repository.id, _get_exclude_spec(ctx.path))
# Load git metadata for targets (for origin context in results)
target_git = await _load_target_git(session, repository.id, targets)
return ctx, repository, all_decisions, target_git
diff --git a/tests/unit/persistence/test_decision_health_ranking.py b/tests/unit/persistence/test_decision_health_ranking.py
new file mode 100644
index 000000000..ff4c04c0a
--- /dev/null
+++ b/tests/unit/persistence/test_decision_health_ranking.py
@@ -0,0 +1,170 @@
+"""``get_decision_health_summary`` ranks the lists its callers truncate.
+
+Four surfaces read these lists: the MCP health dashboard, ``repowise decision
+health``, the overview attention panel and the decisions route. None of them
+ranks. Every score that orders them already rides on the record.
+
+Each fixture below is built so that insertion order, id order and path order
+all disagree with score order. That is not decoration: the sibling defect in
+``used_by`` passed its first test because SQLite happened to serve the join in
+path order, so a fixture whose natural order matches the wanted order cannot
+tell a ranked implementation from an unranked one.
+
+Measured here while proving these red: this scan comes back in primary-key
+order on SQLite rather than insertion order. A fixture inserted ``d4, b2, c3, a1``
+was served ``a1, b2, c3, d4``. So the id tie-break is untestable through this
+function on this backend, since its correct output is the order the unranked
+code already produced. It is in the sort key for a different reason: a total
+key is what makes the result the same on a backend that does not do this. A
+test asserting it here would pass against the code it exists to outlaw.
+"""
+
+from __future__ import annotations
+
+import json
+
+from repowise.core.persistence.crud import get_decision_health_summary
+from repowise.core.persistence.models import DecisionRecord, GitMetadata
+from tests.unit.persistence.helpers import insert_repo
+
+
+async def _add_decision(
+ session,
+ repo_id: str,
+ *,
+ rec_id: str,
+ title: str,
+ status: str,
+ staleness: float = 0.0,
+ confidence: float = 1.0,
+ files: list[str] | None = None,
+) -> None:
+ session.add(
+ DecisionRecord(
+ id=rec_id,
+ repository_id=repo_id,
+ title=title,
+ decision=f"{title} because reasons",
+ status=status,
+ staleness_score=staleness,
+ confidence=confidence,
+ affected_files_json=json.dumps(files or []),
+ source="changelog",
+ )
+ )
+ await session.flush()
+
+
+async def _add_hotspot(session, repo_id: str, path: str, score: float | None) -> None:
+ session.add(
+ GitMetadata(
+ repository_id=repo_id,
+ file_path=path,
+ is_hotspot=True,
+ temporal_hotspot_score=score,
+ )
+ )
+ await session.flush()
+
+
+async def test_stale_decisions_come_back_worst_first(async_session):
+ repo = await insert_repo(async_session)
+ # Inserted least-stale first, and the ids ascend the same way, so scan order
+ # and id order are both the exact reverse of the answer.
+ for rec_id, staleness in (("a1", 0.55), ("b2", 0.70), ("c3", 0.85), ("d4", 0.95)):
+ await _add_decision(
+ async_session,
+ repo.id,
+ rec_id=rec_id,
+ title=f"Decision {rec_id}",
+ status="active",
+ staleness=staleness,
+ )
+
+ health = await get_decision_health_summary(async_session, repo.id)
+
+ assert [d.id for d in health["stale_decisions"]] == ["d4", "c3", "b2", "a1"]
+
+
+async def test_proposed_decisions_come_back_most_confident_first(async_session):
+ repo = await insert_repo(async_session)
+ for rec_id, confidence in (("a1", 0.30), ("b2", 0.55), ("c3", 0.80), ("d4", 0.95)):
+ await _add_decision(
+ async_session,
+ repo.id,
+ rec_id=rec_id,
+ title=f"Proposal {rec_id}",
+ status="proposed",
+ confidence=confidence,
+ )
+
+ health = await get_decision_health_summary(async_session, repo.id)
+
+ assert [d.id for d in health["proposed_awaiting_review"]] == ["d4", "c3", "b2", "a1"]
+
+
+async def test_ungoverned_hotspots_come_back_hottest_first(async_session):
+ repo = await insert_repo(async_session)
+ # Paths sort alphabetically in the exact reverse of their heat, which is the
+ # order this list used to be served in.
+ await _add_hotspot(async_session, repo.id, "src/a_barely_warm.py", 0.10)
+ await _add_hotspot(async_session, repo.id, "src/m_middling.py", 0.50)
+ await _add_hotspot(async_session, repo.id, "src/z_on_fire.py", 0.90)
+
+ health = await get_decision_health_summary(async_session, repo.id)
+
+ assert health["ungoverned_hotspots"] == [
+ "src/z_on_fire.py",
+ "src/m_middling.py",
+ "src/a_barely_warm.py",
+ ]
+
+
+async def test_a_hotspot_with_no_score_sorts_last_rather_than_raising(async_session):
+ """``temporal_hotspot_score`` is nullable, unlike the two decision keys."""
+ repo = await insert_repo(async_session)
+ await _add_hotspot(async_session, repo.id, "src/aaa_unscored.py", None)
+ await _add_hotspot(async_session, repo.id, "src/zzz_scored.py", 0.40)
+
+ health = await get_decision_health_summary(async_session, repo.id)
+
+ assert health["ungoverned_hotspots"] == ["src/zzz_scored.py", "src/aaa_unscored.py"]
+
+
+async def test_a_governed_hotspot_is_still_excluded(async_session):
+ """Ranking must not change which hotspots count as ungoverned."""
+ repo = await insert_repo(async_session)
+ await _add_hotspot(async_session, repo.id, "src/governed.py", 0.99)
+ await _add_hotspot(async_session, repo.id, "src/ungoverned.py", 0.10)
+ await _add_decision(
+ async_session,
+ repo.id,
+ rec_id="g1",
+ title="Governs the hot one",
+ status="active",
+ files=["src/governed.py"],
+ )
+
+ health = await get_decision_health_summary(async_session, repo.id)
+
+ assert health["ungoverned_hotspots"] == ["src/ungoverned.py"]
+
+
+async def test_ranking_does_not_drop_or_duplicate_a_record(async_session):
+ """The sort re-orders the lists; it must not change what is in them."""
+ repo = await insert_repo(async_session)
+ for rec_id, status in (("a1", "active"), ("b2", "proposed"), ("c3", "active")):
+ await _add_decision(
+ async_session,
+ repo.id,
+ rec_id=rec_id,
+ title=f"Decision {rec_id}",
+ status=status,
+ staleness=0.80 if status == "active" else 0.0,
+ )
+
+ health = await get_decision_health_summary(async_session, repo.id)
+
+ assert sorted(d.id for d in health["stale_decisions"]) == ["a1", "c3"]
+ assert [d.id for d in health["proposed_awaiting_review"]] == ["b2"]
+ assert health["summary"]["stale"] == 2
diff --git a/tests/unit/server/mcp/test_why_health_payload.py b/tests/unit/server/mcp/test_why_health_payload.py
new file mode 100644
index 000000000..57aebeb9d
--- /dev/null
+++ b/tests/unit/server/mcp/test_why_health_payload.py
@@ -0,0 +1,115 @@
+"""What the health dashboard spends an agent's context on.
+
+This mode is an orientation call: asked once, skimmed. It served 45 items
+to be read as a verdict. The cut is only defensible now that
+``get_decision_health_summary`` ranks what it returns, so these pin both halves:
+the tool takes the front of each list, and it does not re-order it on the way
+out. A tool that re-sorted here would put the owner's ranking back at the call
+site, which is the defect this whole change removes.
+"""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+
+from repowise.core.persistence.models import DecisionRecord
+from repowise.server.mcp_server.tool_why import (
+ _MAX_HEALTH_PROPOSED,
+ _MAX_HEALTH_STALE,
+ _MAX_HEALTH_UNGOVERNED,
+)
+
+
+def _record(rec_id: str, *, staleness: float = 0.0, confidence: float = 1.0) -> DecisionRecord:
+ return DecisionRecord(
+ id=rec_id,
+ repository_id="repo-1",
+ title=f"Decision {rec_id}",
+ decision="body",
+ status="active",
+ source="cli",
+ staleness_score=staleness,
+ confidence=confidence,
+ affected_files_json=json.dumps([f"src/{rec_id}.py"]),
+ affected_modules_json="[]",
+ )
+
+
+def oversized_health(monkeypatch):
+ """A summary far longer than every cap, already ranked as the owner ranks it."""
+ from repowise.core.persistence import crud
+
+ stale = [_record(f"s{i}", staleness=1.0 - i / 100) for i in range(20)]
+ proposed = [_record(f"p{i}", confidence=1.0 - i / 100) for i in range(20)]
+ ungoverned = [f"src/hot_{i}.py" for i in range(20)]
+
+ async def _fake(session, repository_id):
+ return {
+ "summary": {"active": 20, "proposed": 20, "stale": 20, "conflicts": 0},
+ "stale_decisions": stale,
+ "proposed_awaiting_review": proposed,
+ "ungoverned_hotspots": ungoverned,
+ "conflicts": [],
+ }
+
+ monkeypatch.setattr(crud, "get_decision_health_summary", _fake)
+ return stale, proposed, ungoverned
+
+
+async def test_health_serves_five_five_and_eight(setup_mcp, oversized_health):
+ """The sizes are written out, not read back from the constants they pin.
+
+ Asserting against ``_MAX_HEALTH_STALE`` would hold for every value of it,
+ including one that cuts nothing. These three numbers are a judgement
+ about what an orientation call should cost an agent, so changing one should
+ have to change a test.
+ """
+ from repowise.server.mcp_server import get_why
+
+ result = await get_why()
+
+ assert result["mode"] == "health"
+ assert len(result["stale_decisions"]) == 5
+ assert len(result["proposed_awaiting_review"]) == 5
+ assert len(result["ungoverned_hotspots"]) == 8
+
+
+async def test_health_takes_the_front_of_each_list_without_re_sorting_it(
+ setup_mcp, oversized_health
+):
+ """The owner ranks; this mode may truncate and must not re-order.
+
+ Re-sorting here would put the ranking back at the call site, which is the
+ defect the change removes.
+ """
+ from repowise.server.mcp_server import get_why
+
+ stale, proposed, ungoverned = oversized_health
+ result = await get_why()
+
+ assert [d["id"] for d in result["stale_decisions"]] == [
+ d.id for d in stale[:_MAX_HEALTH_STALE]
+ ]
+ assert [d["id"] for d in result["proposed_awaiting_review"]] == [
+ d.id for d in proposed[:_MAX_HEALTH_PROPOSED]
+ ]
+ assert result["ungoverned_hotspots"] == ungoverned[:_MAX_HEALTH_UNGOVERNED]
+
+
+async def test_health_still_states_the_sizes_it_is_not_showing(setup_mcp, oversized_health):
+ """Cutting is only honest while the full counts stay legible."""
+ from repowise.server.mcp_server import get_why
+
+ result = await get_why()
+
+ assert result["counts"]["stale"] == 20
+ assert result["counts"]["proposed"] == 20
+ # The summary line is where the ungoverned total survives. It has no
+ # counter of its own, so cutting the list without this would hide it.
+ assert "20 ungoverned hotspots" in result["summary"]
diff --git a/tests/unit/server/mcp/test_why_workspace_ranking.py b/tests/unit/server/mcp/test_why_workspace_ranking.py
new file mode 100644
index 000000000..69d84bd8d
--- /dev/null
+++ b/tests/unit/server/mcp/test_why_workspace_ranking.py
@@ -0,0 +1,214 @@
+"""``get_why(repo="all")`` answers with the same machinery as one repo.
+
+This path kept the whole pre-relevance tool alive one argument away: substring
+match on any query word, appended in workspace-resolution order, fifteen whole
+records, no floor and no redirect, over several stores at once. These pin that
+it now loads its corpus the way single-repo mode does, ranks, caps and refuses.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.persistence.models import DecisionRecord
+from tests.unit.server.test_mcp_workspace import _make_repo_context, _MockRegistry
+
+_MCP_STATE = (
+ "_registry",
+ "_workspace_root",
+ "_session_factory",
+ "_fts",
+ "_vector_store",
+ "_decision_store",
+ "_repo_path",
+ "_vector_store_ready",
+ "_cross_repo_enricher",
+)
+
+
+def _decision(rec_id: str, repo_id: str, title: str, body: str, **kw) -> DecisionRecord:
+ return DecisionRecord(
+ id=rec_id,
+ repository_id=repo_id,
+ title=title,
+ decision=body,
+ rationale=kw.pop("rationale", ""),
+ status=kw.pop("status", "active"),
+ source="cli",
+ affected_files_json="[]",
+ affected_modules_json="[]",
+ **kw,
+ )
+
+
+def _install(contexts: dict, default: str, root) -> _MockRegistry:
+ import repowise.server.mcp_server as mcp_mod
+
+ registry = _MockRegistry(contexts=contexts, default_alias=default)
+ primary = contexts[default]
+ mcp_mod._registry = registry
+ mcp_mod._workspace_root = str(root)
+ mcp_mod._session_factory = primary.session_factory
+ mcp_mod._fts = primary.fts
+ mcp_mod._vector_store = primary.vector_store
+ mcp_mod._decision_store = primary.decision_store
+ mcp_mod._repo_path = str(primary.path)
+ mcp_mod._vector_store_ready = primary.vector_store_ready
+ return registry
+
+
+async def _uninstall(registry: _MockRegistry) -> None:
+ import repowise.server.mcp_server as mcp_mod
+
+ await registry.close()
+ for attr in _MCP_STATE:
+ setattr(mcp_mod, attr, None)
+
+
+async def _store(tmp_path, alias: str, records: list) -> tuple:
+ repo_dir = tmp_path / alias
+ repo_dir.mkdir()
+ return await _make_repo_context(alias, str(repo_dir), pages=[], extra_models=records)
+
+
+async def two_repos(tmp_path):
+ """A workspace whose answer lives in the second store to be resolved."""
+ alpha = await _store(
+ tmp_path,
+ "alpha",
+ [
+ # Carries some of the question's words and not the rest, so it lands
+ # under the floor. The old substring match served it.
+ _decision("a-1", "repo-alpha", "Session cache warmup", "We warm the cache on boot"),
+ # A tombstone that would otherwise match a question outright.
+ _decision(
+ "a-2",
+ "repo-alpha",
+ "Redis for rate limiting",
+ "Use Redis for rate limiting counters",
+ status="dismissed",
+ ),
+ ],
+ )
+ beta = await _store(
+ tmp_path,
+ "beta",
+ [
+ _decision(
+ "b-1",
+ "repo-beta",
+ "Redis for the session cache",
+ "Use Redis as the session cache backend",
+ rationale="Shared across web workers",
+ )
+ ],
+ )
+ registry = _install({"alpha": alpha, "beta": beta}, "alpha", tmp_path)
+ yield registry
+ await _uninstall(registry)
+
+
+async def test_a_partial_match_in_an_earlier_store_is_left_under_the_floor(two_repos):
+ """``alpha`` resolves first and holds a partial match; ``beta`` holds the answer.
+
+ This pins the floor rather than the merge. ``a-1`` covers two of the question's
+ four terms and scores 0.5, so it never reaches the merge to be ordered. The
+ merge has its own test below.
+ """
+ from repowise.server.mcp_server import get_why
+
+ result = await get_why(query="why is Redis used for the session cache", repo="all")
+
+ assert result["workspace"] is True
+ assert [d["id"] for d in result["decisions"]] == ["b-1"]
+ assert result["decisions"][0]["repo"] == "beta"
+
+
+async def test_the_merge_keeps_each_store_s_own_tiebreaks(tmp_path):
+ """Two stores, one score: what separates them must be the ranker's rules.
+
+ Both records carry every term of the question, so ``relevance`` is exactly
+ 1.0 for each, and the occurrence count is equal too because the text is
+ identical.
+ The only thing left to separate them is status, which is the third rule the
+ single-repo ranker applies and which a merge ordering on repo alias would
+ throw away. Alias order is deliberately the opposite of the right answer.
+ """
+ from repowise.server.mcp_server import get_why
+
+ body = "Use Redis as the session cache backend"
+ alpha = await _store(
+ tmp_path, "alpha", [_decision("a-1", "repo-alpha", "Redis", body, status="deprecated")]
+ )
+ beta = await _store(
+ tmp_path, "beta", [_decision("b-1", "repo-beta", "Redis", body, status="active")]
+ )
+ registry = _install({"alpha": alpha, "beta": beta}, "alpha", tmp_path)
+ try:
+ result = await get_why(query="why is Redis the session cache backend", repo="all")
+ assert [d["id"] for d in result["decisions"]] == ["b-1", "a-1"]
+ finally:
+ await _uninstall(registry)
+
+
+async def test_a_dismissed_record_is_not_served(two_repos):
+ """Dismissed is a tombstone everywhere else; this path used to serve it."""
+ from repowise.server.mcp_server import get_why
+
+ result = await get_why(query="why is Redis used for rate limiting", repo="all")
+
+ assert all(d["id"] != "a-2" for d in result["decisions"])
+
+
+async def test_a_question_the_workspace_cannot_answer_gets_a_redirect(two_repos):
+ from repowise.server.mcp_server import get_why
+
+ result = await get_why(query="how does the parser handle Kotlin generics", repo="all")
+
+ assert result["decisions"] == []
+ assert result["try_instead"]
+ assert "reason" in result
+
+
+async def test_workspace_search_serves_five_of_nine_answers(tmp_path):
+ """The count is written out rather than read from the constant.
+
+ Comparing the result against ``_MAX_WORKSPACE_DECISIONS`` would hold for any
+ value of it, including one that caps nothing. The number is a judgement
+ about an agent's context, which is exactly the kind of thing a test should
+ fail on when it changes.
+ """
+ from repowise.server.mcp_server import get_why
+
+ ctx = await _store(
+ tmp_path,
+ "solo",
+ [
+ # Distinct evidence per record, so the restatement collapse does not
+ # fold them and the cap is what the count is measuring.
+ _decision(
+ f"s-{i}",
+ "repo-solo",
+ f"Redis session cache decision {i}",
+ "Use Redis as the session cache backend",
+ evidence_file=f"src/cache_{i}.py",
+ )
+ for i in range(9)
+ ],
+ )
+ registry = _install({"solo": ctx}, "solo", tmp_path)
+ try:
+ # Every content word occurs in every record, so all nine clear the floor
+ # and the cap is the only thing deciding the count. A question carrying a
+ # word none of them holds would be refused outright instead, since an unseen
+ # term takes the rarest weight the store can award.
+ result = await get_why(query="why is Redis the session cache backend", repo="all")
+ assert len(result["decisions"]) == 5
+ finally:
+ await _uninstall(registry)