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(mcp): redirect no_such_path to a renamed or split file (#2922)

Aman1996c9f42a49
diff --git a/docs/reference/MCP_RESPONSE_FIELDS.md b/docs/reference/MCP_RESPONSE_FIELDS.md
index f4595592d..a0cd508e3 100644
--- a/docs/reference/MCP_RESPONSE_FIELDS.md
+++ b/docs/reference/MCP_RESPONSE_FIELDS.md
@@ -315,7 +315,7 @@ Opt-in blocks: `outline` (wiki page tree, two levels), `tour` (`guided_tour`, `r
### Modes and identity
-`mode` is `dashboard` (no targets), `targeted`, `fix_item` (`fix_id`), or `conflict` (two selectors passed). `unresolved` names targets that matched nothing, with a reason: `not_indexed`, `no_such_path`, `excluded`, `not_measured`, `no_such_module` (which also returns `known_modules`). `mode`, `_meta`, `unresolved`, `known_modules` and every kept list's `*_total` survive any `only` projection. `scope` and `counts` are echoed on the response.
+`mode` is `dashboard` (no targets), `targeted`, `fix_item` (`fix_id`), or `conflict` (two selectors passed). `unresolved` names targets that matched nothing, with a reason: `not_indexed`, `no_such_path`, `excluded`, `not_measured`, `no_such_module` (which also returns `known_modules`). A `no_such_path` entry adds `removed_by_commit` and `moved_to` (the file or files that replaced it) when git history explains the miss. `mode`, `_meta`, `unresolved`, `known_modules` and every kept list's `*_total` survive any `only` projection. `scope` and `counts` are echoed on the response.
`_meta.health_analysis` labels the result as stored analysis that this call did not recompute. Its `status` is `available`, `provenance_unknown` (metrics exist but no row recorded their commit) or `unavailable`. `_meta.health_analyzed_at` and `_meta.health_analyzed_commit` date the health pass, which can lag indexing; `_meta.health_analyzed_commits_distinct` appears when rows come from several passes.
diff --git a/packages/core/src/repowise/core/git_refs.py b/packages/core/src/repowise/core/git_refs.py
index 40ed79ab4..e790c30fb 100644
--- a/packages/core/src/repowise/core/git_refs.py
+++ b/packages/core/src/repowise/core/git_refs.py
@@ -11,11 +11,13 @@ from __future__ import annotations
import subprocess
from collections.abc import Sequence
from dataclasses import dataclass
+from pathlib import PurePosixPath
from .analysis.change_risk.features import _git, split_revspec
__all__ = [
"BranchRef",
+ "PathRemoval",
"ahead_behind",
"ahead_behind_many",
"change_base",
@@ -24,6 +26,7 @@ __all__ = [
"current_branch",
"default_base",
"files_by_ref",
+ "find_path_removal",
"is_shallow",
"list_branches",
"refs_containing",
@@ -291,3 +294,47 @@ def ahead_behind(repo_path: str, base: str, head: str) -> tuple[int, int]:
except ValueError:
return (0, 0)
return (ahead, behind)
+
+
+@dataclass(frozen=True)
+class PathRemoval:
+ """The most recent commit that removed a path, and where it likely went."""
+
+ commit: str
+ #: The rename target, or the files a same-named directory split into.
+ #: Empty when the deletion is not explainable either way.
+ moved_to: list[str]
+
+
+def find_path_removal(repo_path: str, path: str) -> PathRemoval | None:
+ """Where *path* went, from the newest commit that removed it. ``None`` if git never had it.
+
+ Only the newest deleting commit is inspected — an older rename chain is a
+ rarer shape than "renamed once, then left alone", and a caller asking
+ "where did this go" wants a redirect, not a full history walk.
+
+ A pathspec cannot find a rename directly: git prunes the diff to it before
+ rename detection runs, so ``-- old.py`` would see only a deletion. The
+ commit is instead read whole with ``-M``, then filtered to the line whose
+ old side is *path*. When that finds nothing, the commit is checked for a
+ split into a same-named directory (``shell.py`` -> ``shell/``, `#1929's`
+ shape): every file the commit added under ``<path without extension>/``.
+ """
+ if not path or path.startswith("/") or ".." in PurePosixPath(path).parts:
+ return None
+ sha = _read(repo_path, ["log", "-1", "--diff-filter=D", "--format=%H", "--", path])
+ if not sha:
+ return None
+
+ renames = _read(repo_path, ["show", "-M", "--diff-filter=R", "--name-status", "--format=", sha])
+ for line in renames.splitlines():
+ parts = line.split("\t")
+ if len(parts) == 3 and parts[0].startswith("R") and parts[1] == path:
+ return PathRemoval(commit=sha, moved_to=[parts[2]])
+
+ stem_dir = f"{PurePosixPath(path).with_suffix('').as_posix()}/"
+ added = _read(repo_path, ["show", "--diff-filter=A", "--name-only", "--format=", sha])
+ split_into = sorted(
+ {line.strip() for line in added.splitlines() if line.strip().startswith(stem_dir)}
+ )
+ return PathRemoval(commit=sha, moved_to=split_into)
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/targets.py b/packages/server/src/repowise/server/mcp_server/tool_health/targets.py
index d1256dcf6..554c022dd 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health/targets.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health/targets.py
@@ -6,6 +6,7 @@ from pathlib import Path
from typing import Any
from repowise.core.analysis.health.complexity.languages import NO_DIALECT_STATUS
+from repowise.core.git_refs import find_path_removal
def _expand_module_targets(
@@ -38,7 +39,7 @@ def _unresolved_targets(
unscored_paths: set[str],
repo_root: Any,
unanalysed_paths: set[str] = frozenset(),
-) -> list[dict[str, str]]:
+) -> list[dict[str, Any]]:
"""Name every requested target that produced no rows, with a reason.
Otherwise an empty ``findings`` list reads as "this file is healthy". The
@@ -51,8 +52,8 @@ def _unresolved_targets(
out = [
{
"target": t,
- "reason": (
- NO_DIALECT_STATUS
+ **(
+ {"reason": NO_DIALECT_STATUS}
if t in unanalysed_paths
else _miss_reason(t, excluded_paths, unscored_paths, repo_root)
),
@@ -70,14 +71,27 @@ def _unresolved_targets(
def _miss_reason(
target: str, excluded_paths: set[str], unscored_paths: set[str], repo_root: Any
-) -> str:
- """Why one file target produced no row."""
+) -> dict[str, Any]:
+ """Why one file target produced no row, plus a redirect when one is known."""
if target in excluded_paths:
- return "excluded"
+ return {"reason": "excluded"}
if target in unscored_paths:
- return "not_measured"
+ return {"reason": "not_measured"}
try:
on_disk = (Path(repo_root) / target).exists()
except (OSError, ValueError):
on_disk = False
- return "not_indexed" if on_disk else "no_such_path"
+ if on_disk:
+ return {"reason": "not_indexed"}
+ return {"reason": "no_such_path", **_removal_hint(repo_root, target)}
+
+
+def _removal_hint(repo_root: Any, target: str) -> dict[str, Any]:
+ """``{}``, or ``moved_to``/``removed_by_commit`` when git can explain the miss (#2633)."""
+ try:
+ removal = find_path_removal(str(repo_root), target)
+ except (OSError, ValueError):
+ return {}
+ if removal is None:
+ return {}
+ return {"removed_by_commit": removal.commit, "moved_to": removal.moved_to}
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/tool.py b/packages/server/src/repowise/server/mcp_server/tool_health/tool.py
index 308e26ccf..eb8ee7ade 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health/tool.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health/tool.py
@@ -8,6 +8,7 @@ accounting and projection passes (``paging`` / ``projection``).
from __future__ import annotations
+import asyncio
from time import perf_counter
from typing import Any
@@ -232,7 +233,11 @@ async def get_health(
# The rest stays inside the session: the analysis meta queries it, and a
# query on a closed session checks out a connection nothing returns.
if data.pop.scoped:
- result, mode_totals = build_targeted(data, req, pager, ctx.path)
+ # A missing target is explained from git history (a sync subprocess
+ # per miss), so keep it off the event loop.
+ result, mode_totals = await asyncio.to_thread(
+ build_targeted, data, req, pager, ctx.path
+ )
else:
result, mode_totals = build_dashboard(data, req, pager)
add_optional_blocks(result, data, req, pager, str(ctx.path))
diff --git a/packages/server/src/repowise/server/mcp_server/tool_risk/assessment.py b/packages/server/src/repowise/server/mcp_server/tool_risk/assessment.py
index c15dd91fe..1f0f4728b 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_risk/assessment.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_risk/assessment.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import asyncio
import contextlib
import json
from datetime import UTC, datetime
@@ -13,6 +14,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.analysis.health.engine import _has_paired_test_file, _path_basenames
from repowise.core.co_change import confidence_ratio, parse_partners
+from repowise.core.git_refs import find_path_removal
from repowise.core.persistence.models import (
GitMetadata,
GraphNode,
@@ -447,7 +449,9 @@ def _load_commit_categories(meta: Any) -> dict:
return categories
-def _unresolved_reason(target: str, lookup_path: str, repo_root: str | None) -> str:
+async def _unresolved_reason(
+ target: str, lookup_path: str, repo_root: str | None
+) -> dict[str, Any]:
"""Why *target* names nothing this tool can score, in the caller's terms.
``not_indexed`` and ``no_such_path`` are spelled as
@@ -455,18 +459,32 @@ def _unresolved_reason(target: str, lookup_path: str, repo_root: str | None) ->
borrowed: ``get_health``'s ``no_such_module`` means "no module of that
name", and it resolves a directory to ``not_indexed`` — both would
prescribe a fix that cannot help here.
+
+ ``no_such_path`` also carries ``moved_to``/``removed_by_commit`` when git
+ can explain the miss as a rename or a same-named-directory split (#2633),
+ found off the thread so the blocking git call does not stall the loop.
"""
if target.startswith("module:"):
- return "unsupported_target_kind"
+ return {"unresolved_reason": "unsupported_target_kind"}
try:
on_disk = Path(repo_root) / lookup_path if repo_root else Path(lookup_path)
if on_disk.is_dir():
- return "directory"
+ return {"unresolved_reason": "directory"}
if on_disk.exists():
- return "not_indexed"
+ return {"unresolved_reason": "not_indexed"}
except (OSError, ValueError):
pass
- return "no_such_path"
+ removal = None
+ if repo_root:
+ with contextlib.suppress(OSError, ValueError):
+ removal = await asyncio.to_thread(find_path_removal, repo_root, lookup_path)
+ if removal is None:
+ return {"unresolved_reason": "no_such_path"}
+ return {
+ "unresolved_reason": "no_such_path",
+ "removed_by_commit": removal.commit,
+ "moved_to": removal.moved_to,
+ }
async def _assess_one_target(
@@ -615,7 +633,7 @@ async def _assess_one_target(
return {
"target": target,
"resolved": False,
- "unresolved_reason": _unresolved_reason(target, lookup_path, repository.local_path),
+ **await _unresolved_reason(target, lookup_path, repository.local_path),
"risk_summary": (
f"{target} — not resolved to an indexed file; no risk signal was computed"
),
diff --git a/tests/unit/server/mcp/test_health.py b/tests/unit/server/mcp/test_health.py
index 5a87e420e..9efbb901f 100644
--- a/tests/unit/server/mcp/test_health.py
+++ b/tests/unit/server/mcp/test_health.py
@@ -7,12 +7,17 @@ test data, mirroring the conftest pattern from the REST API tests.
from __future__ import annotations
import json
+import subprocess
import pytest
from repowise.core.persistence.models import HealthFinding
+def _git(repo, *args: str) -> None:
+ subprocess.run(["git", *args], cwd=str(repo), check=True, capture_output=True)
+
+
@pytest.mark.asyncio
async def test_get_health_dashboard(setup_mcp, health_data):
from repowise.server.mcp_server import get_health
@@ -1572,6 +1577,26 @@ async def test_only_projection_keeps_unresolved(setup_mcp, health_data):
assert result["unresolved"] == [{"target": "does/not/exist.py", "reason": "no_such_path"}]
+async def test_no_such_path_redirects_to_a_renamed_file(setup_mcp, health_data, tmp_path):
+ """A stale doc's old path should not be a dead end when git knows where it went (#2633)."""
+ from repowise.server.mcp_server import get_health
+
+ _git(tmp_path, "init", "-b", "main")
+ (tmp_path / "old_name.py").write_text("def f():\n return 1\n" * 5, encoding="utf-8")
+ _git(tmp_path, "add", "old_name.py")
+ _git(tmp_path, "-c", "user.email=t@t", "-c", "user.name=t", "commit", "-m", "add old_name")
+ _git(tmp_path, "mv", "old_name.py", "new_name.py")
+ _git(tmp_path, "-c", "user.email=t@t", "-c", "user.name=t", "commit", "-m", "rename")
+
+ result = await get_health(targets=["old_name.py"])
+ unresolved = result["unresolved"][0]
+
+ assert unresolved["reason"] == "no_such_path"
+ assert unresolved["moved_to"] == ["new_name.py"]
+ assert unresolved["removed_by_commit"]
+
+
@pytest.mark.asyncio
async def test_only_projection_keeps_known_modules(setup_mcp, health_data):
"""``known_modules`` is the recovery path for a bad ``module:`` and rides along."""
diff --git a/tests/unit/server/mcp/test_risk_unresolved_targets.py b/tests/unit/server/mcp/test_risk_unresolved_targets.py
index 815dd6dd2..be6393b3a 100644
--- a/tests/unit/server/mcp/test_risk_unresolved_targets.py
+++ b/tests/unit/server/mcp/test_risk_unresolved_targets.py
@@ -7,8 +7,15 @@ path prefix bound real signal to the same card.
from __future__ import annotations
+import subprocess
+from pathlib import Path
+
import pytest
+
+def _git(repo: Path, *args: str) -> None:
+ subprocess.run(["git", *args], cwd=str(repo), check=True, capture_output=True)
+
#: Fields no unresolved card may carry. The four ``*_total``/direction counts
#: are ``include=["graph"]`` keys popped from every card otherwise, so tests
#: asserting their absence must ask for the block or prove nothing.
@@ -74,6 +81,26 @@ async def test_missing_path_reports_the_reason_that_names_the_fix(setup_mcp, tmp
assert result["targets"]["src/auth/typo.py"]["unresolved_reason"] == "no_such_path"
+async def test_a_renamed_path_redirects_to_its_new_name(setup_mcp, tmp_path):
+ """A stale doc's old path should not be a dead end when git knows where it went (#2633)."""
+ from repowise.server.mcp_server import get_risk
+
+ _git(tmp_path, "init", "-b", "main")
+ (tmp_path / "old_name.py").write_text("def f():\n return 1\n" * 5, encoding="utf-8")
+ _git(tmp_path, "add", "old_name.py")
+ _git(tmp_path, "-c", "user.email=t@t", "-c", "user.name=t", "commit", "-m", "add old_name")
+ _git(tmp_path, "mv", "old_name.py", "new_name.py")
+ _git(tmp_path, "-c", "user.email=t@t", "-c", "user.name=t", "commit", "-m", "rename")
+
+ result = await get_risk(["old_name.py"])
+ card = result["targets"]["old_name.py"]
+
+ assert card["unresolved_reason"] == "no_such_path"
+ assert card["moved_to"] == ["new_name.py"]
+ assert card["removed_by_commit"]
+
+
@pytest.mark.asyncio
async def test_a_real_file_keeps_its_real_counts(setup_mcp):
"""The discriminator: rejecting bad targets must not reject good ones."""
diff --git a/tests/unit/test_git_refs.py b/tests/unit/test_git_refs.py
index f65c9342b..426d8a023 100644
--- a/tests/unit/test_git_refs.py
+++ b/tests/unit/test_git_refs.py
@@ -14,6 +14,7 @@ from repowise.core.git_refs import (
commit_file_sets,
current_branch,
default_base,
+ find_path_removal,
list_branches,
remote_name,
resolve,
@@ -196,6 +197,72 @@ class TestCommitFileSets:
assert commit_file_sets(str(tmp_path / "nowhere_at_all"), "main..feat") == []
+class TestFindPathRemoval:
+ def test_a_pure_rename_names_its_new_path(self, tmp_path: Path) -> None:
+ root = tmp_path / "renamed"
+ root.mkdir()
+ _run(root, "init", "-b", "main")
+ _commit(root, "old_name.py", "def f():\n return 1\n" * 5, "add old_name")
+ _run(root, "mv", "old_name.py", "new_name.py")
+ _run(root, "-c", "user.email=t@t", "-c", "user.name=t", "commit", "-m", "rename")
+
+ removal = find_path_removal(str(root), "old_name.py")
+
+ assert removal is not None
+ assert removal.moved_to == ["new_name.py"]
+
+ def test_a_split_into_a_same_named_directory_lists_its_files(self, tmp_path: Path) -> None:
+ """The #1929 shape: ``shell.py`` becomes the package ``shell/``."""
+ root = tmp_path / "split"
+ root.mkdir()
+ _run(root, "init", "-b", "main")
+ _commit(root, "shell.py", "def run():\n pass\n", "add shell")
+ _run(root, "rm", "shell.py")
+ (root / "shell").mkdir()
+ # Content unlike the original on both sides: close enough to it and
+ # git's similarity index calls it a rename instead of a split, and the
+ # rename branch above wins before this one is ever reached.
+ (root / "shell" / "__init__.py").write_text("PACKAGE_VERSION = 1\n", encoding="utf-8")
+ (root / "shell" / "commands.py").write_text(
+ "class Commands:\n def dispatch(self, *args):\n raise NotImplementedError\n",
+ encoding="utf-8",
+ )
+ _run(root, "add", "-A")
+ _run(root, "-c", "user.email=t@t", "-c", "user.name=t", "commit", "-m", "split into shell/")
+
+ removal = find_path_removal(str(root), "shell.py")
+
+ assert removal is not None
+ assert removal.moved_to == ["shell/__init__.py", "shell/commands.py"]
+
+ def test_an_unexplained_deletion_names_the_commit_with_nothing_moved(
+ self, tmp_path: Path
+ ) -> None:
+ root = tmp_path / "deleted"
+ root.mkdir()
+ _run(root, "init", "-b", "main")
+ _commit(root, "gone.py", "x = 1\n", "add gone")
+ _run(root, "rm", "gone.py")
+ _run(root, "-c", "user.email=t@t", "-c", "user.name=t", "commit", "-m", "delete gone")
+
+ removal = find_path_removal(str(root), "gone.py")
+
+ assert removal is not None
+ assert removal.moved_to == []
+
+ def test_a_path_never_committed_yields_none(self, repo: Path) -> None:
+ assert find_path_removal(str(repo), "never_existed.py") is None
+
+ def test_a_path_still_on_disk_yields_none(self, repo: Path) -> None:
+ assert find_path_removal(str(repo), "base.txt") is None
+
+ def test_a_non_repository_yields_none(self, tmp_path: Path) -> None:
+ assert find_path_removal(str(tmp_path / "nowhere_at_all"), "gone.py") is None
+
+ def test_a_path_escaping_the_repo_is_rejected(self, repo: Path) -> None:
+ assert find_path_removal(str(repo), "../outside.py") is None
+
+
@pytest.mark.parametrize(
"url",
[