Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
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.pyindex 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 clickfrom rich.table import Tablefrom repowise.cli.helpers import console+from repowise.core.analysis.health.effort import EFFORT_WEIGHT, effort_bucketfrom 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:continuetotal_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.pynew file mode 100644index 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.pyindex 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 Mappingfrom math import log2from typing import Any+from ..rank_common import top_factors, weakestfrom ..rows import detail_map, fieldfrom ..worth import cost_proof, lead_reasonfrom .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. Theyread 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 aredropped, 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.pynew file mode 100644index 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__.pyindex 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_suggestionsfrom .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.pyindex 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 annotationsfrom ..complexity.class_analysis import cohesion_applies, holds_statefrom ..complexity.models import CohesionGroup+from ..effort import effort_bucketfrom .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 neverdiff --git a/packages/core/src/repowise/core/analysis/health/refactoring/extract_helper.py b/packages/core/src/repowise/core/analysis/health/refactoring/extract_helper.pyindex 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 Anyfrom ....code_origin import is_migration_path, is_vendored_or_generated_pathfrom ....test_paths import is_test_related_pathfrom ..duplication.detector import clone_ranges, union_line_count+from ..effort import effort_bucketfrom .language_family import same_language_familyfrom .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.pyindex 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_markupfrom ..complexity.languages import get_language_mapfrom ..complexity.nloc import is_string_stmtfrom ..dataflow import find_extractions+from ..effort import effort_bucketfrom ..perf.dialects import PERF_DIALECTSfrom ..scoring import severity_deductionfrom .models import RefactoringContext, RefactoringSuggestionfrom .naming import join_identifier, split_words-from .registry import RefactoringDetector, effort_bucket, register+from .registry import RefactoringDetector, registerif TYPE_CHECKING:from ..complexity.languages import LanguageNodeMapdiff --git a/packages/core/src/repowise/core/analysis/health/refactoring/move_method.py b/packages/core/src/repowise/core/analysis/health/refactoring/move_method.pyindex 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_methodfrom repowise.core.analysis.execution_graph import is_reliable_call_edgefrom ....test_paths import is_test_related_path+from ..effort import effort_bucketfrom .language_family import same_language_familyfrom .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.pyindex 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 dataclassfrom typing import Anyfrom ...finding_registry import excluded_types+from ..effort import EFFORT_ORDERfrom ..refactoring_summary import ADVISORY_TYPES, needs_designfrom ..rows import fieldfrom .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.pyindex 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 Anyfrom repowise.core.code_origin import ship_rank+from ..rank_common import top_factorsfrom .models import CONFIDENCE_LEVELS, RefactoringSuggestionfrom .recommendations import EFFORT_COST, detector_native_benefit, priority_scorefrom .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.pyindex 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, RefactoringSuggestionlog = 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`` andimplements ``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.pyindex 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 dataclassfrom typing import Anyfrom repowise.core.analysis.health import queue_rules+from repowise.core.analysis.health.effort import EFFORT_ORDERfrom repowise.core.analysis.health.queue_rules import Facet, FilterRule, SortKeysfrom 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 thatdiff --git a/packages/core/src/repowise/core/analysis/health/refactoring/split_file.py b/packages/core/src/repowise/core/analysis/health/refactoring/split_file.pyindex 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_edgefrom ....code_origin import is_migration_path, is_vendored_or_generated_pathfrom ....test_paths import is_test_related_pathfrom ...dead_code.file_reachability import BARREL_FILENAMES+from ..effort import effort_bucketfrom .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.0diff --git a/packages/server/src/repowise/server/routers/code_health/refactoring_routes.py b/packages/server/src/repowise/server/routers/code_health/refactoring_routes.pyindex 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 Anyfrom fastapi import Depends, HTTPException, Queryfrom sqlalchemy.ext.asyncio import AsyncSession+from repowise.core.analysis.health.effort import EFFORT_WEIGHT, effort_bucketfrom repowise.core.analysis.health.impact_effort import build_impact_effort, fix_first_marksfrom repowise.core.analysis.health.models import primary_finding, split_by_originfrom 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 += 1continue- 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_onlydiff --git a/packages/server/src/repowise/server/routers/refactoring.py b/packages/server/src/repowise/server/routers/refactoring.pyindex 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, Queryfrom pydantic import BaseModel, Fieldfrom sqlalchemy.ext.asyncio import AsyncSession+from repowise.core.analysis.health.effort import EFFORT_ORDERfrom 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.pynew file mode 100644index 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.pynew file mode 100644index 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},+ )