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(fix-first): say when a borrowed plan leaves a function above the break-up bar (#3484)
Raghav Chamadiya044425022152
diff --git a/docs/layers/CODE_HEALTH.md b/docs/layers/CODE_HEALTH.mdindex 1fde1ba82..8c3227976 100644--- a/docs/layers/CODE_HEALTH.md+++ b/docs/layers/CODE_HEALTH.md@@ -131,6 +131,8 @@ worth doing.| `next` | Worth doing, needs judgment || `later` | Real but can wait; the reason is shown |+A refactoring item is `later` when the plan of any of its steps would still leave a function above the break-up bar: it needs more stages before it is worth starting. When a finding's first step borrows such a plan, the finding keeps its tier and the step says the plan alone leaves the function above the bar.+A `now` or `next` item shows its first step and the command that checks it without opening it, on the card, and over MCP for the lead and for each item of an `only=["fix_first"]` page. When no test reaches the code, Verify says to add a characterization test first. An Extract Method step shows the helper's header and the call that replaces the lines, ready to copy. It finds the lines by the text they start and end with, as the plan does, since line numbers move with the first edit; when that text also appears elsewhere in the file, the step says to keep the edit inside its function.Findings, performance causes, refactoring plans and Fix first items are counted thediff --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 0a59dcc59..e162fd716 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@@ -35,7 +35,8 @@ Row shapes (field names are the SQL columns):Plan rows named by a refactoring step: ``public_id``, ``evidence`` /``evidence_json`` and ``plan`` / ``plan_json`` (an extract-method ``span``,``params``, ``returns``, ``suggested_name``, ``anchors``; a move's destination; a- split's named groups; a helper's ``occurrences``). A plan row that also+ split's named groups; a helper's ``occurrences``) and ``rank`` / ``rank_json``+ (``leaves_above_bar``). A plan row that alsocarries ``refactoring_type`` ``extract_method``, ``file_path`` and``target_symbol`` can give a finding with no plan of its own its firstconcrete step. Every Extract Helper plan's occurrences say where verified@@ -99,6 +100,8 @@ from repowise.core.analysis.health.suggestions import suggestion_forfrom repowise.core.analysis.health.worth import (SIZE_MARKERS,WORTH_MAGNITUDE,+ LowPriority,+ by_function,execution_role,low_priority,magnitude,@@ -402,7 +405,8 @@ class _Files:if best is not None:start, end = _span(best)body = _plan_body(best)- return FixStep(1, _extract_text(tail, body, start, end), path, start, **_helper_code(body))+ step = _above_bar_note(_extract_text(tail, body, start, end), best)+ return FixStep(1, step, path, start, **_helper_code(body))shape = self.shape(path, function)start, end = shape.get("deep_start"), shape.get("deep_end")if start and end:@@ -607,6 +611,23 @@ def _plan_body(plan: Any) -> dict[str, Any]:return body if isinstance(body, dict) else {}+def _above_bar(details: Mapping[str, Any]) -> LowPriority | None:+ """An opportunity one of whose plans, applied as written, still leaves a+ function above the break-up bar: half a fix, so it can wait."""+ return "above_bar_after" if details.get("leaves_above_bar") else None+++def _above_bar_note(step: str, plan: Any) -> str:+ """A finding's borrowed *step*, saying so when the plan, applied as+ written, leaves the function above the break-up bar (its rank facts'+ ``leaves_above_bar``, in the plan's own words)."""+ rank = json_field(plan, "rank", None) or json_field(plan, "rank_json", {})+ reason = rank.get("leaves_above_bar") if isinstance(rank, dict) else None+ if not (isinstance(reason, str) and reason):+ return step+ return f"{step.removesuffix('.')}. This plan alone {reason}."++def _evidence(plan: Any) -> dict[str, Any]:if plan is None:return {}@@ -884,7 +905,7 @@ class _RefactorPlan:central,files.churning(path),cloned=function_size and files.cloned(path, shape),- low=low_priority(marker, shape, function_size=function_size),+ low=low_priority(marker, shape, function_size=function_size) or _above_bar(details),gain=gain,ccn_removed=sum(_extraction_worth(plans.get(s.get("plan_id")))[0] for s in steps),dependents=deps,@@ -1431,15 +1452,6 @@ def _clone_spans(plans: Iterable[Any]) -> dict[str, list[tuple[int, int]]]:return dict(out)-def _by_function(findings: Iterable[Any]) -> dict[tuple[str, str], list[Any]]:- out: dict[tuple[str, str], list[Any]] = defaultdict(list)- for f in findings:- name = field(f, "function_name")- if name:- out[(field(f, "file_path"), name)].append(f)- return dict(out)--def _basis(metrics: Rows) -> dict[str, str | None]:stamped = [(str(at), at, m) for m in metrics if (at := field(m, "updated_at"))]if not stamped:@@ -1478,7 +1490,7 @@ def _prepare(files = _Files(metrics,{p: hist for p, (_shape, hist) in split.items() if hist},- _by_function(f for shape, _hist in split.values() for f in shape),+ by_function(f for shape, _hist in split.values() for f in shape),hot_cuts,_clone_spans(plans),_extractions(plans),diff --git a/packages/core/src/repowise/core/analysis/health/worth.py b/packages/core/src/repowise/core/analysis/health/worth.pyindex 2182e73da..c0ae95d1a 100644--- a/packages/core/src/repowise/core/analysis/health/worth.py+++ b/packages/core/src/repowise/core/analysis/health/worth.py@@ -63,6 +63,7 @@ LowPriority = Literal["not_production","unknown_context","unreached_call",+ "above_bar_after",]#: Why an item can wait, as the tier reason a surface shows beside it.@@ -87,6 +88,7 @@ LOW_PRIORITY_LABEL: dict[str, str] = {"not_production": "lower priority: it runs outside production code","unknown_context": "lower priority: where this code runs is unknown","unreached_call": "lower priority: no entry point is known to reach it",+ "above_bar_after": "lower priority: the plan alone leaves a function above the break-up bar",}#: Findings about one expression or one error site: real, and small to fix.diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/fix_first.py b/packages/core/src/repowise/core/persistence/crud/analysis/fix_first.pyindex 79b608ed9..44dcc693a 100644--- a/packages/core/src/repowise/core/persistence/crud/analysis/fix_first.py+++ b/packages/core/src/repowise/core/persistence/crud/analysis/fix_first.py@@ -390,6 +390,7 @@ async def _plans(s.target_symbol,s.evidence_json,s.plan_json,+ s.rank_json,).where(s.repository_id == repo_id, or_(*wanted))))diff --git a/tests/unit/health/test_fix_first_build.py b/tests/unit/health/test_fix_first_build.pyindex 51a75405e..7516401aa 100644--- a/tests/unit/health/test_fix_first_build.py+++ b/tests/unit/health/test_fix_first_build.py@@ -506,3 +506,49 @@ def test_malformed_anchors_fall_back_to_lines() -> None:plans = _anchored_plans({"first": "a = 1", "last": None})core = next(i for i in _build(plans=plans).items if i.kind == "refactor")assert core.action.steps[0].text == "Extract lines 20-35 of run into sum_rows(rows, limit) -> total"+++def test_a_plan_that_leaves_its_function_above_the_bar_can_wait() -> None:+ from repowise.core.analysis.health.worth import LOW_PRIORITY_LABEL++ rows = copy.deepcopy(REFACTORING)+ rows[0]["details"]["leaves_above_bar"] = (+ "leaves run at CCN 41, still above the break-up bar; more stages needed"+ )+ core = next(i for i in _build(refactoring=rows).items if i.kind == "refactor")+ assert core.tier == "later"+ assert ("tier", LOW_PRIORITY_LABEL["above_bar_after"]) in [+ (f.factor, f.value) for f in core.why_ranked+ ]+ # Without the reason the same plan is worth doing now.+ assert next(i for i in _build().items if i.kind == "refactor").tier == "now"+++def test_a_finding_borrowing_a_plan_that_leaves_it_above_the_bar_says_so() -> None:+ plans = copy.deepcopy(PLANS)+ plans[0].update(+ file_path="src/core.py",+ target_symbol="src/core.py::run",+ rank_json='{"leaves_above_bar": "leaves run at CCN 41, still above the break-up bar; '+ 'more stages needed"}',+ )+ lone = _build(plans=plans, refactoring=[], performance=[]).lead+ # The finding keeps its tier; only its step says the plan is not the whole fix.+ assert lone.tier != "later"+ assert lone.action.steps[0].text == (+ "Extract lines 20-35 of run into sum_rows(rows, limit) -> total. This plan alone "+ "leaves run at CCN 41, still above the break-up bar; more stages needed."+ )+++def test_plans_without_above_bar_facts_read_as_before() -> None:+ # No rank facts, or rank facts without the reason: same steps, same tiers.+ before = _build()+ plans = copy.deepcopy(PLANS)+ for plan in plans:+ plan["rank_json"] = '{"position": 1}'+ for queue in (_build(plans=plans), _build(plans=copy.deepcopy(PLANS))):+ assert [(i.id, i.tier, [s.text for s in i.action.steps]) for i in queue.items] == [+ (i.id, i.tier, [s.text for s in i.action.steps]) for i in before.items+ ]+ assert all("This plan alone" not in s.text for i in before.items for s in i.action.steps)