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
feat(health): Fix first says when its plan is a staged split (#3392)
Raghav Chamadiya92e343eeb7fd
diff --git a/packages/core/src/repowise/core/analysis/health/fix_first/build.py b/packages/core/src/repowise/core/analysis/health/fix_first/build.pyindex c867ef653..4deaec3ae 100644--- a/packages/core/src/repowise/core/analysis/health/fix_first/build.py+++ b/packages/core/src/repowise/core/analysis/health/fix_first/build.py@@ -362,7 +362,7 @@ class _Files:)return FixStep(1,- f"Extract lines {start}-{end} of {tail} into {into}",+ _stage_one(f"Extract lines {start}-{end} of {tail} into {into}", tail, body),path,start,**_helper_code(body),@@ -594,7 +594,7 @@ def _refactor_step(is_async=bool(body.get("needs_async", False)),)where = f"lines {start}-{end} of {sym}" if start and end else f"part of {sym}"- line_text = f"Extract {where} into {into}"+ line_text = _stage_one(f"Extract {where} into {into}", sym, body)elif kind == "extract_helper":line_text = f"Replace the duplicate in {sym} with a call to one shared helper"elif kind == "extract_class":@@ -636,6 +636,42 @@ def _refactor_step()+def _stage_count(body: Mapping[str, Any]) -> int:+ """How many helpers a staged Extract Method plan splits its function into;+ 0 when unstaged. Counts stages with a span, as the plan detail page does,+ and fewer than two is no split."""+ stages = body.get("stages")+ if not isinstance(stages, (list, tuple)):+ return 0+ count = sum(_has_span(stage) for stage in stages)+ return count if count >= 2 else 0+++def _has_span(stage: Any) -> bool:+ """A stage with nonzero integer line bounds (a bool is not a line)."""+ span = stage.get("span") if isinstance(stage, dict) else None+ if not isinstance(span, dict):+ return False+ start, end = span.get("start"), span.get("end")+ return type(start) is int and type(end) is int and bool(start and end)+++def _stage_one(line_text: str, sym: str, body: Mapping[str, Any]) -> str:+ """A staged plan's step is its first stage (the plan's top-level span),+ so it says so and names what the whole plan does."""+ count = _stage_count(body)+ if not count:+ return line_text+ residual = body.get("orchestrator")+ before, after = (+ (residual.get("ccn_before"), residual.get("ccn_after"))+ if isinstance(residual, dict)+ else (None, None)+ )+ ccn = f", CCN {before} -> {after}" if before is not None and after is not None else ""+ return f"Stage 1 of {count}: {line_text} (the plan splits {sym} into {count} helpers{ccn})"++def _uncut_cycle_text(path: str, plan: Any) -> str:"""A cycle step with no import line to cut, labelled when it is idiomatic."""if _plan_body(plan).get("idiom"):@@ -874,8 +910,16 @@ def _refactor_fix_steps(def _refactor_title(plan: _RefactorPlan, lead_plan: Any) -> str:- """A big function's first lift names the problem and the span; any other- plan reads its title off the lead step's kind."""+ """A staged plan names how many helpers it splits the function into, a big+ function's first lift names the problem and the span, and any other plan+ reads its title off the lead step's kind."""+ stages = _stage_count(_plan_body(lead_plan)) if plan.lead_type == "extract_method" else 0+ if stages:+ return _with_more_steps(plan, f"Split {plan.sym} into {stages} helpers")+ return _span_title(plan, lead_plan)+++def _span_title(plan: _RefactorPlan, lead_plan: Any) -> str:start, end = _span(lead_plan)name = _plan_body(lead_plan).get("suggested_name") or NAME_PLACEHOLDERspanned = plan.lead_type == "extract_method" and bool(start and end)@@ -884,6 +928,10 @@ def _refactor_title(plan: _RefactorPlan, lead_plan: Any) -> str:title = text.REFACTOR_TITLE.get("extract_method_span" if spanned else plan.lead_type, "Refactor {file}").format(sym=plan.sym, file=text.basename(plan.path), start=start, end=end, name=name)+ return _with_more_steps(plan, title)+++def _with_more_steps(plan: _RefactorPlan, title: str) -> str:if len(plan.steps) > 1:title += f" (+{text.plural(len(plan.steps) - 1, 'more step')})"return titlediff --git a/tests/unit/health/test_fix_first_build.py b/tests/unit/health/test_fix_first_build.pyindex 024a95a86..258ae2157 100644--- a/tests/unit/health/test_fix_first_build.py+++ b/tests/unit/health/test_fix_first_build.py@@ -4,6 +4,8 @@ from __future__ import annotationsimport copy+import pytest+from repowise.core.analysis.health.fix_first import FIX_EXCLUSIONS, build_fix_firstfrom tests.unit.health.fix_first_rows import (FINDINGS,@@ -368,3 +370,77 @@ def test_an_item_no_test_reaches_says_to_pin_its_behaviour_first() -> None:queue = _build(validate=lambda *_: {"prerequisite": first})walk = next(i for i in queue.items if i.target.file_path == "src/plain.py")assert (walk.verify.basis, walk.verify.prerequisite) == ("unknown", first)+++def _staged_plans(count: int = 3, orchestrator: dict | None = None) -> list:+ plans = copy.deepcopy(PLANS)+ stage = {k: v for k, v in plans[0]["plan"].items() if k != "stages"}+ plans[0]["plan"]["stages"] = [copy.deepcopy(stage) for _ in range(count)]+ plans[0]["plan"]["orchestrator"] = (+ {"ccn_before": 44, "ccn_after": 9} if orchestrator is None else orchestrator+ )+ return plans+++def test_a_staged_lead_plan_names_its_helpers_and_stage_one() -> None:+ core = next(i for i in _build(plans=_staged_plans()).items if i.kind == "refactor")+ assert core.title == "Split run into 3 helpers (+1 more step)"+ assert core.action.steps[0].text == (+ "Stage 1 of 3: Extract lines 20-35 of run into sum_rows(rows, limit) -> total "+ "(the plan splits run into 3 helpers, CCN 44 -> 9)"+ )+ # Only the staged plan's step says so; the plan's next step reads as before.+ assert core.action.steps[1].text == (+ "Extract lines 40-41 of run into <name>(); name it for what the lines do"+ )+++def test_a_staged_plan_without_its_complexity_figures_leaves_them_out() -> None:+ core = next(+ i for i in _build(plans=_staged_plans(2, orchestrator={})).items if i.kind == "refactor"+ )+ assert core.action.steps[0].text.endswith("(the plan splits run into 2 helpers)")+++def test_a_finding_borrowing_a_staged_span_says_it_is_staged() -> None:+ plans = _staged_plans()+ plans[0].update(file_path="src/core.py", target_symbol="src/core.py::run")+ lone = _build(plans=plans, refactoring=[], performance=[]).lead+ assert lone.action.steps[0].text == (+ "Stage 1 of 3: Extract lines 20-35 of run into sum_rows(rows, limit) -> total "+ "(the plan splits run into 3 helpers, CCN 44 -> 9)"+ )+++ ("stages", "orchestrator"),+ [+ ("not a list", {"ccn_before": 44, "ccn_after": 9}),+ ([None, 3, "x"], {"ccn_before": 44, "ccn_after": 9}),+ ([{"span": {"start": 20, "end": 35}}], {"ccn_before": 44, "ccn_after": 9}),+ ([{"span": {"start": 20}}, {"span": None}], {"ccn_before": 44}),+ ([{"span": {"start": 20, "end": 35}}, {"span": {"start": 36, "end": 40}}], "bad"),+ ([{"span": {"start": 20, "end": 35}}, {"span": {"start": 36, "end": 40}}], {"ccn_after": 9}),+ ([{"span": {"start": "20", "end": "35"}}, {"span": {"start": "a", "end": "b"}}], {}),+ ([{"span": {"start": True, "end": True}}, {"span": {"start": 36, "end": 40}}], {}),+ ([{"span": {"start": 1.5, "end": 9.0}}, {"span": {"start": 36, "end": 40}}], {}),+ ],+)+def test_malformed_stages_never_crash_or_say_one_helper(stages, orchestrator) -> None:+ plans = copy.deepcopy(PLANS)+ plans[0]["plan"].update(stages=stages, orchestrator=orchestrator)+ core = next(i for i in _build(plans=plans).items if i.kind == "refactor")+ step = core.action.steps[0].text+ assert "into 1 helpers" not in step and "into 1 helpers" not in core.title+ if step.startswith("Stage 1 of 2"):+ assert step.endswith("(the plan splits run into 2 helpers)")+ else:+ assert step == "Extract lines 20-35 of run into sum_rows(rows, limit) -> total"+++def test_an_unstaged_plan_reads_as_before() -> None:+ core = next(i for i in _build().items if i.kind == "refactor")+ assert core.title == (+ "Start breaking up run (CCN 44, 50 lines): first lift lines 20-35 into sum_rows"+ )+ assert core.action.steps[0].text == "Extract lines 20-35 of run into sum_rows(rows, limit) -> total"