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.

feat(health): add ownership and relative-churn process signals (#300)

Raghav Chamadiyafd592bceaa74
diff --git a/docs/CODE_HEALTH.md b/docs/CODE_HEALTH.md
index eab9f1fc6..00b45a898 100644
--- a/docs/CODE_HEALTH.md
+++ b/docs/CODE_HEALTH.md
@@ -1,9 +1,9 @@
# Code Health
-Repowise computes a 1–10 health score for every file in your repo from fifteen
+Repowise computes a 1–10 health score for every file in your repo from seventeen
deterministic biomarkers — McCabe complexity, deep nesting, brain methods,
clone detection, untested hotspots, function-level churn, code-age volatility,
-organizational risk, and more. **No LLM calls, no cloud requirement.** Pure
+ownership dispersion, relative churn, organizational risk, and more. **No LLM calls, no cloud requirement.** Pure
Python over tree-sitter + git data, designed to finish in under 30 seconds on a
3 000-file repo.
@@ -26,13 +26,13 @@ most:
| Category | Cap | Biomarkers |
|------------------------|-------|------------|
-| Organizational | −3.5 | developer_congestion, knowledge_loss, hidden_coupling, function_hotspot, code_age_volatility |
+| Organizational | −3.5 | developer_congestion, knowledge_loss, hidden_coupling, function_hotspot, code_age_volatility, ownership_risk, churn_risk |
| Structural complexity | −2.5 | brain_method, nested_complexity, bumpy_road, complex_conditional |
| Test coverage | −2.0 | untested_hotspot, coverage_gap |
| Size & complexity | −1.5 | complex_method, large_method, primitive_obsession |
| Duplication | −1.0 | dry_violation |
-Fifteen biomarkers across five categories. `function_hotspot` and
+Seventeen biomarkers across five categories. `function_hotspot` and
`code_age_volatility` are blame-based and sit in the organizational bucket —
both are tier-aware and stay silent on ESSENTIAL-tier repos until the per-line
blame index is built.
@@ -40,8 +40,9 @@ blame index is built.
Per-biomarker weight multipliers (see `scoring._BIOMARKER_WEIGHT_MULTIPLIER`)
let the strongest empirical predictors deduct more than the uniform severity
table alone allows. `developer_congestion` is multiplied by 1.5,
-`untested_hotspot` by 1.3, `function_hotspot` (a follow-up biomarker) by 1.2,
-and `knowledge_loss` is de-rated to 0.4. The de-rating is OSS-calibrated
+`untested_hotspot` by 1.3, `ownership_risk` by 1.3 (the strongest defect
+correlate in the literature), `function_hotspot` (a follow-up biomarker) and
+`churn_risk` by 1.2, and `knowledge_loss` is de-rated to 0.4. The de-rating is OSS-calibrated
(legacy code gets handed off because it works); enterprise users where
attrition is a real risk should raise it back via per-repo overrides — see
plan §3.5.
@@ -88,7 +89,9 @@ Severity grades along coverage depth.
Usually an ownership problem dressed up as a code problem.
**knowledge_loss** — The primary authors of the file are no longer active
-on the project. Refactor while someone still remembers why.
+on the project. Refactor while someone still remembers why. Gated on recent
+activity — an abandoned-but-stable file is low risk (the survivor effect),
+so this only fires while the code is still being changed.
**hidden_coupling** — Files that consistently change in the same commits
without an explicit import or dependency edge between them. Captures
@@ -117,6 +120,21 @@ days. Severity escalates with both axes (CRIT when median age ≥ 2y AND
≥ 5 recent commits). Tier-aware: same ESSENTIAL no-op as
`function_hotspot`.
+**ownership_risk** — Long-run ownership dispersion. Counts *minor
+contributors* — authors who each own less than 5% of the file's commits —
+and the dominant owner's share. Many drive-by authors with no clear owner is
+the single strongest defect correlate in the literature (Bird et al.). Fires
+on files with ≥ 5 commits where ≥ 3 contributors are minor or no owner holds
+40%. Complements `developer_congestion`, which measures *active* (90-day)
+contention rather than lifetime dispersion.
+
+**churn_risk** — Relative churn: the fraction of a file's lines rewritten in
+the last 90 days, normalized by file size. A file whose recent window rewrote
+more lines than it contains is structurally unstable regardless of how big it
+is. Because the trigger is a ratio to NLOC, it does not simply re-flag large
+files. Fires when the file is actively churning (≥ 5 recent commits, top
+quartile of repo churn) and relative churn ≥ 1.0.
+
## Test coverage
Pass coverage reports straight into the analyzer:
@@ -211,7 +229,7 @@ Health: 7.4 (avg) · 6.2 (hotspots) · 2.1 (worst: payments/processor.ts)
| Feature | Repowise | CodeScene | DeepSource | Sourcery |
|----------------------------------|:--:|:--:|:--:|:--:|
-| Code health score (1–10) | ✅ 15 biomarkers | ✅ 25–30 | ❌ | ❌ |
+| Code health score (1–10) | ✅ 17 biomarkers | ✅ 25–30 | ❌ | ❌ |
| Brain Method detection | ✅ | ✅ | ❌ | ❌ |
| Test coverage intelligence | ✅ LCOV/Cobertura/Clover | ❌ | ❌ | ❌ |
| Untested hotspot detection | ✅ coverage × hotspot | ❌ | ❌ | ❌ |
diff --git a/docs/architecture/code-health.md b/docs/architecture/code-health.md
index 7ee2c5483..b4029f521 100644
--- a/docs/architecture/code-health.md
+++ b/docs/architecture/code-health.md
@@ -101,7 +101,13 @@ analysis/health/
├── untested_hotspot.py
├── coverage_gap.py
├── developer_congestion.py
- └── knowledge_loss.py
+ ├── knowledge_loss.py
+ ├── hidden_coupling.py
+ ├── complex_conditional.py
+ ├── function_hotspot.py
+ ├── code_age_volatility.py
+ ├── ownership_risk.py
+ └── churn_risk.py
```
### Persistence
@@ -304,7 +310,7 @@ higher than dormant ones.
---
-## 5. The 12 biomarkers and their categories
+## 5. The 17 biomarkers and their categories
Each biomarker is a stateless class implementing the `Biomarker` Protocol
from `biomarkers/base.py`:
@@ -318,11 +324,18 @@ class Biomarker(Protocol):
| Category | Cap | Biomarkers |
|------------------------|------|------------|
-| Structural complexity | −3.5 | brain_method, nested_complexity, bumpy_road |
-| Size & complexity | −2.0 | complex_method, large_method, primitive_obsession |
-| Duplication | −1.5 | dry_violation |
+| Organizational | −3.5 | developer_congestion, knowledge_loss, hidden_coupling, function_hotspot, code_age_volatility, ownership_risk, churn_risk |
+| Structural complexity | −2.5 | brain_method, nested_complexity, bumpy_road, complex_conditional |
| Test coverage | −2.0 | untested_hotspot, coverage_gap |
-| Organizational | −1.0 | developer_congestion, knowledge_loss |
+| Size & complexity | −1.5 | complex_method, large_method, primitive_obsession |
+| Duplication | −1.0 | dry_violation |
+
+`ownership_risk` (long-run minor-contributor dispersion, Bird et al.) and
+`churn_risk` (size-normalized relative churn, Nagappan-Ball) are git-only
+process signals computed from `top_authors_json` / `lines_added_90d` /
+`churn_percentile` — fields the git indexer already produces. `knowledge_loss`
+is activity-gated so abandoned-but-stable files (the survivor effect) no longer
+fire.
`biomarkers/registry.py` is an **explicit list**, not auto-discovery —
keeps the registration order deterministic and lets tests inject extras
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/README.md b/packages/core/src/repowise/core/analysis/health/biomarkers/README.md
index 0cabdc6c0..db8554adb 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/README.md
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/README.md
@@ -9,7 +9,7 @@ class Biomarker(Protocol):
def detect(self, ctx: FileContext) -> list[BiomarkerResult]: ...
```
-## Registered detectors (14)
+## Registered detectors (17)
Structural complexity (cap −2.5):
- `brain_method` — symbols simultaneously long, complex, and central.
@@ -38,6 +38,12 @@ Organizational (cap −3.5):
frequently modified (per-function churn from the FULL-tier blame index).
- `code_age_volatility` — dormant functions (median line age ≥ 1y) that
are suddenly being modified again. Uses the same blame index.
+- `ownership_risk` — long-run ownership dispersion: many minor
+ contributors (each < 5% of commits) or no dominant owner. Bird's
+ strongest literature defect correlate.
+- `churn_risk` — relative churn: a file whose 90-day window rewrote a
+ large fraction of its own lines (size-normalized, so it doesn't simply
+ re-flag big files).
Caps were recalibrated to lift `organizational` (was −1.0) and de-rate
`size_and_complexity` / `duplication` per plan §3.1. A per-biomarker
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/churn_risk.py b/packages/core/src/repowise/core/analysis/health/biomarkers/churn_risk.py
new file mode 100644
index 000000000..d0d489c3b
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/churn_risk.py
@@ -0,0 +1,104 @@
+"""Churn Risk — a file being rewritten faster than its size.
+
+Nagappan & Ball (ICSE 2005) found that *relative* churn — code churn
+normalized by file size — predicts defect density ~89% accurately,
+while raw churn is a weak predictor. A file whose 90-day window rewrote
+more lines than the file contains is structurally unstable regardless
+of how large it is.
+
+The trigger is a *ratio* to NLOC, so this does not simply re-flag big
+files — that is the point. It is the size-normalized counterpart to the
+raw-activity signals, designed to survive the partial-Spearman / NLOC
+control.
+
+Fires when the file is actively and disproportionately churning
+relative to its size:
+
+- ``commit_count_90d`` ≥ 5, AND
+- ``churn_percentile`` ≥ 0.75 (top quartile of repo-relative churn), AND
+- ``relative_churn`` ≥ 1.0 (the 90-day window rewrote ≥100% of lines).
+
+Reads ``git_meta`` only. When git indexing was skipped the fields are
+absent/zero and the detector emits nothing.
+"""
+
+from __future__ import annotations
+
+from ..models import Severity
+from .base import BiomarkerResult, FileContext
+
+_MIN_COMMITS_90D = 5
+_CHURN_PCT_FLOOR = 0.75
+_RELATIVE_CHURN_FLOOR = 1.0
+
+
+def _as_int(value: object, default: int = 0) -> int:
+ try:
+ return int(value or 0) # type: ignore[arg-type]
+ except (TypeError, ValueError):
+ return default
+
+
+def _as_float(value: object, default: float = 0.0) -> float:
+ try:
+ return float(value or 0.0) # type: ignore[arg-type]
+ except (TypeError, ValueError):
+ return default
+
+
+class ChurnRiskDetector:
+ name = "churn_risk"
+ category = "organizational"
+
+ def detect(self, ctx: FileContext) -> list[BiomarkerResult]:
+ meta = ctx.git_meta or {}
+ commits_90d = _as_int(meta.get("commit_count_90d"))
+ if commits_90d < _MIN_COMMITS_90D:
+ return []
+
+ churn_pct = _as_float(meta.get("churn_percentile"))
+ if churn_pct < _CHURN_PCT_FLOOR:
+ return []
+
+ added = _as_int(meta.get("lines_added_90d"))
+ deleted = _as_int(meta.get("lines_deleted_90d"))
+ nloc = max(ctx.nloc, 1)
+ relative_churn = (added + deleted) / nloc
+ if relative_churn < _RELATIVE_CHURN_FLOOR:
+ return []
+
+ is_hotspot = bool(meta.get("is_hotspot"))
+ if relative_churn >= 4 and is_hotspot:
+ severity = Severity.CRITICAL
+ elif relative_churn >= 2.5:
+ severity = Severity.HIGH
+ elif relative_churn >= 1.5:
+ severity = Severity.MEDIUM
+ else:
+ severity = Severity.LOW
+
+ return [
+ BiomarkerResult(
+ biomarker_type=self.name,
+ severity=severity,
+ function_name=None,
+ line_start=None,
+ line_end=None,
+ details={
+ "relative_churn": round(relative_churn, 2),
+ "churn_percentile": round(churn_pct, 3),
+ "lines_added_90d": added,
+ "lines_deleted_90d": deleted,
+ "commit_count_90d": commits_90d,
+ "nloc": ctx.nloc,
+ },
+ reason=(
+ f"90-day churn rewrote {relative_churn:.0%} of the file's lines "
+ f"({added + deleted} lines over {ctx.nloc} NLOC, "
+ f"top {(1 - churn_pct):.0%} of repo churn)"
+ ),
+ )
+ ]
+
+
+BIOMARKER = ChurnRiskDetector()
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/knowledge_loss.py b/packages/core/src/repowise/core/analysis/health/biomarkers/knowledge_loss.py
index 551f7b3af..582f96530 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/knowledge_loss.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/knowledge_loss.py
@@ -8,10 +8,17 @@ this code.
Fires when:
-- ``bus_factor`` ≤ 1 (the file has one true author)
-- AND ``primary_owner_name`` differs from ``recent_owner_name`` OR the
+- the file is still changing (``commit_count_90d`` ≥ 1 or it is a
+ hotspot; an ``is_stable`` file never fires), AND
+- ``bus_factor`` ≤ 1 (the file has one true author), AND
+- ``primary_owner_name`` differs from ``recent_owner_name`` OR the
recent owner contributes < 20% of recent commits
+The activity gate is what makes this signal point the right way: an
+abandoned-but-stable file is *low* risk (the survivor effect — code
+nobody touches doesn't break), so knowledge loss only matters while the
+code is live and the lost author's intent is still being edited around.
+
Severity grades on whether the file is also a hotspot.
"""
@@ -50,6 +57,14 @@ class KnowledgeLossDetector:
def detect(self, ctx: FileContext) -> list[BiomarkerResult]:
meta = ctx.git_meta or {}
+
+ # Activity gate: an abandoned-but-stable file is low risk
+ # (survivor effect). Only fire while the code is still live.
+ if meta.get("is_stable"):
+ return []
+ if _as_int(meta.get("commit_count_90d")) < 1 and not _is_hotspot(meta):
+ return []
+
bus = _as_int(meta.get("bus_factor"))
if bus > _BUS_FACTOR_THRESHOLD or bus == 0:
# bus_factor 0 means git indexing was skipped or the file
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
new file mode 100644
index 000000000..1e1c6b5f1
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/ownership_risk.py
@@ -0,0 +1,109 @@
+"""Ownership Risk — fragmented, drive-by ownership of a file.
+
+Bird et al. ("Don't Touch My Code", FSE 2011) found that the count of
+*minor contributors* — developers who each own less than 5% of a file's
+commits — is the single strongest defect correlate in the literature
+(0.86-0.93), beating size, churn, and complexity. A file with many
+drive-by authors and no clear owner accumulates inconsistent mental
+models and is far more defect-prone.
+
+This measures *long-run* ownership dispersion, complementing
+``developer_congestion`` (which captures *active*, 90-day contention).
+The two deliberately overlap; the benchmark measures their independent
+lift.
+
+Fires when the file is non-trivial and ownership is fragmented:
+
+- ``total_commits`` ≥ 5, AND
+- ``minor_contributors`` ≥ 3 OR ``top_owner_share`` < 0.4.
+
+Reads ``git_meta["top_authors_json"]`` only; no AST work needed. When
+git indexing was skipped the field is empty and the detector emits
+nothing.
+"""
+
+from __future__ import annotations
+
+import json
+from typing import Any
+
+from ..models import Severity
+from .base import BiomarkerResult, FileContext
+
+_MIN_COMMITS = 5
+_MINOR_SHARE = 0.05
+_MINOR_THRESHOLD = 3
+_TOP_OWNER_FLOOR = 0.4
+
+
+def _parse_authors(meta: dict[str, Any]) -> list[tuple[str, int]]:
+ raw = meta.get("top_authors_json")
+ if not raw:
+ return []
+ try:
+ authors = json.loads(raw)
+ except (TypeError, ValueError):
+ return []
+ out: list[tuple[str, int]] = []
+ for a in authors:
+ if not isinstance(a, dict):
+ continue
+ name = a.get("name") or ""
+ try:
+ count = int(a.get("commit_count") or 0)
+ except (TypeError, ValueError):
+ continue
+ if count > 0:
+ out.append((str(name), count))
+ return out
+
+
+class OwnershipRiskDetector:
+ name = "ownership_risk"
+ category = "organizational"
+
+ def detect(self, ctx: FileContext) -> list[BiomarkerResult]:
+ meta = ctx.git_meta or {}
+ authors = _parse_authors(meta)
+ total = sum(c for _, c in authors)
+ if total < _MIN_COMMITS:
+ return []
+
+ minor_contributors = sum(1 for _, c in authors if c / total < _MINOR_SHARE)
+ top_owner_share = max((c / total for _, c in authors), default=0.0)
+
+ if not (minor_contributors >= _MINOR_THRESHOLD or top_owner_share < _TOP_OWNER_FLOOR):
+ return []
+
+ is_hotspot = bool(meta.get("is_hotspot"))
+ if minor_contributors >= 6 and is_hotspot:
+ severity = Severity.CRITICAL
+ elif minor_contributors >= 5 or (minor_contributors >= 3 and is_hotspot):
+ severity = Severity.HIGH
+ elif minor_contributors >= 3:
+ severity = Severity.MEDIUM
+ else:
+ severity = Severity.LOW
+
+ return [
+ BiomarkerResult(
+ biomarker_type=self.name,
+ severity=severity,
+ function_name=None,
+ line_start=None,
+ line_end=None,
+ details={
+ "minor_contributors": minor_contributors,
+ "top_owner_share": round(top_owner_share, 3),
+ "contributor_count": len(authors),
+ "total_commits": total,
+ },
+ reason=(
+ f"{minor_contributors} minor contributors (each <5% of commits); "
+ f"top owner holds {top_owner_share:.0%}"
+ ),
+ )
+ ]
+
+
+BIOMARKER = OwnershipRiskDetector()
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/registry.py b/packages/core/src/repowise/core/analysis/health/biomarkers/registry.py
index 7d810c4b2..4a169bafe 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/registry.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/registry.py
@@ -14,6 +14,7 @@ from collections.abc import Sequence
from .base import Biomarker, BiomarkerResult, FileContext
from .brain_method import BrainMethodDetector
from .bumpy_road import BumpyRoadDetector
+from .churn_risk import ChurnRiskDetector
from .code_age_volatility import CodeAgeVolatilityDetector
from .complex_conditional import ComplexConditionalDetector
from .complex_method import ComplexMethodDetector
@@ -25,6 +26,7 @@ from .hidden_coupling import HiddenCouplingDetector
from .knowledge_loss import KnowledgeLossDetector
from .large_method import LargeMethodDetector
from .nested_complexity import NestedComplexityDetector
+from .ownership_risk import OwnershipRiskDetector
from .primitive_obsession import PrimitiveObsessionDetector
from .untested_hotspot import UntestedHotspotDetector
@@ -44,6 +46,8 @@ _DETECTOR_FACTORIES: list[type[Biomarker]] = [
ComplexConditionalDetector, # type: ignore[list-item]
FunctionHotspotDetector, # type: ignore[list-item]
CodeAgeVolatilityDetector, # type: ignore[list-item]
+ OwnershipRiskDetector, # type: ignore[list-item]
+ ChurnRiskDetector, # type: ignore[list-item]
]
diff --git a/packages/core/src/repowise/core/analysis/health/scoring.py b/packages/core/src/repowise/core/analysis/health/scoring.py
index 638c4d9e0..a3568b6da 100644
--- a/packages/core/src/repowise/core/analysis/health/scoring.py
+++ b/packages/core/src/repowise/core/analysis/health/scoring.py
@@ -57,6 +57,8 @@ _BIOMARKER_WEIGHT_MULTIPLIER: dict[str, float] = {
"function_hotspot": 1.2,
"code_age_volatility": 1.1,
"hidden_coupling": 1.0,
+ "ownership_risk": 1.3,
+ "churn_risk": 1.2,
"knowledge_loss": 0.4,
# Governance — additive pass, weights are informational
"contradictory_decision": 1.0,
@@ -83,6 +85,8 @@ _BIOMARKER_CATEGORY: dict[str, str] = {
"hidden_coupling": "organizational",
"function_hotspot": "organizational",
"code_age_volatility": "organizational",
+ "ownership_risk": "organizational",
+ "churn_risk": "organizational",
# Governance biomarkers — written by the additive governance pass
"ungoverned_hotspot": "organizational",
"stale_governance": "organizational",
diff --git a/packages/core/src/repowise/core/analysis/health/suggestions.py b/packages/core/src/repowise/core/analysis/health/suggestions.py
index a2dc3cf05..e0a542e7b 100644
--- a/packages/core/src/repowise/core/analysis/health/suggestions.py
+++ b/packages/core/src/repowise/core/analysis/health/suggestions.py
@@ -97,6 +97,20 @@ _TEMPLATES: dict[str, str] = {
"the original author or write down the design intent before "
"shipping the next change."
),
+ "ownership_risk": (
+ "Assign a clear owner and reduce drive-by contributors on this "
+ "file. Fragmented ownership — many authors each touching a small "
+ "slice — is one of the strongest defect predictors; nominate a "
+ "DRI for reviews, or split the file along its natural seams so "
+ "each part has a coherent owner."
+ ),
+ "churn_risk": (
+ "This file is being rewritten faster than its size. Stabilize "
+ "the interface and add characterization tests before the next "
+ "change — high relative churn means the design hasn't settled, "
+ "so lock in current behavior and slow the rate of structural "
+ "edits."
+ ),
"knowledge_loss": (
"Document the surviving knowledge. The primary author(s) of "
"this file are no longer active — pair-program with someone "
diff --git a/tests/unit/health/test_organizational_biomarkers.py b/tests/unit/health/test_organizational_biomarkers.py
index 11a04e18a..aa98368a1 100644
--- a/tests/unit/health/test_organizational_biomarkers.py
+++ b/tests/unit/health/test_organizational_biomarkers.py
@@ -1,14 +1,25 @@
-"""Developer Congestion + Knowledge Loss biomarker tests."""
+"""Organizational biomarker tests: Developer Congestion, Knowledge Loss,
+Ownership Risk, Churn Risk."""
from __future__ import annotations
+import json
+
from repowise.core.analysis.health.biomarkers import FileContext
+from repowise.core.analysis.health.biomarkers.churn_risk import ChurnRiskDetector
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,
+)
+
+
+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) -> FileContext:
@@ -94,11 +105,38 @@ def test_knowledge_loss_fires_when_recent_share_collapses():
"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,
@@ -110,4 +148,103 @@ def test_knowledge_loss_skips_when_bus_factor_healthy():
def test_knowledge_loss_skips_without_owner_data():
- assert KnowledgeLossDetector().detect(_ctx({})) == []
+ assert KnowledgeLossDetector().detect(_ctx({"commit_count_90d": 3})) == []
+
+
+# ---- 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)) == []
+
+
+# ---- 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)) == []
diff --git a/tests/unit/health/test_scoring_snapshot.py b/tests/unit/health/test_scoring_snapshot.py
index 6bd4af43d..7981ce006 100644
--- a/tests/unit/health/test_scoring_snapshot.py
+++ b/tests/unit/health/test_scoring_snapshot.py
@@ -43,6 +43,8 @@ _EXPECTED_BIOMARKER_WEIGHT_MULTIPLIER = {
"function_hotspot": 1.2,
"code_age_volatility": 1.1,
"hidden_coupling": 1.0,
+ "ownership_risk": 1.3,
+ "churn_risk": 1.2,
"knowledge_loss": 0.4,
# Phase 4B governance biomarkers (informational — surfaced as findings,
# not fed back into the score pass, which has already run upstream).
@@ -67,6 +69,8 @@ _EXPECTED_BIOMARKER_CATEGORY = {
"hidden_coupling": "organizational",
"function_hotspot": "organizational",
"code_age_volatility": "organizational",
+ "ownership_risk": "organizational",
+ "churn_risk": "organizational",
# Phase 4B governance biomarkers.
"ungoverned_hotspot": "organizational",
"stale_governance": "organizational",