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.

feat(refactoring): rank a plan last when it leaves a function above the break-up bar (#3482)

Raghav Chamadiya2fb0921bceb1
diff --git a/docs/layers/REFACTORING.md b/docs/layers/REFACTORING.md
index 2c65a4753..c2e6caea7 100644
--- a/docs/layers/REFACTORING.md
+++ b/docs/layers/REFACTORING.md
@@ -289,6 +289,11 @@ Most plans answer a health finding, so per-path marker rules in
Each batch names the tests to run before the next one, and a batch whose
tests fail stops the plan there. The code runs after every batch, so a
failure points at the stages just applied.
+- An Extract Method plan that would still leave the function, or one of its new
+ helpers, above the break-up bar says so, for example "leaves build_from_json
+ at CCN 83, still above the break-up bar; more stages needed". The plan and
+ its file's opportunity rank after the work that finishes the job. The mark is
+ set when the repository is indexed, so a plan ranked live is not marked.
- Move Method never targets a class the method only instantiates, or an ancestor of
its own class.
- Split File works on any language with call resolution and suggests a split only
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 a14389fad..cbda90f1b 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/opportunity.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/opportunity.py
@@ -74,7 +74,7 @@ from .opportunity_rank import (
why_ranked,
)
from .preconditions import StepApplicability, classify_step
-from .recommendations import affected_files, rehydrate_suggestion
+from .recommendations import affected_files, leaves_above_bar, rehydrate_suggestion
# Opportunity ids share the plan id's version and digest, and differ in the
# prefix alone, so a reader can tell the two units apart without a lookup and
@@ -141,6 +141,10 @@ class OpportunityStep:
# findings were supplied or none in this file is addressable by id, which
# is "unknown", not "this cause produced no finding".
finding_ids: tuple[str, ...] | None = None
+ # Why the plan still leaves a function at the break-up bar
+ # (:func:`.recommendations.leaves_above_bar`); ``None`` when it does not
+ # or no findings were supplied.
+ leaves_above_bar: str | None = None
def as_dict(self) -> dict[str, Any]:
return {
@@ -157,6 +161,7 @@ class OpportunityStep:
"relocated_by": self.relocated_by,
"applicability": self.applicability.as_dict(),
**({"finding_ids": list(self.finding_ids)} if self.finding_ids is not None else {}),
+ **({"leaves_above_bar": self.leaves_above_bar} if self.leaves_above_bar else {}),
}
@@ -208,6 +213,12 @@ class RefactoringOpportunity:
def step_count(self) -> int:
return len(self.steps)
+ @property
+ def leaves_above_bar(self) -> str | None:
+ """The first step's reason it leaves a function at the break-up bar:
+ the file's work is not done after it, so it ranks after work that is."""
+ return next((s.leaves_above_bar for s in self.steps if s.leaves_above_bar), None)
+
def as_dict(self) -> dict[str, Any]:
return {
"opportunity_id": self.opportunity_id,
@@ -228,6 +239,7 @@ class RefactoringOpportunity:
"rank_score": self.rank_score,
"rank_factors": dict(self.rank_factors),
"why_ranked": [dict(entry) for entry in self.why_ranked],
+ **({"leaves_above_bar": self.leaves_above_bar} if self.leaves_above_bar else {}),
}
@@ -397,6 +409,7 @@ def _step_of(
suggestion, governed=None if governed is None else plan_id in governed
),
finding_ids=finding_ids,
+ leaves_above_bar=None if findings is None else leaves_above_bar(suggestion, findings),
)
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 8ff58ab93..cfbac5934 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
@@ -132,7 +132,7 @@ def why_ranked(factors: dict[str, float], *, limit: int = 3) -> list[dict[str, A
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]:
+def rank_sort_key(opportunity: Any) -> tuple[int, bool, bool, float, str, str]:
"""A total order, production files first. The id tail is what stops ties
floating between runs.
@@ -145,11 +145,14 @@ def rank_sort_key(opportunity: Any) -> tuple[int, bool, float, str, str]:
benefit (a cycle's size, a split's group count) is not health, and on this
repo it outranked every real extraction once those were credited
proportionally; those opportunities stay listed, after the credited ones,
- in their own order.
+ in their own order. Credited work that leaves a function at the
+ break-up bar (:func:`leads_queue`) ranks after the credited work that does
+ not.
"""
return (
ship_rank(opportunity.file_path),
not has_credit(opportunity),
+ not leads_queue(opportunity),
-opportunity.rank_score,
opportunity.file_path,
opportunity.opportunity_id,
@@ -161,10 +164,17 @@ def has_credit(opportunity: Any) -> bool:
return float(opportunity.recoverable_health or 0.0) > 0.0
+def leads_queue(opportunity: Any) -> bool:
+ """Whether credited work may lead the queue: it recovers health and leaves
+ no function at the break-up bar."""
+ return has_credit(opportunity) and not getattr(opportunity, "leaves_above_bar", None)
+
+
__all__ = [
"MECHANICAL_SHARE_WEIGHT",
"PRIMARY_PROBLEM_WEIGHT",
"has_credit",
+ "leads_queue",
"opportunity_benefit",
"opportunity_risk",
"rank_factors",
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py b/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py
index 12cc159b4..4e99b38e0 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py
@@ -21,6 +21,14 @@ from repowise.core.analysis.health.grading import TARGET_SCORE
from repowise.core.analysis.health.perf.ranking import _percentile_threshold
from repowise.core.analysis.health.queue_rules import FilterRule
from repowise.core.analysis.health.refactoring_summary import STRUCTURAL_TYPES
+from repowise.core.analysis.health.rows import field as row_field
+from repowise.core.analysis.health.worth import (
+ SIZE_MARKERS,
+ above_bar_after,
+ by_function,
+ measure,
+ worst_after,
+)
from repowise.core.analysis.pr_blast import rank_tests_by_reach
from repowise.core.analysis.test_reachability import (
DEFAULT_CALL_DEPTH,
@@ -1045,6 +1053,9 @@ class Recommendation:
# What other layers say about the target (:mod:`.annotations`), stored at
# finalize and served on plan detail only; ``None`` when never checked.
annotations: PlanAnnotations | None = field(default=None, repr=False, compare=False)
+ # Set when the plan leaves a function at the break-up bar
+ # (:func:`leaves_above_bar`): it ranks after the plans that do not.
+ leaves_above_bar: str | None = None
@property
def id(self) -> str:
@@ -1076,6 +1087,7 @@ class Recommendation:
"file_nloc": self.file_nloc,
"file_weighted_deficit": self.file_weighted_deficit,
"validation": self.validation.as_dict(),
+ **({"leaves_above_bar": self.leaves_above_bar} if self.leaves_above_bar else {}),
}
def detail_dict(self) -> dict[str, Any]:
@@ -1124,6 +1136,7 @@ class Recommendation:
if self.annotations is not None
else {}
),
+ **({"leaves_above_bar": self.leaves_above_bar} if self.leaves_above_bar else {}),
}
@@ -1166,6 +1179,7 @@ def stored_recommendation(row: Any) -> Recommendation | None:
suggestion=suggestion,
validation=validation,
annotations=PlanAnnotations.from_dict(facts.get("annotations")),
+ leaves_above_bar=facts.get("leaves_above_bar"),
**{name: facts[name] for name in _RANK_FACTS},
)
@@ -1232,11 +1246,17 @@ def build_recommendations(
metric_by_path: Mapping[str, Any] | None = None,
centrality: Mapping[str, float] | None = None,
validations: Mapping[int, ValidationPlan] | None = None,
+ findings: Sequence[Any] | None = None,
) -> list[Recommendation]:
- """Pure recommendation construction used by every surface and tests."""
+ """Pure recommendation construction used by every surface and tests.
+
+ *findings* (the repository's health findings) give each Extract Method
+ target its measured size, which :func:`leaves_above_bar` reads; without
+ them no plan is marked."""
metrics = metric_by_path or {}
centrality = centrality or {}
validations = validations or {}
+ findings_by_function = by_function(findings or ())
out: list[Recommendation] = []
for index, row in enumerate(rows):
suggestion = rehydrate_suggestion(row)
@@ -1267,18 +1287,64 @@ def build_recommendations(
file_nloc=nloc,
file_weighted_deficit=deficit,
validation=validation,
+ leaves_above_bar=leaves_above_bar(
+ suggestion,
+ findings_by_function.get((suggestion.file_path, suggestion.target_symbol), ()),
+ ),
)
)
return canonical_order(out)
+def leaves_above_bar(suggestion: RefactoringSuggestion, findings: Sequence[Any]) -> str | None:
+ """Why an Extract Method plan, applied as written, still leaves a function
+ at the break-up bar (:func:`..worth.above_bar_after`), or ``None``.
+
+ *findings* are the file's or the target's; the size findings on the
+ target give its measured CCN and lines before the plan."""
+ if suggestion.refactoring_type != "extract_method":
+ return None
+ named = [
+ f
+ for f in findings
+ if row_field(f, "biomarker_type") in SIZE_MARKERS
+ and row_field(f, "function_name") == suggestion.target_symbol
+ ]
+ own = _on_target(suggestion, named)
+ after = worst_after(
+ suggestion.evidence or {}, suggestion.plan or {}, suggestion.target_symbol, measure(own)
+ )
+ return above_bar_after(after)
+
+
+def _on_target(suggestion: RefactoringSuggestion, named: Sequence[Any]) -> list[Any]:
+ """The same-named findings on the target: those whose lines overlap it,
+ and those without lines unless a finding elsewhere in the file shows a
+ second function of that name. A plan without lines keeps them all."""
+ first, last = suggestion.line_start, suggestion.line_end
+ if not (first and last):
+ return list(named)
+ inside, unlined, elsewhere = [], [], False
+ for f in named:
+ start = row_field(f, "line_start")
+ if not start:
+ unlined.append(f)
+ elif start <= last and (row_field(f, "line_end") or start) >= first:
+ inside.append(f)
+ else:
+ elsewhere = True
+ return inside if elsewhere else inside + unlined
+
+
def canonical_order(recommendations: Sequence[Recommendation]) -> list[Recommendation]:
"""Rank order, production files first: a plan on a build script, a tool or
- copied code comes after them, and a test plan last."""
+ copied code comes after them, and a test plan last. Within each, a plan
+ that leaves a function at the break-up bar ranks after those that do not."""
return sorted(
recommendations,
key=lambda recommendation: (
ship_rank(recommendation.suggestion.file_path),
+ bool(recommendation.leaves_above_bar),
-recommendation.rank_score,
recommendation.suggestion.refactoring_type,
recommendation.suggestion.file_path,
@@ -1390,6 +1456,7 @@ __all__ = [
"detector_native_benefit",
"enrich_blast_radius",
"hub_files",
+ "leaves_above_bar",
"listed_steps",
"plan_types",
"priority_score",
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 e0e0ae911..00f43cfd0 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/serving.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/serving.py
@@ -442,6 +442,8 @@ def serialize(
for key in ("file_nloc", "dependents"):
if isinstance(details.get(key), int):
payload[key] = details[key]
+ if details.get("leaves_above_bar"):
+ payload["leaves_above_bar"] = details["leaves_above_bar"]
if steps_limit is not None:
kept = steps[: max(steps_limit, 0)]
payload["steps"] = kept
diff --git a/packages/core/src/repowise/core/analysis/health/worth.py b/packages/core/src/repowise/core/analysis/health/worth.py
index ecfbe8cfe..2182e73da 100644
--- a/packages/core/src/repowise/core/analysis/health/worth.py
+++ b/packages/core/src/repowise/core/analysis/health/worth.py
@@ -268,6 +268,15 @@ def _size_reason(shape: Mapping[str, int]) -> LowPriority | None:
return None
+def by_function(findings: Iterable[Any]) -> dict[tuple[str, str], list[Any]]:
+ """Findings that name a function, by ``(file_path, function_name)``."""
+ out: dict[tuple[str, str], list[Any]] = defaultdict(list)
+ for f in findings:
+ if name := field(f, "function_name"):
+ out[(field(f, "file_path"), name)].append(f)
+ return dict(out)
+
+
def finding_priorities(findings: Sequence[Any]) -> list[LowPriority | None]:
""":func:`low_priority` for each finding, in order. A function's shape is
measured over every finding on it in ``findings``; a finding that rests
@@ -275,10 +284,6 @@ def finding_priorities(findings: Sequence[Any]) -> list[LowPriority | None]:
from .models import split_by_origin
history = {id(f) for f in split_by_origin(findings)[1]}
- by_function: dict[tuple[str, str], list[Any]] = defaultdict(list)
- for f in findings:
- if field(f, "function_name"):
- by_function[(field(f, "file_path"), field(f, "function_name"))].append(f)
# Measured once per function, not once per finding on it, and each row's
# details parsed once: every list tiers a repository's whole open set.
parsed: dict[int, Mapping[str, Any]] = {}
@@ -289,7 +294,7 @@ def finding_priorities(findings: Sequence[Any]) -> list[LowPriority | None]:
found = parsed[id(f)] = detail_map(f)
return found
- shapes = {key: measure(rows, details_of) for key, rows in by_function.items()}
+ shapes = {key: measure(rows, details_of) for key, rows in by_function(findings).items()}
out: list[LowPriority | None] = []
for f in findings:
if id(f) in history:
@@ -303,6 +308,55 @@ def finding_priorities(findings: Sequence[Any]) -> list[LowPriority | None]:
return out
+def _helpers_after(
+ plan: Mapping[str, Any], target: str, removed: int, sliced: int
+) -> list[tuple[str, int, int]]:
+ """``(name, ccn, nloc)`` of each helper a plan creates: a stage's own
+ figures, or for an unstaged plan the one span it lifts, whose CCN is at
+ most what it removes."""
+ stages = [s for s in plan.get("stages") or () if isinstance(s, Mapping)]
+ return [
+ (str(s.get("suggested_name") or target), int(s.get("ccn") or 0), int(s.get("nloc") or 0))
+ for s in stages
+ ] or [(str(plan.get("suggested_name") or target), removed, sliced)]
+
+
+def worst_after(
+ evidence: Mapping[str, Any], plan: Mapping[str, Any], target: str, shape: Mapping[str, int]
+) -> dict[str, Any] | None:
+ """The largest function an Extract Method plan leaves, by its own figures:
+ ``{"function", "ccn", "nloc"}``, or ``None`` with nothing to read.
+
+ The target keeps its measured CCN and lines (``shape``, or a staged plan's
+ ``orchestrator``) less what the plan moves out, plus one call line per
+ helper. Each helper is a stage's own ``ccn`` and ``nloc``; an unstaged
+ plan's one helper is the span it lifts. Nesting after is not estimated.
+ """
+ removed = int(evidence.get("ccn_removed") or 0)
+ sliced = int(evidence.get("slice_nloc") or 0)
+ helpers = _helpers_after(plan, target, removed, sliced)
+ before = (plan.get("orchestrator") or {}).get("ccn_before") or shape.get("ccn")
+ nloc = measured_nloc(shape)
+ candidates = list(helpers)
+ if before or nloc:
+ candidates.append(
+ (target, max(int(before or 0) - removed, 1), max(nloc - sliced + len(helpers), 0))
+ )
+ name, ccn, lines = max(
+ candidates, key=lambda c: (magnitude({"ccn": c[1], "nloc": c[2]}), c[1], c[2])
+ )
+ return {"function": name, "ccn": ccn, "nloc": lines} if ccn or lines else None
+
+
+def above_bar_after(after: Mapping[str, Any] | None) -> str | None:
+ """Why a plan leaves work at the break-up bar (:data:`WORTH_MAGNITUDE`), or
+ ``None`` when every function it leaves is under it."""
+ if not after or magnitude(after) < WORTH_MAGNITUDE:
+ return None
+ by = f"CCN {after['ccn']}" if after["ccn"] >= SIZE_CCN[1] else f"{after['nloc']} lines"
+ return f"leaves {after['function']} at {by}, still above the break-up bar; more stages needed"
+
+
#: Performance causes that cost once per call, not once per loop iteration:
#: they lead when an entry point reaches them.
_PER_CALL_MARKERS = frozenset(
@@ -373,6 +427,8 @@ __all__ = [
"WORTH_MAGNITUDE",
"CostProof",
"LowPriority",
+ "above_bar_after",
+ "by_function",
"cost_proof",
"dispatch_shaped",
"dormant",
@@ -386,5 +442,6 @@ __all__ = [
"measured_nloc",
"perf_facets",
"terminal_shaped",
+ "worst_after",
"worth_size",
]
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_opportunities.py b/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_opportunities.py
index d84de0e61..f8545abfd 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_opportunities.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_opportunities.py
@@ -76,22 +76,23 @@ def _diversified_order(opportunities: list[OpportunityModel]) -> list[int]:
Only opportunities that recover health are interleaved. The rest (rank
order already puts them last) follow in rank order, so a zero-credit cycle
- never takes a head slot from real work.
+ never takes a head slot from real work. Credited work that leaves a
+ function at the break-up bar follows the interleaved head, in rank order.
Test files are round-robined apart and queue after every production file,
as they rank, so the lead is never a test.
"""
- from ....analysis.health.refactoring.opportunity_rank import has_credit
+ from ....analysis.health.refactoring.opportunity_rank import leads_queue
order: list[int] = []
for is_test in (False, True):
groups: dict[tuple[str, str, str], list[int]] = {}
- uncredited: list[int] = []
+ trailing: list[int] = []
for position, item in enumerate(opportunities):
if is_test_related_path(item.file_path) is not is_test:
continue
- if not has_credit(item):
- uncredited.append(position)
+ if not leads_queue(item):
+ trailing.append(position)
continue
parent = item.file_path.rsplit("/", 1)[0] if "/" in item.file_path else ""
area = "/".join(parent.split("/")[:2])
@@ -99,7 +100,7 @@ def _diversified_order(opportunities: list[OpportunityModel]) -> list[int]:
(item.lead_biomarker or "", item.lead_refactoring_type, area), []
).append(position)
order.extend(_round_robin(list(groups.values())))
- order.extend(uncredited)
+ order.extend(trailing)
return order
@@ -163,6 +164,12 @@ def _details_payload(
if finding_ids
else {}
),
+ # Why it ranks after the rest; Fix first reads the same field.
+ **(
+ {"leaves_above_bar": opportunity.leaves_above_bar}
+ if opportunity.leaves_above_bar
+ else {}
+ ),
}
@@ -271,7 +278,9 @@ def _open_items(
return [o for o in opportunities if statuses.get(o.opportunity_id, "open") == "open"]
-async def _rank_live_plans(session: AsyncSession, repository_id: str) -> list[Any]:
+async def _rank_live_plans(
+ session: AsyncSession, repository_id: str, findings: list[Any]
+) -> list[Any]:
"""Rank, validate and annotate every live plan the lists can show, and store it.
Performance plans are not composed here, but they share the plan lists, so
@@ -295,7 +304,9 @@ async def _rank_live_plans(session: AsyncSession, repository_id: str) -> list[An
)
)
).scalars()
- ranked = await hydrate_recommendations(session, repository_id, list(rows), step_verify=True)
+ ranked = await hydrate_recommendations(
+ session, repository_id, list(rows), step_verify=True, findings=findings
+ )
facts = await load_annotation_facts(
session,
repository_id,
@@ -380,7 +391,7 @@ async def finalize_refactoring_opportunities(
# Rank and validation are resolved once, here, for every live plan. They
# used to be rebuilt on every request for every open plan, which is the
# single largest cost the serving path used to carry.
- ranked = await _rank_live_plans(session, repository_id)
+ ranked = await _rank_live_plans(session, repository_id, findings)
# Every ranked non-performance plan is a live plan, so the lookup is total;
# a miss raises rather than leaving a governed step mechanical.
public_of = {row.id: row.public_id for row in live_plans}
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_recommendations.py b/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_recommendations.py
index cc8419b63..660052c49 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_recommendations.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_recommendations.py
@@ -62,6 +62,7 @@ async def hydrate_recommendations(
view: RecommendationView = "canonical",
test_limit: int = DEFAULT_TEST_LIMIT,
step_verify: bool = False,
+ findings: Sequence[Any] | None = None,
) -> list[Recommendation]:
"""Hydrate, enrich, validate, rank, and serialize-ready all *rows*.
@@ -71,7 +72,9 @@ async def hydrate_recommendations(
*step_verify* also validates each step of a multi-step plan
(:func:`with_step_verify`). Finalize asks, so it is stored once; a live
- read never rebuilds it and serves the plan-level answer.
+ read never rebuilds it and serves the plan-level answer. Finalize also
+ passes the repository's *findings*, so a plan that leaves a function at
+ the break-up bar is marked and ranked after the rest.
"""
if not rows:
return []
@@ -98,6 +101,7 @@ async def hydrate_recommendations(
metric_by_path={metric.file_path: metric for metric in metrics},
centrality=centrality,
validations=dict(enumerate(plans)),
+ findings=findings,
)
return apply_view(recommendations, view)
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/plans.py b/packages/server/src/repowise/server/mcp_server/tool_health/plans.py
index d76410d65..55f9a00e4 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health/plans.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health/plans.py
@@ -79,6 +79,8 @@ def _plan_row(step: dict[str, Any]) -> dict[str, Any]:
row["classification"] = (step.get("applicability") or {}).get("classification")
if step.get("relocated_by"):
row["relocated_by"] = step["relocated_by"]
+ if step.get("leaves_above_bar"):
+ row["leaves_above_bar"] = step["leaves_above_bar"]
if step.get("relocates"):
# The plans after a split, which it stands for in the list.
row["relocates"] = step["relocates"]
diff --git a/packages/types/src/refactoring.ts b/packages/types/src/refactoring.ts
index 717a31e14..1fdbcd941 100644
--- a/packages/types/src/refactoring.ts
+++ b/packages/types/src/refactoring.ts
@@ -122,6 +122,9 @@ export interface RefactoringPlan {
file_nloc?: number;
file_weighted_deficit?: number;
validation?: RecommendationValidation;
+ /** Why it still leaves a function above the break-up bar, so it ranks after
+ * the rest. Absent when it does not. */
+ leaves_above_bar?: string;
/** Plan detail only: ids of the accepted decisions governing the file.
* Absent when the plan was never checked (not yet re-indexed). */
governed_by?: string[];
@@ -387,6 +390,9 @@ export interface OpportunityStep {
/** Findings this step's cause produced, for a round trip to the diagnosis. */
finding_ids?: string[];
validation_profile_id?: string;
+ /** Why it still leaves a function above the break-up bar, so it ranks after
+ * the rest. Absent when it does not. */
+ leaves_above_bar?: string;
}
/** A supporting observation. Never an instruction to change anything. */
@@ -464,6 +470,9 @@ export interface RefactoringOpportunity {
/** Files importing the lead file. Absent when the store predates the figure. */
dependents?: number;
steps?: OpportunityStep[];
+ /** Why it still leaves a function above the break-up bar, so it ranks after
+ * the rest. Absent when it does not. */
+ leaves_above_bar?: string;
steps_total?: number;
steps_emitted?: number;
steps_reduced_reason?: string;
diff --git a/tests/unit/health/test_worth_after_plan.py b/tests/unit/health/test_worth_after_plan.py
new file mode 100644
index 000000000..e122fcf72
--- /dev/null
+++ b/tests/unit/health/test_worth_after_plan.py
@@ -0,0 +1,158 @@
+"""A plan that leaves a function at the break-up bar says so and ranks after the rest."""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import repowise.core.analysis.health.refactoring # noqa: F401 (import order: worth <-> perf)
+from repowise.core.analysis.health.refactoring.models import RefactoringSuggestion
+from repowise.core.analysis.health.refactoring.opportunity import compose_opportunities
+from repowise.core.analysis.health.refactoring.opportunity_rank import rank_sort_key
+from repowise.core.analysis.health.refactoring.recommendations import (
+ build_recommendations,
+ leaves_above_bar,
+)
+from repowise.core.analysis.health.worth import above_bar_after, worst_after
+from repowise.core.persistence.crud.analysis.refactoring_opportunities import _diversified_order
+
+
+def _stage(name: str, ccn: int, nloc: int) -> dict:
+ return {"suggested_name": name, "ccn": ccn, "nloc": nloc}
+
+
+def test_a_staged_plan_reads_the_target_after_from_its_orchestrator() -> None:
+ # graphify build_from_json: 141 -> 83 after four stages.
+ plan = {
+ "stages": [_stage("_a", 20, 60), _stage("_b", 15, 40)],
+ "orchestrator": {"ccn_before": 141, "ccn_after": 83},
+ }
+ after = worst_after({"ccn_removed": 58, "slice_nloc": 100}, plan, "build_from_json", {})
+ assert after == {"function": "build_from_json", "ccn": 83, "nloc": 0}
+ assert above_bar_after(after) == (
+ "leaves build_from_json at CCN 83, still above the break-up bar; more stages needed"
+ )
+
+
+def test_an_unstaged_plan_reads_the_target_from_its_measured_shape() -> None:
+ shape = {"ccn": 70, "nloc": 180}
+ after = worst_after({"ccn_removed": 12, "slice_nloc": 40}, {}, "run", shape)
+ # 70 - 12 = 58 left in the target; the one helper is at most CCN 12.
+ assert after == {"function": "run", "ccn": 58, "nloc": 141}
+ assert above_bar_after(after) is not None
+
+
+def test_a_helper_that_takes_the_whole_body_is_still_judged() -> None:
+ # Moving everything into one helper empties the target but not the work.
+ plan = {"suggested_name": "_body"}
+ after = worst_after(
+ {"ccn_removed": 150, "slice_nloc": 300}, plan, "f", {"ccn": 151, "nloc": 310}
+ )
+ assert after["function"] == "_body"
+ assert above_bar_after(after) == (
+ "leaves _body at CCN 150, still above the break-up bar; more stages needed"
+ )
+
+
+def test_length_alone_trips_the_bar_and_names_the_lines() -> None:
+ after = worst_after({"ccn_removed": 3, "slice_nloc": 20}, {}, "table", {"ccn": 8, "nloc": 260})
+ assert above_bar_after(after) == (
+ "leaves table at 241 lines, still above the break-up bar; more stages needed"
+ )
+
+
+def test_a_plan_that_brings_everything_under_the_bar_is_not_marked() -> None:
+ plan = {
+ "stages": [_stage("_a", 12, 50), _stage("_b", 10, 40)],
+ "orchestrator": {"ccn_before": 45, "ccn_after": 25},
+ }
+ after = worst_after({"ccn_removed": 20, "slice_nloc": 90}, plan, "f", {"nloc": 150})
+ assert above_bar_after(after) is None
+ assert above_bar_after(None) is None
+
+
+def _plan(target: str, removed: int, line: int, *, impact: float = 1.0) -> RefactoringSuggestion:
+ return RefactoringSuggestion(
+ refactoring_type="extract_method",
+ file_path=f"pkg/{target}.py",
+ target_symbol=target,
+ line_start=line,
+ line_end=line + 200,
+ plan={"span": {"start": line + 5, "end": line + 30}},
+ evidence={"ccn_removed": removed, "slice_nloc": 25},
+ impact_delta=impact,
+ effort_bucket="M",
+ blast_radius={"scope": "local"},
+ confidence="high",
+ source_biomarker="complex_method",
+ )
+
+
+def _finding(target: str, ccn: int, line: int) -> dict:
+ return {
+ "file_path": f"pkg/{target}.py",
+ "function_name": target,
+ "biomarker_type": "complex_method",
+ "severity": "high",
+ "line_start": line,
+ "line_end": line + 200,
+ "details": {"ccn": ccn, "nloc": 150},
+ }
+
+
+def test_only_the_targets_own_size_findings_count() -> None:
+ plan = _plan("big", 10, 10)
+ elsewhere = {**_finding("big", 90, 10), "line_start": 500, "line_end": 600}
+ other = _finding("other", 90, 10) | {"file_path": "pkg/big.py"}
+ assert leaves_above_bar(plan, [elsewhere, other]) is None
+ assert leaves_above_bar(plan, [_finding("big", 90, 10)]).startswith("leaves big at CCN 80")
+
+
+def test_a_finding_without_lines_is_dropped_when_the_name_repeats() -> None:
+ plan = _plan("big", 10, 10)
+ unlined = {**_finding("big", 90, 10), "line_start": None, "line_end": None}
+ assert leaves_above_bar(plan, [unlined]) is not None
+ other_big = {**_finding("big", 20, 10), "line_start": 500, "line_end": 520}
+ assert leaves_above_bar(plan, [unlined, other_big]) is None
+
+
+def test_a_plan_that_leaves_the_bar_ranks_after_one_that_does_not() -> None:
+ # The marked plan scores higher, and still ranks second.
+ big, small = _plan("big", 10, 10, impact=3.0), _plan("small", 10, 10, impact=1.0)
+ findings = [_finding("big", 90, 10), _finding("small", 30, 10)]
+ ranked = build_recommendations([big, small], findings=findings)
+ assert [r.suggestion.target_symbol for r in ranked] == ["small", "big"]
+ assert ranked[1].leaves_above_bar and "leaves_above_bar" in ranked[1].rank_facts()
+ assert "leaves_above_bar" not in ranked[0].as_dict()
+ # Without findings nothing is marked.
+ assert not any(r.leaves_above_bar for r in build_recommendations([big, small]))
+
+
+def test_the_opportunity_carries_the_reason_and_queues_after_finished_work() -> None:
+ big, small = _plan("big", 10, 10, impact=3.0), _plan("small", 10, 10, impact=1.0)
+ findings = [_finding("big", 90, 10), _finding("small", 30, 10)]
+ opportunities = compose_opportunities([big, small], findings=findings)
+ assert [o.file_path for o in opportunities] == ["pkg/small.py", "pkg/big.py"]
+ demoted = opportunities[1]
+ assert demoted.leaves_above_bar == demoted.steps[0].leaves_above_bar
+ assert demoted.as_dict()["steps"][0]["leaves_above_bar"].startswith("leaves big at")
+ assert "leaves_above_bar" not in opportunities[0].as_dict()
+
+
+def test_marked_credited_work_sorts_and_queues_after_the_interleaved_head() -> None:
+ def item(path: str, health: float, rank: float, above: str | None = None) -> SimpleNamespace:
+ return SimpleNamespace(
+ file_path=path,
+ opportunity_id=path,
+ lead_biomarker="complex_method" if health else None,
+ lead_refactoring_type="extract_method" if health else "break_cycle",
+ recoverable_health=health,
+ rank_score=rank,
+ leaves_above_bar=above,
+ )
+
+ marked = item("pkg/a/x.py", 0.9, 0.9, "leaves x at CCN 60")
+ plain = item("pkg/b/y.py", 0.5, 0.3)
+ cycle = item("pkg/c/z.py", 0.0, 0.8)
+ ranked = sorted([cycle, marked, plain], key=rank_sort_key)
+ assert [o.file_path for o in ranked] == ["pkg/b/y.py", "pkg/a/x.py", "pkg/c/z.py"]
+ assert _diversified_order(ranked) == [0, 1, 2]