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.

fix(refactoring): attach only the findings a step's target answers (#2571)

Raghav Chamadiyacad84b064104
diff --git a/docs/layers/REFACTORING.md b/docs/layers/REFACTORING.md
index f1b2ca613..7691bfb99 100644
--- a/docs/layers/REFACTORING.md
+++ b/docs/layers/REFACTORING.md
@@ -119,7 +119,7 @@ page cost the whole repository.
| `steps[].applicability` | `mechanical` or `judgment`, with the reasons and the facts behind it, and the facts it could not establish under `unknowns`. Extraction is the only mechanical class. |
| `steps[].relocated_by` | An earlier step that moves this step's symbol to another file. The step's own `file_path` and span describe where the symbol *was*: locate it again before applying. Any surface that renders an ordered step list must say so. |
| `status` | Rolled up from the member plans' triage. Resolved only when every step is; one step marked a false positive does not resolve the rest. An `acknowledged` step is still outstanding work, so it keeps composing. |
-| `steps[].finding_ids` | The findings this step's cause produced, so a step round-trips to its diagnosis through `get_health(finding_id=...)`. The key is **omitted entirely** when no finding on the file is addressable by id (a store written before findings carried public ids); an empty list means "none for this cause", which is a different answer. `lead_finding_ids` on the opportunity follows the same rule. |
+| `steps[].finding_ids` | The findings this step's own target answers (its source biomarker's findings on the same symbol and span, never every finding of that biomarker in the file), so a step round-trips to its diagnosis through `get_health(finding_id=...)`. The key is **omitted entirely** when no finding on the file is addressable by id (a store written before findings carried public ids); an empty list means "none for this cause", which is a different answer. `lead_finding_ids` on the opportunity follows the same rule. |
| `steps[].validation_profile_id` | Points into the opportunity's `validation_profiles`. Resolved once at index time; the test-reachability walk behind it is never repeated per request. |
`performance_fix` plans are excluded by construction: the performance layer
diff --git a/packages/cli/src/repowise/cli/commands/health_cmd/refactoring_targets.py b/packages/cli/src/repowise/cli/commands/health_cmd/refactoring_targets.py
index ab41c7338..6f0cd57d9 100644
--- a/packages/cli/src/repowise/cli/commands/health_cmd/refactoring_targets.py
+++ b/packages/cli/src/repowise/cli/commands/health_cmd/refactoring_targets.py
@@ -180,7 +180,9 @@ def _compose(findings: list, suggestions: list) -> tuple[list, dict]:
from repowise.core.analysis.health.refactoring.opportunity import compose_opportunities
leads = primary_biomarker_by_file(findings) if findings else {}
- opportunities = compose_opportunities(suggestions, primary_biomarker_by_file=leads)
+ opportunities = compose_opportunities(
+ suggestions, primary_biomarker_by_file=leads, findings=findings or None
+ )
return opportunities, leads
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 4fcc1c9f8..66772ad42 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/opportunity.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/opportunity.py
@@ -27,6 +27,13 @@ across files *and* co-changed. The rest still appears, attached to the file's
opportunity as the supporting evidence it always was, never as an instruction.
Nothing is deleted: the plans remain plans, addressable by id.
+**A finding is recovered once.** A step names the findings its own target
+answers: the source biomarker's findings whose span it covers, and for a
+named finding only the one on the same symbol. Two steps answering one
+finding (a file-level clone finding several blocks overlap) are credited
+once, at the larger claim, in both ``recoverable_health`` and the rank's
+benefit.
+
``performance_fix`` is excluded. Those rows belong to the performance layer,
which composes and ranks its own opportunities and owns their lifecycle; folding
them in here would publish the same work twice under two ids.
@@ -38,6 +45,7 @@ from collections.abc import Iterable, Mapping, Sequence
from dataclasses import dataclass
from typing import Any
+from ..rows import field
from .extract_helper import ACTIVE_CO_CHANGE
from .identity import REFACTORING_MODEL_VERSION, assign_public_ids, stable_id
from .models import RefactoringSuggestion
@@ -116,6 +124,10 @@ class OpportunityStep:
# another file, so this one's location must be re-derived before it is
# applied. ``None`` when nothing ahead of it relocates anything.
relocated_by: str | None
+ # Public ids of the findings this step's target answers. ``None`` when no
+ # 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
def as_dict(self) -> dict[str, Any]:
return {
@@ -131,6 +143,7 @@ class OpportunityStep:
"source_biomarker": self.source_biomarker,
"relocated_by": self.relocated_by,
"applicability": self.applicability.as_dict(),
+ **({"finding_ids": list(self.finding_ids)} if self.finding_ids is not None else {}),
}
@@ -289,9 +302,69 @@ def opportunity_public_id(step_plan_ids: Sequence[str], file_path: str) -> str:
)
+def step_answers(suggestion: RefactoringSuggestion, finding: Any) -> bool:
+ """Whether *finding* is one *suggestion*'s target answers.
+
+ Same biomarker, same symbol when the finding names one, and an overlapping
+ span when both carry lines. A file-level finding (no lines) is answered by
+ any step on its biomarker, as the detectors credit it.
+ """
+ if not suggestion.source_biomarker:
+ return False
+ if field(finding, "biomarker_type") != suggestion.source_biomarker:
+ return False
+ name = field(finding, "function_name")
+ if name and name != suggestion.target_symbol:
+ return False
+ start = field(finding, "line_start")
+ if start is None or suggestion.line_start is None or suggestion.line_end is None:
+ return True
+ end = field(finding, "line_end") or start
+ return start <= suggestion.line_end and end >= suggestion.line_start
+
+
+def _finding_key(finding: Any) -> Any:
+ return field(finding, "public_id") or (
+ field(finding, "biomarker_type"),
+ field(finding, "function_name"),
+ field(finding, "line_start"),
+ )
+
+
+def _credited(
+ step_rows: Sequence[tuple[RefactoringSuggestion, str]],
+ findings: Sequence[Any] | None,
+) -> set[str]:
+ """Plan ids whose gain counts toward the set: largest claim first, and a
+ step answering a finding an earlier one already recovered adds nothing."""
+ if findings is None:
+ return {plan_id for _, plan_id in step_rows}
+ claimed: set[Any] = set()
+ credited: set[str] = set()
+ for suggestion, plan_id in sorted(
+ step_rows, key=lambda row: -float(row[0].impact_delta or 0.0)
+ ):
+ keys = {_finding_key(f) for f in findings if step_answers(suggestion, f)}
+ if keys & claimed:
+ continue
+ claimed |= keys
+ credited.add(plan_id)
+ return credited
+
+
def _step_of(
- suggestion: RefactoringSuggestion, plan_id: str, relocated_by: str | None
+ suggestion: RefactoringSuggestion,
+ plan_id: str,
+ relocated_by: str | None,
+ findings: Sequence[Any] | None,
) -> OpportunityStep:
+ finding_ids = None
+ if findings is not None and any(field(f, "public_id") for f in findings):
+ finding_ids = tuple(
+ field(f, "public_id")
+ for f in findings
+ if field(f, "public_id") and step_answers(suggestion, f)
+ )
return OpportunityStep(
plan_id=plan_id,
refactoring_type=suggestion.refactoring_type,
@@ -305,6 +378,7 @@ def _step_of(
source_biomarker=suggestion.source_biomarker,
relocated_by=relocated_by,
applicability=classify_step(suggestion),
+ finding_ids=finding_ids,
)
@@ -324,6 +398,7 @@ def _evidence_of(suggestion: RefactoringSuggestion, plan_id: str) -> Opportunity
def _sequence(
step_rows: Sequence[tuple[RefactoringSuggestion, str]],
+ findings: Sequence[Any] | None,
) -> list[OpportunityStep]:
"""Build the steps in execution order, marking the ones a move displaces.
@@ -336,7 +411,7 @@ def _sequence(
steps: list[OpportunityStep] = []
relocated_by: str | None = None
for suggestion, plan_id in step_rows:
- steps.append(_step_of(suggestion, plan_id, relocated_by))
+ steps.append(_step_of(suggestion, plan_id, relocated_by, findings))
if suggestion.refactoring_type in _RELOCATING_TYPES:
relocated_by = plan_id
return steps
@@ -346,6 +421,7 @@ def _compose_one(
file_path: str,
members: Sequence[tuple[RefactoringSuggestion, str]],
primary_biomarker: str | None,
+ findings: Sequence[Any] | None,
) -> RefactoringOpportunity | None:
ordered = sorted(members, key=_member_sort_key)
step_rows = [row for row in ordered if _is_step(row[0])]
@@ -354,7 +430,7 @@ def _compose_one(
# own; there is simply no composed refactoring to publish for this file.
return None
- steps = tuple(_sequence(step_rows))
+ steps = tuple(_sequence(step_rows, findings))
evidence = tuple(
_evidence_of(suggestion, plan_id)
for suggestion, plan_id in ordered
@@ -362,11 +438,14 @@ def _compose_one(
)
step_suggestions = [suggestion for suggestion, _ in step_rows]
+ credited = _credited(step_rows, findings)
touched = sorted({path for item in step_suggestions for path in affected_files(item)})
biomarker, lead_type, addresses = _lead(steps, primary_biomarker)
mechanical = sum(1 for step in steps if step.applicability.mechanical)
factors = rank_factors(
- benefit=opportunity_benefit(step_suggestions),
+ benefit=opportunity_benefit(
+ [suggestion for suggestion, plan_id in step_rows if plan_id in credited]
+ ),
addresses_primary_problem=addresses is True,
mechanical_share=mechanical / len(steps),
cost=step_cost(step_suggestions),
@@ -381,7 +460,7 @@ def _compose_one(
addresses_primary_problem=addresses,
steps=steps,
evidence=evidence,
- recoverable_health=sum(step.impact_delta for step in steps),
+ recoverable_health=sum(step.impact_delta for step in steps if step.plan_id in credited),
mechanical_steps=mechanical,
judgment_steps=len(steps) - mechanical,
affected_files=tuple(touched),
@@ -397,6 +476,7 @@ def compose_opportunities(
rows: Iterable[Any],
*,
primary_biomarker_by_file: Mapping[str, str] | None = None,
+ findings: Iterable[Any] | None = None,
) -> list[RefactoringOpportunity]:
"""Fold plans into one ranked opportunity per file.
@@ -409,8 +489,18 @@ def compose_opportunities(
(:func:`..models.primary_biomarker_by_file`). Supplying it is what makes
``addresses_primary_problem`` a real question; omitting it leaves the answer
explicitly unknown rather than assumed.
+
+ *findings* are the repository's health findings. Supplying them is what
+ attaches each step's ``finding_ids`` and credits a finding once when
+ several steps answer it; omitting them leaves both unknown and sums every
+ step's own impact.
"""
leads = primary_biomarker_by_file or {}
+ findings_by_file: dict[str, list[Any]] | None = None
+ if findings is not None:
+ findings_by_file = {}
+ for finding in findings:
+ findings_by_file.setdefault(field(finding, "file_path"), []).append(finding)
suggestions = [
suggestion
for suggestion in (rehydrate_suggestion(row) for row in rows)
@@ -425,7 +515,12 @@ def compose_opportunities(
opportunity
for file_path in sorted(by_file)
if (
- opportunity := _compose_one(file_path, by_file[file_path], leads.get(file_path))
+ opportunity := _compose_one(
+ file_path,
+ by_file[file_path],
+ leads.get(file_path),
+ None if findings_by_file is None else findings_by_file.get(file_path, []),
+ )
)
is not None
]
@@ -480,4 +575,5 @@ __all__ = [
"opportunity_public_id",
"opportunity_status",
"roll_up_status",
+ "step_answers",
]
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 42aa2b799..794027d07 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
@@ -145,14 +145,6 @@ def _details_payload(
profile_id = _validation_profile_id(validation)
profiles.setdefault(profile_id, {"id": profile_id, **validation})
payload["validation_profile_id"] = profile_id
- # The findings this step's cause names, so an agent can round-trip from
- # a step back to the diagnosis that produced it in one call. Emitted
- # only when this file has addressable findings at all: on a store
- # written before findings carried public ids there are none, and an
- # empty list there would claim "this cause produced no finding" when
- # the truth is "no finding here is addressable by id".
- if finding_ids:
- payload["finding_ids"] = finding_ids.get(step.source_biomarker, [])
steps.append(payload)
return {
"steps": steps,
@@ -305,8 +297,12 @@ async def finalize_refactoring_opportunities(
.all()
)
+ # Findings let each step name the diagnosis its own target answers, so an
+ # agent round-trips from a step to it in one call.
opportunities = compose_opportunities(
- live_plans, primary_biomarker_by_file=primary_biomarker_by_file(findings)
+ live_plans,
+ primary_biomarker_by_file=primary_biomarker_by_file(findings),
+ findings=findings,
)
# Validation is resolved once, here, for exactly the plans that became
diff --git a/tests/unit/health/test_refactoring_opportunity.py b/tests/unit/health/test_refactoring_opportunity.py
index c7776ed01..7975bc22e 100644
--- a/tests/unit/health/test_refactoring_opportunity.py
+++ b/tests/unit/health/test_refactoring_opportunity.py
@@ -340,3 +340,77 @@ def test_dicts_and_dataclasses_compose_to_the_same_opportunity() -> None:
from_objects = compose_opportunities(rows)[0]
from_dicts = compose_opportunities([asdict(row) for row in rows])[0]
assert from_objects.as_dict() == from_dicts.as_dict()
+
+
+# --------------------------------------------------------------------------
+# finding attribution
+# --------------------------------------------------------------------------
+
+
+def finding(public_id: str, function_name: str | None, line_start: int | None, **kwargs):
+ row = {
+ "public_id": public_id,
+ "file_path": "svc/orders.py",
+ "biomarker_type": "complex_method",
+ "function_name": function_name,
+ "line_start": line_start,
+ "line_end": None if line_start is None else line_start + 20,
+ }
+ row.update(kwargs)
+ return row
+
+
+def test_a_step_names_only_the_findings_its_target_answers() -> None:
+ rows = [
+ plan("extract_method", "handle", line_start=10, line_end=40),
+ plan("extract_method", "render", line_start=60, line_end=90),
+ ]
+ findings = [
+ finding("hf_handle", "handle", 10),
+ finding("hf_render", "render", 60),
+ finding("hf_other_biomarker", "handle", 10, biomarker_type="large_method"),
+ finding("hf_elsewhere", "handle", 10, file_path="svc/billing.py"),
+ ]
+ (opportunity,) = compose_opportunities(rows, findings=findings)
+ ids = {step.target_symbol: step.finding_ids for step in opportunity.steps}
+ assert ids == {"handle": ("hf_handle",), "render": ("hf_render",)}
+ assert opportunity.steps[0].as_dict()["finding_ids"] in (["hf_handle"], ["hf_render"])
+
+
+def test_finding_ids_stay_unknown_without_addressable_findings() -> None:
+ rows = [plan("extract_method")]
+ assert compose_opportunities(rows)[0].steps[0].finding_ids is None
+ unaddressable = [finding("", "handle", 10)]
+ step = compose_opportunities(rows, findings=unaddressable)[0].steps[0]
+ assert step.finding_ids is None
+ assert "finding_ids" not in step.as_dict()
+
+
+def block(name: str, **kwargs) -> RefactoringSuggestion:
+ return plan(
+ "extract_helper",
+ name,
+ evidence={"is_intra_file": False, "co_change_count": 7},
+ blast_radius={"files": ["svc/billing.py"], "file_count": 1},
+ source_biomarker="dry_violation",
+ **kwargs,
+ )
+
+
+def test_a_finding_several_steps_answer_is_recovered_once() -> None:
+ # Two cross-file, co-changed clone blocks both overlap one file-level
+ # dry_violation finding: the file recovers it once, at the larger claim.
+ rows = [
+ block("a", line_start=10, line_end=20, impact_delta=0.7),
+ block("b", line_start=15, line_end=30, impact_delta=0.5),
+ plan("extract_method", "handle", impact_delta=1.0),
+ ]
+ findings = [
+ finding("hf_dry", None, 12, biomarker_type="dry_violation"),
+ finding("hf_handle", "handle", 10),
+ ]
+ (without,) = compose_opportunities(rows)
+ (deduped,) = compose_opportunities(rows, findings=findings)
+ 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)
diff --git a/tests/unit/server/test_refactoring_opportunities.py b/tests/unit/server/test_refactoring_opportunities.py
index 425c74287..7b27b3f15 100644
--- a/tests/unit/server/test_refactoring_opportunities.py
+++ b/tests/unit/server/test_refactoring_opportunities.py
@@ -56,12 +56,14 @@ def _plan(path: str, symbol: str, **over: Any) -> dict[str, Any]:
return plan
-def _finding(path: str, biomarker: str = "complex_method", impact: float = 3.0) -> dict[str, Any]:
+def _finding(
+ path: str, biomarker: str = "complex_method", impact: float = 3.0, function_name: str = "f"
+) -> dict[str, Any]:
return {
"file_path": path,
"biomarker_type": biomarker,
"severity": "high",
- "function_name": "f",
+ "function_name": function_name,
"line_start": 10,
"line_end": 30,
"details": {},
@@ -76,7 +78,11 @@ async def _seed(client: AsyncClient, app, *, files: int = 8) -> str:
repo_id = await _repo(client)
paths = [f"pkg{i % 3}/mod{i}.py" for i in range(files)]
async with app.state.session_factory() as session:
- await crud.save_health_findings(session, repo_id, [_finding(p) for p in paths])
+ await crud.save_health_findings(
+ session,
+ repo_id,
+ [_finding(p, function_name=f"sym{i}") for i, p in enumerate(paths)],
+ )
await crud.save_refactoring_suggestions(
session,
repo_id,