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): word ownership_risk by the arm that fired, cap small files, rank test findings last (#3656)

Swati Ahujac5877ab7b3c2
diff --git a/docs/layers/CODE_HEALTH.md b/docs/layers/CODE_HEALTH.md
index 0e0edd080..5425773be 100644
--- a/docs/layers/CODE_HEALTH.md
+++ b/docs/layers/CODE_HEALTH.md
@@ -216,6 +216,7 @@ below 9.0 from history alone.
On a small team, `knowledge_loss` and `ownership_risk` are capped at low severity
unless the file is a hotspot, and the `small-team` profile lowers them further.
+`ownership_risk` is also low on a file under 40 code lines.
`large_assertion_block` and `duplicated_assertion_block` fire only in test files.
House assertion helpers go in the [`assertions:` block](../reference/CONFIG.md#the-assertions-block).
Per-language coverage: [LANGUAGE_SUPPORT.md](LANGUAGE_SUPPORT.md#code-health-coverage).
diff --git a/docs/layers/OWNERSHIP.md b/docs/layers/OWNERSHIP.md
index 72e017270..adbe4f5b5 100644
--- a/docs/layers/OWNERSHIP.md
+++ b/docs/layers/OWNERSHIP.md
@@ -86,7 +86,7 @@ rest of [code health](CODE_HEALTH.md) and appear in its findings list.
| Detector | Fires when | Severity |
|---|---|---|
| `knowledge_loss` | The file is still changing (a commit in 90 days, or a hotspot; never a file marked stable), its bus factor is 1, and the primary owner is no longer the recent owner or the recent owner makes under 20% of recent commits | High on a hotspot; medium when both conditions hold; otherwise low |
-| `ownership_risk` | The file has 5 or more commits and either 3 or more minor contributors (each under 5% of commits) or no author above 40% | Critical at 6+ minor contributors on a hotspot; high at 5+, or 3+ on a hotspot; medium at 3+; otherwise low |
+| `ownership_risk` | The file has 5 or more commits and either 3 or more minor contributors (each under 5% of commits) or no author above 40% | Critical at 6+ minor contributors on a hotspot; high at 5+, or 3+ on a hotspot; medium at 3+; otherwise low. Low on a file under 40 code lines |
| `developer_congestion` | 5 or more contributors, the file is in the top quarter of churn for this repository, and nobody holds half the commits | High at 10+ contributors and 20+ commits in 90 days; medium at 7+ contributors or 12+ commits; otherwise low |
A stable file whose author left never fires `knowledge_loss`: code nobody edits
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/ownership_risk.py b/packages/core/src/repowise/core/analysis/health/biomarkers/ownership_risk.py
index 29064c5ac..56f1ecc2f 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/ownership_risk.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/ownership_risk.py
@@ -17,6 +17,15 @@ Fires when the file is non-trivial and ownership is fragmented:
- ``total_commits`` ≥ 5, AND
- ``minor_contributors`` ≥ 3 OR ``top_owner_share`` < 0.4.
+Under 20 commits no author can hold under 5%, so only the share arm can
+fire there. It stays: on the 21-repo T0 defect corpus, dropping it or
+requiring 10 to 30 commits for it lowered the marker's size-controlled
+coefficient from 0.35 to 0.23-0.31. The reason names the arm that fired.
+
+A file under ``_SMALL_NLOC`` code lines (an interface, a DTO) is capped at
+LOW: on the same corpus that raised the score's defect AUC (+0.002 keyword,
++0.004 SZZ labels) and kept every finding.
+
On a small team (≤ ``SMALL_TEAM_MAX_CONTRIBUTORS`` active contributors
in 90d) ownership dispersion across the same few people is the normal
operating model, not Bird-style drive-by fragmentation — severity is
@@ -36,6 +45,10 @@ from ..models import Severity
from .base import SMALL_TEAM_MAX_CONTRIBUTORS, BiomarkerResult, FileContext
_MIN_COMMITS = 5
+#: Below this NLOC the finding stays LOW. Gains were flat from 40 to 100;
+#: this is the smallest floor on the plateau. Dropping small files instead
+#: (floors 20 to 50) lowered the coefficient and gained less AUC.
+_SMALL_NLOC = 40
_MINOR_SHARE = 0.05
_MINOR_THRESHOLD = 3
_TOP_OWNER_FLOOR = 0.4
@@ -89,11 +102,22 @@ class OwnershipRiskDetector:
severity = Severity.MEDIUM
else:
severity = Severity.LOW
+ small_file = ctx.nloc < _SMALL_NLOC and severity != Severity.LOW
+ if small_file:
+ severity = Severity.LOW
- reason = (
- f"{minor_contributors} minor contributors (each <5% of commits); "
- f"top owner holds {top_owner_share:.0%}"
- )
+ if minor_contributors >= _MINOR_THRESHOLD:
+ reason = (
+ f"{minor_contributors} minor contributors (each <5% of commits); "
+ f"top owner holds {top_owner_share:.0%}"
+ )
+ else:
+ reason = (
+ f"no clear owner: the top author holds {top_owner_share:.0%} "
+ f"of {total} commits across {len(authors)} contributors"
+ )
+ if small_file:
+ reason += f" (low: only {ctx.nloc} code lines)"
# Small-team calibration (issue #361): with ≤3 active contributors,
# ownership concentration/dispersion is the expected shape of the
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/health.py b/packages/core/src/repowise/core/persistence/crud/analysis/health.py
index 62108986a..3046388ca 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/health.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/health.py
@@ -48,6 +48,7 @@ from ...models import (
_now_utc,
)
from .._shared import _BATCH_SIZE
+from ..graph import get_test_file_paths
from .plain_rows import plain_rows
from .shown import shown
@@ -498,8 +499,9 @@ async def get_health_findings(
include_unverified: bool = False,
limit: int | None = None,
) -> list[HealthFinding]:
- """Findings for one repository: worth doing first ahead of lower-priority
- ones (``worth.finding_priorities``), each part ordered by health impact.
+ """Findings for one repository: production ahead of test files, worth doing
+ first ahead of lower-priority ones (``worth.finding_priorities``), each part
+ ordered by health impact.
Finding types the registry withholds (``finding_registry``) are left out,
so every surface built on this read shows only what has earned a place; a
@@ -587,8 +589,14 @@ async def get_health_findings(
if narrowed
else dict(zip((f.id for f in kept), finding_priorities(kept), strict=True))
)
+ # Test files go below production, then lower-priority below worth doing.
# Stable: each tier keeps the impact order. The cap applies after the tier.
- ordered = sorted(kept, key=lambda f: reasons[f.id] is not None)
+ tests = await get_test_file_paths(
+ session,
+ repository_id,
+ None if file_path is None and file_paths is None else {f.file_path for f in kept},
+ )
+ ordered = sorted(kept, key=lambda f: (f.file_path in tests, reasons[f.id] is not None))
return ordered if limit is None else ordered[:limit]
diff --git a/tests/unit/health/test_organizational_biomarkers.py b/tests/unit/health/test_organizational_biomarkers.py
index 22b4f8ad1..b5ef0bb67 100644
--- a/tests/unit/health/test_organizational_biomarkers.py
+++ b/tests/unit/health/test_organizational_biomarkers.py
@@ -246,6 +246,27 @@ def test_ownership_risk_skips_low_commit_files():
assert OwnershipRiskDetector().detect(_ctx(meta)) == []
+def test_ownership_risk_no_clear_owner_names_the_share_arm():
+ # Under 20 commits nobody can hold <5%, so only the share arm fires.
+ meta = {"top_authors_json": _authors(("a", 3), ("b", 3), ("c", 2), ("d", 2))}
+ out = OwnershipRiskDetector().detect(_ctx(meta))
+ assert len(out) == 1
+ assert out[0].severity == "low"
+ assert out[0].details["minor_contributors"] == 0
+ assert out[0].reason == (
+ "no clear owner: the top author holds 30% of 10 commits across 4 contributors"
+ )
+
+
+def test_ownership_risk_caps_a_small_file_at_low():
+ ctx = _ctx(dict(_FRAGMENTED, is_hotspot=True))
+ ctx.nloc = 9 # a bodyless Spring Data interface
+ out = OwnershipRiskDetector().detect(ctx)
+ assert len(out) == 1
+ assert out[0].severity == "low" # high on a 120-line file
+ assert out[0].reason.endswith("(low: only 9 code lines)")
+
+
# ---- small-team calibration (issue #361) ---------------------------------
diff --git a/tests/unit/persistence/test_health_findings_worth_order.py b/tests/unit/persistence/test_health_findings_worth_order.py
index be05df46d..6abe474e7 100644
--- a/tests/unit/persistence/test_health_findings_worth_order.py
+++ b/tests/unit/persistence/test_health_findings_worth_order.py
@@ -11,6 +11,7 @@ from repowise.core.persistence.crud.analysis import (
health_finding_priorities,
save_health_findings,
)
+from repowise.core.persistence.models import GraphNode
from tests.unit.persistence.helpers import insert_repo
@@ -54,3 +55,36 @@ async def test_worth_first_then_impact_and_filters_keep_the_whole_shape(async_se
nested = await get_health_findings(async_session, repo.id, biomarker_type="nested_complexity")
reasons = await health_finding_priorities(async_session, repo.id, nested)
assert [reasons[f.id] for f in nested] == [None]
+
+
+async def test_test_file_findings_rank_below_production(async_session):
+ repo = await insert_repo(async_session)
+ async_session.add(
+ GraphNode(repository_id=repo.id, node_id="tests/test_a.py", node_type="file", is_test=True)
+ )
+ await save_health_findings(
+ async_session,
+ repo.id,
+ [
+ HealthFindingData(
+ biomarker_type="change_entropy",
+ severity=Severity.CRITICAL,
+ file_path="tests/test_a.py",
+ function_name=None,
+ line_start=None,
+ line_end=None,
+ details={},
+ health_impact=5.0,
+ ),
+ _finding("complex_method", "tidy", 3.0, ccn=14, nloc=40),
+ _finding("complex_method", "knot", 0.4, ccn=27, nloc=80),
+ ],
+ )
+ await async_session.commit()
+
+ rows = await get_health_findings(async_session, repo.id)
+ # Production first, even its lower-priority row; the test file last.
+ assert [f.file_path for f in rows] == ["a.py", "a.py", "tests/test_a.py"]
+ one = await get_health_findings(async_session, repo.id, file_path="tests/test_a.py")
+ assert [f.biomarker_type for f in one] == ["change_entropy"]