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(actions): name a fragile file's lead to simplify only when it is worth breaking up (#4361)
Raghav Chamadiyaea91769f4814
diff --git a/docs/layers/CODE_HEALTH.md b/docs/layers/CODE_HEALTH.mdindex 4c4b16a27..826eb2225 100644--- a/docs/layers/CODE_HEALTH.md+++ b/docs/layers/CODE_HEALTH.md@@ -122,7 +122,9 @@ repowise next --json # the whole stored viewcause (one in the performance queue) or lost measured coverage; the long, complex or nested code a week leaves is onerow to plan.- A fragile file asks for tests only when no measured coverage and no test in the graph- reaches it, else to simplify its lead function. A folder where fixes concentrate names+ reaches it, else to simplify its lead function. That lead is named only when its+ function is worth breaking up by the same rule Fix first uses; otherwise the row asks to+ review why fixes keep landing and shows no finding. A folder where fixes concentrate namesits most fixed file's first step, or is left out. Under five commits, history-rankedrows are left out.diff --git a/packages/core/src/repowise/core/analysis/actions/build.py b/packages/core/src/repowise/core/analysis/actions/build.pyindex 316fc7e1a..e8af25b71 100644--- a/packages/core/src/repowise/core/analysis/actions/build.py+++ b/packages/core/src/repowise/core/analysis/actions/build.py@@ -21,7 +21,8 @@ Row shapes (the field names are the SQL columns):``file_path``, ``fix_sha``, ``committed_at``, ``shape_kind``, ``attribution``.``health_findings````file_path``, ``biomarker_type``, ``severity``, ``function_name``,- ``line_start``, ``reason``, ``health_impact``, ``status`` (absent = open).+ ``line_start``, ``reason``, ``health_impact``, ``status`` (absent = open);+ a lead also reads ``line_end`` and ``details_json``, which measure its function.``authors````author_name``, ``author_email``, ``committed_at``: one row per commit, orper identity with its latest commit.@@ -69,7 +70,7 @@ from typing import Anyfrom repowise.core.analysis.dead_code.risk_factors import REVIEW_ONLY_KINDSfrom repowise.core.analysis.finding_registry import excluded_types, is_servedfrom repowise.core.analysis.health.fix_first import build_fix_first-from repowise.core.analysis.health.models import primary_finding, split_by_origin+from repowise.core.analysis.health.models import lead_and_worth, split_by_originfrom repowise.core.analysis.health.queue.eligibility import perf_confident_verdictfrom repowise.core.analysis.health.rows import fieldfrom repowise.core.analysis.health.scoring import HISTORY_CATEGORY, biomarker_category@@ -212,7 +213,7 @@ def with_leads(files: Mapping[str, FileFacts], findings: Rows) -> dict[str, Fileout = dict(files)for path, found in by_path.items():shape, _history = split_by_origin(found)- lead = primary_finding(shape)+ lead, worth = lead_and_worth(shape)if lead is not None:out[path] = replace(out[path],@@ -222,6 +223,7 @@ def with_leads(files: Mapping[str, FileFacts], findings: Rows) -> dict[str, Filefunction=field(lead, "function_name"),line=field(lead, "line_start"),reason=field(lead, "reason") or "",+ worth=worth,),)return outdiff --git a/packages/core/src/repowise/core/analysis/actions/facts.py b/packages/core/src/repowise/core/analysis/actions/facts.pyindex d46ae05b0..b6c97c954 100644--- a/packages/core/src/repowise/core/analysis/actions/facts.py+++ b/packages/core/src/repowise/core/analysis/actions/facts.py@@ -32,6 +32,9 @@ class LeadFinding:function: str | Noneline: int | Nonereason: str+ #: Its function is worth breaking up first by the shared rule+ #: (``health.models.lead_and_worth``): only then is "simplify it" the step.+ worth: bool = False@dataclass(frozen=True, slots=True)diff --git a/packages/core/src/repowise/core/analysis/actions/rules/code.py b/packages/core/src/repowise/core/analysis/actions/rules/code.pyindex ae776cfa4..9d1d9a0a1 100644--- a/packages/core/src/repowise/core/analysis/actions/rules/code.py+++ b/packages/core/src/repowise/core/analysis/actions/rules/code.py@@ -348,7 +348,9 @@ def _fragile_step(f: FileFacts) -> tuple[str, str, str] | None:Measured coverage decides first. Without it, "add tests" holds only when notest reaches the file in the code graph; a file tests do reach gets the- simplify step instead, as an inferred claim.+ simplify step instead, as an inferred claim. "Simplify" names the lead only+ when its function is worth breaking up by the shared rule; otherwise the+ step is to review why fixes keep landing, which names no finding."""cov = f.line_coverage_pctif cov is not None and cov < COVERED_PCT:@@ -369,13 +371,24 @@ def _fragile_step(f: FileFacts) -> tuple[str, str, str] | None:)if f.lead is None:return None+ return _lead_step(f, measured=cov is not None)+++def _lead_step(f: FileFacts, *, measured: bool) -> tuple[str, str, str]:+ """:func:`_fragile_step` for a tested file with a lead finding."""+ tested = "it is tested" if measured else "tests reach it"+ if not f.lead or not f.lead.worth:+ return (+ f"Review why fixes keep landing in {code(f.path)}: {tested}",+ "Bug-fix commits slow down.",+ "review" if measured else "review_reached",+ )name = _lead_name(f)where = code(name) + " in " if name else ""- tested = "it is tested" if cov is not None else "tests reach it"return (f"Simplify {where}{code(f.path)}: {tested}, and fixes keep landing","Its lead finding closes and bug-fix commits slow down.",- "simplify" if cov is not None else "reached",+ "simplify" if measured else "reached",)@@ -412,74 +425,85 @@ def fragile_file(facts: RepoFacts, ctx: RepoContext) -> RuleOutcome:actions = []for f in fragile:step = _fragile_step(f)- if step is None:- continue- title, done, variant = step- why = [- WhyFact("commits in 90 days", str(f.commits_90d)),- WhyFact("bug-fix commits", str(f.fix_commits_90d)),- _coverage_fact(f, facts),- ]- if f.line_coverage_pct is None:- why.append(_reach_fact(f))- impact = (- f"Changed {f.commits_90d} times in 90 days, and {f.fix_commits_90d} "- "of those commits were bug fixes."- )- if f.dependents and f.dependents >= 5:- why.append(WhyFact("files that import it", str(f.dependents)))- impact += f" {f.dependents} files import it."- actions.append(- Action(- rule=rule,- tier="plan",- horizons=("week", "quarter") if f.path in week_rows else ("quarter",),- severity="high" if f.fix_commits_90d >= 10 else "medium",- title=title,- impact=impact,- why=tuple(why),- target_kind="file",- target_path=f.path,- target_symbol=_lead_name(f) if variant in ("simplify", "reached") else None,- identity=f.path,- surface="file",- effort="M" if (f.nloc or 0) < 600 else "L",- confidence="high" if variant in ("raise", "simplify") else "medium",- done_when=done,- marker=f.lead.biomarker if f.lead else None,- weight=float(f.fix_commits_90d * f.commits_90d),- fingerprint=fingerprint(variant, f.fix_commits_90d // 5),- details=(- (- ActionDetail(- path=f.path,- line=f.lead.line,- symbol=f.lead.function,- marker=f.lead.biomarker,- severity=f.lead.severity,- reason=f.lead.reason,- ),- )- if f.lead- else ()- ),- commands=(- ActionCommand.call(- "Its bug-fix history, co-change partners and test gaps",- "get_risk",- {"targets": [f.path]},- cli=f"repowise risk -t {f.path}",- ),- ActionCommand.call(- "Every open finding in the file",- "get_health",- {"targets": [f.path], "include": ["biomarkers"]},- cli=f"repowise health --file {f.path}",- ),+ if step is not None:+ actions.append(_fragile_action(f, step, facts, week=f.path in week_rows))+ return RuleOutcome(rule, "evaluated", "", tuple(actions))+++def _fragile_why(f: FileFacts, facts: RepoFacts) -> tuple[tuple[WhyFact, ...], str]:+ """A fragile file's why facts and impact line."""+ why = [+ WhyFact("commits in 90 days", str(f.commits_90d)),+ WhyFact("bug-fix commits", str(f.fix_commits_90d)),+ _coverage_fact(f, facts),+ ]+ if f.line_coverage_pct is None:+ why.append(_reach_fact(f))+ impact = (+ f"Changed {f.commits_90d} times in 90 days, and {f.fix_commits_90d} "+ "of those commits were bug fixes."+ )+ if f.dependents and f.dependents >= 5:+ why.append(WhyFact("files that import it", str(f.dependents)))+ impact += f" {f.dependents} files import it."+ return tuple(why), impact+++def _fragile_action(+ f: FileFacts, step: tuple[str, str, str], facts: RepoFacts, *, week: bool+) -> Action:+ title, done, variant = step+ # A review step names no finding, so it shows none as its lead.+ lead = None if variant.startswith("review") else f.lead+ why, impact = _fragile_why(f, facts)+ return Action(+ rule="fragile_file",+ tier="plan",+ horizons=("week", "quarter") if week else ("quarter",),+ severity="high" if f.fix_commits_90d >= 10 else "medium",+ title=title,+ impact=impact,+ why=why,+ target_kind="file",+ target_path=f.path,+ target_symbol=_lead_name(f) if variant in ("simplify", "reached") else None,+ identity=f.path,+ surface="file",+ effort="M" if (f.nloc or 0) < 600 else "L",+ confidence="high" if variant in ("raise", "simplify", "review") else "medium",+ done_when=done,+ marker=lead.biomarker if lead else None,+ weight=float(f.fix_commits_90d * f.commits_90d),+ fingerprint=fingerprint(variant, f.fix_commits_90d // 5),+ details=(+ (+ ActionDetail(+ path=f.path,+ line=lead.line,+ symbol=lead.function,+ marker=lead.biomarker,+ severity=lead.severity,+ reason=lead.reason,),)- )- return RuleOutcome(rule, "evaluated", "", tuple(actions))+ if lead+ else ()+ ),+ commands=(+ ActionCommand.call(+ "Its bug-fix history, co-change partners and test gaps",+ "get_risk",+ {"targets": [f.path]},+ cli=f"repowise risk -t {f.path}",+ ),+ ActionCommand.call(+ "Every open finding in the file",+ "get_health",+ {"targets": [f.path], "include": ["biomarkers"]},+ cli=f"repowise health --file {f.path}",+ ),+ ),+ )def fix_concentration(facts: RepoFacts, ctx: RepoContext) -> RuleOutcome:diff --git a/packages/core/src/repowise/core/analysis/health/models.py b/packages/core/src/repowise/core/analysis/health/models.pyindex 636524cad..337fb7816 100644--- a/packages/core/src/repowise/core/analysis/health/models.py+++ b/packages/core/src/repowise/core/analysis/health/models.py@@ -58,13 +58,20 @@ def primary_finding(findings: Sequence[Any]) -> Any | None:of 3,011 files moved, and every one of them had been led by``coverage_gradient``."""+ return lead_and_worth(findings)[0]+++def lead_and_worth(findings: Sequence[Any]) -> tuple[Any | None, bool]:+ """:func:`primary_finding`, and whether its function is worth breaking up+ first by the shared rule (:func:`worth.low_priority`, at the break-up bar).+ A surface that tells someone to simplify the lead asks the second."""from .biomarkers.registry import continuous_biomarkersfrom .governance import GOVERNANCE_BIOMARKERSfrom .rows import field as row_fieldfrom .scoring import HISTORY_CATEGORY, biomarker_category, is_advisoryif not findings:- return None+ return None, False# An advisory finding describes; it never accuses. Leaving it eligible made# it the stated "one reason" for any file whose only open finding was# advisory - printed beside a total deduction of zero.@@ -72,7 +79,7 @@ def primary_finding(findings: Sequence[Any]) -> Any | None:item for item in findings if not is_advisory(row_field(item, "biomarker_type"))]if not candidates:- return None+ return None, False# A history marker is measured from git, so it names a file's context, not# something an edit changes. When the file also carries a code-shape# finding, that one leads: the Findings list put `change_entropy` at the@@ -100,7 +107,7 @@ def primary_finding(findings: Sequence[Any]) -> Any | None:# quantise to the same deduction), and a bare ``max`` let input order pick# the lead, so two indexes of one tree disagreed. Severity breaks the tie# first; the rest only makes it stable.- return min(+ lead = min(pool,key=lambda item: (-break_up.get(id(item), -1),@@ -111,6 +118,7 @@ def primary_finding(findings: Sequence[Any]) -> Any | None:str(row_field(item, "function_name") or ""),),)+ return lead, id(lead) in break_updef _break_up_ccn(findings: Sequence[Any]) -> dict[int, int]:diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/actions.py b/packages/core/src/repowise/core/persistence/crud/analysis/actions.pyindex 86078382e..c2199b966 100644--- a/packages/core/src/repowise/core/persistence/crud/analysis/actions.py+++ b/packages/core/src/repowise/core/persistence/crud/analysis/actions.py@@ -89,6 +89,12 @@ _HEALTH_FINDING_COLUMNS = (HealthFinding.reason,HealthFinding.health_impact,)+#: A lead's function is measured from its details (``health.worth.measure``).+_LEAD_FINDING_COLUMNS = (+ *_HEALTH_FINDING_COLUMNS,+ HealthFinding.line_end,+ HealthFinding.details_json,+)async def _anchor(session: AsyncSession, repo_id: str) -> tuple[datetime | None, str | None]:@@ -162,7 +168,7 @@ async def _files(session: AsyncSession, repo_id: str, since: datetime | None) ->if paths:findings = (await session.execute(- select(*_HEALTH_FINDING_COLUMNS).where(+ select(*_LEAD_FINDING_COLUMNS).where(HealthFinding.repository_id == repo_id,HealthFinding.status == "open",HealthFinding.file_path.in_(paths),diff --git a/tests/unit/analysis/test_actions_rules.py b/tests/unit/analysis/test_actions_rules.pyindex 2fc4d5602..dd37a6b22 100644--- a/tests/unit/analysis/test_actions_rules.py+++ b/tests/unit/analysis/test_actions_rules.py@@ -5,6 +5,7 @@ tests.from __future__ import annotations+import jsonfrom dataclasses import replacefrom datetime import datetime, timedelta@@ -90,7 +91,7 @@ def test_fragile_below_80_says_raise_coverage() -> None:def test_fragile_covered_with_lead_says_simplify() -> None:- lead = LeadFinding("complex_method", "high", "build", 12, "ccn 20")+ lead = LeadFinding("complex_method", "high", "build", 12, "CCN 45", worth=True)f = _file("src/a.py", line_coverage_pct=91.0, lead=lead)(a,) = _run(code.fragile_file, _facts([f])).actionsassert a.title.startswith("Simplify `build` in `src/a.py`")@@ -98,6 +99,46 @@ def test_fragile_covered_with_lead_says_simplify() -> None:assert a.marker == "complex_method"+def test_fragile_lead_not_worth_breaking_up_says_review_and_names_no_finding() -> None:+ """Ours: call_language_strategies.py at 93% led by coverage_gradient, and+ health/engine.py led by `__init__` at CCN 10, both read "Simplify"."""+ for lead in (+ LeadFinding("coverage_gradient", "low", None, None, "7% of lines uncovered"),+ LeadFinding("complex_method", "medium", "__init__", 40, "CCN 10"),+ ):+ f = _file("src/a.py", line_coverage_pct=93.0, lead=lead)+ (a,) = _run(code.fragile_file, _facts([f])).actions+ assert a.title == "Review why fixes keep landing in `src/a.py`: it is tested"+ assert a.done_when == "Bug-fix commits slow down."+ assert (a.target_symbol, a.marker, a.details) == (None, None, ())+ assert a.confidence == "high"+ reached = _file("src/a.py", lead=lead, tests_reaching=3)+ (a,) = _run(code.fragile_file, _facts([reached])).actions+ assert a.title == "Review why fixes keep landing in `src/a.py`: tests reach it"+ assert a.confidence == "medium"+++def test_leads_carry_the_shared_break_up_verdict() -> None:+ from repowise.core.analysis.actions.build import with_leads++ def row(path: str, marker: str, fn: str | None, details: dict) -> dict:+ return {"file_path": path, "biomarker_type": marker, "severity": "high",+ "function_name": fn, "line_start": 1, "line_end": 90, "reason": "",+ "health_impact": 1.0, "details_json": json.dumps(details)}++ files = {p: _file(p) for p in ("src/big.py", "src/small.py", "src/cov.py")}+ out = with_leads(files, [+ row("src/big.py", "complex_method", "run", {"ccn": 44, "nloc": 90, "max_nesting": 3}),+ row("src/small.py", "complex_method", "__init__", {"ccn": 10, "nloc": 30}),+ row("src/cov.py", "coverage_gradient", None, {}),+ ])+ assert {p: (f.lead.biomarker, f.lead.worth) for p, f in out.items()} == {+ "src/big.py": ("complex_method", True),+ "src/small.py": ("complex_method", False),+ "src/cov.py": ("coverage_gradient", False),+ }++def test_fragile_covered_without_lead_is_silent() -> None:f = _file("src/a.py", line_coverage_pct=91.0)assert _run(code.fragile_file, _facts([f])).actions == ()@@ -766,7 +807,7 @@ def test_week_rollup_does_not_hide_a_fragile_file_from_the_quarter() -> None:def test_fragile_id_survives_a_change_of_lead_function() -> None:- lead = LeadFinding("complex_method", "high", "a", 1, "")+ lead = LeadFinding("complex_method", "high", "a", 1, "", worth=True)before = _file("src/x.py", fix_commits_90d=9, commits_90d=20, line_coverage_pct=90.0, lead=lead)after = replace(before, lead=replace(lead, function="b"))ctx = dict(busy_threshold=5, fix_threshold=3)@@ -808,7 +849,7 @@ def test_rollup_carries_evidence_starting_with_the_worst_file_and_commands() -># Self-checks: "add tests" needs no test reaching the file; short history# ----------------------------------------------------------------------------_LEAD = LeadFinding("complex_method", "high", "runEmbeddedAttempt", 40, "CCN 90")+_LEAD = LeadFinding("complex_method", "high", "runEmbeddedAttempt", 40, "CCN 90", worth=True)def test_fragile_reached_by_tests_says_simplify_not_add_tests() -> None:@@ -857,7 +898,7 @@ def test_fragile_unknown_reach_is_not_zero() -> None:def test_an_anonymous_lead_function_is_left_out_of_the_title() -> None:- lead = LeadFinding("complex_method", "high", "<anonymous@3167>", 3167, "")+ lead = LeadFinding("complex_method", "high", "<anonymous@3167>", 3167, "", worth=True)f = _file("src/gateway/chat.ts", lead=lead, tests_reaching=3)(a,) = _run(code.fragile_file, _facts([f])).actionsassert a.title == "Simplify `src/gateway/chat.ts`: tests reach it, and fixes keep landing"@@ -866,10 +907,10 @@ def test_an_anonymous_lead_function_is_left_out_of_the_title() -> None:def test_measured_coverage_wins_over_the_test_map() -> None:"""Ours: update_cmd/command.py (68 changes, 27 fixes, 70%) keeps "raise coverage",- and call_resolver.py keeps "simplify _csharp_type_id", whatever reaches them."""+ and a covered file keeps its simplify step, whatever reaches them."""raise_path = "packages/cli/src/repowise/cli/commands/update_cmd/command.py"tested_path = "packages/core/src/repowise/core/ingestion/call_resolver.py"- lead = LeadFinding("complex_method", "high", "_csharp_type_id", 10, "")+ lead = LeadFinding("complex_method", "high", "_csharp_type_id", 10, "", worth=True)files = [_file(raise_path, commits_90d=68, fix_commits_90d=27, line_coverage_pct=70.0,tests_reaching=40),diff --git a/tests/unit/persistence/test_actions_loader.py b/tests/unit/persistence/test_actions_loader.pyindex 2d6d1aa7e..6f95d235b 100644--- a/tests/unit/persistence/test_actions_loader.py+++ b/tests/unit/persistence/test_actions_loader.py@@ -328,6 +328,9 @@ async def test_a_test_reaching_through_a_helper_turns_add_tests_into_simplify(asfacts = await load_repo_facts(async_session, rid)assert facts.history_commits == 5assert facts.files["src/core.py"].tests_reaching == 0+ # The lead is measured from its stored details: CCN 44 is worth breaking up.+ lead = facts.files["src/core.py"].lead+ assert (lead.function, lead.worth) == ("run", True)for path, is_test in (("src/core.py", False),