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
"""Organizational biomarker tests: Developer Congestion, Knowledge Loss,
Ownership Risk, Churn Risk, Change Entropy, Co-change Scatter."""
from __future__ import annotations
import json
from repowise.core.analysis.health.biomarkers import FileContext
from repowise.core.analysis.health.biomarkers.change_entropy import (
ChangeEntropyDetector,
)
from repowise.core.analysis.health.biomarkers.churn_risk import ChurnRiskDetector
from repowise.core.analysis.health.biomarkers.co_change_scatter import (
CoChangeScatterDetector,
)
from repowise.core.analysis.health.biomarkers.developer_congestion import (
DeveloperCongestionDetector,
)
from repowise.core.analysis.health.biomarkers.knowledge_loss import (
KnowledgeLossDetector,
)
from repowise.core.analysis.health.biomarkers.ownership_risk import (
OwnershipRiskDetector,
)
from repowise.core.analysis.health.biomarkers.prior_defect import (
PriorDefectDetector,
)
from repowise.core.analysis.health.complexity import FunctionComplexity
def _authors(*pairs: tuple[str, int]) -> str:
return json.dumps([{"name": n, "email": f"{n}@x", "commit_count": c} for n, c in pairs])
def _ctx(meta: dict, *, active_contributors: int | None = None) -> FileContext:
return FileContext(
file_path="src/payments.py",
language="python",
nloc=120,
has_test_file=False,
module=None,
git_meta=meta,
dependents_count=4,
pagerank_score=0.0,
repo_active_contributors_90d=active_contributors,
)
# ---- developer_congestion ------------------------------------------------
def test_developer_congestion_fires_on_crowded_hotspot():
meta = {
"contributor_count": 12,
"commit_count_90d": 25,
"churn_percentile": 0.9,
"primary_owner_commit_pct": 0.25,
"primary_owner_name": "Alice",
}
out = DeveloperCongestionDetector().detect(_ctx(meta))
assert len(out) == 1
assert out[0].severity == "high"
assert out[0].details["contributor_count"] == 12
def test_developer_congestion_normalizes_percent_form():
meta = {
"contributor_count": 6,
"commit_count_90d": 8,
"churn_percentile": 0.8,
"primary_owner_commit_pct": 30.0, # percent form
}
out = DeveloperCongestionDetector().detect(_ctx(meta))
assert out
assert out[0].details["primary_owner_share"] == 0.3
def test_developer_congestion_skips_with_clear_owner():
meta = {
"contributor_count": 8,
"commit_count_90d": 15,
"churn_percentile": 0.9,
"primary_owner_commit_pct": 0.65,
}
assert DeveloperCongestionDetector().detect(_ctx(meta)) == []
def test_developer_congestion_skips_quiet_files_for_this_repo():
"""The activity gate is the repository's own churn ranking. A busy file by
absolute count is not busy if most of the repository is busier."""
meta = {
"contributor_count": 8,
"commit_count_90d": 15,
"churn_percentile": 0.4,
"primary_owner_commit_pct": 0.2,
}
assert DeveloperCongestionDetector().detect(_ctx(meta)) == []
def _quiet_hotspot_meta(commits_90d: int) -> dict:
return {
"contributor_count": 5,
"churn_percentile": 0.9,
"commit_count_90d": commits_90d,
"primary_owner_commit_pct": 0.3,
}
def test_developer_congestion_skips_files_with_no_recent_commits():
"""A high percentile alone does not mean the file changed in the window."""
assert DeveloperCongestionDetector().detect(_ctx(_quiet_hotspot_meta(0))) == []
def test_developer_congestion_needs_the_hotspot_commit_floor():
assert DeveloperCongestionDetector().detect(_ctx(_quiet_hotspot_meta(2))) == []
out = DeveloperCongestionDetector().detect(_ctx(_quiet_hotspot_meta(3)))
assert len(out) == 1
assert out[0].severity == "low"
# ---- knowledge_loss ------------------------------------------------------
def test_knowledge_loss_fires_when_primary_owner_left():
meta = {
"bus_factor": 1,
"primary_owner_name": "Alice",
"recent_owner_name": "Bob",
"recent_owner_commit_pct": 0.8,
"is_hotspot": True,
}
out = KnowledgeLossDetector().detect(_ctx(meta))
assert len(out) == 1
assert out[0].severity == "high" # hotspot escalation
assert out[0].details["primary_owner"] == "Alice"
def test_knowledge_loss_fires_when_recent_share_collapses():
meta = {
"bus_factor": 1,
"primary_owner_name": "Alice",
"recent_owner_name": "Alice",
"recent_owner_commit_pct": 0.05,
"is_hotspot": False,
"commit_count_90d": 3, # still active → passes the activity gate
}
out = KnowledgeLossDetector().detect(_ctx(meta))
assert len(out) == 1
def test_knowledge_loss_skips_abandoned_stable_file():
"""Regression: an abandoned-but-stable file is low risk (survivor
effect) and must no longer fire after the activity gate."""
meta = {
"bus_factor": 1,
"primary_owner_name": "Alice",
"recent_owner_name": "Bob",
"recent_owner_commit_pct": 0.8,
"is_hotspot": False,
"commit_count_90d": 0,
}
assert KnowledgeLossDetector().detect(_ctx(meta)) == []
def test_knowledge_loss_skips_when_is_stable():
meta = {
"bus_factor": 1,
"primary_owner_name": "Alice",
"recent_owner_name": "Bob",
"recent_owner_commit_pct": 0.8,
"is_hotspot": True, # even a hotspot must not fire when stable
"is_stable": True,
}
assert KnowledgeLossDetector().detect(_ctx(meta)) == []
def test_knowledge_loss_skips_when_bus_factor_healthy():
meta = {
"bus_factor": 4,
"primary_owner_name": "Alice",
"recent_owner_name": "Bob",
"recent_owner_commit_pct": 0.1,
}
assert KnowledgeLossDetector().detect(_ctx(meta)) == []
def test_knowledge_loss_skips_without_owner_data():
assert KnowledgeLossDetector().detect(_ctx({"commit_count_90d": 3})) == []
def test_knowledge_loss_skips_a_pure_rename_with_no_authored_activity():
"""A file whose only recent commit is a pure rename has no authored
activity in the window: ``recent_owner_commit_pct`` is None (#2957), not
a real 0% share, so the quiet-owner check must not fire. The rename
itself still counts toward ``commit_count_90d``, keeping the file out of
``is_stable`` and past the activity gate."""
meta = {
"bus_factor": 1,
"primary_owner_name": "Alice",
"commit_count_90d": 1,
"is_hotspot": False,
}
assert KnowledgeLossDetector().detect(_ctx(meta)) == []
def test_knowledge_loss_still_fires_when_someone_else_authored_the_recent_commits():
"""Contrast with the rename-only case: real authored commits by another
person, even a genuine 0% share for the primary owner, still flags the
quiet owner."""
meta = {
"bus_factor": 1,
"primary_owner_name": "Alice",
"recent_owner_name": "Bob",
"recent_owner_commit_pct": 0.0,
"commit_count_90d": 2,
"is_hotspot": False,
}
out = KnowledgeLossDetector().detect(_ctx(meta))
assert len(out) == 1
assert out[0].details["primary_owner"] == "Alice"
# ---- ownership_risk ------------------------------------------------------
def test_ownership_risk_fires_on_fragmented_ownership():
# Owner holds 50/55; five drive-by authors each <5% of commits.
meta = {
"top_authors_json": _authors(
("Alice", 50), ("b", 1), ("c", 1), ("d", 1), ("e", 1), ("f", 1)
),
"is_hotspot": False,
}
out = OwnershipRiskDetector().detect(_ctx(meta))
assert len(out) == 1
assert out[0].severity == "high" # minor_contributors >= 5
assert out[0].details["minor_contributors"] == 5
assert out[0].details["total_commits"] == 55
def test_ownership_risk_escalates_to_critical_on_hotspot():
meta = {
"top_authors_json": _authors(
("Alice", 60),
("b", 1),
("c", 1),
("d", 1),
("e", 1),
("f", 1),
("g", 1),
),
"is_hotspot": True,
}
out = OwnershipRiskDetector().detect(_ctx(meta))
assert out
assert out[0].severity == "critical" # >= 6 minor + hotspot
def test_ownership_risk_skips_clear_single_owner():
# One dominant owner, one substantial co-owner, no minor contributors.
meta = {"top_authors_json": _authors(("Alice", 30), ("Bob", 10))}
assert OwnershipRiskDetector().detect(_ctx(meta)) == []
def test_ownership_risk_skips_low_commit_files():
meta = {"top_authors_json": _authors(("Alice", 2), ("Bob", 1))}
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) ---------------------------------
_FRAGMENTED = {
"top_authors_json": _authors(("Alice", 50), ("b", 1), ("c", 1), ("d", 1), ("e", 1), ("f", 1)),
"is_hotspot": False,
}
def test_ownership_risk_small_team_caps_at_low():
out = OwnershipRiskDetector().detect(_ctx(dict(_FRAGMENTED), active_contributors=2))
assert len(out) == 1
assert out[0].severity == "low" # was high — capped on a 2-person team
assert out[0].details["small_team"] is True
assert "small team" in out[0].reason
def test_ownership_risk_small_team_hotspot_keeps_severity():
meta = dict(_FRAGMENTED)
meta["is_hotspot"] = True
out = OwnershipRiskDetector().detect(_ctx(meta, active_contributors=2))
assert out
assert out[0].severity == "high" # corroborated by hotspot — not capped
def test_ownership_risk_unknown_team_size_keeps_severity():
out = OwnershipRiskDetector().detect(_ctx(dict(_FRAGMENTED), active_contributors=None))
assert out
assert out[0].severity == "high" # None = unknown → historical behaviour
assert out[0].details["small_team"] is False
def test_ownership_risk_large_team_keeps_severity():
out = OwnershipRiskDetector().detect(_ctx(dict(_FRAGMENTED), active_contributors=12))
assert out
assert out[0].severity == "high"
def test_knowledge_loss_small_team_caps_at_low():
meta = {
"bus_factor": 1,
"primary_owner_name": "Alice",
"recent_owner_name": "Bob",
"recent_owner_commit_pct": 0.05,
"is_hotspot": False,
"commit_count_90d": 3,
}
out = KnowledgeLossDetector().detect(_ctx(meta, active_contributors=2))
assert len(out) == 1
assert out[0].severity == "low" # was medium (gone + quiet) — capped
assert out[0].details["small_team"] is True
def test_knowledge_loss_small_team_hotspot_keeps_high():
meta = {
"bus_factor": 1,
"primary_owner_name": "Alice",
"recent_owner_name": "Bob",
"recent_owner_commit_pct": 0.8,
"is_hotspot": True,
}
out = KnowledgeLossDetector().detect(_ctx(meta, active_contributors=2))
assert len(out) == 1
assert out[0].severity == "high" # hotspot corroboration wins
# ---- churn_risk ----------------------------------------------------------
def test_churn_risk_fires_on_high_relative_churn():
# nloc=120 (from _ctx); 180 lines churned in 90d → relative_churn 1.5.
meta = {
"commit_count_90d": 8,
"churn_percentile": 0.9,
"lines_added_90d": 100,
"lines_deleted_90d": 80,
"is_hotspot": False,
}
out = ChurnRiskDetector().detect(_ctx(meta))
assert len(out) == 1
assert out[0].severity == "medium" # 1.5 <= rc < 2.5
assert out[0].details["relative_churn"] == 1.5
def test_churn_risk_escalates_to_critical_on_hotspot():
meta = {
"commit_count_90d": 12,
"churn_percentile": 0.95,
"lines_added_90d": 400,
"lines_deleted_90d": 200, # 600/120 = 5.0
"is_hotspot": True,
}
out = ChurnRiskDetector().detect(_ctx(meta))
assert out
assert out[0].severity == "critical" # rc >= 4 and hotspot
def test_churn_risk_skips_low_percentile():
meta = {
"commit_count_90d": 8,
"churn_percentile": 0.4, # below the 0.75 floor
"lines_added_90d": 100,
"lines_deleted_90d": 80,
}
assert ChurnRiskDetector().detect(_ctx(meta)) == []
def test_churn_risk_skips_size_proportionate_churn():
# High percentile + active, but churn is small relative to the file.
meta = {
"commit_count_90d": 8,
"churn_percentile": 0.9,
"lines_added_90d": 20,
"lines_deleted_90d": 10, # 30/120 = 0.25 < 1.0
}
assert ChurnRiskDetector().detect(_ctx(meta)) == []
# ---- change_entropy ------------------------------------------------------
def test_change_entropy_fires_on_high_percentile():
meta = {
"change_entropy": 1.4,
"change_entropy_pct": 0.88,
"commit_count_90d": 6,
"is_hotspot": False,
}
out = ChangeEntropyDetector().detect(_ctx(meta))
assert len(out) == 1
assert out[0].severity == "medium" # 0.80 <= pct < 0.90
# Stored 0-1 in, emitted 0-100 out: the detail shares its key with
# FileSignals.change_entropy_pct, which has always been 0-100, and the two
# land in the same get_health response.
assert out[0].details["change_entropy_pct"] == 88.0
def test_change_entropy_escalates_to_critical_on_hotspot():
meta = {
"change_entropy": 3.2,
"change_entropy_pct": 0.97,
"commit_count_90d": 9,
"is_hotspot": True,
}
out = ChangeEntropyDetector().detect(_ctx(meta))
assert out
assert out[0].severity == "critical" # pct >= 0.95 and hotspot
def test_change_entropy_skips_when_below_percentile():
meta = {
"change_entropy": 0.6,
"change_entropy_pct": 0.5, # below the 0.80 floor
"commit_count_90d": 6,
}
assert ChangeEntropyDetector().detect(_ctx(meta)) == []
def test_change_entropy_skips_low_activity():
meta = {
"change_entropy": 2.0,
"change_entropy_pct": 0.95,
"commit_count_90d": 2, # below the 3-commit activity gate
}
assert ChangeEntropyDetector().detect(_ctx(meta)) == []
def test_change_entropy_silent_without_signal():
# ESSENTIAL tier / file that never co-changed → no entropy, no firing
# even though the (defaulted) percentile field is present.
meta = {"change_entropy": 0.0, "change_entropy_pct": 0.0, "commit_count_90d": 8}
assert ChangeEntropyDetector().detect(_ctx(meta)) == []
# ---- co_change_scatter ---------------------------------------------------
def _partners(*pairs: tuple[str, float]) -> str:
return json.dumps(
[{"file_path": p, "co_change_count": c, "frequency": int(c)} for p, c in pairs]
)
def _scatter_meta(**over) -> dict:
meta = {
"co_change_scatter_pct": 0.85,
"co_change_partner_count": 41,
"co_change_mass": 12.5,
"co_change_partners_json": _partners(*[(f"m{i}.py", 3.0) for i in range(25)]),
"commit_count_90d": 5,
}
meta.update(over)
return meta
def test_co_change_scatter_fires_in_the_top_fifth():
(finding,) = CoChangeScatterDetector().detect(_ctx(_scatter_meta()))
assert finding.severity == "medium" # 0.80 <= pct < 0.95
assert finding.details["co_change_scatter_pct"] == 85.0
def test_co_change_scatter_high_severity_in_the_top_twentieth():
out = CoChangeScatterDetector().detect(_ctx(_scatter_meta(co_change_scatter_pct=0.97)))
assert out[0].severity == "high"
def test_co_change_scatter_reports_the_true_partner_count_not_the_stored_list():
"""The stored list is capped, so counting it saturates. The finding quotes
the count measured before truncation and carries the capped one beside it,
so a reader can see the stored list is a truncation."""
(finding,) = CoChangeScatterDetector().detect(_ctx(_scatter_meta()))
assert finding.details["scatter"] == 41
assert finding.details["recorded_partners"] == 25
assert "41 distinct files" in finding.reason
def test_co_change_scatter_falls_below_the_gate():
assert CoChangeScatterDetector().detect(_ctx(_scatter_meta(co_change_scatter_pct=0.79))) == []
def test_co_change_scatter_skips_low_activity():
assert CoChangeScatterDetector().detect(_ctx(_scatter_meta(commit_count_90d=1))) == []
def test_co_change_scatter_silent_on_essential_tier():
# No breadth columns (ESSENTIAL git tier, or an index written before they
# existed) -> no signal, rather than a guess off the truncated list.
assert CoChangeScatterDetector().detect(_ctx({"commit_count_90d": 8})) == []
def test_co_change_scatter_exempts_test_files():
"""A test co-changes with its subject by definition, so breadth says
nothing about it -- the same exemption hidden_coupling makes."""
ctx = FileContext(
file_path="tests/unit/test_payments.py",
language="python",
nloc=120,
has_test_file=False,
module=None,
git_meta=_scatter_meta(co_change_scatter_pct=0.99),
)
assert CoChangeScatterDetector().detect(ctx) == []
def test_co_change_scatter_exempts_a_barrel_that_defines_nothing():
ctx = FileContext(
file_path="packages/ui/src/zoom/index.ts",
language="typescript",
nloc=20,
has_test_file=False,
module=None,
git_meta=_scatter_meta(co_change_scatter_pct=0.99),
)
assert CoChangeScatterDetector().detect(ctx) == []
def test_co_change_scatter_exempts_a_barrel_named_file_even_with_logic():
"""The exemption is the filename alone, on purpose: history_refresh
re-scores from git metadata without a parse, so a structural corroboration
would answer differently depending on which pass ran."""
ctx = FileContext(
file_path="packages/ui/src/zoom/index.ts",
language="typescript",
nloc=400,
has_test_file=False,
module=None,
git_meta=_scatter_meta(co_change_scatter_pct=0.99),
all_functions=(
FunctionComplexity(
name="render",
start_line=1,
end_line=40,
ccn=6,
max_nesting=2,
cognitive=8,
nloc=35,
),
),
)
assert CoChangeScatterDetector().detect(ctx) == []
# ---- prior_defect --------------------------------------------------------
def _pd(count: int, **over) -> dict:
"""Fix history for a file in the top fifth of this repository."""
meta = {"prior_defect_count": count, "prior_defect_pct": 0.9}
meta.update(over)
return meta
def test_prior_defect_fires_low_on_single_fix():
out = PriorDefectDetector().detect(_ctx(_pd(1)))
assert len(out) == 1
assert out[0].severity == "low"
assert out[0].details["prior_defect_count"] == 1
assert out[0].details["window_days"] == 180
def test_prior_defect_scales_severity_with_count():
assert PriorDefectDetector().detect(_ctx(_pd(2)))[0].severity == "medium"
assert PriorDefectDetector().detect(_ctx(_pd(3)))[0].severity == "high"
assert PriorDefectDetector().detect(_ctx(_pd(6)))[0].severity == "critical"
def test_prior_defect_escalates_to_critical_on_hotspot():
# A mid-band count (3) on a churn hotspot compounds to CRITICAL.
out = PriorDefectDetector().detect(_ctx(_pd(3, is_hotspot=True)))
assert out[0].severity == "critical"
def test_prior_defect_silent_without_prior_fixes():
# No defect history (or ESSENTIAL tier where the field is absent) → silent.
assert PriorDefectDetector().detect(_ctx(_pd(0))) == []
assert PriorDefectDetector().detect(_ctx({"commit_count_90d": 9})) == []
def test_prior_defect_silent_below_the_repo_percentile():
"""Six months is a fixed window, so on a repository landing many commits a
day most files carry a fix or two. The entry is a share of the repository,
which is what stops the signal firing on half the tree."""
assert PriorDefectDetector().detect(_ctx(_pd(2, prior_defect_pct=0.5))) == []
def test_prior_defect_keeps_the_calibrated_ladder_above_the_gate():
"""Only the entry moved. Above it the count still decides the band, so a
file reports the severity the benchmark calibrated for its fix count."""
out = PriorDefectDetector().detect(_ctx(_pd(6, prior_defect_pct=0.81)))
assert out[0].severity == "critical"
assert out[0].details["prior_defect_pct"] == 81.0