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(health): keep Fix first item detail about the item itself (#3693)

Swati Ahujad0acf935615f
diff --git a/packages/core/src/repowise/core/analysis/dead_code/file_reachability.py b/packages/core/src/repowise/core/analysis/dead_code/file_reachability.py
index 3d573650a..164bab139 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/file_reachability.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/file_reachability.py
@@ -46,6 +46,7 @@ from repowise.core.entry_candidacy import is_reachability_root
from repowise.core.ids import SYMBOL_SEP, file_path_of, is_external
from ...ingestion.barrels import BARREL_FILENAMES
+from ...ingestion.cohesion import records_no_use
from .constants import never_flag_path
from .cpp_reachability import build_cpp_package_files, is_cpp_file_reachable, is_cpp_path
from .go_reachability import build_go_package_files, is_go_file_reachable
@@ -194,14 +195,18 @@ def _is_structural_edge(neighbor: str, path: str, edge_data: Mapping[str, Any],
return not (SYMBOL_SEP in neighbor and file_path_of(neighbor) == path)
-def file_dependency_neighbors(graph: Any, path: str, *, incoming: bool) -> list[str]:
+def file_dependency_neighbors(
+ graph: Any, path: str, *, incoming: bool, uses_only: bool = False
+) -> list[str]:
"""Structural file neighbours of *path* in the requested direction.
Every file-to-file edge except co-change counts, which keeps import,
type-use, framework and future structural edge types while excluding
symbol containment and historical association. Code we do not own is
excluded outright: this list names files, and a reader following it wants
- somewhere in the repository to go.
+ somewhere in the repository to go. ``uses_only`` also drops edges that
+ record no use (a Go package sibling, the reverse of a header pair):
+ reachability needs them, a count of the files that use *path* does not.
"""
if path not in graph:
return []
@@ -212,6 +217,8 @@ def file_dependency_neighbors(graph: Any, path: str, *, incoming: bool) -> list[
neighbor = source if incoming else target
if is_external(neighbor) or graph.nodes.get(neighbor, {}).get("language") == "external":
continue
+ if uses_only and records_no_use(edge_data, source, target):
+ continue
if _is_structural_edge(neighbor, path, edge_data, graph):
neighbors.append(neighbor)
return neighbors
diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.py
index 5ef073f83..6502a40df 100644
--- a/packages/core/src/repowise/core/analysis/health/engine.py
+++ b/packages/core/src/repowise/core/analysis/health/engine.py
@@ -659,8 +659,9 @@ def _compute_repo_function_mod_p80(
def _dependents_count(graph: Any, path: str) -> int:
- """Distinct files that depend on *path* in code; co-change is history, not a dependent."""
- return len(set(file_dependency_neighbors(graph, path, incoming=True)))
+ """Distinct files that use *path* in code: co-change is history, and a Go
+ package sibling or a synthetic header pair edge uses nothing."""
+ return len(set(file_dependency_neighbors(graph, path, incoming=True, uses_only=True)))
def _compute_repo_dependents_p80(parsed_files: list[Any], graph: Any) -> int | None:
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.py
index 1d106fd1a..217573c4a 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
@@ -191,6 +191,19 @@ def _tail(symbol: str | None) -> str | None:
return re.split(r"::|\.", symbol)[-1] if symbol else None
+def _about(function: str | None, symbol: str | None) -> bool:
+ """Whether a history row on ``function`` speaks to an item on ``symbol``:
+ a file-level row or item, the same function, or a member of the item's
+ class. ``Engine.run`` never keeps ``Other.run``; a bare name on either
+ side matches by name, since it names no class to tell them apart."""
+ if not function or not symbol:
+ return True
+ own = text.short_symbol(symbol) or ""
+ if function == own or function.startswith(f"{own}."):
+ return True
+ return ("." not in function or "." not in own) and _tail(function) == _tail(own)
+
+
def symbol_key(path: str, symbol: str | None) -> str | None:
"""A function's ``git_function_blame`` key, ``path::name``; ``None`` for no symbol."""
name = text.short_symbol(symbol)
@@ -227,7 +240,7 @@ def _quantile_cut(values: list[int]) -> float:
return hot_cut(sorted(values)[hot_cut_offset(len(values))])
-def _risk(files_touched: int, dependents: int | None) -> FixRisk:
+def _risk(files_touched: int, dependents: int | None, *, function: bool = False) -> FixRisk:
deps = dependents or 0
if files_touched >= 5 or deps >= 20:
level = "high"
@@ -237,7 +250,7 @@ def _risk(files_touched: int, dependents: int | None) -> FixRisk:
level = "low"
parts = [f"touches {text.plural(files_touched, 'file')}"]
if dependents:
- parts.append(text.imports_it(dependents))
+ parts.append(text.imports_it(dependents, function=function))
return FixRisk(level, dependents, files_touched, "; ".join(parts).capitalize() + ".")
@@ -476,6 +489,7 @@ class _Files:
dependents: int | None = None,
cloned: bool = False,
changes: int | None = None,
+ function: bool = False,
) -> str:
"""One sentence: the problem, then why it matters here (how often the
function changed, who imports the file, how often it changes, how much
@@ -486,10 +500,15 @@ class _Files:
head += f", {text.CLONED}"
if changes is not None and changes >= MIN_CHURN_COMMITS:
head += f"; {text.own_changes(changes)}"
- return f"{head}{text.exposure(deps, self.commits(path), self.coverage(path))}."
+ exposure = text.exposure(
+ deps, self.commits(path), self.coverage(path), function=function
+ )
+ return f"{head}{exposure}."
- def context(self, path: str) -> tuple[FixContext, ...]:
- """History is context: shown beside the item, never lifting its band."""
+ def context(self, path: str, symbol: str | None = None) -> tuple[FixContext, ...]:
+ """History is context: shown beside the item, never lifting its band.
+ An item on ``symbol`` shows its file's rows and its own, never another
+ function's."""
out: list[FixContext] = []
commits = self.commits(path)
if commits:
@@ -499,17 +518,22 @@ class _Files:
out.append(FixContext("file kind", "test"))
ranked = sorted(self.history.get(path, ()), key=lambda f: -_num(field(f, "health_impact")))
for f in ranked:
+ if not _about(field(f, "function_name"), symbol):
+ continue
marker = field(f, "biomarker_type") or ""
sentence = text.history_fact(marker, detail_map(f), field(f, "function_name"))
if sentence:
out.append(FixContext(text.HISTORY_LABEL.get(marker, "history"), sentence))
return tuple(out[:MAX_CONTEXT])
- def common_facts(self, path: str, dependents: int | None = None) -> list[FixFact]:
+ def common_facts(
+ self, path: str, dependents: int | None = None, *, function: bool = False
+ ) -> list[FixFact]:
out = []
deps = dependents if dependents is not None else self.dependents(path)
if deps:
- out.append(FixFact("files that import it", str(deps)))
+ label = "files that import its file" if function else "files that import it"
+ out.append(FixFact(label, str(deps)))
commits = self.commits(path)
if commits:
out.append(FixFact("changes in 90 days", str(commits)))
@@ -1023,11 +1047,13 @@ def _refactor_fields(plan: _RefactorPlan) -> dict[str, Any]:
)
fix_steps = _refactor_fix_steps(plan, profiles, verify.command)
n_steps, mechanical_n = text.plural(len(plan.steps), "step"), plan.mechanical_n
+ # The symbol the lead step edits; ``None`` for a file-level plan.
+ symbol = plan.sym if lead.get("target_symbol") else None
return {
"title": text.clip(_refactor_title(plan, lead_plan)),
"target": FixTarget(
path,
- plan.sym if lead.get("target_symbol") else None,
+ symbol,
fix_steps[0].line,
lead.get("line_end"),
),
@@ -1038,17 +1064,22 @@ def _refactor_fields(plan: _RefactorPlan) -> dict[str, Any]:
dependents=rank.dependents,
cloned=rank.cloned,
changes=rank.changes,
+ function=symbol is not None,
),
- "facts": _refactor_facts(plan),
+ "facts": _refactor_facts(plan, function=symbol is not None),
"action": _action(f"{n_steps}, {mechanical_n} mechanical", fix_steps, plan.mechanical),
"gain": _health_gain(rank.gain, ceiling=False),
"effort": FixEffortEstimate(plan.effort, "sized by the stored plan"),
- "risk": _risk(int(field(plan.row, "affected_files_total") or 1), rank.dependents),
+ "risk": _risk(
+ int(field(plan.row, "affected_files_total") or 1),
+ rank.dependents,
+ function=symbol is not None,
+ ),
"confidence": FixConfidence(
plan.confidence, f"{mechanical_n} of {n_steps} proven mechanical by the plan"
),
"verify": verify,
- "context": files.context(path),
+ "context": files.context(path, symbol),
"source": FixSource(
field(plan.row, "opportunity_id"),
tuple(s.get("plan_id") for s in plan.steps if s.get("plan_id")),
@@ -1118,14 +1149,14 @@ def _break_up_title(sym: str, shape: Mapping[str, int], span: str, suffix: str =
return head + suffix
-def _refactor_facts(plan: _RefactorPlan) -> tuple[FixFact, ...]:
+def _refactor_facts(plan: _RefactorPlan, *, function: bool) -> tuple[FixFact, ...]:
rank, held_back = plan.rank, plan.held_back
facts = [
FixFact("health recoverable", f"+{rank.gain:.1f}", "inferred"),
*_size_facts(rank.shape),
FixFact("steps", f"{len(plan.steps)} ({plan.mechanical_n} mechanical)"),
*([FixFact("steps held back", text.held_back(held_back))] if held_back else []),
- *plan.files.common_facts(plan.path, rank.dependents),
+ *plan.files.common_facts(plan.path, rank.dependents, function=function),
]
nloc = plan.files.nloc(plan.path)
if nloc:
@@ -1301,7 +1332,7 @@ def _perf_fields(cause: _PerfCause) -> dict[str, Any]:
or f"{text.humanize(field(lead, 'actionability_state'))} plan",
),
"verify": verify,
- "context": cause.files.context(path),
+ "context": cause.files.context(path, symbol),
"source": FixSource(field(lead, "opportunity_id")),
"next_call": _opportunity_call(
"The full opportunity: ordered steps, validation and other causes here",
@@ -1459,22 +1490,23 @@ def _finding_unit(lead: Any, files: _Files, first: FixStep, validate: Validate |
fallback=text.problem(marker, where),
cloned=rank.cloned,
changes=rank.changes,
+ function=function is not None,
),
"facts": tuple(
[
FixFact("finding", text.marker_label(marker)),
*_size_facts(rank.shape),
FixFact("severity", _severity(field(lead, "severity"), rank.low)),
- *files.common_facts(path),
+ *files.common_facts(path, function=function is not None),
][:MAX_FACTS]
),
"action": _action(text.first_sentence(suggestion_for(marker)), (first,), False),
"gain": _health_gain(rank.gain, ceiling=True),
- "risk": _risk(1, files.dependents(path)),
+ "risk": _risk(1, files.dependents(path), function=function is not None),
"verify": _verify(
validate(path, function, line, field(lead, "line_end")) if validate else None
),
- "context": files.context(path),
+ "context": files.context(path, function),
**_finding_plan_fields(led, path, public_id),
}
diff --git a/packages/core/src/repowise/core/analysis/health/fix_first/text.py b/packages/core/src/repowise/core/analysis/health/fix_first/text.py
index f11403e7d..edb44447c 100644
--- a/packages/core/src/repowise/core/analysis/health/fix_first/text.py
+++ b/packages/core/src/repowise/core/analysis/health/fix_first/text.py
@@ -125,8 +125,11 @@ def loop_size(magnitude: str | None) -> str:
return humanize(magnitude) if magnitude else "unknown"
-def imports_it(dependents: int) -> str:
- """``1 file imports it`` / ``7 files import it``."""
+def imports_it(dependents: int, *, function: bool = False) -> str:
+ """``1 file imports it`` / ``7 files import it``; for a function or class,
+ which no file imports on its own, ``its file is imported by 7 files``."""
+ if function:
+ return f"its file is imported by {plural(dependents, 'file')}"
return f"{plural(dependents, 'file')} import{'s' if dependents == 1 else ''} it"
@@ -236,12 +239,18 @@ def size_brief(shape: dict[str, int]) -> str:
return ", ".join(parts) or "large"
-def exposure(dependents: int | None, commits: int, coverage: float | None = None) -> str:
+def exposure(
+ dependents: int | None,
+ commits: int,
+ coverage: float | None = None,
+ *,
+ function: bool = False,
+) -> str:
"""``; 7 files import it, changed 15 times in 90 days, tests run 40% of
its lines``, or nothing. Coverage only when a report measured the file."""
parts = []
if dependents:
- parts.append(imports_it(dependents))
+ parts.append(imports_it(dependents, function=function))
if commits:
parts.append(f"changed {plural(commits, 'time')} in 90 days")
if coverage is not None:
diff --git a/packages/core/src/repowise/core/ingestion/cohesion.py b/packages/core/src/repowise/core/ingestion/cohesion.py
index 20efb63c2..63789ac2e 100644
--- a/packages/core/src/repowise/core/ingestion/cohesion.py
+++ b/packages/core/src/repowise/core/ingestion/cohesion.py
@@ -97,6 +97,35 @@ COHESION_HINTS: frozenset[str] = frozenset(
)
+#: ``hint_source`` values on an edge that records no use of its target: the
+#: synthetic reverse of a header pair, fragments of one partial type, a name
+#: seen only in a comment, a name the source declares itself, and a parent
+#: module declaring its child. The text-scan hints (JVM ``same_package``,
+#: ``same_namespace``, ``global_using``, ``same_module``) are left out: there the
+#: hinted edge is the only record of a real use.
+NON_USE_HINTS: frozenset[str] = frozenset(
+ {
+ "header_source_pair",
+ "partial_class",
+ DOC_COMMENT_HINT,
+ OWN_TYPE_NAME_HINT,
+ MODULE_DECLARATION_HINT,
+ }
+)
+
+
+def records_no_use(data: Any, source: str, target: str) -> bool:
+ """True if the edge *data* from *source* to *target* records no use of *target*.
+
+ A Go same-package edge joins two files of one package, which import
+ nothing from each other; a JVM one is a resolved type reference and counts.
+ """
+ hint = data.get("hint_source")
+ if hint in NON_USE_HINTS:
+ return True
+ return hint == SAME_PACKAGE_HINT and source.endswith(".go") and target.endswith(".go")
+
+
def withdraw_declaration_hint(data: dict[str, Any]) -> None:
"""Drop the module-declaration hint once a real reference shares the edge."""
if data.get("hint_source") == MODULE_DECLARATION_HINT:
diff --git a/tests/unit/health/test_dependents_count.py b/tests/unit/health/test_dependents_count.py
index f1dc3733a..d28927605 100644
--- a/tests/unit/health/test_dependents_count.py
+++ b/tests/unit/health/test_dependents_count.py
@@ -8,6 +8,7 @@ from __future__ import annotations
import networkx as nx
+from repowise.core.analysis.dead_code.file_reachability import file_dependency_neighbors
from repowise.core.analysis.health import HealthAnalyzer
from repowise.core.analysis.health.engine import _dependents_count
from repowise.core.analysis.health.models import Severity
@@ -56,3 +57,45 @@ def test_the_engine_reports_importers_only(tmp_path):
assert finding.reason.split("— ")[-1] == "4 dependents"
# Ten or more dependents would have made it critical; four at 0% is high.
assert finding.severity == Severity.HIGH
+
+
+def test_go_package_siblings_are_not_importers():
+ """A Go package is one compilation unit: a sibling referencing ``command.go``
+ imports nothing, while a file in another package that imports it does."""
+ target = "cobra/command.go"
+ g = nx.DiGraph()
+ g.add_node(target, node_type="file", language="go")
+ for i in range(3):
+ g.add_edge(
+ f"cobra/sibling_{i}.go", target, edge_type="type_use", hint_source="same_package"
+ )
+ g.add_edge("cmd/main.go", target, edge_type="imports")
+ assert _dependents_count(g, target) == 1
+ # Reachability still sees the siblings.
+ assert len(file_dependency_neighbors(g, target, incoming=True)) == 4
+
+
+def _users(edges: list[tuple[str, str, str | None]], target: str) -> int:
+ g = nx.DiGraph()
+ for source, dest, hint in edges:
+ g.add_edge(source, dest, edge_type="imports", **({"hint_source": hint} if hint else {}))
+ for n in g.nodes:
+ g.nodes[n]["node_type"] = "file"
+ return _dependents_count(g, target)
+
+
+def test_a_java_same_package_text_scan_user_still_counts():
+ """``Foo.class`` in a sibling test is a use with no import: its hinted edge counts."""
+ target = "src/main/java/app/App.java"
+ assert _users([("src/test/java/app/AppTests.java", target, "same_package")], target) == 1
+
+
+def test_a_swift_same_module_user_counts():
+ assert _users([("Sources/App/View.swift", "Sources/App/Model.swift", "same_module")],
+ "Sources/App/Model.swift") == 1
+
+
+def test_a_source_including_its_header_counts_but_the_reverse_pair_edge_does_not():
+ edges = [("src/foo.c", "src/foo.h", None), ("src/foo.h", "src/foo.c", "header_source_pair")]
+ assert _users(edges, "src/foo.h") == 1
+ assert _users(edges, "src/foo.c") == 0
diff --git a/tests/unit/health/test_fix_first_build.py b/tests/unit/health/test_fix_first_build.py
index b477676bf..a6bd5af67 100644
--- a/tests/unit/health/test_fix_first_build.py
+++ b/tests/unit/health/test_fix_first_build.py
@@ -99,7 +99,7 @@ def test_text_quotes_the_stored_numbers() -> None:
# The size is a fact; the why says why it matters here.
assert core.why == (
"run has many paths; easier to read and change once split; "
- "9 files import it, changed 12 times in 90 days."
+ "its file is imported by 9 files, changed 12 times in 90 days."
)
assert ("size", "CCN 44, 50 lines, nests 4 deep") in [(f.label, f.value) for f in core.facts]
assert core.action.steps[0].text == "Extract lines 20-35 of run into sum_rows(rows, limit) -> total"
@@ -638,3 +638,44 @@ def test_a_dismissed_plan_never_gives_a_finding_its_step() -> None:
run = _run(plans, refactoring)
assert run.title == "Break up run (CCN 44, 50 lines)"
assert run.source.plan_ids == () and "Extract" not in run.action.steps[0].text
+
+
+def _hotspot(function: str, commits: int) -> dict:
+ return {
+ "file_path": "src/core.py", "biomarker_type": "function_hotspot", "severity": "medium",
+ "function_name": function, "health_impact": 0.4, "public_id": f"finding_fh_{function}",
+ "dimension": "defect", "details": {"modification_count": commits},
+ }
+
+
+def test_a_function_item_shows_its_own_history_never_another_functions() -> None:
+ findings = [*FINDINGS, _hotspot("Client.__init__", 7), _hotspot("Engine.run", 9)]
+ core = next(i for i in _build(findings=findings).items if i.kind == "refactor")
+ values = [c.value for c in core.context]
+ assert "Engine.run changed in 9 commits" in values
+ assert not any("__init__" in v for v in values)
+ # File-level history still rides along.
+ assert ("recent changes", "changed 12 times in 90 days") in [
+ (c.label, c.value) for c in core.context
+ ]
+
+
+def test_a_function_item_says_its_file_is_imported_not_that_it_is() -> None:
+ core = next(i for i in _build().items if i.kind == "refactor")
+ assert core.why.endswith("its file is imported by 9 files, changed 12 times in 90 days.")
+ assert core.risk.text == "Touches 1 file; its file is imported by 9 files."
+ assert ("files that import its file", "9") in [(f.label, f.value) for f in core.facts]
+
+
+def test_history_matches_the_items_qualified_symbol() -> None:
+ from repowise.core.analysis.health.fix_first.build import _about
+
+ # Same method name in two classes: only the item's own class.
+ assert _about("Engine.run", "src/core.py::Engine.run")
+ assert not _about("Other.run", "src/core.py::Engine.run")
+ # A class item keeps its members, not a class sharing its prefix.
+ assert _about("Engine.run", "Engine")
+ assert not _about("EngineTest.run", "Engine")
+ # File-level rows and items keep everything; a bare name matches by name.
+ assert _about(None, "Engine.run") and _about("Other.run", None)
+ assert _about("run", "Engine.run") and not _about("walk", "Engine.run")
diff --git a/tests/unit/health/test_fix_first_closeout.py b/tests/unit/health/test_fix_first_closeout.py
index 632f2d812..863a4dc8c 100644
--- a/tests/unit/health/test_fix_first_closeout.py
+++ b/tests/unit/health/test_fix_first_closeout.py
@@ -6,7 +6,7 @@ import re
import pytest
-from repowise.core.analysis.health.fix_first import FixFirstQueue, build_fix_first
+from repowise.core.analysis.health.fix_first import FixFirstQueue, build_fix_first, text
from repowise.core.analysis.health.queue.eligibility import LOW_VALUE_KINDS
from repowise.core.analysis.health.refactoring.performance_fix import fix_steps
from tests.unit.health.fix_first_rows import FINDINGS, METRICS, _perf
@@ -133,4 +133,5 @@ def test_no_text_field_carries_an_internal_token(via: str, magnitude: str) -> No
def test_one_importer_reads_in_the_singular() -> None:
item = next(i for i in _validated("unknown", "mixed", 1).items if i.kind == "finding")
- assert item.risk.text == "Touches 1 file; 1 file imports it."
+ assert item.risk.text == "Touches 1 file; its file is imported by 1 file."
+ assert text.imports_it(1) == "1 file imports it"
diff --git a/tests/unit/health/test_fix_first_precision.py b/tests/unit/health/test_fix_first_precision.py
index cce880f8d..4f0db975f 100644
--- a/tests/unit/health/test_fix_first_precision.py
+++ b/tests/unit/health/test_fix_first_precision.py
@@ -426,7 +426,7 @@ def test_why_says_why_it_matters_not_the_titles_size() -> None:
assert "249" not in item.why and "1,280" not in item.why and "CCN" not in item.why
assert item.why == (
"run has many paths; easier to read and change once split; "
- "9 files import it, changed 12 times in 90 days."
+ "its file is imported by 9 files, changed 12 times in 90 days."
)