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): say which checkout and commit change risk and health read (#3719)

Swati Ahujabc75a0fd696a
diff --git a/packages/claude-mod/test/fixtures/change-risk/nothing-to-score.json b/packages/claude-mod/test/fixtures/change-risk/nothing-to-score.json
index 276021ade..1b82e73c9 100644
--- a/packages/claude-mod/test/fixtures/change-risk/nothing-to-score.json
+++ b/packages/claude-mod/test/fixtures/change-risk/nothing-to-score.json
@@ -4,7 +4,7 @@
"warning": "No counted file changes in 'HEAD' (check the revspec, extensions, or exclusion filters).",
"scored_repo": {
"root": "C:\\work\\requests",
- "head": "3bb56ba566ce783ebdc4e61929522fd1648c2527"
+ "head": "3bb56ba566ce"
},
"_meta": {
"contract_version": 2,
diff --git a/packages/cli/src/repowise/cli/commands/impacted_tests_cmd.py b/packages/cli/src/repowise/cli/commands/impacted_tests_cmd.py
index cda182c4a..0765dea26 100644
--- a/packages/cli/src/repowise/cli/commands/impacted_tests_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/impacted_tests_cmd.py
@@ -141,7 +141,7 @@ def impacted_tests_command(
cannot_evaluate(fmt, exc.code, str(exc))
explain = explain.replace("\\", "/").removeprefix("./") if explain else None
- checkout = read_checkout(repo_path)
+ checkout = read_checkout(repo_path, change.head)
plan = plan_scopes(change, config, checkout) if config is not None else None
result = run_async(_collect(repo_path, change, checkout, config, explain, plan, prioritize))
result["diff"] = change.label
diff --git a/packages/core/src/repowise/core/analysis/test_collection.py b/packages/core/src/repowise/core/analysis/test_collection.py
index 1992250aa..203ff1abf 100644
--- a/packages/core/src/repowise/core/analysis/test_collection.py
+++ b/packages/core/src/repowise/core/analysis/test_collection.py
@@ -59,8 +59,14 @@ class Checkout:
holding: Callable[[Collection[str]], Collection[str] | None] | None = None
-def read_checkout(repo_path) -> Checkout:
- """Tracked files, their conftests and pytest configs, and pytest's collection roots."""
+def read_checkout(repo_path, head: str | None = None) -> Checkout:
+ """Tracked files, their conftests and pytest configs, and pytest's collection roots.
+
+ With *head* (a change's head commit) ``exists`` also counts that commit's
+ tree: a change read from another worktree's branch holds files this working
+ tree lacks. Ceiling: tracked paths and texts still come from the working
+ tree; reading them at *head* too is the upgrade.
+ """
from .. import git_refs
from ..pytest_roots import PYTEST_CONFIG_NAMES, read_pytest_roots
from .test_selection import is_code_file, is_scan_source
@@ -81,9 +87,18 @@ def read_checkout(repo_path) -> Checkout:
if (text := read(p)) is not None
]
roots = read_pytest_roots((p, t) for p, t in texts if Path(p).name in PYTEST_CONFIG_NAMES)
- return Checkout(
- tracked, texts, roots, read, lambda p: (root / p).is_file(), lambda n: _git_holding(root, n)
- )
+ at_head: list[frozenset[str]] = []
+
+ def exists(path: str) -> bool:
+ if (root / path).is_file():
+ return True
+ if head is None:
+ return False
+ if not at_head: # read once, on the first path the disk lacks
+ at_head.append(git_refs.tracked_paths_at(str(root), head))
+ return path in at_head[0]
+
+ return Checkout(tracked, texts, roots, read, exists, lambda n: _git_holding(root, n))
# A cold grep of a large checkout takes seconds; past this the full read answers.
diff --git a/packages/core/src/repowise/core/git_refs.py b/packages/core/src/repowise/core/git_refs.py
index 7818da118..5510ff165 100644
--- a/packages/core/src/repowise/core/git_refs.py
+++ b/packages/core/src/repowise/core/git_refs.py
@@ -11,7 +11,7 @@ from __future__ import annotations
import subprocess
from collections.abc import Sequence
from dataclasses import dataclass
-from pathlib import PurePosixPath
+from pathlib import Path, PurePosixPath
from .analysis.change_risk.features import _git, split_revspec
from .forges import parse_remote
@@ -21,6 +21,7 @@ __all__ = [
"PathRemoval",
"ahead_behind",
"ahead_behind_many",
+ "branch_with_path",
"change_base",
"changed_files",
"commit_file_sets",
@@ -356,3 +357,30 @@ def find_path_removal(repo_path: str, path: str) -> PathRemoval | None:
{line.strip() for line in added.splitlines() if line.strip().startswith(stem_dir)}
)
return PathRemoval(commit=sha, moved_to=split_into)
+
+
+def branch_with_path(repo_path: str, path: str) -> str | None:
+ """The newest other local branch whose tip has *path*, ``None`` when none does.
+
+ Worktrees share the repository's branches, so this finds a file that exists
+ only in another worktree's branch. Two git calls whatever the branch count.
+ Ceiling: a detached worktree HEAD is not a branch and is not looked at.
+ """
+ from .analysis.doc_drift.suggest import git_run
+
+ # A path that escapes the tree (``../x``, ``/x``) is simply missing in every
+ # tree, and the read only reads, so no guard is needed here.
+ listing = _read(
+ repo_path,
+ ["for-each-ref", "--sort=-committerdate", "--format=%(refname:short)%09%(HEAD)", "refs/heads"],
+ )
+ # ``*`` marks the checked-out branch, whose tree the caller already read.
+ rows = (line.partition("\t") for line in listing.splitlines())
+ names = [name for name, _, mark in rows if mark.strip() != "*"]
+ # No other branch sends an empty request, which answers with no lines: None.
+ request = "".join(f"refs/heads/{name}:{path}\n" for name in names).encode("utf-8")
+ ran = git_run(Path(repo_path), "cat-file", "--batch-check=%(objecttype)", stdin=request)
+ lines = ran[1].decode("utf-8", "replace").splitlines() if ran and ran[0] == 0 else []
+ if len(lines) != len(names):
+ return None
+ return next((name for name, kind in zip(names, lines, strict=True) if kind == "blob"), None)
diff --git a/packages/server/src/repowise/server/mcp_server/_test_selection.py b/packages/server/src/repowise/server/mcp_server/_test_selection.py
index 5e97ce63c..cf76f11ee 100644
--- a/packages/server/src/repowise/server/mcp_server/_test_selection.py
+++ b/packages/server/src/repowise/server/mcp_server/_test_selection.py
@@ -103,7 +103,7 @@ async def _select(
from repowise.core.persistence.database import get_session
from repowise.server.mcp_server._helpers import _get_repo
- checkout = await asyncio.to_thread(read_checkout, repo_path)
+ checkout = await asyncio.to_thread(read_checkout, repo_path, change.head)
async with get_session(session_factory) as session:
repository = await _get_repo(session)
result, selection = await select_for_change(
diff --git a/packages/server/src/repowise/server/mcp_server/tool_change_risk.py b/packages/server/src/repowise/server/mcp_server/tool_change_risk.py
index 33787b50c..f7281f114 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_change_risk.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_change_risk.py
@@ -28,6 +28,7 @@ from repowise.core.analysis.change_risk import (
normalize_extensions,
score_live_change,
)
+from repowise.core.analysis.change_risk.features import revspec_head
from repowise.core.analysis.change_risk.render import LIMITS, size_text
from repowise.core.analysis.prior_fix_impact import (
FixRecord,
@@ -68,7 +69,6 @@ from repowise.server.mcp_server._helpers import (
resolve_enum_argument,
)
from repowise.server.mcp_server._meta import build_meta as _build_meta
-from repowise.server.mcp_server._meta import read_live_head
from repowise.server.mcp_server._test_impact import (
_norm,
cross_repo_tests,
@@ -266,7 +266,7 @@ async def _attach_branch_blocks(
# would reach the caller; both are pure cost on that path.
if finding_id is not None:
return None
- overlap = await _branch_overlap_block(ctx, changed, collector)
+ overlap = await _branch_overlap_block(ctx, changed, collector, revspec_head(revspec))
if overlap is not None:
payload["branch_overlap"] = overlap
return await _independent_changes_block(ctx, changed, collector, revspec)
@@ -360,8 +360,10 @@ async def get_change_risk(
ignored: list[dict] = []
include_set = _include_blocks(include, ignored)
payload, diagnostics = _shape_payload(result, include_set, revspec)
+ scored = await asyncio.to_thread(_scored_repo, str(ctx.path), revspec, result.working_tree)
if result.features.nf == 0:
- return await _nothing_to_score(ctx, payload["ref"], started)
+ return await _nothing_to_score(ctx, payload["ref"], scored, started)
+ payload = {"ref": payload.pop("ref"), "scored_repo": scored, **payload}
# Changed lines over the SAME file universe the score counted (its
# extensions + riskignore + request excludes), so nothing downstream
# disagrees with the score about which files the change touches. Read once
@@ -580,7 +582,20 @@ def _attach_health(
payload.update(ordered)
-async def _nothing_to_score(ctx: Any, ref: str, started: float) -> dict:
+def _scored_repo(path: str, revspec: str | None, working_tree: bool) -> dict[str, Any]:
+ """The checkout the change was read in and the commit its head resolved to.
+
+ ``HEAD`` or a branch name resolves in the served checkout, not in the
+ caller's worktree, so naming both makes a review of the wrong tree visible.
+ Uncommitted work is marked, so its ``head`` does not read as the change.
+ """
+ from repowise.core import git_refs
+
+ head = git_refs.resolve(path, revspec_head(revspec))[:12] or None
+ return {"root": path, "head": head, **({"working_tree": True} if working_tree else {})}
+
+
+async def _nothing_to_score(ctx: Any, ref: str, scored: dict[str, Any], started: float) -> dict:
"""An empty diff, reported as one rather than scored.
Scoring it anyway produced a real-looking "Below typical" verdict, which
@@ -594,7 +609,7 @@ async def _nothing_to_score(ctx: Any, ref: str, started: float) -> dict:
f"No counted file changes in {ref!r} "
"(check the revspec, extensions, or exclusion filters)."
),
- "scored_repo": {"root": str(ctx.path), "head": read_live_head(str(ctx.path))},
+ "scored_repo": scored,
"_meta": _build_meta(
timing_ms=(time.perf_counter() - started) * 1000,
repository=await _repository(ctx),
@@ -1157,21 +1172,25 @@ async def _independent_changes_block(
return block
-def _scan_from_trunk(path: str, files: list[str]) -> Any:
- """The base lookup and the scan, both git, in one hop off the event loop."""
+def _scan_from_trunk(path: str, files: list[str], current: str) -> Any:
+ """The base lookup and the scan, both git, in one hop off the event loop.
+
+ *current* is the reviewed change's head, so a branch reviewed from another
+ worktree is the change itself, not a rival to the served checkout's branch.
+ """
from repowise.core.analysis.branch_overlap import scan_branches
from repowise.core.git_refs import default_base
- return scan_branches(path, files, base=default_base(path))
+ return scan_branches(path, files, base=default_base(path), current=current)
-async def _scan_overlap(ctx: Any, files: list[str]) -> Any:
+async def _scan_overlap(ctx: Any, files: list[str], current: str = "HEAD") -> Any:
"""Run the branch scan, with the index when one opens and without when it does not."""
from repowise.core.analysis.branch_overlap import rank_with_index
from repowise.core.persistence.database import get_session
path = str(ctx.path)
- scan = await asyncio.to_thread(_scan_from_trunk, path, files)
+ scan = await asyncio.to_thread(_scan_from_trunk, path, files, current)
session_factory = getattr(ctx, "session_factory", None)
if session_factory is not None:
try:
@@ -1184,7 +1203,7 @@ async def _scan_overlap(ctx: Any, files: list[str]) -> Any:
async def _branch_overlap_block(
- ctx: Any, changed: dict[str, set[int]], collector: OmissionCollector
+ ctx: Any, changed: dict[str, set[int]], collector: OmissionCollector, current: str = "HEAD"
) -> dict[str, Any] | None:
"""Other open branches editing the files this change edits, or ``None``.
@@ -1196,7 +1215,7 @@ async def _branch_overlap_block(
return None
try:
overlap = await asyncio.wait_for(
- _scan_overlap(ctx, sorted(changed)), timeout=_BRANCH_OVERLAP_TIMEOUT_SECONDS
+ _scan_overlap(ctx, sorted(changed), current), timeout=_BRANCH_OVERLAP_TIMEOUT_SECONDS
)
except (TimeoutError, subprocess.SubprocessError, OSError):
return None
@@ -1306,7 +1325,6 @@ async def _patch_coverage_block(
the last coverage ingest came after the newest edit to the changed files.
"""
from repowise.core import git_refs
- from repowise.core.analysis.change_risk.features import revspec_head
from repowise.core.analysis.health.coverage import configured_coverage
from repowise.core.analysis.health.coverage.freshness import newest_mtime
from repowise.core.analysis.patch_coverage import (
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 554c022dd..3252c85e5 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,7 +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
+from repowise.server.repo_paths import missing_path_hint
def _expand_module_targets(
@@ -83,15 +83,5 @@ def _miss_reason(
on_disk = False
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}
+ root = str(repo_root) if repo_root else None
+ return {"reason": "no_such_path", **missing_path_hint(root, target)}
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 ff8791bdd..6bc583134 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
@@ -15,7 +15,6 @@ from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.analysis.pr_blast import untested_files
from repowise.core.analysis.security_scan import SYMBOL_NAME_KINDS
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,
Repository,
@@ -26,7 +25,7 @@ from repowise.server.mcp_server._helpers import (
is_excluded,
)
from repowise.server.mcp_server._meta import served_root
-from repowise.server.repo_paths import normalize_target_path
+from repowise.server.repo_paths import missing_path_hint, normalize_target_path
#: A file carrying this many counted bug fixes reads as bug-prone. Same trigger
#: the PR bot uses for prior defects, so the two surfaces agree on "a lot".
@@ -417,9 +416,9 @@ async def _unresolved_reason(
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.
+ ``no_such_path`` also carries what :func:`missing_path_hint` finds (a
+ rename, or another branch holding the path), off the thread so the
+ blocking git calls do not stall the loop.
"""
if target.startswith("module:"):
return {"unresolved_reason": "unsupported_target_kind"}
@@ -431,17 +430,8 @@ async def _unresolved_reason(
return {"unresolved_reason": "not_indexed"}
except (OSError, ValueError):
pass
- 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,
- }
+ hint = await asyncio.to_thread(missing_path_hint, repo_root, lookup_path)
+ return {"unresolved_reason": "no_such_path", **hint}
async def _assess_one_target(
diff --git a/packages/server/src/repowise/server/repo_paths.py b/packages/server/src/repowise/server/repo_paths.py
index 7b1de7e04..d516b936f 100644
--- a/packages/server/src/repowise/server/repo_paths.py
+++ b/packages/server/src/repowise/server/repo_paths.py
@@ -7,6 +7,7 @@ risk tool and the code-health routes.
from __future__ import annotations
from pathlib import Path
+from typing import Any
def normalize_target_path(target: str, repo_root: str | None = None) -> str:
@@ -47,3 +48,35 @@ def normalize_target_path(target: str, repo_root: str | None = None) -> str:
# Collapse duplicate slashes and any trailing separator.
parts = [p for p in normalized.split("/") if p]
return "/".join(parts)
+
+
+def missing_path_hint(repo_root: str | None, path: str) -> dict[str, Any]:
+ """Why a ``no_such_path`` target is absent from *repo_root*, when git can say.
+
+ ``moved_to``/``removed_by_commit`` when the served branch renamed or removed
+ it (#2633). Otherwise, when another local branch has it (a worktree's
+ branch, typically), ``on_branch`` and a ``note`` naming the checkout and
+ commit that were read, so the miss does not read as a typo.
+ """
+ from repowise.core.git_head import read_head_commit
+ from repowise.core.git_refs import branch_with_path, find_path_removal
+
+ if not repo_root:
+ return {}
+ try:
+ removal = find_path_removal(repo_root, path)
+ if removal is not None:
+ return {"removed_by_commit": removal.commit, "moved_to": removal.moved_to}
+ branch = branch_with_path(repo_root, path)
+ except (OSError, ValueError):
+ return {}
+ if branch is None:
+ return {}
+ head = (read_head_commit(repo_root) or "")[:12] or "its HEAD"
+ return {
+ "on_branch": branch,
+ "note": (
+ f"Not in the served checkout {repo_root} at {head}; branch {branch} has it. "
+ "Only the served checkout is indexed."
+ ),
+ }
diff --git a/tests/unit/analysis/test_selection_scopes.py b/tests/unit/analysis/test_selection_scopes.py
index a66387596..7a95c83bd 100644
--- a/tests/unit/analysis/test_selection_scopes.py
+++ b/tests/unit/analysis/test_selection_scopes.py
@@ -403,3 +403,29 @@ def test_a_blob_read_that_stops_early_does_not_read_as_unmoved(tmp_path) -> None
assert _unread(tmp_path, specs, whole) == set() # added.py is absent at old
assert _unread(tmp_path, specs, {(old, "kept.py"): b"x"}) == {"kept.py", "added.py"}
assert _unread(tmp_path, specs, None) == set() # nothing read: the caller fails closed
+
+
+def test_read_checkout_with_a_head_answers_exists_for_that_commit(tmp_path) -> None:
+ """A change read from another worktree's branch: its tests exist at its head, not on disk."""
+ import subprocess
+
+ from repowise.core.analysis.test_collection import read_checkout
+
+ def git(*args: str) -> str:
+ return subprocess.run(
+ ["git", "-c", "user.email=t@t", "-c", "user.name=t", *args],
+ cwd=tmp_path, check=True, capture_output=True, text=True,
+ ).stdout.strip() # fmt: skip
+
+ git("init", "-q", "-b", "main")
+ (tmp_path / "test_a.py").write_text("def test_a():\n pass\n", encoding="utf-8")
+ git("add", "-A")
+ git("commit", "-q", "-m", "seed")
+ head = git("rev-parse", "HEAD")
+ git("rm", "-q", "test_a.py")
+ git("commit", "-q", "-m", "served branch drops it")
+
+ assert not read_checkout(tmp_path).exists("test_a.py")
+ at_head = read_checkout(tmp_path, head)
+ assert at_head.exists("test_a.py")
+ assert not at_head.exists("test_b.py")
diff --git a/tests/unit/server/mcp/test_branch_overlap_block.py b/tests/unit/server/mcp/test_branch_overlap_block.py
index 328c6cd84..9c10f3913 100644
--- a/tests/unit/server/mcp/test_branch_overlap_block.py
+++ b/tests/unit/server/mcp/test_branch_overlap_block.py
@@ -94,6 +94,23 @@ async def test_block_names_only_the_overlapping_branch_and_states_its_basis(tmp_
assert "edit files this change also edits" in block["summary"]
+async def test_a_branch_reviewed_by_its_sha_is_the_change_not_a_rival(tmp_path):
+ """A worktree branch reviewed from the served checkout: the scan is from its head."""
+ repo = _repo(tmp_path, others={"reviewed": {"a.py": "a reviewed\n"}})
+ head = subprocess.run(
+ ["git", "rev-parse", "reviewed"], cwd=repo, check=True, capture_output=True, text=True
+ ).stdout.strip()
+
+ block = await _branch_overlap_block(
+ _ctx(repo), {"a.py": {1}}, OmissionCollector("t", repo_root=tmp_path), head
+ )
+
+ assert block is not None
+ assert block["current"] == head
+ # The served checkout's branch edits a.py too, so it is the rival now.
+ assert [entry["branch"] for entry in block["branches"]] == ["work"]
+
+
async def test_branch_list_is_capped_and_says_by_how_much(tmp_path):
over = _BRANCH_OVERLAP_LIMIT + 2
repo = _repo(
diff --git a/tests/unit/server/mcp/test_change_risk.py b/tests/unit/server/mcp/test_change_risk.py
index 3f546f49b..7452ee96c 100644
--- a/tests/unit/server/mcp/test_change_risk.py
+++ b/tests/unit/server/mcp/test_change_risk.py
@@ -177,6 +177,40 @@ async def test_get_change_risk_empty_diff_warns(tmp_path, monkeypatch) -> None:
assert result["scored_repo"]["root"] == str(repo)
+async def test_get_change_risk_names_the_checkout_and_commit_it_scored(tmp_path, monkeypatch) -> None:
+ """``HEAD`` resolves in the served checkout, so a worktree caller sees whose HEAD it was."""
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ _git(["init", "-q", "-b", "main"], repo)
+ _commit(repo, {"README.md": "# seed\n"}, "chore: seed")
+ _git(["worktree", "add", "-q", "-b", "feature", str(tmp_path / "wt")], repo)
+ _commit(tmp_path / "wt", {"app.py": "value = 1\n"}, "feat: on the worktree branch")
+ _commit(repo, {"main.py": "value = 2\n"}, "feat: on main")
+
+ def sha(ref: str) -> str:
+ return subprocess.run(
+ ["git", "rev-parse", ref], cwd=repo, check=True, capture_output=True, text=True
+ ).stdout.strip()
+
+ module = importlib.import_module("repowise.server.mcp_server.tool_change_risk")
+
+ async def _context(_: str | None) -> SimpleNamespace:
+ return SimpleNamespace(path=str(repo))
+
+ monkeypatch.setattr(module, "_resolve_repo_context", _context)
+ served = await module.get_change_risk("HEAD~1..HEAD", baseline=0)
+ branch = await module.get_change_risk(f"HEAD~1..{sha('feature')}", baseline=0)
+
+ assert served["scored_repo"] == {"root": str(repo), "head": sha("main")[:12]}
+ assert branch["scored_repo"] == {"root": str(repo), "head": sha("feature")[:12]}
+
+ # Uncommitted work is marked, so its head does not read as the scored change.
+ (repo / "main.py").write_text("value = 3\n", encoding="utf-8")
+ dirty = await module.get_change_risk(baseline=0)
+ assert dirty["scored_repo"] == {"root": str(repo), "head": sha("main")[:12], "working_tree": True}
+
+
@pytest.mark.asyncio
async def test_get_change_risk_rejects_repo_all() -> None:
module = importlib.import_module("repowise.server.mcp_server.tool_change_risk")
diff --git a/tests/unit/server/mcp/test_health.py b/tests/unit/server/mcp/test_health.py
index b096c208c..4e389e08d 100644
--- a/tests/unit/server/mcp/test_health.py
+++ b/tests/unit/server/mcp/test_health.py
@@ -1898,6 +1898,26 @@ async def test_no_such_path_redirects_to_a_renamed_file(setup_mcp, health_data,
assert unresolved["removed_by_commit"]
+async def test_no_such_path_names_the_branch_that_has_it(setup_mcp, health_data, tmp_path):
+ """A file only a worktree's branch has is absent from the served checkout, not a typo."""
+ from repowise.server.mcp_server import get_health
+
+ ident = ("-c", "user.email=t@t", "-c", "user.name=t")
+ _git(tmp_path, "init", "-b", "main")
+ _git(tmp_path, *ident, "commit", "--allow-empty", "-m", "seed")
+ _git(tmp_path, "worktree", "add", "-b", "feature", str(tmp_path / "wt"), "main")
+ (tmp_path / "wt" / "only_there.py").write_text("x = 1\n", encoding="utf-8")
+ _git(tmp_path / "wt", "add", "only_there.py")
+ _git(tmp_path / "wt", *ident, "commit", "-m", "add on the branch")
+
+ unresolved = (await get_health(targets=["only_there.py"]))["unresolved"][0]
+
+ assert unresolved["reason"] == "no_such_path"
+ assert unresolved["on_branch"] == "feature"
+ assert "branch feature has it" in unresolved["note"]
+
+
@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 be6393b3a..b35d364b0 100644
--- a/tests/unit/server/mcp/test_risk_unresolved_targets.py
+++ b/tests/unit/server/mcp/test_risk_unresolved_targets.py
@@ -101,6 +101,26 @@ async def test_a_renamed_path_redirects_to_its_new_name(setup_mcp, tmp_path):
assert card["removed_by_commit"]
+async def test_a_path_on_another_branch_names_that_branch(setup_mcp, tmp_path):
+ """A file committed on a worktree's branch is absent here, not a typo."""
+ from repowise.server.mcp_server import get_risk
+
+ ident = ("-c", "user.email=t@t", "-c", "user.name=t")
+ _git(tmp_path, "init", "-b", "main")
+ _git(tmp_path, *ident, "commit", "--allow-empty", "-m", "seed")
+ _git(tmp_path, "worktree", "add", "-b", "feature", str(tmp_path / "wt"), "main")
+ (tmp_path / "wt" / "only_there.py").write_text("x = 1\n", encoding="utf-8")
+ _git(tmp_path / "wt", "add", "only_there.py")
+ _git(tmp_path / "wt", *ident, "commit", "-m", "add on the branch")
+
+ card = (await get_risk(["only_there.py"]))["targets"]["only_there.py"]
+
+ assert card["unresolved_reason"] == "no_such_path"
+ assert card["on_branch"] == "feature"
+ assert "branch feature has it" in card["note"]
+
+
@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/server/mcp/test_tool_change_risk.py b/tests/unit/server/mcp/test_tool_change_risk.py
index 936b201b5..510830b40 100644
--- a/tests/unit/server/mcp/test_tool_change_risk.py
+++ b/tests/unit/server/mcp/test_tool_change_risk.py
@@ -317,7 +317,7 @@ async def test_branch_scan_falls_back_to_git_only_when_the_index_will_not_open(
):
"""Branch overlap needs only git, so an index failure costs the ranking, not the block."""
scan = SimpleNamespace(overlap="git-only overlap")
- monkeypatch.setattr(tool, "_scan_from_trunk", lambda _path, _files: scan)
+ monkeypatch.setattr(tool, "_scan_from_trunk", lambda _path, _files, _current: scan)
_get_repo_raising(monkeypatch, LookupError("no repo"))
ctx = SimpleNamespace(path="/repo", session_factory=factory)
assert await tool._scan_overlap(ctx, ["a.py"]) == "git-only overlap"
diff --git a/tests/unit/test_git_refs.py b/tests/unit/test_git_refs.py
index 973c5467a..33cccb2bd 100644
--- a/tests/unit/test_git_refs.py
+++ b/tests/unit/test_git_refs.py
@@ -10,6 +10,7 @@ import pytest
from repowise.core.git_refs import (
BranchRef,
ahead_behind,
+ branch_with_path,
changed_files,
commit_file_sets,
current_branch,
@@ -197,6 +198,24 @@ class TestCommitFileSets:
assert commit_file_sets(str(tmp_path / "nowhere_at_all"), "main..feat") == []
+class TestBranchWithPath:
+ def test_names_the_other_branch_that_has_the_path(self, repo: Path) -> None:
+ assert branch_with_path(str(repo), "feat_two.txt") == "feat"
+
+ def test_skips_the_checked_out_branch(self, repo: Path) -> None:
+ # Only main, the checked-out branch whose tree the caller read, has it.
+ _commit(repo, "late.txt", "late\n", "main only")
+ assert branch_with_path(str(repo), "late.txt") is None
+ assert branch_with_path(str(repo), "typo.txt") is None
+
+ def test_finds_a_file_committed_in_a_linked_worktree(self, repo: Path, tmp_path: Path) -> None:
+ wt = tmp_path / "wt"
+ _run(repo, "worktree", "add", "-b", "wt-branch", str(wt), "main")
+ _commit(wt, "only_in_wt.txt", "x\n", "worktree work")
+
+ assert branch_with_path(str(repo), "only_in_wt.txt") == "wt-branch"
+
+
class TestFindPathRemoval:
def test_a_pure_rename_names_its_new_path(self, tmp_path: Path) -> None:
root = tmp_path / "renamed"