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): get_why serves rationale comments when no decision matches (#2692)
Swati Ahuja35083ee49340
diff --git a/packages/server/src/repowise/server/mcp_server/_code_rationale.py b/packages/server/src/repowise/server/mcp_server/_code_rationale.pyindex e7595f0ab..a7dd28eb2 100644--- a/packages/server/src/repowise/server/mcp_server/_code_rationale.py+++ b/packages/server/src/repowise/server/mcp_server/_code_rationale.py@@ -38,10 +38,13 @@ from pathlib import Pathfrom typing import Anyfrom repowise.core.analysis.decisions.rationale_comments import (+ CODE_EXTENSIONS,RATIONALE_MARKERS,extract_comment_blocks,+ harvest_file_rationale,)from repowise.core.exclusion import build_exclude_spec, is_excluded+from repowise.server.mcp_server._why_relevance import floor_ranked_log = logging.getLogger("repowise.mcp.code_rationale")@@ -438,3 +441,87 @@ def grep_comment_candidates(spec = build_exclude_spec(root)ranked = [p for p, _ in counts.most_common() if not is_excluded(p, spec)]return ranked[:max_files]+++# One repository's harvest, keyed on (root, HEAD): harvesting reads every+# tracked code file (about 2s cold on a 3,000-file repository), so a session+# asking several questions pays it once. Ceiling: edits since HEAD are not seen+# until the next commit; the path-scoped miner above stays live for those.+_HARVEST_CACHE: dict[tuple[str, str], list[dict]] = {}+_MAX_HARVEST_FILES = 20_000+++def _head(root: Path) -> str | None:+ try:+ proc = subprocess.run(+ ["git", "--no-pager", "rev-parse", "HEAD"],+ cwd=str(root),+ capture_output=True,+ text=True,+ stdin=subprocess.DEVNULL,+ timeout=_GREP_TIMEOUT_S,+ )+ except Exception:+ return None+ return proc.stdout.strip() if proc.returncode == 0 else None+++def _harvest_repo(root: Path) -> list[dict]:+ """Every tracked file's strong-marker comments, strongest first per file.++ ``harvest_file_rationale`` with its defaults: a causal marker is required+ and docstrings are skipped. That is the precision bar a comment must clear+ to be served for a question naming no file, where nothing else vouches for+ it. These are never decisions (#751); they are served as comments.+ """+ try:+ proc = subprocess.run(+ ["git", "--no-pager", "ls-files", "-z"],+ cwd=str(root),+ capture_output=True,+ stdin=subprocess.DEVNULL,+ timeout=_GREP_TIMEOUT_S,+ )+ except Exception:+ return []+ if proc.returncode != 0:+ return []+ spec = build_exclude_spec(root)+ rows: list[dict] = []+ paths = [p for p in proc.stdout.decode("utf-8", "replace").split("\0") if p]+ for path in paths[:_MAX_HARVEST_FILES]:+ ext = path.rsplit(".", 1)[-1].lower() if "." in path else ""+ if ext not in CODE_EXTENSIONS or is_excluded(path, spec):+ continue+ text = _read_text(root, path)+ if text is None:+ continue+ for h in harvest_file_rationale(text, ext):+ rows.append({"path": path, "lines": [h.start_line, h.end_line], "comment": h.text})+ return rows+++def repo_rationale(repo_root: Any, query: str, *, max_results: int = 3) -> list[dict]:+ """Strong-marker comments anywhere in the repository that answer *query*.++ For a question naming no file, when no decision record matched. Ranked by+ the decision store's own relevance floor, with rarity taken over the whole+ harvest, so a comment is served only when it carries most of the+ question's weighted vocabulary. Rows have the ``mine_rationale`` shape.+ Best-effort: ``[]`` on any failure.+ """+ if not repo_root or not query:+ return []+ try:+ root = Path(str(repo_root))+ head = _head(root)+ if head is None:+ return []+ key = (str(root.resolve()), head)+ if key not in _HARVEST_CACHE:+ _HARVEST_CACHE.clear()+ _HARVEST_CACHE[key] = _harvest_repo(root)+ return floor_ranked(query, _HARVEST_CACHE[key], lambda r: r["comment"], max_results)+ except Exception as exc: # never let the harvest break a tool+ _log.debug("repo rationale harvest failed: %s", exc)+ return []diff --git a/packages/server/src/repowise/server/mcp_server/_why_relevance.py b/packages/server/src/repowise/server/mcp_server/_why_relevance.pyindex 4a4eb7f25..982468465 100644--- a/packages/server/src/repowise/server/mcp_server/_why_relevance.py+++ b/packages/server/src/repowise/server/mcp_server/_why_relevance.py@@ -173,6 +173,19 @@ def query_scorer(query: str, corpus: list[str]) -> Callable[[str], float]:return lambda text: relevance(text.lower(), idf)+def floor_ranked(query: str, rows: list[Any], text: Callable[[Any], str], limit: int) -> list[Any]:+ """The *rows* whose ``text(row)`` clears the floor for *query*, best first.++ Rarity comes from every row passed, so pass the whole population (every+ harvested comment, every commit subject), not a shortlist. Ties keep input+ order, so a caller that pre-sorts by strength or recency keeps that order.+ """+ score = query_scorer(query, [text(r).lower() for r in rows])+ scored = [(s, i) for i, r in enumerate(rows) if clears_floor(s := score(text(r)))]+ scored.sort(key=lambda t: -t[0])+ return [rows[i] for _, i in scored[:limit]]++def recovery_note(total: int, recall: str) -> dict[str, Any]:"""What a block reduces to when a query is present and nothing bears on it.@@ -223,13 +236,14 @@ def redirect_for(query: str) -> dict[str, Any]: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."+ "No recorded rationale: no decision record covers this question. "+ "The store holds none carrying its terms, and the closest ones "+ "would be noise."),}-def redirect_when_served(lanes: list[str], recall: str) -> dict[str, Any]:+def redirect_when_served(lanes: list[str], recall: str | None) -> dict[str, Any]:"""The redirect for a call that missed the store but *answered anyway*.Once the relevance floor started rejecting target-anchored records, the@@ -245,8 +259,19 @@ def redirect_when_served(lanes: list[str], recall: str) -> dict[str, Any]:to reach something weaker, and learns from that trade that this tool'sanswers are not to be acted on. What is left is the true and narrowerstatement — the *decision store* was silent, these other lanes were not.++ ``recall`` is None when no file was named: the lanes were then searched+ repository-wide by the question itself, so there is no file to recall."""served = " and ".join(lanes)+ if recall is None:+ return {+ "reason": (+ f"No decision record covers this question. The {served} below "+ "carry its terms. They are quoted from the code and its history, "+ "not a ruling: read them as evidence, not as the recorded reason."+ )+ }return {"reason": (f"No decision record covers this question. This file's {served} "diff --git a/packages/server/src/repowise/server/mcp_server/tool_why/archaeology.py b/packages/server/src/repowise/server/mcp_server/tool_why/archaeology.pyindex b43bb1517..197e41903 100644--- a/packages/server/src/repowise/server/mcp_server/tool_why/archaeology.py+++ b/packages/server/src/repowise/server/mcp_server/tool_why/archaeology.py@@ -9,6 +9,8 @@ import subprocessfrom pathlib import Pathfrom typing import Any+from repowise.server.mcp_server._why_relevance import floor_ranked+_GIT_LOG_FORMAT = "--format=%H\t%an\t%ai\t%s"@@ -170,6 +172,29 @@ def _sync_git_log(repo_path: str, file_path: str, stem: str) -> list[dict]:return results+#: Commits a question is matched against: the recent history ``git log``+#: walks first. Ceiling: older commits are not searched.+_QUESTION_LOG_DEPTH = 2000+_QUESTION_LOG_LIMIT = 5+++def question_commits(repo_path: str | Path | None, query: str) -> list[dict]:+ """Recent commits whose subject clears the relevance floor for *query*.++ The archaeology for a question that names no file: no decision record or+ rationale comment answered it, so the history that carries its terms is+ what is left. Rarity comes from every subject walked. Best-effort.+ """+ if not repo_path or not (Path(repo_path) / ".git").exists():+ return []+ try:+ stdout = _git_log_stdout(str(repo_path), [_GIT_LOG_FORMAT, f"-{_QUESTION_LOG_DEPTH}", "--"])+ except (subprocess.TimeoutExpired, FileNotFoundError, OSError):+ return []+ rows = _parse_git_log(stdout or "", "git_log_question")+ return floor_ranked(query, rows, lambda r: r["message"], _QUESTION_LOG_LIMIT)++def _git_log_stdout(repo_path: str, args: list[str]) -> str | None:"""``git log <args>`` output, or ``None`` when git exits non-zero."""proc = subprocess.run(diff --git a/packages/server/src/repowise/server/mcp_server/tool_why/search.py b/packages/server/src/repowise/server/mcp_server/tool_why/search.pyindex afa22214a..995fcc1a2 100644--- a/packages/server/src/repowise/server/mcp_server/tool_why/search.py+++ b/packages/server/src/repowise/server/mcp_server/tool_why/search.py@@ -11,6 +11,7 @@ from repowise.core.analysis.decision_semantic_match import DECISION_VECTOR_PREFIfrom repowise.core.providers.embedding import store_has_semantic_vectorsfrom repowise.server.mcp_server._budget import OmissionCollector, cap_collectionfrom repowise.server.mcp_server._code_rationale import mine_rationale as _mine_rationale+from repowise.server.mcp_server._code_rationale import repo_rationalefrom repowise.server.mcp_server._episodes import episode_evidencefrom repowise.server.mcp_server._meta import build_meta as _build_metafrom repowise.server.mcp_server._why_evidence import annotate_response_evidence_async@@ -21,6 +22,7 @@ from repowise.server.mcp_server._why_relevance import (redirect_for,redirect_when_served,)+from repowise.server.mcp_server.tool_why.archaeology import question_commitsfrom repowise.server.mcp_server.tool_why.basis import _has_archaeologyfrom repowise.server.mcp_server.tool_why.caps import (_MAX_SEARCH_DECISIONS,@@ -170,7 +172,11 @@ async def _why_no_match(return something, and serving them beside a redirect is padding.Named targets are the exception: their git archaeology and rationale- comments are evidence about the thing asked, as in path mode.+ comments are evidence about the thing asked, as in path mode. With no+ targets, the question itself is searched: strong-marker rationale comments+ across the repository, else the commits carrying its terms. Both must clear+ the same floor the records missed, and are served as evidence, never as a+ decision."""result: dict[str, Any] = {"mode": "search",@@ -189,6 +195,8 @@ async def _why_no_match()if rationale:result["code_rationale"] = rationale+ else:+ result.update(await _question_lanes(ctx.path, query))await _hydrate_response_decision_evidence(ctx, result, all_decisions)await annotate_response_evidence_async(result, ctx.alias, all_decisions, repo_root=ctx.path@@ -206,15 +214,34 @@ async def _why_no_match(served = _served_lanes(result)if served:result.pop("try_instead", None)- result.update(- redirect_when_served(served, f"get_why(targets={json.dumps(targets)})")- )+ recall = f"get_why(targets={json.dumps(targets)})" if targets else None+ result.update(redirect_when_served(served, recall))result["_meta"] = _build_meta(repository=repository, targets=targets if targets else None)if collector is not None:collector.attach(result)return result+async def _question_lanes(repo_root: Any, query: str) -> dict[str, Any]:+ """Rationale comments carrying *query*, else the commits that do, else nothing."""+ rationale = await asyncio.to_thread(repo_rationale, repo_root, query)+ if rationale:+ return {"code_rationale": rationale}+ commits = await asyncio.to_thread(question_commits, repo_root, query)+ if not commits:+ return {}+ return {+ "git_archaeology": {+ "triggered": True,+ "git_log": commits,+ "summary": (+ f"No recorded rationale for this question. {len(commits)} "+ "commit(s) carry its terms: history, not a stated reason."+ ),+ }+ }++def _served_lanes(result: dict[str, Any]) -> list[str]:"""Labels of the evidence lanes *result* carries, top level or on a target card."""cards = (result.get("target_context") or {}).values()diff --git a/tests/unit/server/mcp/test_why_question_lanes.py b/tests/unit/server/mcp/test_why_question_lanes.pynew file mode 100644index 000000000..32c1f7253--- /dev/null+++ b/tests/unit/server/mcp/test_why_question_lanes.py@@ -0,0 +1,208 @@+"""get_why for a question naming no file, when no decision record matches.++Before, such a question got a redirect and nothing else, even when a comment in+the code stated the reason. Now the question is searched across the repository:+strong-marker rationale comments first, then the commits carrying its terms,+each held to the decision store's own relevance floor and served as evidence,+never as a decision. With neither, the answer says there is no recorded+rationale and invents none.+"""++from __future__ import annotations++import json+import subprocess+from pathlib import Path++import pytest++from repowise.server.mcp_server._code_rationale import repo_rationale+from repowise.server.mcp_server._query_shape import _is_path+from repowise.server.mcp_server.tool_why.archaeology import question_commits++_RETRY_SOURCE = (+ "def send(request):\n"+ " # Retry on 429 here rather than in the shared client, because the\n"+ " # client is shared across tenants and a global backoff would starve them.\n"+ " return request\n"+ "\n"+ "# Helper for formatting tenant names.\n"+ "def fmt(name):\n"+ " return name\n"+)+++def _commit(repo: Path, message: str) -> None:+ subprocess.run(["git", "add", "-A"], cwd=repo, check=True)+ subprocess.run(+ ["git", "-c", "[email protected]", "-c", "user.name=t", "commit", "-qm", message],+ cwd=repo,+ check=True,+ )+++def _repo(tmp_path: Path, files: dict[str, str], messages: list[str]) -> Path:+ subprocess.run(["git", "init", "-q"], cwd=tmp_path, check=True)+ for i, message in enumerate(messages):+ for name, content in files.items():+ p = tmp_path / name+ p.parent.mkdir(parents=True, exist_ok=True)+ p.write_text(content + f"\n# rev {i}\n", encoding="utf-8")+ _commit(tmp_path, message)+ return tmp_path+++ ("query", "is_path"),+ [+ ("upload/download split", False),+ ("why is upload/download split into two calls?", False),+ ("client/server boundary", False),+ ("how does the plan/apply flow work", False),+ ("why is retrieval hybrid", False),+ ("src/app/main.py", True),+ ("packages/core/", True),+ ("app/services/upload.py", True),+ ("main.go", True),+ ],+)+def test_natural_language_takes_precedence_over_a_slash(query, is_path):+ assert _is_path(query) is is_path+++def test_repo_rationale_serves_the_comment_that_states_the_reason(tmp_path):+ repo = _repo(tmp_path, {"svc/client.py": _RETRY_SOURCE}, ["init"])++ out = repo_rationale(repo, "why do we retry on 429 in send rather than the shared client")++ assert [r["path"] for r in out] == ["svc/client.py"]+ assert out[0]["lines"][0] == 2+ assert "shared across tenants" in out[0]["comment"]+++def test_repo_rationale_serves_nothing_off_topic_or_markerless(tmp_path):+ repo = _repo(tmp_path, {"svc/client.py": _RETRY_SOURCE}, ["init"])++ # Off topic: no comment carries the question's weight.+ assert repo_rationale(repo, "why is the cache keyed on the snapshot id") == []+ # The marker-less "Helper for formatting tenant names" comment is never+ # harvested, however well the question matches it.+ assert repo_rationale(repo, "why a helper for formatting tenant names") == []+++def test_repo_rationale_outside_a_git_repo_is_empty(tmp_path):+ (tmp_path / "a.py").write_text(_RETRY_SOURCE, encoding="utf-8")+ assert repo_rationale(tmp_path, "why retry on 429 rather than the shared client") == []+++def test_question_commits_keeps_only_subjects_clearing_the_floor(tmp_path):+ repo = _repo(+ tmp_path,+ {"a.py": "X = 1"},+ [+ "Initial import",+ "Use node buffer instead of safe-buffer",+ "Tidy formatting",+ ],+ )++ out = question_commits(repo, "why use node buffer instead of safe-buffer")++ assert [r["message"] for r in out] == ["Use node buffer instead of safe-buffer"]+ assert question_commits(repo, "why is the scheduler capped at forty jobs") == []+++# --- Through the tool ---------------------------------------------------------+++async def _seed_decision(session, rid: str, *, title: str, decision: str) -> None:+ from repowise.core.persistence.models import DecisionRecord++ session.add(+ DecisionRecord(+ id="d1",+ repository_id=rid,+ title=title,+ status="proposed",+ context="ctx",+ decision=decision,+ rationale="why",+ affected_files_json=json.dumps([]),+ affected_modules_json=json.dumps([]),+ evidence_commits_json=json.dumps(["d1"]),+ evidence_file=None,+ source="pr",+ confidence=0.8,+ staleness_score=0.0,+ )+ )+ await session.flush()+++async def test_rationale_is_served_labelled_when_no_decision_matches(setup_mcp, tmp_path):+ from repowise.server.mcp_server import get_why++ _repo(tmp_path, {"svc/client.py": _RETRY_SOURCE}, ["init"])++ result = await get_why("why do we retry on 429 in send rather than the shared client")++ assert result["decisions"] == []+ rows = result["code_rationale"]+ assert rows[0]["path"] == "svc/client.py"+ assert rows[0]["provenance"] == "extracted_rationale"+ assert result["answer_basis"] == "rationale"+ assert "try_instead" not in result+ assert "not as the recorded reason" in result["reason"]+++async def test_rationale_is_not_served_when_a_decision_matches(session, setup_mcp, tmp_path):+ from repowise.server.mcp_server import get_why++ _repo(tmp_path, {"svc/client.py": _RETRY_SOURCE}, ["init"])+ await _seed_decision(+ session,+ setup_mcp,+ title="Retry 429 in send, not in the shared client",+ decision="retry on 429 in send rather than the shared client",+ )++ result = await get_why("why do we retry on 429 in send rather than the shared client")++ assert [d["id"] for d in result["decisions"]] == ["d1"]+ assert "code_rationale" not in result+++async def test_no_recorded_rationale_invents_no_reason(setup_mcp, tmp_path):+ from repowise.server.mcp_server import get_why++ _repo(tmp_path, {"svc/client.py": _RETRY_SOURCE}, ["init"])++ result = await get_why("why is the scheduler capped at forty jobs")++ assert result["decisions"] == []+ assert "code_rationale" not in result+ assert "git_archaeology" not in result+ assert "answer_basis" not in result+ assert result["reason"].startswith("No recorded rationale")+++async def test_commits_are_the_fallback_when_no_comment_answers(setup_mcp, tmp_path):+ from repowise.server.mcp_server import get_why++ _repo(+ tmp_path,+ {"a.py": "X = 1"},+ ["Initial import", "Use node buffer instead of safe-buffer"],+ )++ result = await get_why("why use node buffer instead of safe-buffer")++ assert "code_rationale" not in result+ commits = result["git_archaeology"]["git_log"]+ assert [c["message"] for c in commits] == ["Use node buffer instead of safe-buffer"]+ assert result["git_archaeology"]["summary"].startswith("No recorded rationale")+ assert result["answer_basis"] == "archaeology"