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(health): one effort scale and shared rank helpers (#3288)

Raghav Chamadiya6b021060fb10
diff --git a/packages/cli/src/repowise/cli/commands/health_cmd/refactoring_targets.py b/packages/cli/src/repowise/cli/commands/health_cmd/refactoring_targets.py
index 37d9a2bdf..d944700e1 100644
--- a/packages/cli/src/repowise/cli/commands/health_cmd/refactoring_targets.py
+++ b/packages/cli/src/repowise/cli/commands/health_cmd/refactoring_targets.py
@@ -21,19 +21,10 @@ import click
from rich.table import Table
from repowise.cli.helpers import console
+from repowise.core.analysis.health.effort import EFFORT_WEIGHT, effort_bucket
from repowise.core.analysis.health.models import primary_finding
-def _effort_bucket(nloc: int) -> tuple[str, int]:
- if nloc <= 40:
- return "S", 1
- if nloc <= 150:
- return "M", 2
- if nloc <= 400:
- return "L", 3
- return "XL", 5
-
-
def _suggestion_to_dict(s: object) -> dict[str, Any]:
"""Serialize a ``RefactoringSuggestion`` dataclass to a plain dict."""
import dataclasses
@@ -245,7 +236,7 @@ def _build_targets(
if primary is None:
continue
total_impact = round(sum(x.health_impact for x in fs), 3)
- bucket, weight = _effort_bucket(nloc)
+ bucket = effort_bucket(nloc)
file_sugg = sugg_by_file.get(path, [])
targets.append(
{
@@ -257,7 +248,7 @@ def _build_targets(
"primary_reason": primary.reason,
"total_impact": total_impact,
"effort_bucket": bucket,
- "impact_per_effort": round(total_impact / weight, 3),
+ "impact_per_effort": round(total_impact / EFFORT_WEIGHT[bucket], 3),
"finding_count": len(fs),
"plans": [_suggestion_to_dict(s) for s in file_sugg],
}
diff --git a/packages/core/src/repowise/core/analysis/health/effort.py b/packages/core/src/repowise/core/analysis/health/effort.py
new file mode 100644
index 000000000..23113f893
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/effort.py
@@ -0,0 +1,27 @@
+"""Effort buckets: the size of a change in code lines (NLOC), as S / M / L / XL.
+
+The one definition every surface sizes work with: the refactoring detectors,
+the CLI's refactoring targets and the server's work queue. Dependency-free so
+a surface can import it without loading the refactoring detectors.
+"""
+
+from __future__ import annotations
+
+EFFORT_ORDER = ("S", "M", "L", "XL")
+"""The buckets, smallest first."""
+
+_CEILINGS = tuple(zip((40, 150, 400), EFFORT_ORDER[:-1], strict=True))
+
+EFFORT_WEIGHT = dict(zip(EFFORT_ORDER, (1, 2, 3, 5), strict=True))
+"""Each bucket's divisor in ``impact_per_effort``, and the order a ``max_effort`` cap reads."""
+
+
+def effort_bucket(nloc: int) -> str:
+ """Map a target's NLOC to its effort bucket."""
+ for ceiling, label in _CEILINGS:
+ if nloc <= ceiling:
+ return label
+ return "XL"
+
+
+__all__ = ["EFFORT_ORDER", "EFFORT_WEIGHT", "effort_bucket"]
diff --git a/packages/core/src/repowise/core/analysis/health/perf/opportunity_rank.py b/packages/core/src/repowise/core/analysis/health/perf/opportunity_rank.py
index 127849777..c682238ac 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/opportunity_rank.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/opportunity_rank.py
@@ -20,6 +20,7 @@ from collections.abc import Mapping
from math import log2
from typing import Any
+from ..rank_common import top_factors, weakest
from ..rows import detail_map, field
from ..worth import cost_proof, lead_reason
from .actionability import EXPECTED_REASONS
@@ -184,7 +185,7 @@ def weakest_provenance(provenances: set[str]) -> str:
points where :func:`dominant_marker` is a ``min`` on negated points. They
read alike and mean the opposite; that is intentional.
"""
- return min(provenances, key=lambda value: (PROVENANCE_POINTS.get(value, 0), value))
+ return weakest(provenances, PROVENANCE_POINTS)
def amplification(marker: str) -> str:
@@ -283,13 +284,9 @@ def why_ranked(factors: dict[str, int], values: dict[str, Any], limit: int = 3)
reword never churns anything. Zero-point terms explain nothing and are
dropped, so fewer than ``limit`` entries is a normal answer.
"""
- ranked = sorted(
- ((name, points) for name, points in factors.items() if points),
- key=lambda item: (-item[1], item[0]),
- )
return tuple(
{"factor": name, "value": values.get(name), "points": points}
- for name, points in ranked[:limit]
+ for name, points in top_factors(factors, limit)
)
diff --git a/packages/core/src/repowise/core/analysis/health/rank_common.py b/packages/core/src/repowise/core/analysis/health/rank_common.py
new file mode 100644
index 000000000..d68973361
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/rank_common.py
@@ -0,0 +1,32 @@
+"""Ranking helpers both opportunity orders share.
+
+``refactoring/opportunity_rank.py`` and ``perf/opportunity_rank.py`` rank
+different units with different factor models; those models stay in their own
+modules as data. What they share is the shape: a group is only as trustworthy
+as its weakest member, and "why ranked" is the few largest non-zero factors.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Iterable, Mapping
+
+
+def weakest(labels: Iterable[str], strength: Mapping[str, float]) -> str:
+ """The least trusted of *labels*, ties broken by name.
+
+ A label *strength* does not list counts as 0. Raises on an empty input,
+ as ``min`` does: what an empty group means is the caller's policy.
+ """
+ return min(labels, key=lambda label: (strength.get(label, 0), label))
+
+
+def top_factors(factors: Mapping[str, float], limit: int) -> list[tuple[str, float]]:
+ """The *limit* largest non-zero factors by magnitude, ties broken by name."""
+ ranked = sorted(
+ ((name, value) for name, value in factors.items() if value),
+ key=lambda item: (-abs(item[1]), item[0]),
+ )
+ return ranked[:limit]
+
+
+__all__ = ["top_factors", "weakest"]
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/__init__.py b/packages/core/src/repowise/core/analysis/health/refactoring/__init__.py
index e82d5de4f..92febfd0a 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/__init__.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/__init__.py
@@ -11,6 +11,8 @@ self-register via ``@register``), so ``detect_refactorings`` sees them.
from __future__ import annotations
+from ..effort import effort_bucket
+
# Importing the detector modules triggers their ``@register`` side effect.
# Listed explicitly (and in a fixed order) so the registry is deterministic.
from . import (
@@ -47,7 +49,6 @@ from .rank import rank_suggestions
from .registry import (
RefactoringDetector,
detect_refactorings,
- effort_bucket,
register,
registered_detectors,
)
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/extract_class.py b/packages/core/src/repowise/core/analysis/health/refactoring/extract_class.py
index 977543cb5..b359cac67 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/extract_class.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/extract_class.py
@@ -36,8 +36,9 @@ from __future__ import annotations
from ..complexity.class_analysis import cohesion_applies, holds_state
from ..complexity.models import CohesionGroup
+from ..effort import effort_bucket
from .models import RefactoringContext, RefactoringSuggestion
-from .registry import RefactoringDetector, effort_bucket, register
+from .registry import RefactoringDetector, register
# The cohesion biomarkers this detector answers. A class is only suggested
# for splitting if one of these flagged it, so the suggestion list never
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/extract_helper.py b/packages/core/src/repowise/core/analysis/health/refactoring/extract_helper.py
index 6796cb08b..936fa9529 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/extract_helper.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/extract_helper.py
@@ -48,9 +48,10 @@ from typing import Any
from ....code_origin import is_migration_path, is_vendored_or_generated_path
from ....test_paths import is_test_related_path
from ..duplication.detector import clone_ranges, union_line_count
+from ..effort import effort_bucket
from .language_family import same_language_family
from .models import RefactoringContext, RefactoringSuggestion
-from .registry import RefactoringDetector, effort_bucket, register
+from .registry import RefactoringDetector, register
# The biomarker this detector answers — the recovered impact is read off it.
_SOURCE_BIOMARKER = "dry_violation"
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/extract_method.py b/packages/core/src/repowise/core/analysis/health/refactoring/extract_method.py
index 0a9b33138..96d3b8524 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/extract_method.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/extract_method.py
@@ -76,11 +76,12 @@ from ..complexity.cyclomatic import _is_boolean_operator, is_markup
from ..complexity.languages import get_language_map
from ..complexity.nloc import is_string_stmt
from ..dataflow import find_extractions
+from ..effort import effort_bucket
from ..perf.dialects import PERF_DIALECTS
from ..scoring import severity_deduction
from .models import RefactoringContext, RefactoringSuggestion
from .naming import join_identifier, split_words
-from .registry import RefactoringDetector, effort_bucket, register
+from .registry import RefactoringDetector, register
if TYPE_CHECKING:
from ..complexity.languages import LanguageNodeMap
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/move_method.py b/packages/core/src/repowise/core/analysis/health/refactoring/move_method.py
index 6e2fe467a..39bbe96a8 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/move_method.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/move_method.py
@@ -65,9 +65,10 @@ from repowise.core.analysis.dead_code.contract_methods import is_contract_method
from repowise.core.analysis.execution_graph import is_reliable_call_edge
from ....test_paths import is_test_related_path
+from ..effort import effort_bucket
from .language_family import same_language_family
from .models import RefactoringContext, RefactoringSuggestion
-from .registry import RefactoringDetector, effort_bucket, register
+from .registry import RefactoringDetector, register
# Distinct foreign members the method must access for the envy to be real
# (a single shared call is incidental, not envy).
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/opportunity.py b/packages/core/src/repowise/core/analysis/health/refactoring/opportunity.py
index e8df027d3..0ddac4cdb 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/opportunity.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/opportunity.py
@@ -57,6 +57,7 @@ from dataclasses import dataclass
from typing import Any
from ...finding_registry import excluded_types
+from ..effort import EFFORT_ORDER
from ..refactoring_summary import ADVISORY_TYPES, needs_design
from ..rows import field
from .extract_helper import ACTIVE_CO_CHANGE
@@ -107,8 +108,6 @@ _UNORDERED = len(STEP_ORDER)
# place entirely.
_RELOCATING_TYPES = frozenset({"split_file", "extract_class", "move_method"})
-_EFFORT_ORDER = ("S", "M", "L", "XL")
-
# Evidence restates the plan's own signals; these three are read-model
# additions the plan layer already publishes elsewhere.
_EVIDENCE_OMIT = frozenset({"provenance", "rank_factors", "rank_score"})
@@ -296,8 +295,8 @@ def _aggregate_effort(steps: Sequence[OpportunityStep]) -> str:
label no detector could emit. Total work enters the ranking through
``step_cost`` instead, where it belongs.
"""
- present = [step.effort_bucket for step in steps if step.effort_bucket in _EFFORT_ORDER]
- return max(present, key=_EFFORT_ORDER.index) if present else "M"
+ present = [step.effort_bucket for step in steps if step.effort_bucket in EFFORT_ORDER]
+ return max(present, key=EFFORT_ORDER.index) if present else "M"
def opportunity_kernel(step_plan_ids: Sequence[str], file_path: str) -> tuple[Any, ...]:
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/opportunity_rank.py b/packages/core/src/repowise/core/analysis/health/refactoring/opportunity_rank.py
index 627c77c95..8ff58ab93 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/opportunity_rank.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/opportunity_rank.py
@@ -24,8 +24,8 @@ uplift for a whole step set.
Nothing here is a health score, and no value it produces is blended into one.
It is an ordering key whose weights are frozen policy. The performance layer's
-``perf/opportunity_rank.py`` is the same role for a different domain and shares
-no code with this one.
+``perf/opportunity_rank.py`` is the same role for a different domain; the two
+share only the helpers in :mod:`..rank_common`.
"""
from __future__ import annotations
@@ -35,6 +35,7 @@ from typing import Any
from repowise.core.code_origin import ship_rank
+from ..rank_common import top_factors
from .models import CONFIDENCE_LEVELS, RefactoringSuggestion
from .recommendations import EFFORT_COST, detector_native_benefit, priority_score
from .recommendations import surface_confidence_risk as _surface_confidence_risk
@@ -128,11 +129,7 @@ def opportunity_benefit(steps: Sequence[RefactoringSuggestion]) -> float:
def why_ranked(factors: dict[str, float], *, limit: int = 3) -> list[dict[str, Any]]:
"""The factors that actually moved this one, largest first. Structured."""
- ordered = sorted(
- ((name, value) for name, value in factors.items() if value),
- key=lambda item: (-abs(item[1]), item[0]),
- )
- return [{"factor": name, "value": value} for name, value in ordered[:limit]]
+ return [{"factor": name, "value": value} for name, value in top_factors(factors, limit)]
def rank_sort_key(opportunity: Any) -> tuple[int, bool, float, str, str]:
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/registry.py b/packages/core/src/repowise/core/analysis/health/refactoring/registry.py
index 92beb7710..d78e245b2 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/registry.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/registry.py
@@ -22,21 +22,6 @@ from .models import CONFIDENCE_LEVELS, RefactoringContext, RefactoringSuggestion
log = structlog.get_logger(__name__)
-def effort_bucket(nloc: int) -> str:
- """Map a target's NLOC to a coarse effort bucket.
-
- Shared by every detector so the effort label is consistent across
- refactoring types (matches the CLI's refactoring-targets thresholds).
- """
- if nloc <= 40:
- return "S"
- if nloc <= 150:
- return "M"
- if nloc <= 400:
- return "L"
- return "XL"
-
-
class RefactoringDetector(ABC):
"""Detector contract. Each concrete detector sets a unique ``name`` and
implements ``detect`` over a single file's ``RefactoringContext``.
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/serving.py b/packages/core/src/repowise/core/analysis/health/refactoring/serving.py
index f45d2ada2..e188b7194 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/serving.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/serving.py
@@ -16,6 +16,7 @@ from dataclasses import dataclass
from typing import Any
from repowise.core.analysis.health import queue_rules
+from repowise.core.analysis.health.effort import EFFORT_ORDER
from repowise.core.analysis.health.queue_rules import Facet, FilterRule, SortKeys
from repowise.core.analysis.health.rows import detail_map, field
@@ -54,7 +55,6 @@ DEFAULT_SCOPE = "fix_first"
_STATUSES = ("open", "acknowledged", "resolved", "false_positive")
_CONFIDENCES = ("low", "medium", "high")
-_EFFORTS = ("S", "M", "L", "XL")
_TYPES = (
"break_cycle",
"extract_class",
@@ -244,7 +244,7 @@ def parse_query(
lead_types=admit_many("refactoring_type", lead_type, _TYPES),
status=resolved_status,
confidence=admit("confidence", confidence, _CONFIDENCES),
- effort=admit("effort", effort, _EFFORTS),
+ effort=admit("effort", effort, EFFORT_ORDER),
mechanical_only=bool(mechanical),
addresses_primary=addresses_primary,
# ``is not None``, not truthiness: an empty sequence is a scope that
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/split_file.py b/packages/core/src/repowise/core/analysis/health/refactoring/split_file.py
index 356acc93d..c5a531e72 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/split_file.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/split_file.py
@@ -59,8 +59,9 @@ from repowise.core.analysis.execution_graph import is_reliable_call_edge
from ....code_origin import is_migration_path, is_vendored_or_generated_path
from ....test_paths import is_test_related_path
from ...dead_code.file_reachability import BARREL_FILENAMES
+from ..effort import effort_bucket
from .models import RefactoringContext, RefactoringSuggestion
-from .registry import RefactoringDetector, effort_bucket, register
+from .registry import RefactoringDetector, register
# Edge weights over the intra-file symbol graph (see module docstring).
_DIRECT_CALL_WEIGHT = 3.0
diff --git a/packages/server/src/repowise/server/routers/code_health/refactoring_routes.py b/packages/server/src/repowise/server/routers/code_health/refactoring_routes.py
index 1a5433bd0..97c879111 100644
--- a/packages/server/src/repowise/server/routers/code_health/refactoring_routes.py
+++ b/packages/server/src/repowise/server/routers/code_health/refactoring_routes.py
@@ -13,6 +13,7 @@ from typing import Any
from fastapi import Depends, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession
+from repowise.core.analysis.health.effort import EFFORT_WEIGHT, effort_bucket
from repowise.core.analysis.health.impact_effort import build_impact_effort, fix_first_marks
from repowise.core.analysis.health.models import primary_finding, split_by_origin
from repowise.core.analysis.health.scope import parse_scope
@@ -31,16 +32,6 @@ from .statuses import STATUS_FILTER_DESCRIPTION, parse_status_filter
_SEVERITY_ORDER = {"low": 0, "medium": 1, "high": 2, "critical": 3}
-_EFFORT_BUCKETS: tuple[tuple[int, str], ...] = (
- (40, "S"),
- (150, "M"),
- (400, "L"),
-)
-
-# The divisor behind ``impact_per_effort``, and the order ``max_effort`` caps.
-_EFFORT_RANK = {"S": 1, "M": 2, "L": 3, "XL": 5}
-
-
_SORT_KEYS = {
"impact_per_effort": lambda t: (-t["impact_per_effort"], -t["total_impact"]),
"total_impact": lambda t: -t["total_impact"],
@@ -58,13 +49,6 @@ _SORT_KEYS = {
}
-def _effort_for_nloc(nloc: int) -> str:
- for ceiling, label in _EFFORT_BUCKETS:
- if nloc <= ceiling:
- return label
- return "XL"
-
-
@dataclass(frozen=True, slots=True)
class QueueFilters:
"""The narrowing the work queue and its impact / effort plane share."""
@@ -198,7 +182,7 @@ def _lead_finding(fs: list[Any]) -> Any:
return max(fs, key=lambda x: (_SEVERITY_ORDER.get(x.severity, 0), -(x.line_start or 0)))
-def _target_row(file_path: str, fs: list[Any], m: Any, effort_bucket: str) -> dict:
+def _target_row(file_path: str, fs: list[Any], m: Any, bucket: str) -> dict:
primary = _lead_finding(fs)
# Impact, and therefore the ranking, counts only findings still open:
# ``score`` on this row was computed from open findings, and a file
@@ -223,8 +207,8 @@ def _target_row(file_path: str, fs: list[Any], m: Any, effort_bucket: str) -> di
"finding_count": len(fs),
"open_finding_count": len(open_fs),
"biomarkers": sorted({x.biomarker_type for x in fs}),
- "effort_bucket": effort_bucket,
- "impact_per_effort": round(total_impact / _EFFORT_RANK[effort_bucket], 3),
+ "effort_bucket": bucket,
+ "impact_per_effort": round(total_impact / EFFORT_WEIGHT[bucket], 3),
}
@@ -238,7 +222,7 @@ async def _queue_targets(
metric_by_path, findings = await _load_queue_rows(session, repo_id, q)
by_file = _group_by_file(findings, _finding_filter(q))
- max_effort_rank = _EFFORT_RANK.get(q.max_effort or "", 99)
+ max_effort_rank = EFFORT_WEIGHT.get(q.max_effort or "", 99)
targets: list[dict] = []
history_only = 0
@@ -254,10 +238,10 @@ async def _queue_targets(
if _is_history_only(fs, q, history):
history_only += 1
continue
- effort_bucket = _effort_for_nloc(m.nloc)
- if _EFFORT_RANK[effort_bucket] > max_effort_rank:
+ bucket = effort_bucket(m.nloc)
+ if EFFORT_WEIGHT[bucket] > max_effort_rank:
continue
- targets.append(_target_row(file_path, fs, m, effort_bucket))
+ targets.append(_target_row(file_path, fs, m, bucket))
return targets, history_only
diff --git a/packages/server/src/repowise/server/routers/refactoring.py b/packages/server/src/repowise/server/routers/refactoring.py
index 28fb1fb2f..f767f7e81 100644
--- a/packages/server/src/repowise/server/routers/refactoring.py
+++ b/packages/server/src/repowise/server/routers/refactoring.py
@@ -19,6 +19,7 @@ from fastapi import APIRouter, Depends, HTTPException, Query
from pydantic import BaseModel, Field
from sqlalchemy.ext.asyncio import AsyncSession
+from repowise.core.analysis.health.effort import EFFORT_ORDER
from repowise.core.analysis.health.refactoring.recommendations import (
apply_view,
blast_size,
@@ -144,7 +145,7 @@ def _to_response(data: dict[str, Any]) -> RefactoringPlanResponse:
_STRUCTURAL_TYPES = STRUCTURAL_TYPES
-_EFFORT_ORDER = {"S": 0, "M": 1, "L": 2, "XL": 3}
+_EFFORT_ORDER = {bucket: rank for rank, bucket in enumerate(EFFORT_ORDER)}
def _summary(recommendations: list[Any]) -> RefactoringSummary:
diff --git a/tests/unit/health/test_effort.py b/tests/unit/health/test_effort.py
new file mode 100644
index 000000000..f6efb67f6
--- /dev/null
+++ b/tests/unit/health/test_effort.py
@@ -0,0 +1,21 @@
+"""The one effort bucket every surface sizes work with."""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.analysis.health import effort
+
+
+ ("nloc", "bucket"),
+ [(0, "S"), (40, "S"), (41, "M"), (150, "M"), (151, "L"), (400, "L"), (401, "XL")],
+)
+def test_effort_bucket_ceilings_are_inclusive(nloc: int, bucket: str) -> None:
+ assert effort.effort_bucket(nloc) == bucket
+
+
+def test_every_bucket_has_a_weight_in_size_order() -> None:
+ assert effort.EFFORT_ORDER == ("S", "M", "L", "XL")
+ assert tuple(effort.EFFORT_WEIGHT) == effort.EFFORT_ORDER
+ assert sorted(effort.EFFORT_WEIGHT.values()) == list(effort.EFFORT_WEIGHT.values())
diff --git a/tests/unit/health/test_rank_common.py b/tests/unit/health/test_rank_common.py
new file mode 100644
index 000000000..2bfba1b6d
--- /dev/null
+++ b/tests/unit/health/test_rank_common.py
@@ -0,0 +1,59 @@
+"""Ranking helpers shared by the refactoring and performance opportunity orders."""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+
+from repowise.core.analysis.health.perf import opportunity_rank as perf_rank
+from repowise.core.analysis.health.rank_common import top_factors, weakest
+from repowise.core.analysis.health.refactoring import opportunity_rank as refactoring_rank
+
+
+def test_weakest_is_lowest_strength_then_name() -> None:
+ strength = {"direct": 3, "call-site": 3, "reliable-edge": 2}
+ assert weakest({"direct", "reliable-edge"}, strength) == "reliable-edge"
+ assert weakest({"direct", "call-site"}, strength) == "call-site"
+
+
+def test_weakest_counts_an_unlisted_label_as_zero() -> None:
+ assert weakest(["direct", "mystery"], {"direct": 3}) == "mystery"
+
+
+def test_top_factors_drops_zeros_and_orders_by_magnitude_then_name() -> None:
+ factors = {"b": 2.0, "a": 2.0, "zero": 0.0, "neg": -5.0, "small": 0.5}
+ assert top_factors(factors, 3) == [("neg", -5.0), ("a", 2.0), ("b", 2.0)]
+ assert top_factors({"zero": 0}, 3) == []
+
+
+def test_refactoring_rank_keeps_its_shape() -> None:
+ steps = [SimpleNamespace(confidence="high"), SimpleNamespace(confidence="medium")]
+ assert refactoring_rank.weakest_confidence(steps) == "medium"
+ assert refactoring_rank.why_ranked({"cost": 2.0, "risk": 0.0, "benefit": 3.0}) == [
+ {"factor": "benefit", "value": 3.0},
+ {"factor": "cost", "value": 2.0},
+ ]
+
+
+# Today both return "high": ``_WORST_FIRST[0]`` is the strongest level. Strict,
+# so the fix flips these to passing and the markers have to come off.
[email protected](strict=True, reason="unknown confidence falls back to high, not low")
+def test_refactoring_unknown_confidence_counts_as_low() -> None:
+ steps = [SimpleNamespace(confidence="high"), SimpleNamespace(confidence="bogus")]
+ assert refactoring_rank.weakest_confidence(steps) == "low"
+
+
[email protected](strict=True, reason="empty step set falls back to high, not low")
+def test_refactoring_empty_steps_count_as_low() -> None:
+ assert refactoring_rank.weakest_confidence([]) == "low"
+
+
+def test_perf_rank_keeps_its_shape() -> None:
+ assert perf_rank.weakest_provenance({"direct", "name-fallback"}) == "name-fallback"
+ assert perf_rank.why_ranked(
+ {"boundary_kind": 4, "provenance": 0, "multiplier_shape": 4}, {"boundary_kind": "db"}
+ ) == (
+ {"factor": "boundary_kind", "value": "db", "points": 4},
+ {"factor": "multiplier_shape", "value": None, "points": 4},
+ )