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): tier dead code after the cross-repo cut and keep partial evidence from reading clear (#4196)

Raghav Chamadiyaea7defcb18a3
diff --git a/packages/cli/src/repowise/cli/commands/risk_cmd/card.py b/packages/cli/src/repowise/cli/commands/risk_cmd/card.py
index 7bc4429c7..964051bc7 100644
--- a/packages/cli/src/repowise/cli/commands/risk_cmd/card.py
+++ b/packages/cli/src/repowise/cli/commands/risk_cmd/card.py
@@ -130,18 +130,17 @@ def _print_cross_repo(cross: dict) -> None:
repos = cross.get("affected_repos") or []
historical = cross.get("cross_repo_consumers") or []
contracts = cross.get("contract_consumers") or []
- console.print(
- " [bold]Crosses repo boundaries[/bold] [dim]"
- f"{cross.get('cross_repo_consumers_total', len(historical))} historical co-change(s)"
- + (
- f", {cross.get('contract_consumers_total', len(contracts))} "
- "typed contract consumer(s)"
- if contracts
- else ""
+ parts = []
+ if historical:
+ parts.append(
+ f"{cross.get('cross_repo_consumers_total', len(historical))} historical co-change(s)"
)
- + (f" in {', '.join(str(r) for r in repos)}" if repos else "")
- + "[/dim]"
- )
+ if contracts:
+ parts.append(
+ f"{cross.get('contract_consumers_total', len(contracts))} typed contract consumer(s)"
+ )
+ where = f" in {', '.join(str(r) for r in repos)}" if repos else ""
+ console.print(f" [bold]Crosses repo boundaries[/bold] [dim]{', '.join(parts)}{where}[/dim]")
def _print_defects(defect: dict | None) -> None:
diff --git a/packages/core/src/repowise/core/analysis/dead_code/serving.py b/packages/core/src/repowise/core/analysis/dead_code/serving.py
index c52b197a2..1c49dc952 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/serving.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/serving.py
@@ -178,14 +178,18 @@ def apply_filters(findings: list, filters: FindingFilters) -> list:
return [f for f in findings if all(check(f) for check in checks)]
-def summary_counts(shown: list) -> dict[str, Any]:
+def summary_counts(
+ shown: list, withdrawn: Callable[[Any], bool] | None = None
+) -> dict[str, Any]:
"""Counts over every shown open finding; merge per-repo parts with
- :func:`merge_summary_counts` so no caller holds every repo's rows at once."""
+ :func:`merge_summary_counts` so no caller holds every repo's rows at once.
+ *withdrawn* (see :func:`cross_repo_withdraws`) keeps safe counts in step with the tiers.
+ """
by_kind: dict[str, int] = {}
for f in shown:
kind = field(f, "kind")
by_kind[kind] = by_kind.get(kind, 0) + 1
- safe = [f for f in shown if is_safe(f)]
+ safe = [f for f in shown if is_safe(f) and not (withdrawn and withdrawn(f))]
return {
"total_findings": len(shown),
"deletable_lines": sum(field(f, "lines") or 0 for f in safe),
@@ -418,14 +422,29 @@ def compute_impact(tiers: dict) -> dict:
return {
"total_lines_reclaimable": total_lines,
"safe_lines_reclaimable": safe_lines,
- "recommendation": (
+ "recommendation": _recommendation(tiers),
+ }
+
+
+def _recommendation(tiers: dict) -> str:
+ """Point at the best tier that has findings, never at an empty one."""
+ if tiers.get("high", {}).get("count"):
+ return (
"Start with the 'high' tier — these have no references in the graph and are the "
"strongest cleanup candidates. Confirm each (runtime-loaded config/bootstrap/database "
"files are flagged but never auto-marked safe), then review 'medium' tier with your team."
- if total_lines > 0
- else "No dead code found matching your filters."
- ),
- }
+ )
+ if tiers.get("medium", {}).get("count"):
+ return (
+ "Review the 'medium' tier with your team — likely unused but may have indirect "
+ "references. Confirm each before deleting."
+ )
+ if tiers.get("low", {}).get("count"):
+ return (
+ "Only 'low' tier findings — they may be used via dynamic imports or reflection. "
+ "Investigate before deleting."
+ )
+ return "No dead code found matching your filters."
class CrossRepoLookup(Protocol):
@@ -436,27 +455,39 @@ class CrossRepoLookup(Protocol):
def get_repos_depending_on(self, repo_alias: str) -> list[str]: ...
+def cross_repo_withdraws(
+ lookup: CrossRepoLookup | None, alias: str | None, file_path: str, kind: Any
+) -> bool:
+ """Whether :func:`adjust_cross_repo` would withdraw ``safe_to_delete``."""
+ if lookup is None or not alias:
+ return False
+ if lookup.has_cross_repo_consumers(alias, file_path):
+ return True
+ return kind == "unused_export" and bool(lookup.get_repos_depending_on(alias))
+
+
def adjust_cross_repo(
- tiers: dict, lookup: CrossRepoLookup | None, repo_alias: str | None = None
+ findings: list[dict], lookup: CrossRepoLookup | None, repo_alias: str | None = None
) -> None:
- """Lower confidence on served findings that other repos consume, in place.
+ """Lower confidence on serialized findings that other repos consume, in place.
- A finding's own ``repo`` wins over *repo_alias*, so one call covers both a
- single repo and the workspace-wide merge.
+ Runs before :func:`build_tiers`, so a lowered finding lands in the tier its
+ new confidence belongs to. A finding's own ``repo`` wins over *repo_alias*,
+ so one call covers both a single repo and the workspace-wide merge.
"""
if lookup is None:
return
- for tier_data in tiers.values():
- for finding in tier_data.get("findings", []):
- alias = finding.get("repo", repo_alias)
- if alias:
- _adjust_one(finding, lookup, alias)
+ for finding in findings:
+ alias = finding.get("repo", repo_alias)
+ if alias:
+ _adjust_one(finding, lookup, alias)
def _adjust_one(finding: dict, lookup: CrossRepoLookup, alias: str) -> None:
consumers = lookup.has_cross_repo_consumers(alias, finding.get("file_path", ""))
if consumers:
finding["confidence"] = round(finding["confidence"] * 0.5, 2)
+ finding["safe_to_delete"] = False
consumer_repos = sorted({c["repo"] for c in consumers})
finding["cross_repo_note"] = (
f"Confidence reduced: {len(consumers)} cross-repo consumer(s) "
@@ -469,6 +500,7 @@ def _adjust_one(finding: dict, lookup: CrossRepoLookup, alias: str) -> None:
depending = lookup.get_repos_depending_on(alias)
if depending:
finding["confidence"] = round(finding["confidence"] * 0.3, 2)
+ finding["safe_to_delete"] = False
finding["cross_repo_note"] = (
f"This export may be consumed by: {', '.join(depending)}. Verify before deletion."
)
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/function_hotspot.py b/packages/core/src/repowise/core/analysis/health/biomarkers/function_hotspot.py
index bb345bcde..5b3f3a127 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/function_hotspot.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/function_hotspot.py
@@ -49,25 +49,41 @@ def meets_structural_floor(fc) -> bool:
return fc.ccn >= _CCN_FLOOR or fc.max_nesting >= _NESTING_FLOOR
-def refresh_replayed(replayed: BiomarkerResult, functions) -> bool:
+def refresh_replayed(
+ replayed: BiomarkerResult, functions, claimed: set[int] | None = None
+) -> bool:
"""Bring a replayed hotspot's complexity up to date; False if it no longer qualifies.
A re-score with no blame index replays the stored row, whose complexity
figures an older walker wrote. Churn cannot be re-measured there, but
complexity can, so a function that no longer clears the floor is dropped.
+ Two same-named functions in one file are told apart by the stored
+ ``line_start``; the nearest start covers a function that has since moved.
+ *claimed* holds start lines already matched, so each function is matched once.
"""
- for fc in functions:
- if fc.name == replayed.function_name and meets_structural_floor(fc):
- replayed.details = {**replayed.details, "ccn": fc.ccn, "max_nesting": fc.max_nesting}
- mods, p80 = replayed.details.get("modification_count"), replayed.details.get("repo_p80")
- if isinstance(mods, int) and isinstance(p80, int):
- replayed.severity = _severity_for(mods, max(p80, _MIN_CHANGES), fc.ccn)
- replayed.reason = (
- f"{fc.name} has been modified across {mods} commits (repo p80={p80}) "
- f"and carries CCN={fc.ccn} / nesting={fc.max_nesting}"
- )
- return True
- return False
+ claimed = set() if claimed is None else claimed
+ named = [
+ fc
+ for fc in functions
+ if fc.name == replayed.function_name and fc.start_line not in claimed
+ ]
+ if not named:
+ return False
+ anchor = replayed.line_start or 0
+ fc = min(named, key=lambda f: abs(f.start_line - anchor))
+ claimed.add(fc.start_line)
+ if not meets_structural_floor(fc):
+ return False
+ replayed.line_start, replayed.line_end = fc.start_line, fc.end_line
+ replayed.details = {**replayed.details, "ccn": fc.ccn, "max_nesting": fc.max_nesting}
+ mods, p80 = replayed.details.get("modification_count"), replayed.details.get("repo_p80")
+ if isinstance(mods, int) and isinstance(p80, int):
+ replayed.severity = _severity_for(mods, max(p80, _MIN_CHANGES), fc.ccn)
+ replayed.reason = (
+ f"{fc.name} has been modified across {mods} commits (repo p80={p80}) "
+ f"and carries CCN={fc.ccn} / nesting={fc.max_nesting}"
+ )
+ return True
def _severity_for(mod_count: int, bar: int, ccn: int) -> Severity:
diff --git a/packages/core/src/repowise/core/analysis/health/file_evaluator.py b/packages/core/src/repowise/core/analysis/health/file_evaluator.py
index 28ca9feb1..28e7466a4 100644
--- a/packages/core/src/repowise/core/analysis/health/file_evaluator.py
+++ b/packages/core/src/repowise/core/analysis/health/file_evaluator.py
@@ -326,12 +326,13 @@ class FileEvaluator:
def _replayed(self, ctx: FileContext, disabled: list[str]) -> list[BiomarkerResult]:
"""Stored blame-marker findings this pass cannot recompute without a blame index."""
out = []
+ claimed: set[int] = set() # function start lines a replayed hotspot took
for stored in self.analyzer.stored_blame_findings.get(ctx.file_path, ()):
replayed = as_biomarker_result(stored)
if replayed.biomarker_type not in BLAME_MARKERS or replayed.biomarker_type in disabled:
continue
if replayed.biomarker_type == "function_hotspot" and not refresh_replayed(
- replayed, ctx.all_functions
+ replayed, ctx.all_functions, claimed
):
continue
out.append(replayed)
diff --git a/packages/core/src/repowise/core/changes/evidence.py b/packages/core/src/repowise/core/changes/evidence.py
index 5b0ebb6fa..ab9786c62 100644
--- a/packages/core/src/repowise/core/changes/evidence.py
+++ b/packages/core/src/repowise/core/changes/evidence.py
@@ -100,6 +100,12 @@ class EvidenceItem:
if data["kind"] == "reaching_tests" and data["basis"] != "unresolved":
# Derived from the rows, so a kept checklist reads under the current rule.
status = _tests_status(data.get("details") or [])
+ elif data["kind"] == "health_delta" and isinstance(data.get("value"), Mapping):
+ value = data["value"]
+ status = _health_status(
+ (value.get("introduced") or 0) + (value.get("worsened") or 0),
+ bool(value.get("complete")),
+ )
return cls(
kind=data["kind"],
label=data["label"],
@@ -441,22 +447,31 @@ def _health(bundle: ChangeReviewBundle) -> EvidenceItem:
]
if delta.status == "partial":
details.append({"note": delta.explanation})
+ complete = delta.status == "available"
return EvidenceItem(
kind,
label,
- "attention" if worse else "ok",
+ _health_status(worse, complete),
"measured",
{
"introduced": delta.introduced_total,
"worsened": delta.worsened_total,
"resolved": delta.resolved_total,
- "complete": delta.status == "available",
+ "complete": complete,
},
details,
source,
)
+def _health_status(worse: int, complete: bool) -> Status:
+ """A regression found is attention either way; finding none clears the
+ change only when the comparison covered all of it."""
+ if worse:
+ return "attention"
+ return "ok" if complete else "unknown"
+
+
def _provenance(inputs: EvidenceInputs) -> EvidenceItem:
kind, label, source = "provenance", "AI provenance", "attribution"
if reason := _missing(inputs.provenance):
diff --git a/packages/server/src/repowise/server/mcp_server/tool_dead_code.py b/packages/server/src/repowise/server/mcp_server/tool_dead_code.py
index 23a44d823..883ca399b 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_dead_code.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_dead_code.py
@@ -19,6 +19,7 @@ from repowise.core.analysis.dead_code.serving import (
build_summary,
build_tiers,
compute_impact,
+ cross_repo_withdraws,
dead_code_finding_id,
excluded_kinds,
merge_summary_counts,
@@ -28,6 +29,7 @@ from repowise.core.analysis.dead_code.serving import (
summary_counts,
)
from repowise.core.analysis.finding_registry import excluded_types, served_previews
+from repowise.core.analysis.health.rows import field
from repowise.core.persistence.crud import get_dead_code_findings
from repowise.core.persistence.database import get_session
from repowise.core.persistence.models import GitMetadata
@@ -57,6 +59,24 @@ def _cross_repo_lookup() -> CrossRepoLookup | None:
return enricher
+def _adjust_cross_repo(
+ findings: list[dict], filters: FindingFilters, repo_alias: str | None
+) -> list[dict]:
+ """The cross-repo cut, then ``safe_only`` again, since the cut withdraws safety."""
+ adjust_cross_repo(findings, _cross_repo_lookup(), repo_alias)
+ if filters.safe_only:
+ return [f for f in findings if f["safe_to_delete"]]
+ return findings
+
+
+def _withdrawn_by(repo_alias: str | None) -> Callable[[Any], bool] | None:
+ """The cross-repo cut as a predicate over stored rows, for the summary."""
+ lookup = _cross_repo_lookup()
+ if lookup is None or not repo_alias:
+ return None
+ return lambda f: cross_repo_withdraws(lookup, repo_alias, field(f, "file_path"), field(f, "kind"))
+
+
async def _get_dead_code_all_repos(
filters: FindingFilters,
limit: int,
@@ -80,7 +100,7 @@ async def _get_dead_code_all_repos(
serialize_finding(f, git_meta_map, repository=ctx.alias)
for f in apply_filters(repo_findings, filters)
]
- return serialized, summary_counts(repo_findings), withheld, gated
+ return serialized, summary_counts(repo_findings, _withdrawn_by(ctx.alias)), withheld, gated
fed = Federation()
answered = await fed.run(_one_repo)
@@ -93,6 +113,7 @@ async def _get_dead_code_all_repos(
merged = into.setdefault(name, {**entry, "count": 0})
merged["count"] += entry["count"]
+ merged_findings = _adjust_cross_repo(merged_findings, filters, None)
summary = build_summary(
merge_summary_counts([part[1] for _, part in answered]),
len(merged_findings),
@@ -101,7 +122,6 @@ async def _get_dead_code_all_repos(
merged_gated,
)
tiers = build_tiers(merged_findings, limit, tier)
- adjust_cross_repo(tiers, _cross_repo_lookup())
result_ws: dict[str, Any] = {
"workspace": True,
@@ -336,15 +356,16 @@ async def get_dead_code(
"\n".join(json.dumps(f, separators=(",", ":")) for f in beyond),
)
+ serialized = _adjust_cross_repo(serialized, filters, ctx.alias)
tiers = build_tiers(serialized, limit, tier, on_overflow=_keep_overflow)
- summary = build_summary(summary_counts(all_findings), len(filtered), filters, withheld, gated)
- adjust_cross_repo(tiers, _cross_repo_lookup(), ctx.alias)
+ counts = summary_counts(all_findings, _withdrawn_by(ctx.alias))
+ summary = build_summary(counts, len(serialized), filters, withheld, gated)
result: dict[str, Any] = {"summary": summary, "tiers": tiers}
if group_by == "directory":
- result["by_directory"] = rollup_by_directory(filtered)
+ result["by_directory"] = rollup_by_directory(serialized)
elif group_by == "owner":
- result["by_owner"] = rollup_by_owner(filtered)
+ result["by_owner"] = rollup_by_owner(serialized)
result["impact"] = compute_impact(tiers)
_maybe_limit_note(result)
diff --git a/packages/server/src/repowise/server/mcp_server/tool_risk/enrichment.py b/packages/server/src/repowise/server/mcp_server/tool_risk/enrichment.py
index 20714bc60..ced2e75a8 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_risk/enrichment.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_risk/enrichment.py
@@ -226,7 +226,8 @@ def _attach_impact(
"""The legacy ``cross_repo_impact`` block, for a target with cross-repo rows.
``cross_repo_consumers`` keeps its old name; each row and the sibling
- marker say it is historical co-change.
+ marker say it is historical co-change. The deprecated list is left out
+ when empty, so it never reads as "no consumers" beside ``affected_repos``.
"""
target = r["target"]
impact = r.setdefault("cross_repo_impact", {})
@@ -242,17 +243,18 @@ def _attach_impact(
}
for p in cross_partners
]
- _set_capped(
- impact,
- "cross_repo_consumers",
- legacy_co_changes,
- collector,
- target,
- extra={
- "cross_repo_consumers_semantics": "historical_co_change_partners",
- "cross_repo_consumers_deprecated": True,
- },
- )
+ if legacy_co_changes:
+ _set_capped(
+ impact,
+ "cross_repo_consumers",
+ legacy_co_changes,
+ collector,
+ target,
+ extra={
+ "cross_repo_consumers_semantics": "historical_co_change_partners",
+ "cross_repo_consumers_deprecated": True,
+ },
+ )
affected = _affected_repos(alias, links["all"])
impact["cross_repo_consumers_analysis"] = cross_state
impact["affected_repos"] = affected
diff --git a/tests/unit/core/test_change_evidence.py b/tests/unit/core/test_change_evidence.py
index 8322875b8..d678344ef 100644
--- a/tests/unit/core/test_change_evidence.py
+++ b/tests/unit/core/test_change_evidence.py
@@ -135,6 +135,18 @@ def test_every_kind_is_present_in_order_and_round_trips():
assert all(i.status == "unknown" and i.basis == "unresolved" for i in evidence.items)
+def test_a_partial_health_comparison_never_reads_ok():
+ partial = dataclasses.replace(_delta([]), status="partial", explanation="base not indexed")
+ evidence = build_change_evidence(_bundle(["src/a.py"], health=partial), change_id=None, revspec="abc")
+ item = next(i for i in evidence.items if i.kind == "health_delta")
+ assert (item.status, item.basis, item.value["complete"]) == ("unknown", "measured", False)
+ # A record kept before this rule reads under it.
+ kept = {**item.to_dict(), "status": "ok"}
+ assert EvidenceItem.from_dict(kept).status == "unknown"
+ full = build_change_evidence(_bundle(["src/a.py"], health=_delta([])), change_id=None, revspec="abc")
+ assert next(i for i in full.items if i.kind == "health_delta").status == "ok"
+
+
def test_statuses_follow_the_facts():
paths = ["src/a.py", "src/b.py", "tests/test_a.py"]
bundle = _bundle(
diff --git a/tests/unit/dead_code/test_serving.py b/tests/unit/dead_code/test_serving.py
index 9f2286cac..281f541b4 100644
--- a/tests/unit/dead_code/test_serving.py
+++ b/tests/unit/dead_code/test_serving.py
@@ -20,6 +20,7 @@ from repowise.core.analysis.dead_code.serving import (
build_summary,
build_tiers,
compute_impact,
+ cross_repo_withdraws,
dead_code_finding_id,
excluded_kinds,
last_meaningful_change,
@@ -237,21 +238,45 @@ class _Lookup:
def test_adjust_cross_repo_lowers_consumed_findings() -> None:
- tiers = build_tiers([serialize_finding(r) for r in _ROWS], 25, "high")
- adjust_cross_repo(tiers, _Lookup(), "api")
- by_path = {f["file_path"]: f for f in tiers["high"]["findings"]}
+ findings = [serialize_finding(r) for r in _ROWS]
+ adjust_cross_repo(findings, _Lookup(), "api")
+ by_path = {f["file_path"]: f for f in findings}
assert by_path["src/a/one.py"]["confidence"] == 0.45
assert "1 cross-repo consumer(s) in web" in by_path["src/a/one.py"]["cross_repo_note"]
assert by_path["src/b/five.py"]["confidence"] == 0.27
assert "mobile" in by_path["src/b/five.py"]["cross_repo_note"]
+ # A finding another repo may consume is never safe to delete.
+ assert not by_path["src/a/one.py"]["safe_to_delete"]
+ assert not by_path["src/b/five.py"]["safe_to_delete"]
+
+
+def test_adjusted_findings_are_tiered_by_their_lowered_confidence() -> None:
+ findings = [serialize_finding(r) for r in _ROWS]
+ adjust_cross_repo(findings, _Lookup(), "api")
+ tiers = build_tiers(findings, 25, None)
+ for name, block in tiers.items():
+ for f in block["findings"]:
+ assert f["confidence"] >= TIER_FLOORS[name]
+ assert "src/a/one.py" not in {f["file_path"] for f in tiers["high"]["findings"]}
def test_adjust_cross_repo_without_data_or_alias_is_a_no_op() -> None:
- tiers = build_tiers([serialize_finding(r) for r in _ROWS], 25, None)
- before = json.dumps(tiers, default=str)
- adjust_cross_repo(tiers, None, "api")
- adjust_cross_repo(tiers, _Lookup(), None)
- assert json.dumps(tiers, default=str) == before
+ findings = [serialize_finding(r) for r in _ROWS]
+ before = json.dumps(findings, default=str)
+ adjust_cross_repo(findings, None, "api")
+ adjust_cross_repo(findings, _Lookup(), None)
+ assert json.dumps(findings, default=str) == before
+
+
+def test_recommendation_never_points_at_an_empty_tier() -> None:
+ def advice(rows: list[dict], tier: str | None = None) -> str:
+ tiers = build_tiers([serialize_finding(r) for r in rows], 25, tier)
+ return compute_impact(tiers)["recommendation"]
+
+ assert advice(_ROWS).startswith("Start with the 'high' tier")
+ assert advice(_ROWS, "medium").startswith("Review the 'medium' tier")
+ assert advice([_row("src/x.py", 0.5)]).startswith("Review the 'medium' tier")
+ assert advice([_row("src/x.py", 0.1)]).startswith("Only 'low' tier findings")
def test_merged_per_repo_counts_equal_counting_everything_at_once() -> None:
@@ -260,3 +285,20 @@ def test_merged_per_repo_counts_equal_counting_everything_at_once() -> None:
whole = summary_counts(_ROWS)
assert merged == whole
assert list(merged["by_kind"]) == list(whole["by_kind"])
+
+
+def test_summary_safe_counts_drop_what_the_cross_repo_cut_withdraws() -> None:
+ lookup = _Lookup()
+
+ def withdrawn(f) -> bool:
+ return cross_repo_withdraws(lookup, "api", f["file_path"], f["kind"])
+
+ plain = summary_counts(_ROWS)
+ cut = summary_counts(_ROWS, withdrawn)
+ adjusted = [serialize_finding(r) for r in _ROWS]
+ adjust_cross_repo(adjusted, lookup, "api")
+ assert cut["safe_to_delete_count"] == sum(f["safe_to_delete"] for f in adjusted)
+ assert cut["safe_to_delete_count"] <= plain["safe_to_delete_count"]
+ assert cut["total_findings"] == plain["total_findings"]
+ assert not cross_repo_withdraws(None, "api", "src/a/one.py", "unused_export")
+ assert not cross_repo_withdraws(lookup, None, "src/a/one.py", "unused_export")
diff --git a/tests/unit/health/test_function_hotspot.py b/tests/unit/health/test_function_hotspot.py
index ec3679afc..4c79c2f56 100644
--- a/tests/unit/health/test_function_hotspot.py
+++ b/tests/unit/health/test_function_hotspot.py
@@ -156,3 +156,38 @@ def test_refresh_replayed_updates_complexity_or_drops_hotspot():
assert "CCN=12 / nesting=5" in kept.reason
assert not refresh_replayed(replayed(), [_fc("hot", 1, 10, ccn=9, nesting=2)])
assert not refresh_replayed(replayed(), [_fc("other", 1, 10, ccn=30)])
+
+
+def test_refresh_replayed_picks_same_named_function_by_line_start():
+ replayed = BiomarkerResult(
+ biomarker_type="function_hotspot",
+ severity=Severity.MEDIUM,
+ function_name="run",
+ line_start=42,
+ line_end=60,
+ details={"ccn": 12, "max_nesting": 3, "modification_count": 6, "repo_p80": 5},
+ )
+ # A simple ``run`` earlier in the file must not stand in for the hot one,
+ # which has since moved down two lines.
+ functions = [_fc("run", 5, 8, ccn=1), _fc("run", 44, 62, ccn=13, nesting=4)]
+ assert refresh_replayed(replayed, functions)
+ assert replayed.details["ccn"] == 13
+ assert (replayed.line_start, replayed.line_end) == (44, 62)
+
+
+def test_refresh_replayed_never_lands_two_rows_on_one_function():
+ def replayed(line: int) -> BiomarkerResult:
+ return BiomarkerResult(
+ biomarker_type="function_hotspot",
+ severity=Severity.MEDIUM,
+ function_name="run",
+ line_start=line,
+ line_end=line + 10,
+ details={"ccn": 12, "max_nesting": 3, "modification_count": 6, "repo_p80": 5},
+ )
+
+ # One of the two ``run`` twins was deleted; only the surviving one matches.
+ functions = [_fc("run", 44, 62, ccn=13, nesting=4)]
+ claimed: set[int] = set()
+ assert refresh_replayed(replayed(42), functions, claimed)
+ assert not refresh_replayed(replayed(5), functions, claimed)
diff --git a/tests/unit/server/mcp/test_dead_code.py b/tests/unit/server/mcp/test_dead_code.py
index d48afd72a..548a23a9f 100644
--- a/tests/unit/server/mcp/test_dead_code.py
+++ b/tests/unit/server/mcp/test_dead_code.py
@@ -119,3 +119,32 @@ async def test_get_dead_code_group_by_owner(setup_mcp):
assert len(owners) >= 1
owner_names = [o["owner"] for o in owners]
assert "Bob" in owner_names # Bob owns dc2 + dc3
+
+
+class _EveryFileConsumed:
+ def has_cross_repo_consumers(self, repo_alias, file_path):
+ return [{"repo": "web"}]
+
+ def get_repos_depending_on(self, repo_alias):
+ return ["web"]
+
+
+async def test_cross_repo_cut_reaches_summary_and_rollups(setup_mcp, monkeypatch):
+ from repowise.server.mcp_server import get_dead_code, tool_dead_code
+
+ monkeypatch.setattr(tool_dead_code, "_cross_repo_lookup", lambda: _EveryFileConsumed())
+
+ result = await get_dead_code(group_by="directory", min_confidence=0.0)
+ summary = result["summary"]
+ # The safe counts agree with the tiers: a consumed finding is never safe.
+ assert summary["total_findings"] == 3
+ assert summary["safe_to_delete_count"] == 0
+ assert summary["deletable_lines"] == 0
+ assert all(d["safe_count"] == 0 for d in result["by_directory"])
+ assert not any(f["safe_to_delete"] for t in result["tiers"].values() for f in t["findings"])
+
+ # The cut empties a safe-only view, and the summary says why.
+ safe = await get_dead_code(safe_only=True)
+ assert safe["summary"]["filtered_findings"] == 0
+ assert "safe_only_note" in safe["summary"]
diff --git a/tests/unit/server/mcp/test_risk_relationship_semantics.py b/tests/unit/server/mcp/test_risk_relationship_semantics.py
index b6879122b..4bfb177c0 100644
--- a/tests/unit/server/mcp/test_risk_relationship_semantics.py
+++ b/tests/unit/server/mcp/test_risk_relationship_semantics.py
@@ -350,3 +350,20 @@ async def test_valid_empty_workspace_analysis_is_not_reported_as_unknown(setup_m
assert card["cross_repo_links"] == []
assert card["cross_repo_links_total"] == card["cross_repo_links_emitted"] == 0
assert card["relationship_analysis"]["cross_repo"]["status"] == "available"
+
+
+def test_empty_deprecated_consumers_list_is_left_out():
+ from repowise.server.mcp_server.tool_risk.enrichment import _attach_impact
+
+ card: dict = {"target": "src/api.py"}
+ link = {
+ "evidence_kind": "structural",
+ "source_repository": "web",
+ "target_repository": "api",
+ }
+ links = {"all": [link], "provider": [], "consumer": []}
+ _attach_impact(card, "api", {"status": "ok"}, [], links, None)
+ impact = card["cross_repo_impact"]
+ assert impact["affected_repos"] == ["web"]
+ legacy = {k for k in impact if k.startswith("cross_repo_consumers")}
+ assert legacy == {"cross_repo_consumers_analysis"}
diff --git a/tests/unit/server/test_changes_routes.py b/tests/unit/server/test_changes_routes.py
index f1d383ca9..3dc9b4522 100644
--- a/tests/unit/server/test_changes_routes.py
+++ b/tests/unit/server/test_changes_routes.py
@@ -129,7 +129,13 @@ def _fake_build(monkeypatch, seen: list[str], gate=None):
generated_at="2026-10-14T00:00:00+00:00",
items=[
EvidenceItem(
- "health_delta", "Health delta", "ok", "measured", {"introduced": 0}, [], "change health"
+ "health_delta",
+ "Health delta",
+ "ok",
+ "measured",
+ {"introduced": 0, "complete": True},
+ [],
+ "change health",
)
],
)
@@ -163,12 +169,12 @@ async def test_detail_carries_evidence_only_when_asked_and_keeps_it(
"label": "Health delta",
"status": "ok",
"basis": "measured",
- "value": {"introduced": 0},
+ "value": {"introduced": 0, "complete": True},
"details": [],
"source": "change health",
# Worded by the client from a key and its numbers.
"line": {
- "key": "health_delta_partial",
+ "key": "health_delta",
"params": {"introduced": 0, "worsened": 0, "resolved": 0},
},
}