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
fix(refactoring): credit the share of a finding a plan actually removes (#2816)
Raghav Chamadiyac27a607aac32
diff --git a/docs/layers/REFACTORING.md b/docs/layers/REFACTORING.mdindex a6a750b00..e441bc1a2 100644--- a/docs/layers/REFACTORING.md+++ b/docs/layers/REFACTORING.md@@ -37,7 +37,7 @@ one**, and produces stable-sorted, deterministic output.| **Move Method** | A feature-envy method and the class it actually belongs to. | The method's entity set (fields/methods it touches, class-qualified) is built from the call graph; Jaccard distance to each class. Fires only when a foreign class is clearly nearer than its own and draws more of the method's calls than its home file does. A class the method instantiates (a result it builds) and an ancestor of its own class are never targets. || **Break Cycle** | The minimal set of import edges to invert to break a dependency cycle. | A strongly-connected component in the import graph → greedy minimum feedback arc set (MFAS) over the real edges picks the smallest cut. || **Split File** | The cohesive files an oversized module should decompose into: which top-level symbols move to each new file, plus the import edits in every dependent. | Community detection (Leiden, Louvain fallback) over a weighted intra-file symbol graph (direct calls, shared local helpers, shared foreign modules); emits only when the partition's **modularity** clears a decomposability gate. The file-level analog of Extract Class. |-| **Extract Method** | The exact line span to lift out of an oversized/complex method, with the helper's inferred signature: the parameters it needs (IN) and the value it must return (OUT). | Intra-procedural dataflow (CFG + def/use + reaching definitions) over methods a `large_method` / `brain_method` / `complex_method` finding already flagged. Only single-exit, statement-boundary spans that remove real complexity qualify, and IN/OUT comes from liveness over the def/use facts. A span is offered only when the gate can prove it behavior-preserving: every returned value must be written on every path through the span, and a span nested in a loop must carry no state between iterations and must not mutate what the loop iterates. What the gate cannot prove is suppressed, not demoted, so the layer under-reports rather than suggest a rewrite that changes behavior. |+| **Extract Method** | The exact line span to lift out of an oversized/complex method, with the helper's inferred signature: the parameters it needs (IN) and the value it must return (OUT). | Intra-procedural dataflow (CFG + def/use + reaching definitions) over methods a `large_method` / `brain_method` / `complex_method` finding already flagged. Only single-exit, statement-boundary spans that remove real complexity qualify, and IN/OUT comes from liveness over the def/use facts. A span is offered only when the gate can prove it behavior-preserving: every returned value must be written on every path through the span, and a span nested in a loop must carry no state between iterations and must not mutate what the loop iterates. What the gate cannot prove is suppressed, not demoted, so the layer under-reports rather than suggest a rewrite that changes behavior. A span must also be worth doing: at least 5 code lines that remove at least 2 decision points (or, for `large_method`, at least 12 code lines), and a helper that would not carry the finding at the function's own severity, since lifting nearly the whole body moves the smell instead of splitting it. When the best span misses that floor the next-best one that clears it is offered. A JSX component whose decision points sit mostly in its markup (conditional spreads, `&&` or ternaries in attributes and children, template ternaries) gets no extraction: that branching is prop plumbing. || **Performance Fix** | A safe shared intervention, affected call sites, and caller-to-sink paths for one causal performance opportunity. | The call-graph opportunity service groups raw findings by stable cause, boundary and context, then emits only supported strategies. Findings with no coherent safe intervention remain visible in Code Health without a plan. |The algorithms are derived from public academic literature (Fokaefs-Tsantalis@@ -63,10 +63,10 @@ web).| `file_path`, `target_symbol`, `line_start`, `line_end` | What the refactoring acts on. || `plan` | The concrete, type-specific plan: the split `groups` (methods + fields), the move `{method, from_class, to_class}`, the clone `occurrences` + `suggested_site`, the cycle + `cut_edges`, the file-split `groups` (`{name, symbols, suggested_file}`) + `residual` core + `shim_required`, or the method-extraction `span` + `params` + `returns` + `suggested_name`. Names are omitted rather than invented: `suggested_name` and a group's `name` / `suggested_file` are `null` whenever no fact anchors a name, and `suggested_site.directory` is `null` unless an occurrence actually lives in that directory. || `evidence` | The signals that justify it: `lcom4`, `wmc`, clone token/line counts + `co_change_count`, Jaccard distances, cycle size, or the split's `modularity` + `symbol_count` + `group_count` + intra/cut edge counts. |-| `impact_delta` | The defect-health score the refactoring would recover; `0` for graph-native and performance plans. Their canonical `benefit` comes from detector-native evidence instead. Extract Method credits only what its one span removes: the residual method and the new helper are re-graded with the source biomarker's own thresholds, so a span that leaves the method in the same severity band recovers `0`, and one that drops a band recovers the difference. |+| `impact_delta` | The defect-health score the refactoring would recover; `0` for graph-native and performance plans. Their canonical `benefit` comes from detector-native evidence instead. Credit is proportional to what the plan removes, never the whole finding for crossing a threshold. Extract Method credits the share of what the finding measures that moves into the helper: `ccn_removed / ccn` for `complex_method`, `slice_nloc / nloc` for `large_method`, the larger of the two for `brain_method`, capped at 1. Both line counts are code lines (blank, comment and docstring lines excluded, the walker's NLOC rule), and `evidence.slice_nloc` reports the same count. Extract Class credits a `low_cohesion` finding whole (the plan is the full LCOM4 partition) and a `god_class` finding by the NLOC or CCN share that leaves the largest group. Extract Helper credits the block's share of the file's duplicated lines. || `effort_bucket` | `S` \| `M` \| `L` \| `XL`, from the target's size. || `blast_radius` | What else must move: the callers, co-change partners, and importing files. Extract Method carries `{"scope": "local"}` instead — extraction adds a private helper and changes no signature, so nothing outside the file moves and there is no count to make. |-| `confidence` | `low` \| `medium` \| `high` (drives the `min_confidence` surface gate). |+| `confidence` | `low` \| `medium` \| `high` (drives the `min_confidence` surface gate). For Extract Method, `high` means the step is mechanical and worth handing off: it removes at least 2 decision points, takes at most 4 parameters, and moves at least a tenth of what its finding measures. Only `high` Extract Method steps classify as mechanical. || `source_biomarker` | The finding this answers (e.g. `low_cohesion`, `god_class`, `dry_violation`). |The per-type `plan` / `evidence` / `blast_radius` shapes are documented in full in@@ -82,7 +82,9 @@ named components and one canonical score:score = (1 + benefit) * (1 + leverage) / (1 + cost + risk)```-`benefit` is recoverable health or detector-native structural/performance gain;+`benefit` is recoverable health (an opportunity's `recoverable_health` is the sum+of its credited steps' proportional `impact_delta`, each finding counted once) or+detector-native structural/performance gain;`leverage` is weighted health deficit, dependents, and reliable entry reach;`cost` includes effort and change surface; `risk` includes blast radius,confidence, provenance, and validation quality. Larger blast radius thereforediff --git a/packages/core/src/repowise/core/analysis/health/dataflow/slice.py b/packages/core/src/repowise/core/analysis/health/dataflow/slice.pyindex 4431e94e5..2b4ef809e 100644--- a/packages/core/src/repowise/core/analysis/health/dataflow/slice.py+++ b/packages/core/src/repowise/core/analysis/health/dataflow/slice.py@@ -31,6 +31,8 @@ from collections import defaultdictfrom dataclasses import dataclassfrom typing import TYPE_CHECKING+from ..complexity.nloc import _code_line_numbers+if TYPE_CHECKING:from tree_sitter import Node@@ -40,7 +42,9 @@ if TYPE_CHECKING:# Gates (precision-first; tuned to suppress trivial or unwieldy extractions)._MIN_STMTS = 2 # at least two statements-_MIN_SLICE_NLOC = 6 # the extracted helper is substantial+# The extracted helper is substantial: code lines, the walker's NLOC rule, so a+# span padded with comments does not clear it.+_MIN_SLICE_NLOC = 5_MIN_CCN_REMOVED = 1 # extraction must remove a real decision point_MAX_PARAMS = 5 # too many ins => the span is not cohesive_MAX_RETURNS = 1 # a single clean return (v1); multi-output is future work@@ -54,9 +58,10 @@ class Extraction:``start_line`` / ``end_line`` bound the span (1-indexed, inclusive).``params`` are the inferred IN variables, ``returns`` the inferred OUT- variable(s). ``slice_nloc`` is the span's statement line count and- ``ccn_removed`` the decision points it carries (the complexity the residual- method sheds).+ variable(s). ``slice_nloc`` is the span's code lines, counted with the+ walker's NLOC rule (blank, comment-only and docstring lines excluded, as in+ the function's own ``nloc``), and ``ccn_removed`` the decision points it+ carries (the complexity the residual method sheds)."""start_line: int@@ -114,6 +119,7 @@ def find_extractions(analysis: FunctionAnalysis, lmap: LanguageNodeMap) -> list[else None)+ lines = _function_lines(fn_node)out: list[Extraction] = []evaluated = 0for block, loop in _all_blocks(fn_node, lmap.block_kinds, scope_kinds, lmap.loop_kinds):@@ -132,6 +138,7 @@ def find_extractions(analysis: FunctionAnalysis, lmap: LanguageNodeMap) -> list[# same reason: the check is a subtree walk, and asking it per# candidate span would put the O(n^2 * subtree) cost straight back.nested_prefix = [0]+ code_prefix = [0]for st in stmts:d, jmp = _span_metrics([st], decision_kinds, jump_kinds, scope_kinds)dec_prefix.append(dec_prefix[-1] + d)@@ -139,6 +146,9 @@ def find_extractions(analysis: FunctionAnalysis, lmap: LanguageNodeMap) -> list[nested_prefix.append(nested_prefix[-1] + (1 if _holds_a_named_nested_function([st], lmap) else 0))+ code_prefix.append(+ code_prefix[-1] + len(_code_line_numbers(st, lines, drop_docstrings=True))+ )for i in range(n):for j in range(i, n):evaluated += 1@@ -160,10 +170,10 @@ def find_extractions(analysis: FunctionAnalysis, lmap: LanguageNodeMap) -> list[has_jump = jump_prefix[j + 1] > jump_prefix[i]if has_jump or decisions < _MIN_CCN_REMOVED:continue- span = stmts[i : j + 1]- slice_nloc = sum(st.end_point[0] - st.start_point[0] + 1 for st in span)+ slice_nloc = code_prefix[j + 1] - code_prefix[i]if slice_nloc < _MIN_SLICE_NLOC:continue+ span = stmts[i : j + 1]s = span[0].start_point[0] + 1e = span[-1].end_point[0] + 1params, returns = _infer_in_out(def_lines, use_lines, s, e)@@ -192,6 +202,16 @@ def find_extractions(analysis: FunctionAnalysis, lmap: LanguageNodeMap) -> list[return _sorted(out)+def _function_lines(fn_node: Node) -> list[str]:+ """Source rows indexed by absolute row, rebuilt from the function's own text.++ Lets the walker's NLOC rule (``_code_line_numbers``) run here without the+ file's bytes; rows above the function are never read, so they stay empty.+ """+ text = (fn_node.text or b"").decode("utf-8", errors="replace")+ return [""] * fn_node.start_point[0] + text.splitlines()++def _sorted(candidates: list[Extraction]) -> list[Extraction]:return sorted(candidates,diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.pyindex 31af5870e..77a534a6b 100644--- a/packages/core/src/repowise/core/analysis/health/engine.py+++ b/packages/core/src/repowise/core/analysis/health/engine.py@@ -111,6 +111,12 @@ log = structlog.get_logger(__name__)# moved 2 -> 3 with it: every performance id now carries the ``perf3_`` prefix,# and a held ``perf2_`` id reports ``stale_model`` instead of a silent miss.#+# v37 (also): refactoring plans credit what they remove. Extract Method, Extract+# Class (``god_class``) and Extract Helper claim the share of the finding that+# moves, a span must clear a minimum-worth floor, ``slice_nloc`` counts code+# lines only, and JSX prop plumbing earns no Extract Method. Stored plans and+# opportunities change, and ``REFACTORING_MODEL_VERSION`` moved with this.+## v36 (also): which files are tests changed (``repowise.core.test_paths``).# Compound directories headed by a test word (``e2e-tests/``, ``pkg_tests/``,# ``integration_test/``) became test trees, and ``test``/``.test.`` filenamesdiff --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 ce349d996..3fa9c4f8f 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@@ -90,7 +90,14 @@ class ExtractClassDetector(RefactoringDetector):continuewmc = sum(getattr(m, "ccn", 0) for m in getattr(cls, "methods", []))- impact_delta, source = impact_by_class.get(cls.name, (0.0, ""))+ share = _moved_share(cls, substantive)+ impact_delta, source = max(+ (+ (impact * (share if marker == "god_class" else 1.0), marker)+ for impact, marker in impact_by_class.get(cls.name, ())+ ),+ default=(0.0, ""),+ )groups = [{"name": None, "methods": list(g.methods), "fields": list(g.fields)}@@ -125,12 +132,12 @@ class ExtractClassDetector(RefactoringDetector):return out@staticmethod- def _impact_by_class(ctx: RefactoringContext) -> dict[str, tuple[float, str]]:- """Map class name -> (recovered impact, source biomarker) from the+ def _impact_by_class(ctx: RefactoringContext) -> dict[str, list[tuple[float, str]]]:+ """Map class name -> [(finding impact, source biomarker)] from thefile's cohesion findings. The biomarkers report ``function_name`` =- the class name; keep the largest impact when both fire on one class.+ the class name."""- by_class: dict[str, tuple[float, str]] = {}+ by_class: dict[str, list[tuple[float, str]]] = {}for f in ctx.findings:if getattr(f, "biomarker_type", "") not in _SOURCE_BIOMARKERS:continue@@ -141,9 +148,7 @@ class ExtractClassDetector(RefactoringDetector):if not name:continueimpact = float(getattr(f, "health_impact", 0.0) or 0.0)- prev = by_class.get(name)- if prev is None or impact > prev[0]:- by_class[name] = (impact, getattr(f, "biomarker_type", ""))+ by_class.setdefault(name, []).append((impact, getattr(f, "biomarker_type", "")))return by_class@staticmethod@@ -155,3 +160,24 @@ class ExtractClassDetector(RefactoringDetector):if lcom4 >= 3 or method_count >= 15:return "high"return "medium"+++def _moved_share(cls: object, groups: list) -> float:+ """Share of the class the split moves out, for a ``god_class`` finding.++ ``low_cohesion`` is answered whole: the split is the full LCOM4 partition.+ ``god_class`` is about size, and the largest group stays behind as the+ class, so only what leaves it is credited: the larger of the moved NLOC+ and moved CCN shares, as Extract Method credits a span.+ """+ methods = list(getattr(cls, "methods", []) or [])++ def size(names: set[str]) -> tuple[int, int]:+ picked = [m for m in methods if getattr(m, "name", None) in names]+ return sum(m.nloc for m in picked), sum(m.ccn for m in picked)++ total_nloc, total_ccn = size({getattr(m, "name", None) for m in methods})+ if total_nloc <= 0 or total_ccn <= 0:+ return 1.0+ kept_nloc, kept_ccn = max(size(set(getattr(g, "methods", []))) for g in groups)+ return max(1 - kept_nloc / total_nloc, 1 - kept_ccn / total_ccn)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.pyindex 507467855..ba6eaa6eb 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@@ -28,8 +28,10 @@ Precision-first, the gate demands a block genuinely worth a helper:vendored bundles) the block still duplicates across ``>= 2`` sites — testfixtures and migration boilerplate duplicate constantly but a sharedhelper is the wrong fix for them;-- the recovered impact is read off the file's ``dry_violation`` finding- when it overlaps the block, else ``0`` (same posture as Extract Class).+- the recovered impact is the block's share of the file's ``dry_violation``+ finding when it overlaps the block, else ``0``: the finding grades the+ whole file's duplication, so one block is credited the duplicated lines it+ removes here, not the whole finding (:func:`clone_share`).Confidence rides the co-change signal: a clone whose sites are activelyco-modified is real, maintained duplication (``high``); a dormant clone is@@ -474,7 +476,9 @@ class ExtractHelperDetector(RefactoringDetector):if region_lines and _is_declaration_only(region_lines):return None- impact = self._impact_for_block(anchor_region, impact_lookup)+ impact = self._impact_for_block(anchor_region, impact_lookup) * clone_share(+ occurrences, ctx.file_path, self._duplication_pct(ctx), ctx.nloc+ )is_intra = len(occ_files) == 1suggested_site = self._suggested_site(occ_files)@@ -608,6 +612,16 @@ class ExtractHelperDetector(RefactoringDetector):out.append((int(start), int(end), impact))return out+ @staticmethod+ def _duplication_pct(ctx: RefactoringContext) -> float | None:+ """The file's duplicated share, as its ``dry_violation`` finding records it."""+ for f in ctx.findings:+ if getattr(f, "biomarker_type", "") == _SOURCE_BIOMARKER:+ pct = (getattr(f, "details", None) or {}).get("duplication_pct")+ if isinstance(pct, (int, float)):+ return float(pct)+ return None+@staticmethoddef _impact_for_block(region: tuple[int, int], impact_lookup: list[tuple[int, int, float]]@@ -622,6 +636,21 @@ class ExtractHelperDetector(RefactoringDetector):return best+def clone_share(+ occurrences: list[tuple[str, int, int]], file_path: str, dup_pct: float | None, nloc: int+) -> float:+ """Share of *file_path*'s duplicated lines that extracting this block removes.++ 1.0 when the file's duplication is unknown, keeping the finding's own+ impact as the other detectors do when they cannot re-measure it.+ """+ duplicated = (dup_pct or 0.0) * nloc / 100.0+ if duplicated <= 0:+ return 1.0+ here = sum(end - start + 1 for path, start, end in occurrences if path == file_path)+ return min(1.0, here / duplicated)++def _merge_ranges_per_file(occurrences: list[tuple[str, int, int]],) -> list[tuple[str, int, int]]: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 d87f50270..d9f51cb52 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@@ -7,16 +7,29 @@ changing behaviour, and infers that helper's signature (IN parameters,OUT return). This detector turns the best such span into one structured``RefactoringSuggestion`` per flagged function.-``impact_delta`` is what the extraction itself recovers, not the whole-finding. The residual method keeps ``ccn - ccn_removed`` decision points and-``nloc - slice_nloc + 1`` lines (the call replaces the span), the new helper-carries ``ccn_removed + 1`` and ``slice_nloc``, and each is re-graded with the-source biomarker's own severity rule. The finding's impact is credited in-proportion to the severity deduction that disappears: all of it when both-shapes fall below the biomarker's bar, the band difference when the residual-only drops a band, and nothing when a CCN 209 method sheds 6 and stays-critical. A function that needs several extractions therefore shows several-partial steps rather than one step claiming the full finding.+``impact_delta`` is the share of the finding the extraction itself removes,+not the whole finding: the share of what the finding measures that moves into+the helper, applied to the finding's ``health_impact``. That is+``ccn_removed / ccn`` for ``complex_method``, ``slice_nloc / nloc`` for+``large_method`` and the larger of the two for ``brain_method``, capped at 1+(:func:`recovered_share`). Both line counts follow the walker's NLOC rule, so+comments credit nothing. Crediting the whole finding whenever the residual and+the helper both fell under the biomarker's bar let a two-line span in a+function barely over the bar claim all of it, and rank first on the repo.++A span is only offered when it is worth doing (:func:`_worth_extracting`): it+removes at least two decision points, or, for a ``large_method`` finding, lifts+at least 12 code lines, and the helper it creates would not carry the finding+at the function's own severity or worse (lifting nearly the whole body moves+the smell, it does not split it).+When the best span misses that floor the next-best one that clears it is+offered instead.++A JSX function component whose decision points sit mostly in its markup+(conditional spreads, ``&&`` and ternaries in attributes or children, template+ternaries, all under a ``jsx_*`` node) is not offered one: that branching is prop plumbing, and a helper+would only move it. CCN is left alone because it feeds the calibrated defect+score; the gate is on eligibility.The candidate spans + IN/OUT come from ``dataflow.find_extractions``; thismodule only matches each analysed function to the biomarker finding that flags@@ -33,7 +46,7 @@ Plan shape (open dict, no migration):value: a name derived from the enclosing function described the contextrather than the span, and collided with every sibling plan in the file.- ``evidence`` = ``{"slice_nloc": int, "ccn_removed": int}`` -- the size and- complexity the residual method sheds.+ complexity (code lines, decision points) the residual method sheds.- ``blast_radius`` = ``{"scope": "local"}`` -- extraction is local (a newprivate helper, the public method's signature is unchanged), so nothingoutside the file moves. This is a *categorical* statement, not a count: it@@ -51,6 +64,7 @@ from typing import TYPE_CHECKING, Anyfrom ..biomarkers.brain_method import BrainMethodDetectorfrom ..biomarkers.complex_method import ComplexMethodDetectorfrom ..biomarkers.large_method import LargeMethodDetector+from ..complexity.cyclomatic import _is_boolean_operatorfrom ..complexity.languages import get_language_mapfrom ..dataflow import find_extractionsfrom ..scoring import severity_deduction@@ -59,6 +73,7 @@ from .naming import identifier_slugfrom .registry import RefactoringDetector, effort_bucket, registerif TYPE_CHECKING:+ from ..complexity.languages import LanguageNodeMapfrom ..dataflow import Extraction, FunctionAnalysisfrom ..models import Severity@@ -73,13 +88,27 @@ _UNINFORMATIVE_OUT = frozenset(# list never exceeds (and stays consistent with) what health surfaces._SOURCE_BIOMARKERS = ("brain_method", "large_method", "complex_method")-# Each source biomarker's own ``(ccn, nloc) -> severity`` rule.+# Each source biomarker's own ``(ccn, nloc) -> severity`` rule, for the helper._SEVERITY_RULE: dict[str, Callable[[int, int], Severity | None]] = {"brain_method": BrainMethodDetector.severity_for,"large_method": LargeMethodDetector.severity_for,"complex_method": ComplexMethodDetector.severity_for,}+# Minimum worth. Census of the 1,162 stored plans on this repo's index: the best+# span of 408 missed this floor (2 code lines lifting 2 decision points out of+# ``walk_file`` was the #1 plan), 187 of those had a next-best span that clears+# it and 221 were dropped. A size-only bar for ``large_method`` keeps big+# low-branching spans that do shrink the finding. Table in the commit that set+# it.+_MIN_CCN_REMOVED = 2+_MIN_LARGE_SPAN_NLOC = 12++# ``high`` confidence also needs the helper to take a real share of the+# function: below a tenth (a 2-point span out of a CCN 249 function) the step+# is safe but moves almost nothing.+_HIGH_MIN_SHARE = 0.1+@registerclass ExtractMethodDetector(RefactoringDetector):@@ -99,11 +128,21 @@ class ExtractMethodDetector(RefactoringDetector):if not matched:# Only suggest where a method biomarker actually fired.continue- candidates = find_extractions(analysis, lmap)- if not candidates:+ if jsx_plumbing_dominates(analysis.fn_node, lmap):+ continue+ markers = {getattr(f, "biomarker_type", "") for f in matched}+ # Best-first, so the first span worth doing is the strongest one.+ best = next(+ (+ c+ for c in find_extractions(analysis, lmap)+ if _worth_extracting(analysis, c, markers)+ ),+ None,+ )+ if best is None:continue- best = candidates[0] # already best-first- impact, source = self._impact_for(analysis, best, matched)+ impact, share, source = self._impact_for(analysis, best, matched)out.append(RefactoringSuggestion(refactoring_type=self.name,@@ -124,7 +163,7 @@ class ExtractMethodDetector(RefactoringDetector):impact_delta=round(float(impact), 3),effort_bucket=effort_bucket(best.slice_nloc),blast_radius={"scope": "local"},- confidence=self._confidence(best),+ confidence=self._confidence(best, share),source_biomarker=source,))@@ -153,17 +192,17 @@ class ExtractMethodDetector(RefactoringDetector):@staticmethoddef _impact_for(analysis: FunctionAnalysis, extraction: Extraction, findings: list[Any]- ) -> tuple[float, str]:- """Impact *extraction* recovers + the source biomarker it recovers it- from. The finding recovering the most wins; when none recovers- anything, the largest finding still names the cause."""- best: tuple[float, float, str] = (-1.0, -1.0, "")+ ) -> tuple[float, float, str]:+ """Impact *extraction* recovers, its share of the finding, and the source+ biomarker. One finding is credited, the one recovering the most: the+ composer counts a finding once across steps."""+ best: tuple[float, float, float, str] = (-1.0, 0.0, -1.0, "")for f in findings:biomarker = getattr(f, "biomarker_type", "")full = float(getattr(f, "health_impact", 0.0) or 0.0)- recovered = full * _recovered_fraction(biomarker, analysis, extraction)- best = max(best, (recovered, full, biomarker))- return best[0], best[2]+ share = recovered_share(biomarker, analysis, extraction)+ best = max(best, (full * share, share, full, biomarker))+ return best[0], best[1], best[3]@staticmethoddef _suggested_name(analysis: FunctionAnalysis, extraction: Extraction) -> str | None:@@ -196,34 +235,83 @@ class ExtractMethodDetector(RefactoringDetector):return None@staticmethod- def _confidence(extraction: Extraction) -> str:- """High when the extraction is unambiguous -- it removes several decision- points with a clean signature; medium otherwise. (Every emitted span is+ def _confidence(extraction: Extraction, share: float) -> str:+ """High when the extraction is unambiguous and worth handing off: it+ removes several decision points with a clean signature and takes a real+ share of the function. Medium otherwise. (Every emitted span issingle-exit with at most one return by construction.)"""- if extraction.ccn_removed >= 2 and len(extraction.params) <= 4:+ if (+ extraction.ccn_removed >= _MIN_CCN_REMOVED+ and len(extraction.params) <= 4+ and share >= _HIGH_MIN_SHARE+ ):return "high"return "medium"-def _recovered_fraction(+def recovered_share(biomarker: str, analysis: FunctionAnalysis, extraction: Extraction) -> float:- """Share of *biomarker*'s deduction that applying *extraction* removes.+ """Share of what *biomarker* measures that *extraction* moves into the helper.++ Decision points for ``complex_method``, code lines for ``large_method``+ (the walker's NLOC rule on both sides), the larger of the two for+ ``brain_method``, capped at 1. Per biomarker because the plain maximum let+ 2 decision points out of a CCN 3, 292-line method claim two thirds of a+ size finding.+ """+ ccn_share = extraction.ccn_removed / analysis.ccn if analysis.ccn > 0 else 0.0+ nloc_share = extraction.slice_nloc / analysis.nloc if analysis.nloc > 0 else 0.0+ if biomarker == "complex_method":+ return min(1.0, ccn_share)+ if biomarker == "large_method":+ return min(1.0, nloc_share)+ return min(1.0, max(ccn_share, nloc_share))+++def _worth_extracting(+ analysis: FunctionAnalysis, extraction: Extraction, markers: set[str]+) -> bool:+ """The minimum-worth floor (the slicer already demands 5 code lines)."""+ for marker in markers:+ rule = _SEVERITY_RULE[marker]+ helper = rule(extraction.ccn_removed + 1, extraction.slice_nloc)+ before = rule(analysis.ccn, analysis.nloc)+ # The helper inherits the finding undiminished: the smell moved.+ if helper is not None and (+ before is None or severity_deduction(helper) >= severity_deduction(before)+ ):+ return False+ if extraction.ccn_removed >= _MIN_CCN_REMOVED:+ return True+ return "large_method" in markers and extraction.slice_nloc >= _MIN_LARGE_SPAN_NLOC+++def jsx_plumbing_dominates(fn_node: Any, lmap: LanguageNodeMap) -> bool:+ """True for a function rendering JSX whose decision points sit mostly in it.- Both post-extraction shapes (the residual method and the new helper) are- graded with the biomarker's own rule; whatever deduction they still earn- is subtracted. Brain Method's file-level centrality gate is unchanged by a- local extraction, so only its size/complexity bar is re-checked.+ Counts decision points the way the CCN walker does (nested functions are+ their own; arrow functions count toward this one) and the share of them+ inside the markup: under any ``jsx_*`` node, which covers spreads, template+ ternaries and ``&&`` in attributes and children. The same shapes outside+ the markup (``const cfg = {...defaults, x: a && b}``) are logic, not wiring."""- rule = _SEVERITY_RULE[biomarker]- before = rule(analysis.ccn, analysis.nloc)- if before is None:- # These metrics do not reproduce the finding, so there is no band to- # re-grade against; keep the finding's own impact.- return 1.0- residual = rule(- analysis.ccn - extraction.ccn_removed, analysis.nloc - extraction.slice_nloc + 1- )- helper = rule(extraction.ccn_removed + 1, extraction.slice_nloc)- remaining = sum(severity_deduction(s) for s in (residual, helper) if s is not None)- return max(0.0, 1.0 - remaining / severity_deduction(before))+ if fn_node is None:+ return False+ body = fn_node.child_by_field_name("body") or fn_node+ kinds = lmap.branch_kinds | lmap.loop_kinds | lmap.case_kinds | lmap.catch_kinds+ total = plumbing = 0+ has_jsx = False+ stack = [(child, False) for child in body.children]+ while stack:+ node, inside = stack.pop()+ if node.type in lmap.function_kinds:+ continue+ in_jsx = node.type.startswith("jsx_")+ has_jsx = has_jsx or in_jsx+ if (node.is_named and node.type in kinds) or _is_boolean_operator(node, lmap):+ total += 1+ plumbing += inside+ inside = inside or in_jsx+ stack.extend((child, inside) for child in node.children)+ return has_jsx and plumbing * 2 > totaldiff --git a/packages/core/src/repowise/core/analysis/health/refactoring/identity.py b/packages/core/src/repowise/core/analysis/health/refactoring/identity.pyindex 56d723f4c..e785a002f 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/identity.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/identity.py@@ -24,7 +24,7 @@ from typing import Anyfrom ..rows import field-REFACTORING_MODEL_VERSION = 2+REFACTORING_MODEL_VERSION = 3"""Version of the identity semantics. v1 was the fresh-UUID-per-index era.The version is the id prefix rather than a hash input, so a stale id isdiff --git a/packages/core/src/repowise/core/analysis/health/refactoring/models.py b/packages/core/src/repowise/core/analysis/health/refactoring/models.pyindex 62ae5d4ea..580f7b767 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/models.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/models.py@@ -51,7 +51,7 @@ For Extract Method:single informative OUT value, else absent). It is an editable starting pointand is not unique within a file.- ``evidence`` = ``{"slice_nloc": int, "ccn_removed": int}`` — the size and- complexity the residual method sheds.+ complexity (code lines, decision points) the residual method sheds.- ``blast_radius`` = ``{"scope": "local"}`` — the one type whose blast radius iscategorical rather than counted: extraction adds a private helper and changesno signature, so nothing outside the file moves. It replaced a hardcodeddiff --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 5f7963e3f..49a79dc9f 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@@ -133,14 +133,31 @@ def why_ranked(factors: dict[str, float], *, limit: int = 3) -> list[dict[str, Areturn [{"factor": name, "value": value} for name, value in ordered[:limit]]-def rank_sort_key(opportunity: Any) -> tuple[float, str, str]:- """A total order. The id tail is what stops ties floating between runs."""- return (-opportunity.rank_score, opportunity.file_path, opportunity.opportunity_id)+def rank_sort_key(opportunity: Any) -> tuple[bool, float, str, str]:+ """A total order. The id tail is what stops ties floating between runs.++ Work that recovers health comes first. A detector-native 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.+ """+ return (+ not has_credit(opportunity),+ -opportunity.rank_score,+ opportunity.file_path,+ opportunity.opportunity_id,+ )+++def has_credit(opportunity: Any) -> bool:+ """Whether the opportunity recovers any health at all."""+ return float(opportunity.recoverable_health or 0.0) > 0.0__all__ = ["MECHANICAL_SHARE_WEIGHT","PRIMARY_PROBLEM_WEIGHT",+ "has_credit","opportunity_benefit","opportunity_risk","rank_factors",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.pyindex 9e8b18271..4fa65a96f 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@@ -93,9 +93,16 @@ def _diversified_order(opportunities: list[OpportunityModel]) -> list[int]:Deterministic, and a repository with one cause in one area degrades toplain rank order rather than inventing a difference.++ 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."""+ from ....analysis.health.refactoring.opportunity_rank import has_credit++ credited = sum(1 for item in opportunities if has_credit(item))groups: dict[tuple[str, str, str], list[int]] = {}- for position, item in enumerate(opportunities):+ for position, item in enumerate(opportunities[:credited]):parent = item.file_path.rsplit("/", 1)[0] if "/" in item.file_path else ""area = "/".join(parent.split("/")[:2])groups.setdefault(@@ -107,7 +114,7 @@ def _diversified_order(opportunities: list[OpportunityModel]) -> list[int]:for members in ordered_groups:if round_index < len(members):order.append(members[round_index])- return order+ return order + list(range(credited, len(opportunities)))def _finding_ids_by_file(findings: list[HealthFinding]) -> dict[str, dict[str, list[str]]]:diff --git a/tests/fixtures/refactoring_corpus/golden_extractions.json b/tests/fixtures/refactoring_corpus/golden_extractions.jsonindex 683502412..616cc7d22 100644--- a/tests/fixtures/refactoring_corpus/golden_extractions.json+++ b/tests/fixtures/refactoring_corpus/golden_extractions.json@@ -9,7 +9,7 @@"rows"],"returns": [],- "slice_nloc": 11,+ "slice_nloc": 8,"start_line": 211},{@@ -20,7 +20,7 @@"rows"],"returns": [],- "slice_nloc": 10,+ "slice_nloc": 8,"start_line": 212},{@@ -31,7 +31,7 @@"rows"],"returns": [],- "slice_nloc": 9,+ "slice_nloc": 8,"start_line": 213},{@@ -57,7 +57,7 @@"returns": ["changed"],- "slice_nloc": 12,+ "slice_nloc": 9,"start_line": 28},{@@ -70,7 +70,7 @@"returns": ["changed"],- "slice_nloc": 10,+ "slice_nloc": 9,"start_line": 30}],@@ -85,7 +85,7 @@"returns": ["average"],- "slice_nloc": 14,+ "slice_nloc": 13,"start_line": 10},{@@ -99,7 +99,7 @@"returns": ["average"],- "slice_nloc": 13,+ "slice_nloc": 12,"start_line": 11},{@@ -114,7 +114,7 @@"returns": ["average"],- "slice_nloc": 12,+ "slice_nloc": 11,"start_line": 12},{@@ -127,7 +127,7 @@"returns": ["average"],- "slice_nloc": 12,+ "slice_nloc": 11,"start_line": 10},{@@ -141,7 +141,7 @@"returns": ["average"],- "slice_nloc": 11,+ "slice_nloc": 10,"start_line": 11},{@@ -156,7 +156,7 @@"returns": ["average"],- "slice_nloc": 10,+ "slice_nloc": 9,"start_line": 12},{@@ -170,7 +170,7 @@"returns": ["average"],- "slice_nloc": 8,+ "slice_nloc": 7,"start_line": 16},{@@ -211,8 +211,21 @@"returns": ["average"],- "slice_nloc": 6,+ "slice_nloc": 5,"start_line": 16+ },+ {+ "ccn_removed": 1,+ "end_line": 21,+ "params": [+ "count",+ "total"+ ],+ "returns": [+ "average"+ ],+ "slice_nloc": 5,+ "start_line": 17}],"elif_else_chain": [@@ -226,7 +239,7 @@"returns": ["label"],- "slice_nloc": 15,+ "slice_nloc": 14,"start_line": 61},{@@ -239,7 +252,7 @@"returns": ["label"],- "slice_nloc": 13,+ "slice_nloc": 12,"start_line": 63},{@@ -252,7 +265,7 @@"returns": ["label"],- "slice_nloc": 12,+ "slice_nloc": 11,"start_line": 63},{@@ -265,12 +278,12 @@"returns": ["label"],- "slice_nloc": 12,+ "slice_nloc": 11,"start_line": 64},{"ccn_removed": 2,- "end_line": 73,+ "end_line": 75,"params": ["limit","value"@@ -279,11 +292,11 @@"label"],"slice_nloc": 11,- "start_line": 63+ "start_line": 65},{"ccn_removed": 2,- "end_line": 74,+ "end_line": 73,"params": ["limit","value"@@ -291,12 +304,12 @@"returns": ["label"],- "slice_nloc": 11,- "start_line": 64+ "slice_nloc": 10,+ "start_line": 63},{"ccn_removed": 2,- "end_line": 75,+ "end_line": 74,"params": ["limit","value"@@ -304,12 +317,12 @@"returns": ["label"],- "slice_nloc": 11,- "start_line": 65+ "slice_nloc": 10,+ "start_line": 64},{"ccn_removed": 2,- "end_line": 73,+ "end_line": 74,"params": ["limit","value"@@ -318,11 +331,11 @@"label"],"slice_nloc": 10,- "start_line": 64+ "start_line": 65},{"ccn_removed": 2,- "end_line": 74,+ "end_line": 73,"params": ["limit","value"@@ -330,8 +343,8 @@"returns": ["label"],- "slice_nloc": 10,- "start_line": 65+ "slice_nloc": 9,+ "start_line": 64}],"else_assigned_twin": [@@ -345,7 +358,7 @@"returns": ["changed"],- "slice_nloc": 13,+ "slice_nloc": 11,"start_line": 44},{@@ -358,7 +371,7 @@"returns": ["changed"],- "slice_nloc": 12,+ "slice_nloc": 11,"start_line": 45},{@@ -371,7 +384,7 @@"returns": ["changed"],- "slice_nloc": 10,+ "slice_nloc": 9,"start_line": 47},{@@ -384,7 +397,7 @@"returns": ["changed"],- "slice_nloc": 9,+ "slice_nloc": 8,"start_line": 47},{@@ -397,12 +410,12 @@"returns": ["changed"],- "slice_nloc": 9,+ "slice_nloc": 8,"start_line": 48},{"ccn_removed": 1,- "end_line": 54,+ "end_line": 56,"params": ["entry","limit"@@ -411,11 +424,11 @@"changed"],"slice_nloc": 8,- "start_line": 47+ "start_line": 49},{"ccn_removed": 1,- "end_line": 55,+ "end_line": 54,"params": ["entry","limit"@@ -423,12 +436,12 @@"returns": ["changed"],- "slice_nloc": 8,- "start_line": 48+ "slice_nloc": 7,+ "start_line": 47},{"ccn_removed": 1,- "end_line": 56,+ "end_line": 55,"params": ["entry","limit"@@ -436,12 +449,12 @@"returns": ["changed"],- "slice_nloc": 8,- "start_line": 49+ "slice_nloc": 7,+ "start_line": 48},{"ccn_removed": 1,- "end_line": 54,+ "end_line": 55,"params": ["entry","limit"@@ -450,11 +463,11 @@"changed"],"slice_nloc": 7,- "start_line": 48+ "start_line": 49},{"ccn_removed": 1,- "end_line": 55,+ "end_line": 54,"params": ["entry","limit"@@ -462,8 +475,8 @@"returns": ["changed"],- "slice_nloc": 7,- "start_line": 49+ "slice_nloc": 6,+ "start_line": 48}],"for_else_clause": [@@ -476,7 +489,7 @@"returns": ["flag"],- "slice_nloc": 15,+ "slice_nloc": 13,"start_line": 159},{@@ -488,7 +501,7 @@"returns": ["flag"],- "slice_nloc": 14,+ "slice_nloc": 13,"start_line": 160},{@@ -498,7 +511,7 @@"rows"],"returns": [],- "slice_nloc": 13,+ "slice_nloc": 12,"start_line": 161},{@@ -530,7 +543,7 @@"returns": ["label"],- "slice_nloc": 10,+ "slice_nloc": 9,"start_line": 80}],@@ -545,7 +558,7 @@"returns": ["out"],- "slice_nloc": 12,+ "slice_nloc": 11,"start_line": 126},{@@ -557,7 +570,7 @@"row"],"returns": [],- "slice_nloc": 10,+ "slice_nloc": 9,"start_line": 128},{@@ -569,7 +582,7 @@"row"],"returns": [],- "slice_nloc": 9,+ "slice_nloc": 8,"start_line": 128},{@@ -581,9 +594,21 @@"row"],"returns": [],- "slice_nloc": 9,+ "slice_nloc": 8,"start_line": 129},+ {+ "ccn_removed": 1,+ "end_line": 137,+ "params": [+ "limit",+ "out",+ "row"+ ],+ "returns": [],+ "slice_nloc": 8,+ "start_line": 130+ },{"ccn_removed": 1,"end_line": 135,@@ -594,7 +619,7 @@"returns": ["scaled"],- "slice_nloc": 8,+ "slice_nloc": 7,"start_line": 128},{@@ -606,19 +631,19 @@"row"],"returns": [],- "slice_nloc": 8,+ "slice_nloc": 7,"start_line": 129},{"ccn_removed": 1,- "end_line": 137,+ "end_line": 136,"params": ["limit","out","row"],"returns": [],- "slice_nloc": 8,+ "slice_nloc": 7,"start_line": 130},{@@ -631,20 +656,8 @@"returns": ["scaled"],- "slice_nloc": 7,+ "slice_nloc": 6,"start_line": 129- },- {- "ccn_removed": 1,- "end_line": 136,- "params": [- "limit",- "out",- "row"- ],- "returns": [],- "slice_nloc": 7,- "start_line": 130}],"loop_mutates_iterated": [@@ -658,7 +671,7 @@"returns": ["seen"],- "slice_nloc": 12,+ "slice_nloc": 11,"start_line": 110}],@@ -673,7 +686,7 @@"returns": ["carry"],- "slice_nloc": 12,+ "slice_nloc": 11,"start_line": 94}],@@ -689,7 +702,7 @@"returns": ["names"],- "slice_nloc": 25,+ "slice_nloc": 18,"start_line": 226},{@@ -702,7 +715,7 @@"returns": ["names"],- "slice_nloc": 19,+ "slice_nloc": 18,"start_line": 232},{@@ -714,7 +727,7 @@"names"],"returns": [],- "slice_nloc": 18,+ "slice_nloc": 17,"start_line": 233},{@@ -726,7 +739,7 @@"names"],"returns": [],- "slice_nloc": 17,+ "slice_nloc": 16,"start_line": 234},{@@ -739,7 +752,7 @@"names"],"returns": [],- "slice_nloc": 16,+ "slice_nloc": 15,"start_line": 235}],@@ -755,7 +768,7 @@"returns": ["rate"],- "slice_nloc": 13,+ "slice_nloc": 11,"start_line": 182},{@@ -768,7 +781,7 @@"returns": ["rate"],- "slice_nloc": 12,+ "slice_nloc": 11,"start_line": 183}]@@ -784,7 +797,7 @@"returns": ["average"],- "slice_nloc": 15,+ "slice_nloc": 14,"start_line": 10},{@@ -797,7 +810,7 @@"returns": ["average"],- "slice_nloc": 14,+ "slice_nloc": 13,"start_line": 11},{@@ -811,7 +824,7 @@"returns": ["average"],- "slice_nloc": 13,+ "slice_nloc": 12,"start_line": 12},{@@ -824,12 +837,12 @@"returns": ["average"],- "slice_nloc": 9,+ "slice_nloc": 8,"start_line": 16},{"ccn_removed": 1,- "end_line": 23,+ "end_line": 24,"params": ["count","total"@@ -838,11 +851,11 @@"average"],"slice_nloc": 8,- "start_line": 16+ "start_line": 17},{"ccn_removed": 1,- "end_line": 24,+ "end_line": 23,"params": ["count","total"@@ -850,12 +863,12 @@"returns": ["average"],- "slice_nloc": 8,- "start_line": 17+ "slice_nloc": 7,+ "start_line": 16},{"ccn_removed": 1,- "end_line": 22,+ "end_line": 23,"params": ["count","total"@@ -864,11 +877,11 @@"average"],"slice_nloc": 7,- "start_line": 16+ "start_line": 17},{"ccn_removed": 1,- "end_line": 23,+ "end_line": 24,"params": ["count","total"@@ -877,11 +890,11 @@"average"],"slice_nloc": 7,- "start_line": 17+ "start_line": 18},{"ccn_removed": 1,- "end_line": 24,+ "end_line": 22,"params": ["count","total"@@ -889,8 +902,8 @@"returns": ["average"],- "slice_nloc": 7,- "start_line": 18+ "slice_nloc": 6,+ "start_line": 16},{"ccn_removed": 1,@@ -930,7 +943,7 @@"returns": ["label"],- "slice_nloc": 14,+ "slice_nloc": 13,"start_line": 45},{@@ -943,7 +956,7 @@"returns": ["label"],- "slice_nloc": 11,+ "slice_nloc": 10,"start_line": 47},{@@ -956,7 +969,7 @@"returns": ["label"],- "slice_nloc": 10,+ "slice_nloc": 9,"start_line": 47},{@@ -969,12 +982,12 @@"returns": ["label"],- "slice_nloc": 10,+ "slice_nloc": 9,"start_line": 48},{"ccn_removed": 1,- "end_line": 55,+ "end_line": 57,"params": ["limit","value"@@ -983,11 +996,11 @@"label"],"slice_nloc": 9,- "start_line": 47+ "start_line": 49},{"ccn_removed": 1,- "end_line": 56,+ "end_line": 55,"params": ["limit","value"@@ -995,12 +1008,12 @@"returns": ["label"],- "slice_nloc": 9,- "start_line": 48+ "slice_nloc": 8,+ "start_line": 47},{"ccn_removed": 1,- "end_line": 57,+ "end_line": 56,"params": ["limit","value"@@ -1008,12 +1021,12 @@"returns": ["label"],- "slice_nloc": 9,- "start_line": 49+ "slice_nloc": 8,+ "start_line": 48},{"ccn_removed": 1,- "end_line": 55,+ "end_line": 56,"params": ["limit","value"@@ -1022,11 +1035,11 @@"label"],"slice_nloc": 8,- "start_line": 48+ "start_line": 49},{"ccn_removed": 1,- "end_line": 56,+ "end_line": 55,"params": ["limit","value"@@ -1034,8 +1047,8 @@"returns": ["label"],- "slice_nloc": 8,- "start_line": 49+ "slice_nloc": 7,+ "start_line": 48}],"elseIfChain": [@@ -1049,7 +1062,7 @@"returns": ["label"],- "slice_nloc": 17,+ "slice_nloc": 16,"start_line": 98},{@@ -1062,7 +1075,7 @@"returns": ["label"],- "slice_nloc": 14,+ "slice_nloc": 13,"start_line": 100},{@@ -1075,7 +1088,7 @@"returns": ["label"],- "slice_nloc": 13,+ "slice_nloc": 12,"start_line": 100},{@@ -1088,12 +1101,12 @@"returns": ["label"],- "slice_nloc": 13,+ "slice_nloc": 12,"start_line": 101},{"ccn_removed": 2,- "end_line": 111,+ "end_line": 113,"params": ["limit","value"@@ -1102,11 +1115,11 @@"label"],"slice_nloc": 12,- "start_line": 100+ "start_line": 102},{"ccn_removed": 2,- "end_line": 112,+ "end_line": 111,"params": ["limit","value"@@ -1114,12 +1127,12 @@"returns": ["label"],- "slice_nloc": 12,- "start_line": 101+ "slice_nloc": 11,+ "start_line": 100},{"ccn_removed": 2,- "end_line": 113,+ "end_line": 112,"params": ["limit","value"@@ -1127,12 +1140,12 @@"returns": ["label"],- "slice_nloc": 12,- "start_line": 102+ "slice_nloc": 11,+ "start_line": 101},{"ccn_removed": 2,- "end_line": 111,+ "end_line": 112,"params": ["limit","value"@@ -1141,11 +1154,11 @@"label"],"slice_nloc": 11,- "start_line": 101+ "start_line": 102},{"ccn_removed": 2,- "end_line": 112,+ "end_line": 111,"params": ["limit","value"@@ -1153,8 +1166,8 @@"returns": ["label"],- "slice_nloc": 11,- "start_line": 102+ "slice_nloc": 10,+ "start_line": 101}],"ifWithoutElse": [@@ -1168,7 +1181,7 @@"returns": ["label"],- "slice_nloc": 12,+ "slice_nloc": 11,"start_line": 29}],@@ -1183,7 +1196,7 @@"returns": ["seen"],- "slice_nloc": 14,+ "slice_nloc": 13,"start_line": 63}],@@ -1198,7 +1211,7 @@"returns": ["bucket"],- "slice_nloc": 14,+ "slice_nloc": 13,"start_line": 120},{@@ -1210,7 +1223,7 @@"page"],"returns": [],- "slice_nloc": 11,+ "slice_nloc": 10,"start_line": 122},{@@ -1222,7 +1235,7 @@"page"],"returns": [],- "slice_nloc": 10,+ "slice_nloc": 9,"start_line": 122},{@@ -1234,12 +1247,12 @@"page"],"returns": [],- "slice_nloc": 10,+ "slice_nloc": 9,"start_line": 123},{"ccn_removed": 1,- "end_line": 130,+ "end_line": 132,"params": ["bucket","limit",@@ -1247,35 +1260,35 @@],"returns": [],"slice_nloc": 9,- "start_line": 122+ "start_line": 124},{"ccn_removed": 1,- "end_line": 131,+ "end_line": 130,"params": ["bucket","limit","page"],"returns": [],- "slice_nloc": 9,- "start_line": 123+ "slice_nloc": 8,+ "start_line": 122},{"ccn_removed": 1,- "end_line": 132,+ "end_line": 131,"params": ["bucket","limit","page"],"returns": [],- "slice_nloc": 9,- "start_line": 124+ "slice_nloc": 8,+ "start_line": 123},{"ccn_removed": 1,- "end_line": 130,+ "end_line": 131,"params": ["bucket","limit",@@ -1283,19 +1296,19 @@],"returns": [],"slice_nloc": 8,- "start_line": 123+ "start_line": 124},{"ccn_removed": 1,- "end_line": 131,+ "end_line": 130,"params": ["bucket","limit","page"],"returns": [],- "slice_nloc": 8,- "start_line": 124+ "slice_nloc": 7,+ "start_line": 123}],"record": [],@@ -1310,7 +1323,7 @@"returns": ["label"],- "slice_nloc": 13,+ "slice_nloc": 11,"start_line": 81}]diff --git a/tests/fixtures/refactoring_corpus/golden_opportunities.json b/tests/fixtures/refactoring_corpus/golden_opportunities.jsonindex 5ed10f098..0e2aa3d43 100644--- a/tests/fixtures/refactoring_corpus/golden_opportunities.json+++ b/tests/fixtures/refactoring_corpus/golden_opportunities.json@@ -13,7 +13,7 @@"lead_biomarker": null,"lead_refactoring_type": "split_file","mechanical_steps": 0,- "opportunity_id": "refop2_f8df0afac1fe67c55d05",+ "opportunity_id": "refop3_f99fabfc0113b941a05f","rank_factors": {"benefit": 1.6931,"cost": 3.0,@@ -23,7 +23,7 @@},"rank_score": 0.4233,"recoverable_health": 0.0,- "refactoring_model_version": 2,+ "refactoring_model_version": 3,"step_count": 1,"steps": [{@@ -50,7 +50,7 @@"effort_bucket": "L","file_path": "inventory.go","impact_delta": 0.0,- "plan_id": "refac2_396717806264bd16aab8",+ "plan_id": "refac3_396717806264bd16aab8","refactoring_type": "split_file","relocated_by": null,"source_biomarker": "",@@ -84,17 +84,17 @@"lead_biomarker": "complex_method","lead_refactoring_type": "extract_method","mechanical_steps": 1,- "opportunity_id": "refop2_d82fe75fc83659cefa14",+ "opportunity_id": "refop3_6e81e602a1892b6fa13d","rank_factors": {- "benefit": 0.605,+ "benefit": 0.256,"cost": 1.0,"mechanical_share": 0.5,"primary_problem": 0.5,"risk": 0.0},- "rank_score": 0.605,- "recoverable_health": 0.605,- "refactoring_model_version": 2,+ "rank_score": 0.256,+ "recoverable_health": 0.256,+ "refactoring_model_version": 3,"step_count": 1,"steps": [{@@ -115,8 +115,8 @@"confidence": "high","effort_bucket": "S","file_path": "account.ts",- "impact_delta": 0.605,- "plan_id": "refac2_a5f94bcfa0d5e0e24f37",+ "impact_delta": 0.256,+ "plan_id": "refac3_a5f94bcfa0d5e0e24f37","refactoring_type": "extract_method","relocated_by": null,"source_biomarker": "complex_method",@@ -129,11 +129,11 @@"value": 1.0},{- "factor": "benefit",- "value": 0.605+ "factor": "mechanical_share",+ "value": 0.5},{- "factor": "mechanical_share",+ "factor": "primary_problem","value": 0.5}]@@ -151,17 +151,17 @@"lead_biomarker": "complex_method","lead_refactoring_type": "extract_method","mechanical_steps": 1,- "opportunity_id": "refop2_443f00cfefc5d4f86685",+ "opportunity_id": "refop3_508583d74573db062900","rank_factors": {- "benefit": 0.605,+ "benefit": 0.256,"cost": 1.0,"mechanical_share": 0.5,"primary_problem": 0.5,"risk": 0.0},- "rank_score": 0.605,- "recoverable_health": 0.605,- "refactoring_model_version": 2,+ "rank_score": 0.256,+ "recoverable_health": 0.256,+ "refactoring_model_version": 3,"step_count": 1,"steps": [{@@ -182,8 +182,8 @@"confidence": "high","effort_bucket": "S","file_path": "workspace.ts",- "impact_delta": 0.605,- "plan_id": "refac2_b21dea1501a82eec255a",+ "impact_delta": 0.256,+ "plan_id": "refac3_b21dea1501a82eec255a","refactoring_type": "extract_method","relocated_by": null,"source_biomarker": "complex_method",@@ -196,11 +196,11 @@"value": 1.0},{- "factor": "benefit",- "value": 0.605+ "factor": "mechanical_share",+ "value": 0.5},{- "factor": "mechanical_share",+ "factor": "primary_problem","value": 0.5}]@@ -216,7 +216,7 @@"effort_bucket": "S","evidence": [{- "plan_id": "refac2_aa609dc289a6e9572306",+ "plan_id": "refac3_aa609dc289a6e9572306","refactoring_type": "extract_helper","source_biomarker": "dry_violation","summary": {@@ -229,7 +229,7 @@"target_symbol": "handlers.py:25-45"},{- "plan_id": "refac2_8ea65569516929f43f5b",+ "plan_id": "refac3_8ea65569516929f43f5b","refactoring_type": "extract_helper","source_biomarker": "dry_violation","summary": {@@ -247,17 +247,17 @@"lead_biomarker": "dry_violation","lead_refactoring_type": "extract_method","mechanical_steps": 3,- "opportunity_id": "refop2_1a90a90d31e0cde5d50b",+ "opportunity_id": "refop3_a0a4fa71a224c520f90b","rank_factors": {- "benefit": 0.75,+ "benefit": 0.249,"cost": 3.0,"mechanical_share": 0.5,"primary_problem": 0.0,"risk": 0.0},- "rank_score": 0.2812,- "recoverable_health": 0.75,- "refactoring_model_version": 2,+ "rank_score": 0.0934,+ "recoverable_health": 0.249,+ "refactoring_model_version": 3,"step_count": 3,"steps": [{@@ -278,8 +278,8 @@"confidence": "high","effort_bucket": "S","file_path": "handlers.py",- "impact_delta": 0.25,- "plan_id": "refac2_cdc5177783ea57d763e5",+ "impact_delta": 0.083,+ "plan_id": "refac3_cdc5177783ea57d763e5","refactoring_type": "extract_method","relocated_by": null,"source_biomarker": "complex_method",@@ -303,8 +303,8 @@"confidence": "high","effort_bucket": "S","file_path": "handlers.py",- "impact_delta": 0.25,- "plan_id": "refac2_48c888afc5af0d975522",+ "impact_delta": 0.083,+ "plan_id": "refac3_48c888afc5af0d975522","refactoring_type": "extract_method","relocated_by": null,"source_biomarker": "complex_method",@@ -328,8 +328,8 @@"confidence": "high","effort_bucket": "S","file_path": "handlers.py",- "impact_delta": 0.25,- "plan_id": "refac2_4ecbf32a9c6419829a56",+ "impact_delta": 0.083,+ "plan_id": "refac3_4ecbf32a9c6419829a56","refactoring_type": "extract_method","relocated_by": null,"source_biomarker": "complex_method",@@ -341,13 +341,13 @@"factor": "cost","value": 3.0},- {- "factor": "benefit",- "value": 0.75- },{"factor": "mechanical_share","value": 0.5+ },+ {+ "factor": "benefit",+ "value": 0.249}]}diff --git a/tests/unit/health/test_model_version_coupling.py b/tests/unit/health/test_model_version_coupling.pyindex db03c4bbd..6e198958a 100644--- a/tests/unit/health/test_model_version_coupling.py+++ b/tests/unit/health/test_model_version_coupling.py@@ -22,7 +22,7 @@ from repowise.core.analysis.health.refactoring.identity import (# The three stamps as they stand together. Moving either identity model means# moving the analyzer with it, and updating this tuple in the same commit.-_STAMPS = (37, 3, 2)+_STAMPS = (37, 3, 3)def test_the_identity_models_and_the_analyzer_stamp_are_pinned_together() -> None:diff --git a/tests/unit/health/test_refactoring_extract_method.py b/tests/unit/health/test_refactoring_extract_method.pyindex b5a715fd5..6a2a7817c 100644--- a/tests/unit/health/test_refactoring_extract_method.py+++ b/tests/unit/health/test_refactoring_extract_method.py@@ -12,14 +12,14 @@ import pytestfrom repowise.core.analysis.health.complexity.languages import get_language_mapfrom repowise.core.analysis.health.dataflow import analyze_file, find_extractions-from repowise.core.analysis.health.models import Severityfrom repowise.core.analysis.health.refactoring import detect_refactoringsfrom repowise.core.analysis.health.refactoring.extract_method import (ExtractMethodDetector,- _recovered_fraction,+ _worth_extracting,+ jsx_plumbing_dominates,+ recovered_share,)from repowise.core.analysis.health.refactoring.models import RefactoringContext-from repowise.core.analysis.health.scoring import severity_deduction# A long function whose tail (compute-average loop) is a clean extraction._PROCESS = """@@ -89,7 +89,7 @@ def test_finds_clean_extraction_with_inferred_signature():# Single clean return, bounded params.assert len(best.returns) <= 1assert best.ccn_removed >= 1- assert best.slice_nloc >= 6+ assert best.slice_nloc >= 5def test_no_extraction_when_every_span_has_a_jump():@@ -357,7 +357,11 @@ def test_detector_emits_suggestion_for_flagged_function():assert s.refactoring_type == "extract_method"assert s.target_symbol == "process"assert s.source_biomarker == "complex_method"- assert s.impact_delta == 1.5+ # Credited the share of the function's decision points the span moves.+ fn = _first(_PROCESS)+ share = s.evidence["ccn_removed"] / fn.ccn+ assert 0 < share < 1+ assert s.impact_delta == round(1.5 * share, 3)# Plan shape is the locked schema.assert set(s.plan) == {"span", "params", "returns", "suggested_name"}assert set(s.plan["span"]) == {"start", "end"}@@ -449,7 +453,7 @@ def test_detector_is_deterministic():assert run() == first-# -- honest impact --------------------------------------------------------------+# -- proportional impact and minimum worth ---------------------------------------@dataclass@@ -464,44 +468,183 @@ class _Span:slice_nloc: int-def test_extraction_that_clears_the_bar_recovers_the_whole_finding():- # CCN 12 -> 6 residual, helper CCN 7: both below complex_method's bar of 9.- assert _recovered_fraction("complex_method", _Shape(12, 40), _Span(6, 15)) == 1.0+def test_share_follows_what_the_biomarker_measures():+ fn, span = _Shape(12, 40), _Span(6, 10)+ assert recovered_share("complex_method", fn, span) == 0.5+ assert recovered_share("large_method", fn, span) == 0.25+ assert recovered_share("brain_method", fn, span) == 0.5+ # Capped: a span cannot recover more than the whole finding.+ assert recovered_share("large_method", _Shape(3, 10), _Span(2, 20)) == 1.0+++def test_two_decision_points_out_of_a_tiny_size_finding_claim_little():+ # 2 decision points out of a CCN 3, 292-line method: the plain maximum of+ # the two shares claimed two thirds of a size finding for 16 lines.+ share = recovered_share("large_method", _Shape(3, 292), _Span(2, 16))+ assert share == pytest.approx(16 / 292)+++def test_floor_drops_a_one_point_span_unless_it_is_a_large_size_lift():+ fn = _Shape(12, 80)+ assert not _worth_extracting(fn, _Span(1, 8), {"complex_method"})+ assert _worth_extracting(fn, _Span(2, 5), {"complex_method"})+ assert not _worth_extracting(fn, _Span(1, 11), {"large_method"})+ assert _worth_extracting(fn, _Span(1, 12), {"large_method"})-def test_extraction_that_only_drops_a_band_recovers_the_band_difference():- # CCN 15 (high) -> 12 (medium): still a complex method, one band lower.- got = _recovered_fraction("complex_method", _Shape(15, 40), _Span(3, 8))- expected = 1 - severity_deduction(Severity.MEDIUM) / severity_deduction(Severity.HIGH)- assert got == pytest.approx(expected)+def test_a_helper_inheriting_the_finding_undiminished_is_not_worth_it():+ # CCN 13 -> helper CCN 13: the complex method moved, it did not split.+ assert not _worth_extracting(_Shape(13, 36), _Span(12, 30), {"complex_method"})+ # CCN 25 (critical) -> helper CCN 9 (medium): a real partial step.+ assert _worth_extracting(_Shape(25, 117), _Span(8, 40), {"complex_method"})-def test_extraction_that_stays_in_band_recovers_nothing():- # CCN 209 -> 203 stays critical for both brain_method and complex_method.- assert _recovered_fraction("brain_method", _Shape(209, 900), _Span(6, 20)) == 0.0- assert _recovered_fraction("complex_method", _Shape(209, 900), _Span(6, 20)) == 0.0+def test_detector_offers_the_next_best_span_when_the_best_misses_the_floor():+ fn = _first(_PROCESS)+ lmap = get_language_map("python")+ candidates = find_extractions(fn, lmap)+ worth = [c for c in candidates if _worth_extracting(fn, c, {"complex_method"})]+ assert worth+ findings = [_Finding("complex_method", "process", line_start=2, health_impact=1.5)]+ (s,) = ExtractMethodDetector().detect(_ctx(_PROCESS, findings))+ assert s.plan["span"] == {"start": worth[0].start_line, "end": worth[0].end_line}-def test_helper_that_inherits_the_smell_is_charged_against_the_recovery():- # 130-line method (high) lifts 100 lines out: the residual clears the bar- # but the helper is itself a 100-line large_method (medium).- got = _recovered_fraction("large_method", _Shape(12, 130), _Span(6, 100))- assert 0.0 < got < 1.0+def test_slice_nloc_counts_code_lines_not_comments():+ src = """+ def tally(items, limit):+ total = 0+ # Comments inside the span are documentation, not code to move.+ # They used to count toward the span's size and its credit.+ for x in items:+ # skip what is over the limit+ if x > limit:+ total += limit+ else:+ total += x+ return total+ """+ fn = _first(src)+ lmap = get_language_map("python")+ loop = [c for c in find_extractions(fn, lmap) if c.end_line - c.start_line >= 7]+ assert loop+ assert all(c.slice_nloc <= c.end_line - c.start_line + 1 - 2 for c in loop)-def test_detector_credits_only_what_the_best_extraction_recovers():- # The finding claims a CCN far above what _PROCESS's best span can clear,- # so the plan still stands but recovers nothing.- fns = _analyses(_PROCESS)- fn = fns[0]- fn.ccn, fn.nloc = 40, 18+def test_confidence_high_needs_a_real_share():+ findings = [_Finding("complex_method", "process", line_start=2, health_impact=1.5)]+ fn = _first(_PROCESS)+ (s,) = ExtractMethodDetector().detect(_ctx(_PROCESS, findings))+ assert s.confidence == "high"+ # The same span out of a much larger function moves almost nothing.+ fn.ccn = 250+ ctx = RefactoringContext(+ file_path="m.py", language="python", nloc=100, findings=findings, function_analyses=[fn]+ )+ (s,) = ExtractMethodDetector().detect(ctx)+ assert s.confidence == "medium"+++def _parse(lang: str, src: str):+ try:+ from tree_sitter import Parser++ from repowise.core.ingestion.parser import _get_language+ except Exception:+ pytest.skip("tree-sitter missing")+ grammar = _get_language(lang)+ if grammar is None:+ pytest.skip(f"tree-sitter language pack missing for {lang}")+ root = Parser(grammar).parse(textwrap.dedent(src).encode()).root_node+ stack = [root]+ while stack:+ node = stack.pop()+ if node.type == "function_declaration":+ return node+ stack.extend(node.children)+ raise AssertionError("no function")+++def test_jsx_prop_plumbing_is_not_offered_an_extraction():+ # TriageTab's shape: the branching is conditional spreads and template+ # ternaries wiring props, not logic a helper would simplify.+ node = _parse(+ "tsx",+ """+ function Tab({ id, scope, counts, lens }) {+ const key = `${id}${scope ? `:${scope}` : ""}`;+ return (+ <View+ k={key}+ {...(scope ? { scope } : {})}+ {...(counts ? { counts } : {})}+ {...(lens ? { lens } : {})}+ />+ );+ }+ """,+ )+ assert jsx_plumbing_dominates(node, get_language_map("tsx"))+++def test_component_with_real_logic_is_still_eligible():+ node = _parse(+ "tsx",+ """+ function Lede({ a, b, items }) {+ let n = 0;+ for (const x of items) {+ if (x > a) {+ n += 1;+ } else if (x < b) {+ n -= 1;+ }+ }+ return <p>{n > 0 && <b>{n}</b>}</p>;+ }+ """,+ )+ assert not jsx_plumbing_dominates(node, get_language_map("tsx"))+ # No JSX at all: never gated, whatever the shape.+ plain = _parse("typescript", "function f(a) { return a ? { ...(a && { a }) } : {}; }")+ assert not jsx_plumbing_dominates(plain, get_language_map("typescript"))+++def test_spreads_and_conditionals_outside_the_markup_are_logic():+ # The same shapes the gate reads as wiring inside JSX are ordinary logic+ # in the component body: a config object built before the return.+ node = _parse(+ "tsx",+ """+ function Panel({ defaults, a, b, c, d }) {+ const cfg = { ...defaults, x: a && b, y: c ? d : null, z: c || d };+ return <View cfg={cfg} />;+ }+ """,+ )+ assert not jsx_plumbing_dominates(node, get_language_map("tsx"))+++def test_a_best_span_below_the_floor_yields_to_the_next_one(monkeypatch):+ from repowise.core.analysis.health.dataflow import Extraction+ from repowise.core.analysis.health.refactoring import extract_method++ trivial = Extraction(10, 17, ("a",), (), slice_nloc=8, ccn_removed=1)+ worth = Extraction(20, 25, ("b",), (), slice_nloc=6, ccn_removed=3)+ monkeypatch.setattr(extract_method, "find_extractions", lambda _a, _l: [trivial, worth])+ fn = _Shape(12, 40)+ analysis = type(+ "A", (), {"name": "f", "start_line": 1, "end_line": 50, "ccn": 12, "nloc": 40,+ "fn_node": None}+ )()+ assert not _worth_extracting(fn, trivial, {"complex_method"})ctx = RefactoringContext(file_path="m.py",language="python",nloc=100,- findings=[_Finding("complex_method", "process", line_start=2, health_impact=2.0)],- function_analyses=[fn],+ findings=[_Finding("complex_method", "f", 1, 1.2)],+ function_analyses=[analysis],)(s,) = ExtractMethodDetector().detect(ctx)- assert s.source_biomarker == "complex_method"- assert s.impact_delta == 0.0+ assert s.plan["span"] == {"start": 20, "end": 25}+ assert s.impact_delta == round(1.2 * 3 / 12, 3)diff --git a/tests/unit/health/test_refactoring_identity_contract.py b/tests/unit/health/test_refactoring_identity_contract.pyindex 7c14fb13c..d08003d15 100644--- a/tests/unit/health/test_refactoring_identity_contract.py+++ b/tests/unit/health/test_refactoring_identity_contract.py@@ -21,8 +21,8 @@ from repowise.core.analysis.health.refactoring.identity import (refactoring_public_id,)-EXTRACT_METHOD_ID = "refac2_f98f466eecc2dd332485"-CLONE_ID = "refac2_e0d9feee45201e014bc3"+EXTRACT_METHOD_ID = "refac3_f98f466eecc2dd332485"+CLONE_ID = "refac3_e0d9feee45201e014bc3"def _extract_method(**overrides):@@ -86,7 +86,7 @@ def _clone(**overrides):def test_the_model_version_is_pinned_and_is_carried_by_the_id_prefix() -> None:- assert REFACTORING_MODEL_VERSION == 2+ assert REFACTORING_MODEL_VERSION == 3assert refactoring_public_id(_extract_method()) == EXTRACT_METHOD_IDassert refactoring_public_id(_clone()) == CLONE_IDassert EXTRACT_METHOD_ID.startswith(f"refac{REFACTORING_MODEL_VERSION}_")@@ -99,6 +99,7 @@ def test_the_model_version_is_pinned_and_is_carried_by_the_id_prefix() -> None:(EXTRACT_METHOD_ID, "current"),("refac_" + "0" * 20, "stale_model"),("refac1_" + "0" * 20, "stale_model"),+ ("refac2_f98f466eecc2dd332485", "stale_model"),("plan_" + "0" * 20, "unrecognized"),("", "unrecognized"),],diff --git a/tests/unit/health/test_refactoring_opportunity.py b/tests/unit/health/test_refactoring_opportunity.pyindex 55e17f381..5efc11bf6 100644--- a/tests/unit/health/test_refactoring_opportunity.py+++ b/tests/unit/health/test_refactoring_opportunity.py@@ -321,7 +321,7 @@ def test_the_id_is_built_over_the_member_plan_ids() -> None:assert opportunity.opportunity_id == opportunity_public_id([step.plan_id for step in opportunity.steps], "svc/orders.py")- assert opportunity.opportunity_id.startswith("refop2_")+ assert opportunity.opportunity_id.startswith("refop3_")def test_the_id_survives_a_uniform_line_shift() -> None:@@ -450,3 +450,23 @@ def test_a_finding_several_steps_answer_is_recovered_once() -> None:assert without.recoverable_health == pytest.approx(2.2)assert deduped.recoverable_health == pytest.approx(1.7)assert deduped.rank_factors["benefit"] == pytest.approx(1.7)+++def test_work_that_recovers_health_ranks_ahead_of_zero_credit_work():+ """A cycle's detector-native benefit outscored every proportionally credited+ extraction on this repo. It stays listed, after the credited work."""+ from types import SimpleNamespace++ from repowise.core.analysis.health.refactoring.opportunity_rank import rank_sort_key++ cycle = SimpleNamespace(+ rank_score=0.78, recoverable_health=0.0, file_path="a.py", opportunity_id="o1"+ )+ small = SimpleNamespace(+ rank_score=0.21, recoverable_health=0.21, file_path="b.py", opportunity_id="o2"+ )+ split = SimpleNamespace(+ rank_score=0.42, recoverable_health=0.0, file_path="c.py", opportunity_id="o3"+ )+ ordered = sorted([cycle, small, split], key=rank_sort_key)+ assert [o.opportunity_id for o in ordered] == ["o2", "o1", "o3"]diff --git a/tests/unit/persistence/test_refactoring_lifecycle.py b/tests/unit/persistence/test_refactoring_lifecycle.pyindex 871ad01a5..14ba4c9d0 100644--- a/tests/unit/persistence/test_refactoring_lifecycle.py+++ b/tests/unit/persistence/test_refactoring_lifecycle.py@@ -69,7 +69,7 @@ async def test_an_unchanged_plan_keeps_its_row_and_its_public_id(async_session):assert len(before) == 2assert after == before, "a second analysis of unchanged source must not mint new rows"- assert all(key.startswith("refac2_") for key in after)+ assert all(key.startswith("refac3_") for key in after)@pytest.mark.asynciodiff --git a/tests/unit/server/mcp/test_performance_levels.py b/tests/unit/server/mcp/test_performance_levels.pyindex efb008274..b604777b9 100644--- a/tests/unit/server/mcp/test_performance_levels.py+++ b/tests/unit/server/mcp/test_performance_levels.py@@ -294,7 +294,7 @@ async def test_one_id_returns_the_cause_its_plan_and_its_rank_rationale(assert result["intervention_symbol"] == "src/shared.py::load"assert result["plan_status"] == "available"# The plan address space is the refactoring layer's content identity.- assert result["plan_reference"].startswith("refac2_")+ assert result["plan_reference"].startswith("refac3_")assert result["confidence"] == "high"assert result["fix"]["safety"] == "advisory"assert [step["order"] for step in result["plan_steps"]] == [1, 2, 3, 4, 5]@@ -428,7 +428,7 @@ async def test_the_lede_links_the_exact_plan_for_the_exact_lead(setup_mcp, mater)lede = result["recommendation_lede"]assert lede["performance_plan_id"] is not None- assert lede["performance_plan_id"].startswith("refac2_")+ assert lede["performance_plan_id"].startswith("refac3_")plan = await get_health(plan_id=lede["performance_plan_id"])assert plan["resolved"] is Truediff --git a/tests/unit/server/mcp/test_refactoring.py b/tests/unit/server/mcp/test_refactoring.pyindex b73b7420e..7c35d34d0 100644--- a/tests/unit/server/mcp/test_refactoring.py+++ b/tests/unit/server/mcp/test_refactoring.py@@ -107,7 +107,7 @@ async def test_generate_code_disabled(factory, _mcp_globals) -> None:result = await generate_refactoring_code(sid)assert result["resolved"] is True# The content-derived plan identity, versioned by its prefix.- assert result["suggestion_id"].startswith("refac2_")+ assert result["suggestion_id"].startswith("refac3_")assert result["generation"]["available"] is Falseassert result["generation"]["reason"] == "disabled"diff --git a/tests/unit/server/test_refactoring.py b/tests/unit/server/test_refactoring.pyindex 3633ec703..1252b463c 100644--- a/tests/unit/server/test_refactoring.py+++ b/tests/unit/server/test_refactoring.py@@ -694,7 +694,7 @@ async def test_plan_status_round_trips_and_hides_the_row(client: AsyncClient, apassert body["status"] == "acknowledged"assert body["status_reason"] == "user"assert body["status_changed_at"] is not None- assert body["public_id"].startswith("refac2_")+ assert body["public_id"].startswith("refac3_")resp = await client.patch(f"/api/repos/{repo_id}/refactoring/{target['id']}/status",diff --git a/tests/unit/server/test_refactoring_opportunities.py b/tests/unit/server/test_refactoring_opportunities.pyindex d9bbb6956..f98804f77 100644--- a/tests/unit/server/test_refactoring_opportunities.py+++ b/tests/unit/server/test_refactoring_opportunities.py@@ -122,7 +122,7 @@ async def test_finalizer_composes_one_opportunity_per_file(client, app):assert body["total"] == 5assert len({item["file_path"] for item in body["items"]}) == 5for item in body["items"]:- assert item["opportunity_id"].startswith("refop2_")+ assert item["opportunity_id"].startswith("refop3_")assert item["step_count"] == 1# The lead was supplied, so this is a real answer rather than unknown.assert item["addresses_primary_problem"] is True@@ -376,7 +376,7 @@ async def test_bare_get_health_carries_one_bounded_refactoring_directive(client,result = await get_health()directive = result["refactoring_directive"]assert directive["status"] == "available"- assert directive["opportunity_id"].startswith("refop2_")+ assert directive["opportunity_id"].startswith("refop3_")assert directive["next_action"]["arguments"]["opportunity_id"] == directive["opportunity_id"]assert directive["opportunities_total"] == 12# Level 0 is a lead, not a queue: it must stay small enough to survive.@@ -511,7 +511,7 @@ async def test_a_plan_id_resolves_to_the_opportunity_that_owns_it(client, app):async def test_an_unknown_opportunity_id_says_which_kind_of_unknown(client, app):await _seed(client, app, files=2)get_health = await _mcp(app)- missing = await get_health(opportunity_id="refop2_" + "0" * 20)+ missing = await get_health(opportunity_id="refop3_" + "0" * 20)assert missing["found"] is Falseassert missing["model_state"]["state"] == "current"stale = await get_health(opportunity_id="refop1_" + "0" * 20)@@ -913,3 +913,32 @@ async def test_a_transition_that_writes_nothing_is_not_reported_as_success(clienassert row is not None# Untouched, rather than silently reset to open.assert row.status == "open"+++def test_the_diversified_queue_never_gives_a_zero_credit_group_a_head_slot():+ from types import SimpleNamespace++ from repowise.core.persistence.crud.analysis.refactoring_opportunities import (+ _diversified_order,+ )++ def item(path, kind, health):+ return SimpleNamespace(+ file_path=path,+ lead_biomarker="complex_method" if health else None,+ lead_refactoring_type=kind,+ recoverable_health=health,+ )++ # Rank order: credited first, zero-credit after (``rank_sort_key``).+ ranked = [+ item("pkg/a/x.py", "extract_method", 0.9),+ item("pkg/a/y.py", "extract_method", 0.8),+ item("pkg/b/z.py", "extract_method", 0.3),+ item("pkg/c/cycle.py", "break_cycle", 0.0),+ item("pkg/d/split.py", "split_file", 0.0),+ ]+ order = _diversified_order(ranked)+ assert order[:3] != [0, 1, 2] # still interleaves the credited work+ assert sorted(order[:3]) == [0, 1, 2]+ assert order[3:] == [3, 4]