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.

refactor(dead-code): serve findings from a session-free core module (#2851)

Raghav Chamadiyad305f4a658f6
diff --git a/packages/core/src/repowise/core/analysis/dead_code/serving.py b/packages/core/src/repowise/core/analysis/dead_code/serving.py
new file mode 100644
index 000000000..739556039
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/dead_code/serving.py
@@ -0,0 +1,439 @@
+"""Serving stored dead-code findings: filter, tier, roll up, serialize.
+
+The single-repo and workspace answers share every step here, so a finding
+reads the same whichever path served it. Rows in (ORM rows, dataclasses or
+mappings, read through :func:`field`), plain dicts out; no session.
+"""
+
+from __future__ import annotations
+
+import json
+from collections.abc import Callable
+from dataclasses import dataclass
+from dataclasses import field as dataclass_field
+from typing import Any, Protocol
+
+from repowise.core.analysis.dead_code.risk_factors import (
+ RISK_CAP_CONFIDENCE,
+ SAFE_CONFIDENCE_THRESHOLD,
+ effective_safe_to_delete,
+ path_risk_factors,
+)
+from repowise.core.analysis.finding_registry import verification_label, withheld_summary
+from repowise.core.analysis.health.rows import field
+from repowise.core.references import path_identity, stable_entity_id
+
+# The bands findings are tiered by, in one place: the tier descriptions quote
+# them and ``min_confidence="high"`` resolves to them, so the vocabulary the
+# response is organised by and the one it accepts cannot drift apart (#1496).
+# The engine's own thresholds, so the MCP tool, the web and the CLI
+# (``DEAD_CODE_CONFIDENCE`` in packages/types/src/dead-code.ts) put a finding in
+# the same tier.
+TIER_FLOORS: dict[str, float] = {
+ "high": SAFE_CONFIDENCE_THRESHOLD,
+ "medium": RISK_CAP_CONFIDENCE,
+ "low": 0.0,
+}
+
+TIER_DESCRIPTIONS: dict[str, str] = {
+ "high": (
+ f"High confidence (>={SAFE_CONFIDENCE_THRESHOLD}): No references found in the codebase. "
+ "Strong cleanup candidates — review (especially whole files and runtime-loaded files) "
+ "before deleting."
+ ),
+ "medium": (
+ f"Medium confidence ({RISK_CAP_CONFIDENCE}-{SAFE_CONFIDENCE_THRESHOLD}): Likely unused "
+ "but may have indirect references. Review before deleting."
+ ),
+ "low": (
+ f"Low confidence (<{RISK_CAP_CONFIDENCE}): Potentially used via dynamic imports or "
+ "reflection. Investigate first."
+ ),
+}
+
+SUMMARY_SCOPE = (
+ "total_findings, by_kind, deletable_lines and safe_to_delete_count cover every "
+ "open finding; filtered_findings and tiers cover what the filters kept "
+ f"(min_confidence defaults to {RISK_CAP_CONFIDENCE})"
+)
+
+
+def excluded_kinds(
+ *,
+ no_unreachable: bool,
+ no_unused_exports: bool,
+ include_internals: bool,
+ include_zombie_packages: bool,
+) -> set[str]:
+ """Derive the set of finding kinds to exclude from the scope flags."""
+ excluded: set[str] = set()
+ if no_unreachable:
+ excluded.add("unreachable_file")
+ if no_unused_exports:
+ excluded.add("unused_export")
+ if not include_internals:
+ excluded.add("unused_internal")
+ if not include_zombie_packages:
+ excluded.add("zombie_package")
+ return excluded
+
+
+# These literals must match get_dead_code()'s default parameters;
+# test_get_dead_code_summary_says_what_it_counts catches drift between them.
+DEFAULT_EXCLUDED_KINDS = excluded_kinds(
+ no_unreachable=False,
+ no_unused_exports=False,
+ include_internals=False,
+ include_zombie_packages=True,
+)
+
+
+@dataclass
+class FindingFilters:
+ """Filter parameters shared by the single-repo and workspace paths."""
+
+ kind: str | None
+ safe_only: bool
+ min_confidence: float
+ directory: str | None
+ owner: str | None
+ excluded_kinds: set[str] = dataclass_field(default_factory=set)
+ # Kinds the finding-type registry keeps off this surface. Applied before
+ # anything is counted, so no total describes a finding the caller cannot see.
+ withheld_kinds: frozenset[str] = frozenset()
+
+ def split_withheld(self, findings: list) -> tuple[list, dict[str, dict]]:
+ """``(shown rows, {withheld kind: count/status/reason})``."""
+ counts: dict[str, int] = {}
+ for f in findings:
+ kind = field(f, "kind")
+ counts[kind] = counts.get(kind, 0) + 1
+ shown = [f for f in findings if field(f, "kind") not in self.withheld_kinds]
+ return shown, withheld_summary(counts, self.withheld_kinds)
+
+ def applied(self) -> dict[str, Any]:
+ """The filters that differ from the defaults, as the summary echoes them."""
+ applied: dict[str, Any] = {}
+ if self.kind:
+ applied["kind"] = self.kind
+ elif self.excluded_kinds != DEFAULT_EXCLUDED_KINDS:
+ applied["excluded_kinds"] = sorted(self.excluded_kinds)
+ if self.safe_only:
+ applied["safe_only"] = True
+ if self.min_confidence != RISK_CAP_CONFIDENCE:
+ applied["min_confidence"] = self.min_confidence
+ if self.directory:
+ applied["directory"] = self.directory
+ if self.owner:
+ applied["owner"] = self.owner
+ return applied
+
+ def summarize(self, summary: dict[str, Any]) -> None:
+ """Say which counts the filters touched, so empty tiers beside a
+ non-zero ``total_findings`` do not read as a contradiction."""
+ summary["scope"] = SUMMARY_SCOPE
+ applied = self.applied()
+ if applied:
+ summary["filters"] = applied
+
+
+def _predicates(filters: FindingFilters) -> list[Callable[[Any], bool]]:
+ checks: list[Callable[[Any], bool]] = []
+ if filters.kind:
+ checks.append(lambda f: field(f, "kind") == filters.kind)
+ elif filters.excluded_kinds:
+ checks.append(lambda f: field(f, "kind") not in filters.excluded_kinds)
+ if filters.safe_only:
+ checks.append(is_safe)
+ if filters.min_confidence > 0:
+ checks.append(lambda f: field(f, "confidence") >= filters.min_confidence)
+ if filters.directory:
+ prefix = filters.directory.rstrip("/") + "/"
+ checks.append(lambda f: field(f, "file_path").startswith(prefix))
+ if filters.owner:
+ owner = filters.owner.lower()
+ checks.append(lambda f: (field(f, "primary_owner") or "").lower() == owner)
+ return checks
+
+
+def apply_filters(findings: list, filters: FindingFilters) -> list:
+ """Keep the findings that pass the kind/safety/confidence/directory/owner filters."""
+ checks = _predicates(filters)
+ return [f for f in findings if all(check(f) for check in checks)]
+
+
+def summary_counts(shown: list) -> 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."""
+ 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)]
+ return {
+ "total_findings": len(shown),
+ "deletable_lines": sum(field(f, "lines") or 0 for f in safe),
+ "safe_to_delete_count": len(safe),
+ "by_kind": by_kind,
+ }
+
+
+def merge_summary_counts(parts: list[dict[str, Any]]) -> dict[str, Any]:
+ """Sum :func:`summary_counts` parts; ``by_kind`` keeps first-seen order."""
+ merged = summary_counts([])
+ for part in parts:
+ for key in ("total_findings", "deletable_lines", "safe_to_delete_count"):
+ merged[key] += part[key]
+ for kind, count in part["by_kind"].items():
+ merged["by_kind"][kind] = merged["by_kind"].get(kind, 0) + count
+ return merged
+
+
+def build_summary(
+ counts: dict[str, Any],
+ filtered_count: int,
+ filters: FindingFilters,
+ withheld: dict[str, dict],
+) -> dict[str, Any]:
+ """The summary block: *counts* from :func:`summary_counts`, plus what the
+ filters kept."""
+ summary: dict[str, Any] = {
+ "total_findings": counts["total_findings"],
+ "filtered_findings": filtered_count,
+ "deletable_lines": counts["deletable_lines"],
+ "safe_to_delete_count": counts["safe_to_delete_count"],
+ "by_kind": counts["by_kind"],
+ }
+ filters.summarize(summary)
+ if withheld:
+ summary["withheld_types"] = withheld
+ return summary
+
+
+def is_safe(f: Any) -> bool:
+ """Re-derive deletion-readiness for a stored finding.
+
+ Mirrors the API/CLI: the persisted boolean is only ever downgraded, never
+ trusted blindly, so config/bootstrap/database/environment/script/asset
+ files (and findings written before risk factors existed) never read as
+ safe-to-delete.
+ """
+ return effective_safe_to_delete(
+ field(f, "confidence"),
+ field(f, "file_path"),
+ field(f, "safe_to_delete"),
+ field(f, "kind"),
+ )
+
+
+def dead_code_finding_id(f: Any, repository: str) -> str:
+ """The stable public id of one dead-code finding."""
+ return stable_entity_id(
+ "finding",
+ repository,
+ {
+ "family": "dead_code",
+ "path": path_identity(field(f, "file_path")),
+ "kind": field(f, "kind"),
+ "symbol": field(f, "symbol_name") or "",
+ "line_start": field(f, "start_line"),
+ "line_end": field(f, "end_line"),
+ },
+ )
+
+
+def last_meaningful_change(gm: Any) -> str | None:
+ """Date of the most recent significant (feature/fix) commit, if any."""
+ if gm is None:
+ return None
+ # Significant commits already filter style/chore noise, most recent first.
+ sig_json = field(gm, "significant_commits_json")
+ if not sig_json:
+ return None
+ try:
+ commits = json.loads(sig_json)
+ except (json.JSONDecodeError, TypeError):
+ return None
+ return commits[0].get("date") if commits else None
+
+
+def serialize_finding(
+ f: Any,
+ git_meta_map: dict | None = None,
+ *,
+ repository: str = "default",
+) -> dict:
+ """Serialize one stored finding to the shape every surface emits."""
+ last_commit_at = field(f, "last_commit_at")
+ result = {
+ "id": dead_code_finding_id(f, repository),
+ "repository": repository,
+ "kind": field(f, "kind"),
+ "file_path": field(f, "file_path"),
+ "symbol_name": field(f, "symbol_name"),
+ "symbol_kind": field(f, "symbol_kind"),
+ "start_line": field(f, "start_line"),
+ "end_line": field(f, "end_line"),
+ "confidence": field(f, "confidence"),
+ "reason": field(f, "reason"),
+ "safe_to_delete": is_safe(f),
+ "risk_factors": list(path_risk_factors(field(f, "file_path"))),
+ "lines": field(f, "lines"),
+ "last_commit_at": last_commit_at.isoformat() if last_commit_at else None,
+ # Recent churn is the top rung of the confidence ladder, so the agent
+ # gets the same reason for a low score that the web page shows.
+ "commit_count_90d": field(f, "commit_count_90d"),
+ "primary_owner": field(f, "primary_owner"),
+ # NB: age_days runs from the file's *first* commit, so it is the file's
+ # age, not how long this has been dead — the two disagree on 75% of
+ # findings. last_commit_at above is the staleness signal.
+ "age_days": field(f, "age_days"),
+ }
+ label = verification_label(result["kind"])
+ if label:
+ result["verification"] = label
+ if git_meta_map:
+ meaningful = last_meaningful_change(git_meta_map.get(result["file_path"]))
+ if meaningful:
+ result["last_meaningful_change"] = meaningful
+ return result
+
+
+def _tier_of(confidence: float) -> str:
+ if confidence >= TIER_FLOORS["high"]:
+ return "high"
+ if confidence >= TIER_FLOORS["medium"]:
+ return "medium"
+ return "low"
+
+
+def build_tiers(
+ findings: list[dict],
+ limit: int,
+ tier: str | None,
+ *,
+ on_overflow: Callable[[str, list[dict]], None] | None = None,
+) -> dict[str, Any]:
+ """Split serialized findings into high/medium/low tiers, best first.
+
+ *on_overflow* receives ``(tier name, findings beyond limit)`` so a caller
+ can keep what the per-tier limit cut instead of dropping it silently.
+ """
+ banded: dict[str, list[dict]] = {"high": [], "medium": [], "low": []}
+ for f in findings:
+ banded[_tier_of(f["confidence"])].append(f)
+
+ tiers: dict[str, Any] = {}
+ for name, items in banded.items():
+ if tier is not None and tier != name:
+ continue
+ items.sort(key=lambda f: (-f["confidence"], -(f["lines"] or 0)))
+ if on_overflow is not None and len(items) > limit:
+ on_overflow(name, items[limit:])
+ tiers[name] = _tier_block(name, items, limit)
+ return tiers
+
+
+def _tier_block(name: str, items: list[dict], limit: int) -> dict[str, Any]:
+ return {
+ "description": TIER_DESCRIPTIONS[name],
+ "count": len(items),
+ "lines": sum(f["lines"] or 0 for f in items),
+ "safe_count": sum(1 for f in items if f["safe_to_delete"]),
+ "findings": items[:limit],
+ "truncated": len(items) > limit,
+ }
+
+
+def _rollup(findings: list, key: str, key_of: Callable[[Any], str]) -> list[dict]:
+ groups: dict[str, dict] = {}
+ for f in findings:
+ name = key_of(f)
+ group = groups.setdefault(name, {key: name, "count": 0, "lines": 0, "safe_count": 0})
+ group["count"] += 1
+ group["lines"] += field(f, "lines") or 0
+ if is_safe(f):
+ group["safe_count"] += 1
+ return sorted(groups.values(), key=lambda g: -g["lines"])
+
+
+def _directory_key(f: Any) -> str:
+ # The first two path segments, or just the first for a shallow path.
+ parts = field(f, "file_path").split("/")
+ return "/".join(parts[:2]) if len(parts) > 2 else parts[0]
+
+
+def rollup_by_directory(findings: list) -> list[dict]:
+ """Group findings by top-level directory, most lines first."""
+ return _rollup(findings, "directory", _directory_key)
+
+
+def rollup_by_owner(findings: list) -> list[dict]:
+ """Group findings by primary owner, most lines first."""
+ return _rollup(findings, "owner", lambda f: field(f, "primary_owner") or "unowned")
+
+
+def compute_impact(tiers: dict) -> dict:
+ """Total impact across the tiers served."""
+ total_lines = sum(t["lines"] for t in tiers.values())
+ # Approximate: only the findings a tier shows count toward safe lines.
+ safe_lines = sum(
+ f["lines"] or 0 for t in tiers.values() for f in t["findings"] if f["safe_to_delete"]
+ )
+ return {
+ "total_lines_reclaimable": total_lines,
+ "safe_lines_reclaimable": safe_lines,
+ "recommendation": (
+ "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."
+ ),
+ }
+
+
+class CrossRepoLookup(Protocol):
+ """What :func:`adjust_cross_repo` needs from the workspace's cross-repo data."""
+
+ def has_cross_repo_consumers(self, repo_alias: str, file_path: str) -> list[dict]: ...
+
+ def get_repos_depending_on(self, repo_alias: str) -> list[str]: ...
+
+
+def adjust_cross_repo(
+ tiers: dict, lookup: CrossRepoLookup | None, repo_alias: str | None = None
+) -> None:
+ """Lower confidence on served 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.
+ """
+ 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)
+
+
+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)
+ consumer_repos = sorted({c["repo"] for c in consumers})
+ finding["cross_repo_note"] = (
+ f"Confidence reduced: {len(consumers)} cross-repo consumer(s) "
+ f"in {', '.join(consumer_repos)}."
+ )
+ return
+ # Package-level dependents may consume an export without a file edge.
+ if finding.get("kind") != "unused_export":
+ return
+ depending = lookup.get_repos_depending_on(alias)
+ if depending:
+ finding["confidence"] = round(finding["confidence"] * 0.3, 2)
+ finding["cross_repo_note"] = (
+ f"This export may be consumed by: {', '.join(depending)}. Verify before deletion."
+ )
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 18a272be2..47e3f8e49 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
@@ -4,23 +4,30 @@ from __future__ import annotations
import json
from collections.abc import Callable
-from dataclasses import dataclass, field
from typing import Any
from sqlalchemy import select
from repowise.core.analysis.dead_code.models import DeadCodeKind
-from repowise.core.analysis.dead_code.risk_factors import (
- RISK_CAP_CONFIDENCE,
- SAFE_CONFIDENCE_THRESHOLD,
- effective_safe_to_delete,
- path_risk_factors,
-)
-from repowise.core.analysis.finding_registry import (
- excluded_types,
- verification_label,
- withheld_summary,
+from repowise.core.analysis.dead_code.risk_factors import RISK_CAP_CONFIDENCE
+from repowise.core.analysis.dead_code.serving import (
+ TIER_FLOORS,
+ CrossRepoLookup,
+ FindingFilters,
+ adjust_cross_repo,
+ apply_filters,
+ build_summary,
+ build_tiers,
+ compute_impact,
+ dead_code_finding_id,
+ excluded_kinds,
+ merge_summary_counts,
+ rollup_by_directory,
+ rollup_by_owner,
+ serialize_finding,
+ summary_counts,
)
+from repowise.core.analysis.finding_registry import excluded_types
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
@@ -40,118 +47,18 @@ from repowise.server.mcp_server._helpers import (
)
from repowise.server.mcp_server._index_state import index_state_key
from repowise.server.mcp_server._meta import build_meta as _build_meta
-from repowise.server.mcp_server._references import path_identity, stable_entity_id
-
-
-@dataclass
-class _FindingFilters:
- """Filter parameters shared by the single-repo and workspace code paths."""
-
- kind: str | None
- safe_only: bool
- min_confidence: float
- directory: str | None
- owner: str | None
- excluded_kinds: set[str] = field(default_factory=set)
- # Kinds the finding-type registry keeps off this surface. Applied before
- # anything is counted, so no total describes a finding the caller cannot see.
- withheld_kinds: frozenset[str] = frozenset()
-
- def split_withheld(self, findings: list) -> tuple[list, dict[str, dict]]:
- """``(shown rows, {withheld kind: count/status/reason})``."""
- counts: dict[str, int] = {}
- for f in findings:
- counts[f.kind] = counts.get(f.kind, 0) + 1
- shown = [f for f in findings if f.kind not in self.withheld_kinds]
- return shown, withheld_summary(counts, self.withheld_kinds)
-
- def applied(self) -> dict[str, Any]:
- """The filters that differ from the defaults, as the summary echoes them."""
- applied: dict[str, Any] = {}
- if self.kind:
- applied["kind"] = self.kind
- elif self.excluded_kinds != _DEFAULT_EXCLUDED_KINDS:
- applied["excluded_kinds"] = sorted(self.excluded_kinds)
- if self.safe_only:
- applied["safe_only"] = True
- if self.min_confidence != RISK_CAP_CONFIDENCE:
- applied["min_confidence"] = self.min_confidence
- if self.directory:
- applied["directory"] = self.directory
- if self.owner:
- applied["owner"] = self.owner
- return applied
-
- def summarize(self, summary: dict[str, Any]) -> None:
- """Say which counts the filters touched, so empty tiers beside a
- non-zero ``total_findings`` do not read as a contradiction."""
- summary["scope"] = _SUMMARY_SCOPE
- applied = self.applied()
- if applied:
- summary["filters"] = applied
-
-
-_SUMMARY_SCOPE = (
- "total_findings, by_kind, deletable_lines and safe_to_delete_count cover every "
- "open finding; filtered_findings and tiers cover what the filters kept "
- f"(min_confidence defaults to {RISK_CAP_CONFIDENCE})"
-)
-
-
-def _compute_excluded_kinds(
- *,
- no_unreachable: bool,
- no_unused_exports: bool,
- include_internals: bool,
- include_zombie_packages: bool,
-) -> set[str]:
- """Derive the set of finding kinds to exclude from the scope flags."""
- excluded: set[str] = set()
- if no_unreachable:
- excluded.add("unreachable_file")
- if no_unused_exports:
- excluded.add("unused_export")
- if not include_internals:
- excluded.add("unused_internal")
- if not include_zombie_packages:
- excluded.add("zombie_package")
- return excluded
-
-
-# These literals must match get_dead_code()'s default parameters below;
-# test_get_dead_code_summary_says_what_it_counts catches drift between them.
-_DEFAULT_EXCLUDED_KINDS = _compute_excluded_kinds(
- no_unreachable=False,
- no_unused_exports=False,
- include_internals=False,
- include_zombie_packages=True,
-)
-def _apply_finding_filters(findings: list, filters: _FindingFilters) -> list:
- """Apply the kind/safety/confidence/directory/owner filters in order."""
- filtered = findings
- if filters.kind:
- filtered = [f for f in filtered if f.kind == filters.kind]
- elif filters.excluded_kinds:
- filtered = [f for f in filtered if f.kind not in filters.excluded_kinds]
- if filters.safe_only:
- filtered = [f for f in filtered if _effective_safe(f)]
- if filters.min_confidence > 0:
- filtered = [f for f in filtered if f.confidence >= filters.min_confidence]
- if filters.directory:
- prefix = filters.directory.rstrip("/") + "/"
- filtered = [f for f in filtered if f.file_path.startswith(prefix)]
- if filters.owner:
- owner_lower = filters.owner.lower()
- filtered = [
- f for f in filtered if f.primary_owner and f.primary_owner.lower() == owner_lower
- ]
- return filtered
+def _cross_repo_lookup() -> CrossRepoLookup | None:
+ """The workspace's cross-repo data, when there is any to adjust by."""
+ enricher = _state._cross_repo_enricher
+ if enricher is None or not enricher.has_data or not _is_workspace_mode():
+ return None
+ return enricher
async def _get_dead_code_all_repos(
- filters: _FindingFilters,
+ filters: FindingFilters,
limit: int,
tier: str | None,
apply_limit_note: Callable[[dict[str, Any]], None],
@@ -159,10 +66,7 @@ async def _get_dead_code_all_repos(
"""Aggregate dead-code findings across every repo in the workspace."""
contexts = await _resolve_all_contexts()
merged_findings: list[dict] = []
- total_all = 0
- total_deletable = 0
- total_safe = 0
- merged_by_kind: dict[str, int] = {}
+ count_parts: list[dict[str, Any]] = []
merged_withheld: dict[str, dict] = {}
for ctx in contexts:
@@ -181,95 +85,34 @@ async def _get_dead_code_all_repos(
git_meta_map = await _load_git_meta_map(session, repository.id, repo_findings)
- repo_filtered = _apply_finding_filters(repo_findings, filters)
-
- for f in repo_filtered:
- serialized = _serialize_finding(f, git_meta_map, repository=ctx.alias)
+ for f in apply_filters(repo_findings, filters):
+ serialized = serialize_finding(f, git_meta_map, repository=ctx.alias)
serialized["repo"] = ctx.alias
merged_findings.append(serialized)
+ count_parts.append(summary_counts(repo_findings))
- # Accumulate summary stats from unfiltered findings
- total_all += len(repo_findings)
- total_deletable += sum(f.lines or 0 for f in repo_findings if _effective_safe(f))
- total_safe += sum(1 for f in repo_findings if _effective_safe(f))
- for f in repo_findings:
- merged_by_kind[f.kind] = merged_by_kind.get(f.kind, 0) + 1
-
- # Sort merged findings by confidence descending
- merged_findings.sort(key=lambda d: (-d["confidence"], -(d["lines"] or 0)))
-
- summary = {
- "total_findings": total_all,
- "filtered_findings": len(merged_findings),
- "deletable_lines": total_deletable,
- "safe_to_delete_count": total_safe,
- "by_kind": merged_by_kind,
- }
- filters.summarize(summary)
- if merged_withheld:
- summary["withheld_types"] = merged_withheld
-
- tiers = _build_tiers_from_dicts(merged_findings, limit, tier)
-
- # Cross-repo confidence adjustment for workspace-wide findings
- _adjust_dead_code_cross_repo(tiers, None)
+ summary = build_summary(
+ merge_summary_counts(count_parts), len(merged_findings), filters, merged_withheld
+ )
+ tiers = build_tiers(merged_findings, limit, tier)
+ adjust_cross_repo(tiers, _cross_repo_lookup())
result_ws: dict[str, Any] = {
"workspace": True,
"summary": summary,
"tiers": tiers,
- "impact": _compute_impact(tiers),
+ "impact": compute_impact(tiers),
}
apply_limit_note(result_ws)
result_ws["_meta"] = _build_meta()
return result_ws
-# The bands this tool tiers by, in one place: the tier descriptions quote them
-# and ``min_confidence="high"`` resolves to them, so the vocabulary the response
-# is organised by and the one it accepts cannot drift apart (#1496). The engine's
-# own thresholds, so this tool, the web and the CLI (``DEAD_CODE_CONFIDENCE`` in
-# packages/types/src/dead-code.ts) put a finding in the same tier.
-_TIER_FLOORS: dict[str, float] = {
- "high": SAFE_CONFIDENCE_THRESHOLD,
- "medium": RISK_CAP_CONFIDENCE,
- "low": 0.0,
-}
-
# The four kinds the analyzer writes, taken from the enum it writes them with
# rather than re-listed here, so a fifth kind never reads as a caller's typo.
_DEAD_CODE_KINDS = frozenset(k.value for k in DeadCodeKind)
-def _build_tiers_from_dicts(
- merged_findings: list[dict], limit: int, tier: str | None
-) -> dict[str, Any]:
- """Build the high/medium/low tier structure from pre-serialized dicts."""
- hi, med = _TIER_FLOORS["high"], _TIER_FLOORS["medium"]
- high = [f for f in merged_findings if f["confidence"] >= hi]
- medium = [f for f in merged_findings if med <= f["confidence"] < hi]
- low = [f for f in merged_findings if f["confidence"] < med]
-
- def _tier_from_dicts(items: list[dict], desc: str) -> dict:
- return {
- "description": desc,
- "count": len(items),
- "lines": sum(f["lines"] or 0 for f in items),
- "safe_count": sum(1 for f in items if f["safe_to_delete"]),
- "findings": items[:limit],
- "truncated": len(items) > limit,
- }
-
- tiers: dict[str, Any] = {}
- if tier is None or tier == "high":
- tiers["high"] = _tier_from_dicts(high, _TIER_DESC_HIGH)
- if tier is None or tier == "medium":
- tiers["medium"] = _tier_from_dicts(medium, _TIER_DESC_MEDIUM)
- if tier is None or tier == "low":
- tiers["low"] = _tier_from_dicts(low, _TIER_DESC_LOW)
- return tiers
-
-
async def _load_git_meta_map(session: Any, repository_id: Any, findings: list) -> dict[str, Any]:
"""Load git metadata keyed by file path for the given findings."""
finding_paths = list({f.file_path for f in findings})
@@ -284,21 +127,6 @@ async def _load_git_meta_map(session: Any, repository_id: Any, findings: list) -
return {g.file_path: g for g in git_res.scalars().all()}
-_TIER_DESC_HIGH = (
- f"High confidence (>={SAFE_CONFIDENCE_THRESHOLD}): No references found in the codebase. "
- "Strong cleanup candidates — review (especially whole files and runtime-loaded files) "
- "before deleting."
-)
-_TIER_DESC_MEDIUM = (
- f"Medium confidence ({RISK_CAP_CONFIDENCE}-{SAFE_CONFIDENCE_THRESHOLD}): Likely unused "
- "but may have indirect references. Review before deleting."
-)
-_TIER_DESC_LOW = (
- f"Low confidence (<{RISK_CAP_CONFIDENCE}): Potentially used via dynamic imports or "
- "reflection. Investigate first."
-)
-
-
def _resolve_min_confidence(value: float | str, ignored: list[dict[str, Any]]) -> float:
"""Resolve ``min_confidence`` to a float, accepting this tool's tier names.
@@ -311,12 +139,12 @@ def _resolve_min_confidence(value: float | str, ignored: list[dict[str, Any]]) -
if isinstance(value, bool) or not isinstance(value, str):
return float(value)
name = value.strip()
- if name in _TIER_FLOORS:
- return _TIER_FLOORS[name]
+ if name in TIER_FLOORS:
+ return TIER_FLOORS[name]
try:
return float(name)
except ValueError:
- resolve_enum_argument(name, _TIER_FLOORS, argument="min_confidence", ignored=ignored)
+ resolve_enum_argument(name, TIER_FLOORS, argument="min_confidence", ignored=ignored)
return RISK_CAP_CONFIDENCE
@@ -375,16 +203,16 @@ async def get_dead_code(
# a note, not "No dead code found matching your filters" over 445 findings.
ignored: list[dict[str, Any]] = []
kind = resolve_enum_argument(kind, _DEAD_CODE_KINDS, argument="kind", ignored=ignored)
- tier = resolve_enum_argument(tier, _TIER_FLOORS, argument="tier", ignored=ignored)
+ tier = resolve_enum_argument(tier, TIER_FLOORS, argument="tier", ignored=ignored)
confidence_floor = _resolve_min_confidence(min_confidence, ignored)
- filters = _FindingFilters(
+ filters = FindingFilters(
kind=kind,
safe_only=safe_only,
min_confidence=confidence_floor,
directory=directory,
owner=owner,
- excluded_kinds=_compute_excluded_kinds(
+ excluded_kinds=excluded_kinds(
no_unreachable=no_unreachable,
no_unused_exports=no_unused_exports,
include_internals=include_internals,
@@ -452,8 +280,7 @@ async def get_dead_code(
(
row
for row in all_findings
- if finding_id
- in {row.id, _dead_code_finding_id(row, reference_repository)}
+ if finding_id in {row.id, dead_code_finding_id(row, reference_repository)}
),
None,
)
@@ -461,7 +288,7 @@ async def get_dead_code(
"mode": "finding",
"finding_id": finding_id,
"finding": (
- _serialize_finding(
+ serialize_finding(
match,
git_meta_map,
repository=reference_repository,
@@ -476,48 +303,27 @@ async def get_dead_code(
),
}
- # --- Apply filters ---
- filtered = _apply_finding_filters(all_findings, filters)
-
- # --- Build tiered structure ---
- tiers = _build_tiers(
- filtered,
- limit,
- tier,
- git_meta_map,
- collector,
- repository=reference_repository,
- )
+ filtered = apply_filters(all_findings, filters)
+ serialized = [
+ serialize_finding(f, git_meta_map, repository=reference_repository) for f in filtered
+ ]
- # --- Summary across ALL open findings (unfiltered) ---
- by_kind: dict[str, int] = {}
- for f in all_findings:
- by_kind[f.kind] = by_kind.get(f.kind, 0) + 1
-
- summary: dict[str, Any] = {
- "total_findings": len(all_findings),
- "filtered_findings": len(filtered),
- "deletable_lines": sum(f.lines or 0 for f in all_findings if _effective_safe(f)),
- "safe_to_delete_count": sum(1 for f in all_findings if _effective_safe(f)),
- "by_kind": by_kind,
- }
- filters.summarize(summary)
- if withheld:
- summary["withheld_types"] = withheld
+ def _keep_overflow(name: str, beyond: list[dict]) -> None:
+ collector.add(
+ f"{name}-tier findings beyond limit={limit} ({len(beyond)} dropped)",
+ "\n".join(json.dumps(f, separators=(",", ":")) for f in beyond),
+ )
- # Cross-repo confidence adjustment (Phase 3)
- _adjust_dead_code_cross_repo(tiers, ctx.alias)
+ tiers = build_tiers(serialized, limit, tier, on_overflow=_keep_overflow)
+ summary = build_summary(summary_counts(all_findings), len(filtered), filters, withheld)
+ adjust_cross_repo(tiers, _cross_repo_lookup(), ctx.alias)
result: dict[str, Any] = {"summary": summary, "tiers": tiers}
-
- # --- Grouping views ---
if group_by == "directory":
- result["by_directory"] = _rollup_by_directory(filtered)
+ result["by_directory"] = rollup_by_directory(filtered)
elif group_by == "owner":
- result["by_owner"] = _rollup_by_owner(filtered)
-
- # --- Impact estimate ---
- result["impact"] = _compute_impact(tiers)
+ result["by_owner"] = rollup_by_owner(filtered)
+ result["impact"] = compute_impact(tiers)
_maybe_limit_note(result)
@@ -531,245 +337,3 @@ async def get_dead_code(
attach_ignored_arguments(result, ignored)
collector.attach(result)
return result
-
-
-def _adjust_dead_code_cross_repo(tiers: dict, repo_alias: str | None) -> None:
- """Reduce confidence for dead code findings that have cross-repo consumers.
-
- Mutates findings in-place within the tier dicts.
- """
- enricher = _state._cross_repo_enricher
- if enricher is None or not enricher.has_data or not _is_workspace_mode():
- return
-
- for tier_data in tiers.values():
- for finding in tier_data.get("findings", []):
- alias = finding.get("repo", repo_alias)
- if not alias:
- continue
- file_path = finding.get("file_path", "")
- consumers = enricher.has_cross_repo_consumers(alias, file_path)
- if consumers:
- original = finding["confidence"]
- finding["confidence"] = round(original * 0.5, 2)
- consumer_repos = sorted(set(c["repo"] for c in consumers))
- finding["cross_repo_note"] = (
- f"Confidence reduced: {len(consumers)} cross-repo consumer(s) "
- f"in {', '.join(consumer_repos)}."
- )
- # Also check if other repos depend on this repo via package deps
- if alias and finding.get("kind") == "unused_export":
- depending = enricher.get_repos_depending_on(alias)
- if depending and not consumers:
- original = finding["confidence"]
- finding["confidence"] = round(original * 0.3, 2)
- finding["cross_repo_note"] = (
- f"This export may be consumed by: {', '.join(depending)}. "
- "Verify before deletion."
- )
-
-
-def _find_last_meaningful_change(gm: Any) -> str | None:
- """Find the date of the last feature/fix commit (not style/chore) from git metadata."""
- if gm is None:
- return None
- sig_json = getattr(gm, "significant_commits_json", None)
- _cat_json = getattr(gm, "commit_categories_json", None)
- # If we have significant commits, the most recent one is the best proxy
- # for "last meaningful change" (significant commits already filter noise)
- if sig_json:
- try:
- commits = json.loads(sig_json)
- if commits:
- return commits[0].get("date") # most recent first
- except (json.JSONDecodeError, TypeError):
- pass
- return None
-
-
-def _effective_safe(f: Any) -> bool:
- """Re-derive deletion-readiness for a DeadCodeFinding ORM row.
-
- Mirrors the API/CLI: the persisted boolean is only ever downgraded, never
- trusted blindly, so config/bootstrap/database/environment/script/asset
- files (and findings written before risk factors existed) never read as
- safe-to-delete.
- """
- return effective_safe_to_delete(f.confidence, f.file_path, f.safe_to_delete, f.kind)
-
-
-def _dead_code_finding_id(f: Any, repository: str) -> str:
- return stable_entity_id(
- "finding",
- repository,
- {
- "family": "dead_code",
- "path": path_identity(f.file_path),
- "kind": f.kind,
- "symbol": f.symbol_name or "",
- "line_start": f.start_line,
- "line_end": f.end_line,
- },
- )
-
-
-def _serialize_finding(
- f: Any,
- git_meta_map: dict | None = None,
- *,
- repository: str = "default",
-) -> dict:
- """Serialize a single DeadCodeFinding to dict."""
- result = {
- "id": _dead_code_finding_id(f, repository),
- "repository": repository,
- "kind": f.kind,
- "file_path": f.file_path,
- "symbol_name": f.symbol_name,
- "symbol_kind": f.symbol_kind,
- "start_line": f.start_line,
- "end_line": f.end_line,
- "confidence": f.confidence,
- "reason": f.reason,
- "safe_to_delete": _effective_safe(f),
- "risk_factors": list(path_risk_factors(f.file_path)),
- "lines": f.lines,
- "last_commit_at": f.last_commit_at.isoformat() if f.last_commit_at else None,
- # Recent churn is the top rung of the confidence ladder, so the agent
- # gets the same reason for a low score that the web page now shows.
- "commit_count_90d": f.commit_count_90d,
- "primary_owner": f.primary_owner,
- # NB: age_days runs from the file's *first* commit, so it is the file's
- # age, not how long this has been dead — the two disagree on 75% of
- # findings. last_commit_at above is the staleness signal.
- "age_days": f.age_days,
- }
- label = verification_label(f.kind)
- if label:
- result["verification"] = label
- # Phase 4: add last meaningful change date
- if git_meta_map:
- gm = git_meta_map.get(f.file_path)
- meaningful = _find_last_meaningful_change(gm)
- if meaningful:
- result["last_meaningful_change"] = meaningful
- return result
-
-
-def _build_tiers(
- findings: list,
- limit: int,
- tier_filter: str | None,
- git_meta_map: dict | None = None,
- collector: OmissionCollector | None = None,
- *,
- repository: str = "default",
-) -> dict:
- """Split findings into high/medium/low confidence tiers.
-
- With a *collector*, findings beyond the per-tier limit are captured for
- the omission store instead of being silently truncated.
- """
- hi, med = _TIER_FLOORS["high"], _TIER_FLOORS["medium"]
- high = sorted(
- [f for f in findings if f.confidence >= hi],
- key=lambda f: (-f.confidence, -(f.lines or 0)),
- )
- medium = sorted(
- [f for f in findings if med <= f.confidence < hi],
- key=lambda f: (-f.confidence, -(f.lines or 0)),
- )
- low = sorted(
- [f for f in findings if f.confidence < med],
- key=lambda f: (-f.confidence, -(f.lines or 0)),
- )
-
- def _tier_block(name: str, items: list, description: str) -> dict:
- beyond_limit = items[limit:]
- if beyond_limit and collector is not None:
- collector.add(
- f"{name}-tier findings beyond limit={limit} ({len(beyond_limit)} dropped)",
- "\n".join(
- json.dumps(
- _serialize_finding(f, git_meta_map, repository=repository),
- separators=(",", ":"),
- )
- for f in beyond_limit
- ),
- )
- return {
- "description": description,
- "count": len(items),
- "lines": sum(f.lines or 0 for f in items),
- "safe_count": sum(1 for f in items if _effective_safe(f)),
- "findings": [
- _serialize_finding(f, git_meta_map, repository=repository)
- for f in items[:limit]
- ],
- "truncated": len(items) > limit,
- }
-
- tiers = {}
- if tier_filter is None or tier_filter == "high":
- tiers["high"] = _tier_block("high", high, _TIER_DESC_HIGH)
- if tier_filter is None or tier_filter == "medium":
- tiers["medium"] = _tier_block("medium", medium, _TIER_DESC_MEDIUM)
- if tier_filter is None or tier_filter == "low":
- tiers["low"] = _tier_block("low", low, _TIER_DESC_LOW)
- return tiers
-
-
-def _rollup_by_directory(findings: list) -> list[dict]:
- """Group findings by top-level directory."""
- dirs: dict[str, dict] = {}
- for f in findings:
- parts = f.file_path.split("/")
- # Use first two path segments as directory key, or just the first
- dir_key = "/".join(parts[:2]) if len(parts) > 2 else parts[0]
- if dir_key not in dirs:
- dirs[dir_key] = {"directory": dir_key, "count": 0, "lines": 0, "safe_count": 0}
- dirs[dir_key]["count"] += 1
- dirs[dir_key]["lines"] += f.lines or 0
- if _effective_safe(f):
- dirs[dir_key]["safe_count"] += 1
-
- return sorted(dirs.values(), key=lambda d: -d["lines"])
-
-
-def _rollup_by_owner(findings: list) -> list[dict]:
- """Group findings by primary owner."""
- owners: dict[str, dict] = {}
- for f in findings:
- name = f.primary_owner or "unowned"
- if name not in owners:
- owners[name] = {"owner": name, "count": 0, "lines": 0, "safe_count": 0}
- owners[name]["count"] += 1
- owners[name]["lines"] += f.lines or 0
- if _effective_safe(f):
- owners[name]["safe_count"] += 1
-
- return sorted(owners.values(), key=lambda o: -o["lines"])
-
-
-def _compute_impact(tiers: dict) -> dict:
- """Compute total impact across tiers."""
- total_lines = 0
- safe_lines = 0
- for tier_data in tiers.values():
- total_lines += tier_data["lines"]
- # Approximate safe lines from findings in the tier
- for f in tier_data["findings"]:
- if f["safe_to_delete"]:
- safe_lines += f["lines"] or 0
-
- return {
- "total_lines_reclaimable": total_lines,
- "safe_lines_reclaimable": safe_lines,
- "recommendation": (
- "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."
- ),
- }
diff --git a/tests/unit/dead_code/test_no_threshold_literals.py b/tests/unit/dead_code/test_no_threshold_literals.py
index 42342779d..7956d1752 100644
--- a/tests/unit/dead_code/test_no_threshold_literals.py
+++ b/tests/unit/dead_code/test_no_threshold_literals.py
@@ -50,6 +50,7 @@ _GUARDED = [
"core/src/repowise/core/analysis/dead_code/name_occurrences.py",
"core/src/repowise/core/analysis/dead_code/entry_shape.py",
"core/src/repowise/core/analysis/dead_code/risk_factors.py",
+ "core/src/repowise/core/analysis/dead_code/serving.py",
"core/src/repowise/core/persistence/crud/analysis/dead_code.py",
"cli/src/repowise/cli/commands/dead_code_cmd.py",
"server/src/repowise/server/routers/dead_code.py",
diff --git a/tests/unit/dead_code/test_serving.py b/tests/unit/dead_code/test_serving.py
new file mode 100644
index 000000000..a1a5a3280
--- /dev/null
+++ b/tests/unit/dead_code/test_serving.py
@@ -0,0 +1,236 @@
+"""Serving stored dead-code findings: filters, tiers, rollups, serialization."""
+
+from __future__ import annotations
+
+import json
+from datetime import UTC, datetime
+from types import SimpleNamespace
+
+from repowise.core.analysis.dead_code.risk_factors import (
+ RISK_CAP_CONFIDENCE,
+ SAFE_CONFIDENCE_THRESHOLD,
+)
+from repowise.core.analysis.dead_code.serving import (
+ DEFAULT_EXCLUDED_KINDS,
+ SUMMARY_SCOPE,
+ TIER_FLOORS,
+ FindingFilters,
+ adjust_cross_repo,
+ apply_filters,
+ build_summary,
+ build_tiers,
+ compute_impact,
+ dead_code_finding_id,
+ excluded_kinds,
+ last_meaningful_change,
+ merge_summary_counts,
+ rollup_by_directory,
+ rollup_by_owner,
+ serialize_finding,
+ summary_counts,
+)
+
+
+def _row(path: str, confidence: float, **overrides) -> dict:
+ row = {
+ "id": f"uuid-{path}-{confidence}",
+ "kind": "unused_export",
+ "file_path": path,
+ "symbol_name": "thing",
+ "symbol_kind": "function",
+ "start_line": 1,
+ "end_line": 10,
+ "confidence": confidence,
+ "reason": "no references",
+ "safe_to_delete": True,
+ "lines": 10,
+ "last_commit_at": datetime(2026, 1, 2, tzinfo=UTC),
+ "commit_count_90d": 0,
+ "primary_owner": "Ada",
+ "age_days": 400,
+ }
+ row.update(overrides)
+ return row
+
+
+_ROWS = [
+ _row("src/a/one.py", 0.9),
+ _row("src/a/two.py", 0.95, lines=3),
+ _row("src/b/three.py", 0.5, primary_owner="Grace"),
+ _row("lib/four.py", 0.2, primary_owner=None, kind="unreachable_file"),
+ _row("src/b/five.py", 0.9, lines=40),
+]
+
+
+def _filters(**overrides) -> FindingFilters:
+ base = {
+ "kind": None,
+ "safe_only": False,
+ "min_confidence": 0.0,
+ "directory": None,
+ "owner": None,
+ "excluded_kinds": set(),
+ }
+ base.update(overrides)
+ return FindingFilters(**base)
+
+
+def test_tier_floors_are_the_engine_thresholds() -> None:
+ assert TIER_FLOORS == {
+ "high": SAFE_CONFIDENCE_THRESHOLD,
+ "medium": RISK_CAP_CONFIDENCE,
+ "low": 0.0,
+ }
+
+
+def test_excluded_kinds_follow_the_scope_flags() -> None:
+ assert {"unused_internal"} == DEFAULT_EXCLUDED_KINDS
+ assert excluded_kinds(
+ no_unreachable=True,
+ no_unused_exports=True,
+ include_internals=True,
+ include_zombie_packages=False,
+ ) == {"unreachable_file", "unused_export", "zombie_package"}
+
+
+def test_apply_filters_reads_rows_and_mappings_alike() -> None:
+ namespaces = [SimpleNamespace(**r) for r in _ROWS]
+ for rows in (_ROWS, namespaces):
+ assert len(apply_filters(rows, _filters(min_confidence=0.4))) == 4
+ assert len(apply_filters(rows, _filters(kind="unreachable_file"))) == 1
+ assert len(apply_filters(rows, _filters(excluded_kinds={"unused_export"}))) == 1
+ assert len(apply_filters(rows, _filters(directory="src/a/"))) == 2
+ assert len(apply_filters(rows, _filters(owner="grace"))) == 1
+
+
+def test_applied_echoes_only_what_differs_from_the_defaults() -> None:
+ defaults = _filters(min_confidence=RISK_CAP_CONFIDENCE, excluded_kinds=DEFAULT_EXCLUDED_KINDS)
+ assert defaults.applied() == {}
+ summary: dict = {}
+ defaults.summarize(summary)
+ assert summary == {"scope": SUMMARY_SCOPE}
+
+ narrowed = _filters(kind="unused_export", safe_only=True, directory="src", owner="Ada")
+ assert narrowed.applied() == {
+ "kind": "unused_export",
+ "safe_only": True,
+ "min_confidence": 0.0,
+ "directory": "src",
+ "owner": "Ada",
+ }
+
+
+def test_build_summary_counts_every_shown_finding() -> None:
+ summary = build_summary(summary_counts(_ROWS), 2, _filters(), {})
+ assert summary["total_findings"] == 5
+ assert summary["filtered_findings"] == 2
+ assert summary["by_kind"] == {"unused_export": 4, "unreachable_file": 1}
+ assert list(summary)[:5] == [
+ "total_findings",
+ "filtered_findings",
+ "deletable_lines",
+ "safe_to_delete_count",
+ "by_kind",
+ ]
+ assert "withheld_types" not in summary
+
+
+def test_serialization_is_the_same_for_rows_and_mappings() -> None:
+ row = _ROWS[0]
+ as_dict = serialize_finding(row, repository="r")
+ assert serialize_finding(SimpleNamespace(**row), repository="r") == as_dict
+ assert as_dict["id"] == dead_code_finding_id(row, "r")
+ assert as_dict["last_commit_at"] == "2026-01-02T00:00:00+00:00"
+
+
+def test_serialization_adds_the_last_meaningful_change() -> None:
+ gm = SimpleNamespace(significant_commits_json=json.dumps([{"date": "2026-03-01"}]))
+ out = serialize_finding(_ROWS[0], {"src/a/one.py": gm})
+ assert out["last_meaningful_change"] == "2026-03-01"
+ assert last_meaningful_change(SimpleNamespace(significant_commits_json="not json")) is None
+ assert last_meaningful_change(None) is None
+
+
+def test_build_tiers_bands_sorts_and_reports_overflow() -> None:
+ serialized = [serialize_finding(r) for r in _ROWS]
+ dropped: list[tuple[str, int]] = []
+ tiers = build_tiers(serialized, 2, None, on_overflow=lambda n, b: dropped.append((n, len(b))))
+
+ assert list(tiers) == ["high", "medium", "low"]
+ high = tiers["high"]
+ assert [f["file_path"] for f in high["findings"]] == ["src/a/two.py", "src/b/five.py"]
+ assert (high["count"], high["lines"], high["truncated"]) == (3, 53, True)
+ assert dropped == [("high", 1)]
+ assert build_tiers(serialized, 2, "low")["low"]["count"] == 1
+ assert list(build_tiers(serialized, 2, "medium")) == ["medium"]
+
+
+def test_single_repo_and_workspace_tiering_have_the_same_shape() -> None:
+ # The single-repo path serializes ORM-like rows; the workspace path merges
+ # repos, tags each finding with its repo and arrives in a different order.
+ single = build_tiers([serialize_finding(SimpleNamespace(**r)) for r in _ROWS], 2, None)
+ merged = []
+ for r in reversed(_ROWS):
+ item = serialize_finding(r)
+ item["repo"] = "default"
+ merged.append(item)
+ workspace = build_tiers(merged, 2, None)
+
+ for tier in workspace.values():
+ for f in tier["findings"]:
+ f.pop("repo")
+ # Equal-score ties keep their input order; this fixture has none.
+ assert workspace == single
+
+
+def test_rollups_group_and_order_by_lines() -> None:
+ assert rollup_by_directory(_ROWS)[0] == {
+ "directory": "src/b",
+ "count": 2,
+ "lines": 50,
+ "safe_count": 1,
+ }
+ owners = {o["owner"]: o["count"] for o in rollup_by_owner(_ROWS)}
+ assert owners == {"Ada": 3, "Grace": 1, "unowned": 1}
+
+
+def test_compute_impact_counts_safe_lines_shown() -> None:
+ tiers = build_tiers([serialize_finding(r) for r in _ROWS], 25, None)
+ impact = compute_impact(tiers)
+ assert impact["total_lines_reclaimable"] == 73
+ assert impact["safe_lines_reclaimable"] == 53
+ assert compute_impact({})["recommendation"] == "No dead code found matching your filters."
+
+
+class _Lookup:
+ def has_cross_repo_consumers(self, repo_alias: str, file_path: str) -> list[dict]:
+ return [{"repo": "web"}] if file_path == "src/a/one.py" else []
+
+ def get_repos_depending_on(self, repo_alias: str) -> list[str]:
+ return ["mobile"]
+
+
+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"]}
+ 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"]
+
+
+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
+
+
+def test_merged_per_repo_counts_equal_counting_everything_at_once() -> None:
+ parts = [summary_counts(_ROWS[:2]), summary_counts([]), summary_counts(_ROWS[2:])]
+ merged = merge_summary_counts(parts)
+ whole = summary_counts(_ROWS)
+ assert merged == whole
+ assert list(merged["by_kind"]) == list(whole["by_kind"])
diff --git a/tests/unit/health/test_failing_types_demoted.py b/tests/unit/health/test_failing_types_demoted.py
index 692a20086..120421de6 100644
--- a/tests/unit/health/test_failing_types_demoted.py
+++ b/tests/unit/health/test_failing_types_demoted.py
@@ -112,10 +112,10 @@ def test_unreachable_file_is_never_deletion_ready():
def test_mcp_dead_code_tiers_are_the_engine_thresholds():
- from repowise.server.mcp_server.tool_dead_code import _TIER_FLOORS
+ from repowise.core.analysis.dead_code.serving import TIER_FLOORS
- assert _TIER_FLOORS["high"] == SAFE_CONFIDENCE_THRESHOLD
- assert _TIER_FLOORS["medium"] == RISK_CAP_CONFIDENCE
+ assert TIER_FLOORS["high"] == SAFE_CONFIDENCE_THRESHOLD
+ assert TIER_FLOORS["medium"] == RISK_CAP_CONFIDENCE
def _metric(path: str, score: float, *, is_test: bool) -> SimpleNamespace:
diff --git a/tests/unit/server/mcp/test_cross_tool_reference_contracts.py b/tests/unit/server/mcp/test_cross_tool_reference_contracts.py
index 22ffddd6b..1c916830b 100644
--- a/tests/unit/server/mcp/test_cross_tool_reference_contracts.py
+++ b/tests/unit/server/mcp/test_cross_tool_reference_contracts.py
@@ -854,8 +854,8 @@ async def test_finding_and_plan_ids_are_stable_and_resolve_in_one_call(
health_data,
session,
) -> None:
+ from repowise.core.analysis.dead_code.serving import dead_code_finding_id
from repowise.server.mcp_server import get_dead_code, get_health
- from repowise.server.mcp_server.tool_dead_code import _dead_code_finding_id
from repowise.server.mcp_server.tool_health import (
_health_finding_id,
_refactoring_plan_id,
@@ -896,7 +896,7 @@ async def test_finding_and_plan_ids_are_stable_and_resolve_in_one_call(
plan_row = (await session.execute(select(RefactoringSuggestion))).scalars().first()
for row, public_id, factory in (
(health_row, health_finding["id"], _health_finding_id),
- (dead_row, dead_finding["id"], _dead_code_finding_id),
+ (dead_row, dead_finding["id"], dead_code_finding_id),
(plan_row, plan["id"], _refactoring_plan_id),
):
replacement = copy(row)