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(health): calibrate hotspot + ownership signals for small teams and quiet repos (#361) (#363)
Raghav Chamadiyab6bbe1f8856c
diff --git a/docs/architecture/ARCHITECTURE.md b/docs/architecture/ARCHITECTURE.mdindex 8a13e8394..9012bfdf2 100644--- a/docs/architecture/ARCHITECTURE.md+++ b/docs/architecture/ARCHITECTURE.md@@ -856,7 +856,8 @@ tracked file, it computes:the code evolved this way and are included in generation prompts.- **Co-change partners** — files that changed in the same commit >= 3 times, evenwithout an import relationship. Reveals hidden structural coupling.-- **Derived signals** — `is_hotspot` (top 25% churn AND complexity), `is_stable`+- **Derived signals** — `is_hotspot` (top-quartile decayed churn AND absolute+ activity floors: >= 3 commits in 90d with real line movement), `is_stable`(>10 commits, 0 in 90 days), `churn_percentile` (0.0–1.0)**Performance targets:**@@ -1205,7 +1206,7 @@ GraphBuilderGitIndexer (if git.enabled)mines git history → git_metadata tablecomputes co-change partners → adds co_changes edges to graph- classifies hotspots (top 25% churn + complexity)+ classifies hotspots (top-quartile decayed churn + absolute activity floors)classifies stable files (>10 commits, 0 in 90 days)│▼diff --git a/docs/architecture/deep-dives.md b/docs/architecture/deep-dives.mdindex b43f9b683..adfbdfc1a 100644--- a/docs/architecture/deep-dives.md+++ b/docs/architecture/deep-dives.md@@ -469,7 +469,9 @@ The commit contains "replace" (conflict keyword) and shares "bcrypt",**Question:** "Which files change a lot but have no documented decisions explaining why?"```-hotspot_files = files where churn_percentile >= 0.75 AND commit_count_90d > 0+hotspot_files = files where churn_percentile >= 0.75+ AND commit_count_90d >= 3+ AND (temporal_hotspot_score >= 0.5 OR commit_count_90d >= 8)governed_files = union of all affected_files across active decisionsdiff --git a/docs/architecture/implementation-deep-dive.md b/docs/architecture/implementation-deep-dive.mdindex 51976aaef..449073c5a 100644--- a/docs/architecture/implementation-deep-dive.md+++ b/docs/architecture/implementation-deep-dive.md@@ -264,7 +264,7 @@ Churn├── lines_added_90d, lines_deleted_90d├── avg_commit_size├── churn_percentile (rank among all files, 0.0-1.0)-├── is_hotspot (churn_percentile >= 0.75 AND active in 90d)+├── is_hotspot (churn_percentile >= 0.75 AND >= 3 commits in 90d AND real line movement)└── is_stable (> 10 total commits BUT 0 in 90d)Significant Commitsdiff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/base.py b/packages/core/src/repowise/core/analysis/health/biomarkers/base.pyindex d2688202c..c3a00c2b6 100644--- a/packages/core/src/repowise/core/analysis/health/biomarkers/base.py+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/base.py@@ -86,6 +86,23 @@ class FileContext:# blame is unavailable or no functions exist. ``function_hotspot``# uses this as the churn threshold for its top-quintile gate.repo_function_mod_p80: int | None = None+ # Distinct non-bot contributors active in the repo's trailing 90-day+ # window, computed once by the engine from ``top_authors_json``+ # timestamps. ``None`` = unknown (git skipped, or the index predates+ # per-author timestamps) — ownership biomarkers must treat ``None``+ # as "no team-size signal" and keep their historical behaviour. On+ # small teams (≤ SMALL_TEAM_MAX_CONTRIBUTORS) concentration-only+ # ownership findings are downgraded to informational severity unless+ # corroborated (issue #361).+ repo_active_contributors_90d: int | None = None+++# A repo whose trailing-90-day window has at most this many active human+# contributors is a "small team": concentrated ownership there is the normal+# operating model, not a silo warning. Used by ``ownership_risk`` /+# ``knowledge_loss`` (and the server's risk classifier) to cap severity of+# concentration-only findings at LOW unless corroborated by a hotspot signal.+SMALL_TEAM_MAX_CONTRIBUTORS: int = 3@dataclassdiff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/knowledge_loss.py b/packages/core/src/repowise/core/analysis/health/biomarkers/knowledge_loss.pyindex 582f96530..f35aa5968 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@@ -20,12 +20,17 @@ nobody touches doesn't break), so knowledge loss only matters while thecode is live and the lost author's intent is still being edited around.Severity grades on whether the file is also a hotspot.++On a small team (≤ ``SMALL_TEAM_MAX_CONTRIBUTORS`` active contributors+in 90d), bus-factor-1 files are the expected operating model — the risk+is real but not actionable, so severity is capped at LOW unless the file+is also a hotspot (issue #361)."""from __future__ import annotationsfrom ..models import Severity-from .base import BiomarkerResult, FileContext+from .base import SMALL_TEAM_MAX_CONTRIBUTORS, BiomarkerResult, FileContext_BUS_FACTOR_THRESHOLD = 1_RECENT_SHARE_THRESHOLD = 0.2@@ -84,13 +89,29 @@ class KnowledgeLossDetector:if not (primary_gone or recent_quiet):return []- if _is_hotspot(meta):+ hotspot = _is_hotspot(meta)+ if hotspot:severity = Severity.HIGHelif primary_gone and recent_quiet:severity = Severity.MEDIUMelse:severity = Severity.LOW+ reason = (+ f"Primary owner {primary} no longer the recent owner"+ if primary_gone+ else f"Primary owner {primary} barely active (recent share {share:.0%})"+ )++ # Small-team calibration (issue #361): on a 1-3 person team,+ # bus_factor ≤ 1 is the norm, not a silo signal. Keep the finding+ # but cap it at LOW unless the file is hotspot-active.+ active = ctx.repo_active_contributors_90d+ small_team = active is not None and active <= SMALL_TEAM_MAX_CONTRIBUTORS+ if small_team and not hotspot and severity != Severity.LOW:+ severity = Severity.LOW+ reason += f" (informational: small team, {active} active contributors in 90d)"+return [BiomarkerResult(biomarker_type=self.name,@@ -103,13 +124,10 @@ class KnowledgeLossDetector:"primary_owner": primary,"recent_owner": recent or None,"recent_owner_share": round(share, 3),- "is_hotspot": _is_hotspot(meta),+ "is_hotspot": hotspot,+ "small_team": small_team,},- reason=(- f"Primary owner {primary} no longer the recent owner"- if primary_gone- else f"Primary owner {primary} barely active (recent share {share:.0%})"- ),+ reason=reason,)]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.pyindex 1e1c6b5f1..29064c5ac 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,11 @@ Fires when the file is non-trivial and ownership is fragmented:- ``total_commits`` ≥ 5, AND- ``minor_contributors`` ≥ 3 OR ``top_owner_share`` < 0.4.+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+capped at LOW unless the file is also a hotspot (issue #361).+Reads ``git_meta["top_authors_json"]`` only; no AST work needed. Whengit indexing was skipped the field is empty and the detector emitsnothing.@@ -28,7 +33,7 @@ import jsonfrom typing import Anyfrom ..models import Severity-from .base import BiomarkerResult, FileContext+from .base import SMALL_TEAM_MAX_CONTRIBUTORS, BiomarkerResult, FileContext_MIN_COMMITS = 5_MINOR_SHARE = 0.05@@ -85,6 +90,21 @@ class OwnershipRiskDetector:else:severity = Severity.LOW+ reason = (+ f"{minor_contributors} minor contributors (each <5% of commits); "+ f"top owner holds {top_owner_share:.0%}"+ )++ # Small-team calibration (issue #361): with ≤3 active contributors,+ # ownership concentration/dispersion is the expected shape of the+ # project. Keep the finding (it's accurate) but cap it at LOW unless+ # corroborated by hotspot-grade activity — accurate ≠ actionable.+ active = ctx.repo_active_contributors_90d+ small_team = active is not None and active <= SMALL_TEAM_MAX_CONTRIBUTORS+ if small_team and not is_hotspot and severity != Severity.LOW:+ severity = Severity.LOW+ reason += f" (informational: small team, {active} active contributors in 90d)"+return [BiomarkerResult(biomarker_type=self.name,@@ -97,11 +117,9 @@ class OwnershipRiskDetector:"top_owner_share": round(top_owner_share, 3),"contributor_count": len(authors),"total_commits": total,+ "small_team": small_team,},- reason=(- f"{minor_contributors} minor contributors (each <5% of commits); "- f"top owner holds {top_owner_share:.0%}"- ),+ reason=reason,)]diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.pyindex ac3954bb2..d0e27ef5c 100644--- a/packages/core/src/repowise/core/analysis/health/engine.py+++ b/packages/core/src/repowise/core/analysis/health/engine.py@@ -26,6 +26,7 @@ from typing import Anyimport structlog+from ...ingestion.git_indexer.enrich import count_active_contributorsfrom ...ingestion.git_indexer.function_blame import (BlameIndex,distinct_commits_in_range,@@ -188,6 +189,24 @@ def _compute_repo_dependents_p80(parsed_files: list[Any], graph: Any) -> int | Nreturn _percentile_p80(counts)+def _compute_repo_active_contributors(git_meta_map: dict[str, dict]) -> int | None:+ """Distinct non-bot contributors active in the repo's trailing 90 days.++ Derived from the per-author ``last_commit_ts`` timestamps already in+ ``top_authors_json`` — no extra git work. ``None`` = unknown (git+ skipped, or a pre-timestamp index); biomarkers then keep their+ historical behaviour rather than mis-gating on a phantom team size.+ """+ metas = [m for m in git_meta_map.values() if isinstance(m, dict)]+ if not metas:+ return None+ try:+ return count_active_contributors(metas)+ except Exception as exc:+ log.debug("health_active_contributors_failed", error=str(exc))+ return None++def _build_repo_commit_counts(git_meta_map: dict[str, dict]) -> dict[str, int]:out: dict[str, int] = {}for path, meta in git_meta_map.items():@@ -315,6 +334,7 @@ class HealthAnalyzer:repo_fn_mod_p80 = _compute_repo_function_mod_p80(walked, self.git_meta_map)repo_dependents_p80 = _compute_repo_dependents_p80(self.parsed_files, self.graph)+ repo_active_contributors = _compute_repo_active_contributors(self.git_meta_map)for pf, fcx in walked:# Side-effect: bump Symbol.complexity_estimate when we can@@ -338,6 +358,7 @@ class HealthAnalyzer:repo_commit_counts=repo_commit_counts,repo_function_mod_p80=repo_fn_mod_p80,repo_dependents_p80=repo_dependents_p80,+ repo_active_contributors_90d=repo_active_contributors,)metrics.append(file_metric)findings.extend(file_findings)@@ -436,6 +457,7 @@ class HealthAnalyzer:walked = await asyncio.gather(*[_one(pf) for pf in target_files])repo_fn_mod_p80 = _compute_repo_function_mod_p80(list(walked), self.git_meta_map)repo_dependents_p80 = _compute_repo_dependents_p80(self.parsed_files, self.graph)+ repo_active_contributors = _compute_repo_active_contributors(self.git_meta_map)findings: list[HealthFindingData] = []metrics: list[HealthFileMetricData] = []@@ -457,6 +479,7 @@ class HealthAnalyzer:repo_commit_counts=repo_commit_counts,repo_function_mod_p80=repo_fn_mod_p80,repo_dependents_p80=repo_dependents_p80,+ repo_active_contributors_90d=repo_active_contributors,)metrics.append(file_metric)findings.extend(file_findings)@@ -534,6 +557,7 @@ class HealthAnalyzer:repo_commit_counts: dict[str, int] | None = None,repo_function_mod_p80: int | None = None,repo_dependents_p80: int | None = None,+ repo_active_contributors_90d: int | None = None,) -> tuple[HealthFileMetricData, list[HealthFindingData]]:file_path = pf.file_info.path@@ -591,6 +615,7 @@ class HealthAnalyzer:repo_commit_counts=repo_commit_counts or {},blame_index=blame_index,repo_function_mod_p80=repo_function_mod_p80,+ repo_active_contributors_90d=repo_active_contributors_90d,)biomarker_results = detect_all(ctx, disabled=disabled)diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/__init__.py b/packages/core/src/repowise/core/ingestion/git_indexer/__init__.pyindex 4c41056f6..3a361f9a5 100644--- a/packages/core/src/repowise/core/ingestion/git_indexer/__init__.py+++ b/packages/core/src/repowise/core/ingestion/git_indexer/__init__.py@@ -24,9 +24,11 @@ from .backfill import BACKFILL_PHASE, backfill_full_tierfrom .co_change import compute_co_changes, compute_co_changes_and_entropyfrom .enrich import (compute_percentiles,+ count_active_contributors,detect_original_path,get_blame_ownership,is_significant_commit,+ meets_hotspot_floors,)from .file_history import index_filefrom .indexer import GitIndexer@@ -62,9 +64,11 @@ __all__ = ["compute_co_changes_and_entropy","compute_percentiles","compute_prior_defects",+ "count_active_contributors","detect_original_path","get_blame_ownership","index_file","is_fix_commit","is_significant_commit",+ "meets_hotspot_floors",]diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/_constants.py b/packages/core/src/repowise/core/ingestion/git_indexer/_constants.pyindex 9b243ec61..0c4ed2929 100644--- a/packages/core/src/repowise/core/ingestion/git_indexer/_constants.py+++ b/packages/core/src/repowise/core/ingestion/git_indexer/_constants.py@@ -203,6 +203,28 @@ _CO_CHANGE_DECAY_TAU: float = 180.0# Hotspot temporal decay: half-life for exponentially weighted churn score.HOTSPOT_HALFLIFE_DAYS: float = 180.0+# Absolute activity floors for hotspot classification (issue #361). The+# churn percentile is repo-relative, so on a quiet repo "top quartile"+# degenerates to "any file touched in the last 90 days" — a single drive-by+# maintenance commit was enough to flag a hotspot. A file must clear BOTH+# the relative gate (top-quartile decayed churn) and these absolute floors:+#+# - at least HOTSPOT_MIN_COMMITS_90D commits in the window (repeated+# recent activity, not one drive-by), AND+# - a decayed-churn score of at least HOTSPOT_MIN_TEMPORAL_SCORE (the+# commits moved real lines — e.g. one ~50-line change today, or ~3+# focused 20-line changes this month — not a string of one-liners),+# OR HOTSPOT_HIGH_COMMITS_90D+ commits in the window (sustained high+# commit volume is hotspot-grade activity even when numstat line counts+# are unavailable, e.g. binary files). The 8-commit escape matches the+# threshold the health biomarkers already treat as hotspot-equivalent.+#+# Mirrored in the SQL PERCENT_RANK path (crud/git.py::recompute_git_percentiles)+# — keep the two in sync.+HOTSPOT_MIN_COMMITS_90D: int = 3+HOTSPOT_MIN_TEMPORAL_SCORE: float = 0.5+HOTSPOT_HIGH_COMMITS_90D: int = 8+# Regex to extract PR/MR numbers from commit messages.# Matches: "#123", "Merge pull request #456", "(#789)", "!42" (GitLab MR)_PR_NUMBER_RE = re.compile(r"(?:pull request |)\#(\d+)|\(#(\d+)\)|!(\d+)")diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/enrich.py b/packages/core/src/repowise/core/ingestion/git_indexer/enrich.pyindex 8c8839351..59e815743 100644--- a/packages/core/src/repowise/core/ingestion/git_indexer/enrich.py+++ b/packages/core/src/repowise/core/ingestion/git_indexer/enrich.py@@ -9,6 +9,7 @@ significance/percentile logic that only the FULL tier needs live here.from __future__ import annotations+import jsonfrom collections import Counterfrom typing import Any@@ -18,13 +19,18 @@ from ._constants import (_MIN_MESSAGE_LEN,_SKIP_AUTHORS,_SOFT_SKIP_PREFIXES,+ HOTSPOT_HIGH_COMMITS_90D,+ HOTSPOT_MIN_COMMITS_90D,+ HOTSPOT_MIN_TEMPORAL_SCORE,)__all__ = ["compute_percentiles",+ "count_active_contributors","detect_original_path","get_blame_ownership","is_significant_commit",+ "meets_hotspot_floors",]@@ -110,6 +116,78 @@ def is_significant_commit(message: str, author: str) -> bool:return True+def meets_hotspot_floors(meta: dict) -> bool:+ """Absolute activity floors for hotspot classification (issue #361).++ The churn percentile is repo-relative, so on a quiet repo the top+ quartile degenerates to "any file touched recently". A hotspot must+ also show enough *absolute* recent activity: repeated commits in the+ 90-day window AND real line movement (or a sustained commit volume+ that is hotspot-grade on its own). See ``_constants`` for the floor+ rationale; the SQL mirror lives in ``crud/git.py``.+ """+ try:+ commit_90d = int(meta.get("commit_count_90d") or 0)+ except (TypeError, ValueError):+ commit_90d = 0+ if commit_90d < HOTSPOT_MIN_COMMITS_90D:+ return False+ if commit_90d >= HOTSPOT_HIGH_COMMITS_90D:+ return True+ try:+ temporal = float(meta.get("temporal_hotspot_score") or 0.0)+ except (TypeError, ValueError):+ temporal = 0.0+ return temporal >= HOTSPOT_MIN_TEMPORAL_SCORE+++def count_active_contributors(metadata_list: list[dict], *, window_days: int = 90) -> int | None:+ """Count distinct non-bot authors active in the trailing *window_days*.++ Reads each file's ``top_authors_json`` (per-author ``last_commit_ts``)+ and anchors the window to the most recent author timestamp seen across+ the repo — deterministic, and correct for historical checkouts (same+ convention as ``index_file``'s ``as_of_ts`` anchoring).++ Returns ``None`` when no author carries a ``last_commit_ts`` (index+ predates the field, or git indexing was skipped) so callers can treat+ team size as *unknown* rather than zero.+ """+ author_last_ts: dict[str, int] = {}+ for meta in metadata_list:+ raw = meta.get("top_authors_json")+ if not raw:+ continue+ try:+ authors = json.loads(raw) if isinstance(raw, str) else raw+ except (TypeError, ValueError):+ continue+ if not isinstance(authors, list):+ continue+ for a in authors:+ if not isinstance(a, dict):+ continue+ ts = a.get("last_commit_ts")+ if not isinstance(ts, int | float) or ts <= 0:+ continue+ name = str(a.get("name") or "").strip()+ if not name:+ continue+ lowered = name.lower()+ if any(skip in lowered for skip in _SKIP_AUTHORS):+ continue+ prev = author_last_ts.get(name)+ if prev is None or ts > prev:+ author_last_ts[name] = int(ts)++ if not author_last_ts:+ return None++ anchor = max(author_last_ts.values())+ cutoff = anchor - window_days * 86400+ return sum(1 for ts in author_last_ts.values() if ts >= cutoff)++def compute_percentiles(metadata_list: list[dict]) -> None:"""Compute churn_percentile and is_hotspot. Mutates in place.@@ -132,11 +210,12 @@ def compute_percentiles(metadata_list: list[dict]) -> None:for rank, idx in enumerate(sorted_by_churn):metadata_list[idx]["churn_percentile"] = rank / total if total > 0 else 0.0- # Hotspot: top 25% churn (i.e., churn_percentile >= 0.75)+ # Hotspot: top 25% churn (churn_percentile >= 0.75) AND the absolute+ # activity floors — without the floors, a quiet repo's top quartile is+ # just "every file touched in 90 days" (issue #361).for meta in metadata_list:- commit_90d = meta.get("commit_count_90d", 0)churn_pct = meta.get("churn_percentile", 0.0)- if churn_pct >= 0.75 and commit_90d > 0:+ if churn_pct >= 0.75 and meets_hotspot_floors(meta):meta["is_hotspot"] = True# change_entropy percentile (mirrors churn_percentile). Rank ONLY filesdiff --git a/packages/core/src/repowise/core/persistence/crud/git.py b/packages/core/src/repowise/core/persistence/crud/git.pyindex 9d14b6b38..dc2ef0206 100644--- a/packages/core/src/repowise/core/persistence/crud/git.py+++ b/packages/core/src/repowise/core/persistence/crud/git.py@@ -143,7 +143,17 @@ async def recompute_git_percentiles(change_entropy ascending — zero-entropy files tie at the minimum (0.0), sothey stay below the biomarker's ≥0.80 gate. Works on both SQLite (3.25+) andPostgreSQL.++ Hotspot classification mirrors ``enrich.meets_hotspot_floors`` (issue #361):+ the repo-relative top-quartile gate AND the absolute activity floors —+ keep the two paths in sync."""+ from repowise.core.ingestion.git_indexer._constants import (+ HOTSPOT_HIGH_COMMITS_90D,+ HOTSPOT_MIN_COMMITS_90D,+ HOTSPOT_MIN_TEMPORAL_SCORE,+ )+# First check how many rows exist so we can return the count without an# extra query after the UPDATE.count_result = await session.execute(@@ -170,11 +180,22 @@ WITH ranked AS (UPDATE git_metadataSET churn_percentile = (SELECT prank FROM ranked WHERE ranked.id = git_metadata.id),is_hotspot = ((SELECT prank FROM ranked WHERE ranked.id = git_metadata.id) >= 0.75- AND git_metadata.commit_count_90d > 0),+ AND git_metadata.commit_count_90d >= :min_commits_90d+ AND (git_metadata.commit_count_90d >= :high_commits_90d+ OR COALESCE(git_metadata.temporal_hotspot_score, 0.0)+ >= :min_temporal_score)),change_entropy_pct = (SELECT erank FROM ranked WHERE ranked.id = git_metadata.id)WHERE repository_id = :repo_id;"""- await session.execute(text(sql), {"repo_id": repository_id})+ await session.execute(+ text(sql),+ {+ "repo_id": repository_id,+ "min_commits_90d": HOTSPOT_MIN_COMMITS_90D,+ "high_commits_90d": HOTSPOT_HIGH_COMMITS_90D,+ "min_temporal_score": HOTSPOT_MIN_TEMPORAL_SCORE,+ },+ )await session.flush()return len(rows)@@ -241,9 +262,7 @@ async def get_latest_commit_committed_at(session: AsyncSession, repository_id: scapturing on a ``repowise update``."""result = await session.execute(- select(func.max(GitCommit.committed_at)).where(- GitCommit.repository_id == repository_id- )+ select(func.max(GitCommit.committed_at)).where(GitCommit.repository_id == repository_id))return result.scalar_one_or_none()diff --git a/packages/server/src/repowise/server/mcp_server/tool_risk.py b/packages/server/src/repowise/server/mcp_server/tool_risk.pyindex e2c79f858..afdc415de 100644--- a/packages/server/src/repowise/server/mcp_server/tool_risk.py+++ b/packages/server/src/repowise/server/mcp_server/tool_risk.py@@ -81,8 +81,17 @@ def _compute_trend(meta: Any) -> str:return "stable"-def _classify_risk_type(meta: Any, dep_count: int) -> str:- """Classify risk as churn-heavy, bug-prone, high-coupling, or bus-factor-risk."""+def _classify_risk_type(meta: Any, dep_count: int, team_size: int | None = None) -> str:+ """Classify risk as churn-heavy, bug-prone, high-coupling, or bus-factor-risk.++ *team_size* is the repo's active-contributor count (90d). On a small+ team (≤ SMALL_TEAM_MAX_CONTRIBUTORS) a single-author file is the+ expected operating model, so ``bus-factor-risk`` is reserved for+ hotspot-active files there (issue #361). ``None`` = unknown → keep+ the historical behaviour.+ """+ from repowise.core.analysis.health.biomarkers.base import SMALL_TEAM_MAX_CONTRIBUTORS+# Count bug-fix commits from significant_commits messagescommits = json.loads(meta.significant_commits_json) if meta.significant_commits_json else []fix_count = sum(1 for c in commits if _FIX_PATTERN.search(c.get("message", "")))@@ -91,18 +100,45 @@ def _classify_risk_type(meta: Any, dep_count: int) -> str:bus_factor = getattr(meta, "bus_factor", 0) or 0total_commits = meta.commit_count_total or 0+ small_team = team_size is not None and team_size <= SMALL_TEAM_MAX_CONTRIBUTORS+# Bug-prone takes priority if fix ratio is highif commits and fix_count / len(commits) >= 0.4:return "bug-prone"if churn_score >= 0.7:return "churn-heavy"- if bus_factor == 1 and total_commits > 20:+ if (+ bus_factor == 1+ and total_commits > 20+ and (not small_team or bool(getattr(meta, "is_hotspot", False)))+ ):return "bus-factor-risk"if dep_count >= 5:return "high-coupling"return "stable"+async def _get_active_contributor_count(session: AsyncSession, repo_id: str) -> int | None:+ """Repo-wide active-contributor count from persisted git metadata.++ Reuses ``count_active_contributors`` (per-author ``last_commit_ts`` in+ ``top_authors_json``) over all rows. ``None`` = unknown (no rows, or an+ index that predates per-author timestamps).+ """+ from repowise.core.ingestion.git_indexer import count_active_contributors++ try:+ rows = await session.execute(+ select(GitMetadata.top_authors_json).where(GitMetadata.repository_id == repo_id)+ )+ metas = [{"top_authors_json": r[0]} for r in rows.all() if r[0]]+ if not metas:+ return None+ return count_active_contributors(metas)+ except Exception:+ return None++def _compute_impact_surface(target: str,reverse_deps: dict[str, set[str]],@@ -205,6 +241,7 @@ async def _assess_one_target(reverse_deps: dict[str, set[str]],node_meta: dict[str, Any],exclude_spec: Any = None,+ team_size: int | None = None,) -> dict:"""Assess risk for a single target file.@@ -278,7 +315,7 @@ async def _assess_one_target(trend = _compute_trend(meta)# --- Risk type classification ---- risk_type = _classify_risk_type(meta, dep_count)+ risk_type = _classify_risk_type(meta, dep_count, team_size)# --- Impact surface ---impact_surface = _compute_impact_surface(target, reverse_deps, node_meta, exclude_spec)@@ -423,6 +460,10 @@ async def get_risk()node_meta = {n.node_id: n for n in node_res.scalars().all()}+ # Team size is repo-wide — compute once, share across targets+ # (small-team calibration for bus-factor-risk, issue #361).+ team_size = await _get_active_contributor_count(session, repo_id)+# Assess each targetresults = await asyncio.gather(*[@@ -435,6 +476,7 @@ async def get_risk(reverse_deps,node_meta,exclude_spec,+ team_size,)for t in targets]@@ -451,9 +493,7 @@ async def get_risk(.order_by(GitMetadata.churn_percentile.desc()).limit(len(targets) + 5))- all_hotspots = filter_rows_by_attr(- list(res.scalars().all()), "file_path", exclude_spec- )+ all_hotspots = filter_rows_by_attr(list(res.scalars().all()), "file_path", exclude_spec)global_hotspots = [{"file_path": h.file_path,diff --git a/tests/unit/health/test_organizational_biomarkers.py b/tests/unit/health/test_organizational_biomarkers.pyindex 57c4f1d58..1cfc207b1 100644--- a/tests/unit/health/test_organizational_biomarkers.py+++ b/tests/unit/health/test_organizational_biomarkers.py@@ -31,7 +31,7 @@ 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:+def _ctx(meta: dict, *, active_contributors: int | None = None) -> FileContext:return FileContext(file_path="src/payments.py",language="python",@@ -42,6 +42,7 @@ def _ctx(meta: dict) -> FileContext:git_meta=meta,dependents_count=4,pagerank_score=0.0,+ repo_active_contributors_90d=active_contributors,)@@ -207,6 +208,72 @@ def test_ownership_risk_skips_low_commit_files():assert OwnershipRiskDetector().detect(_ctx(meta)) == []+# ---- 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 ----------------------------------------------------------diff --git a/tests/unit/server/mcp/test_risk.py b/tests/unit/server/mcp/test_risk.pyindex d4a935836..6745e56ec 100644--- a/tests/unit/server/mcp/test_risk.py+++ b/tests/unit/server/mcp/test_risk.py@@ -89,3 +89,46 @@ async def test_get_risk_stable_file(setup_mcp):assert t["trend"] == "stable"# churn_percentile=0.15, dep_count=1, no fix keywords → stableassert t["risk_type"] == "stable"+++# ---- _classify_risk_type small-team calibration (issue #361) ---------------+++def _bus_factor_meta():+ from types import SimpleNamespace++ return SimpleNamespace(+ significant_commits_json="[]",+ churn_percentile=0.3,+ bus_factor=1,+ commit_count_total=40,+ is_hotspot=False,+ )+++def test_classify_bus_factor_risk_on_normal_team():+ from repowise.server.mcp_server.tool_risk import _classify_risk_type++ assert _classify_risk_type(_bus_factor_meta(), dep_count=1, team_size=8) == "bus-factor-risk"+++def test_classify_bus_factor_suppressed_on_small_team():+ """A single-author file is the expected shape of a 1-3 person repo —+ not a bus-factor warning unless the file is hotspot-active."""+ from repowise.server.mcp_server.tool_risk import _classify_risk_type++ assert _classify_risk_type(_bus_factor_meta(), dep_count=1, team_size=2) == "stable"+++def test_classify_bus_factor_kept_on_small_team_hotspot():+ from repowise.server.mcp_server.tool_risk import _classify_risk_type++ meta = _bus_factor_meta()+ meta.is_hotspot = True+ assert _classify_risk_type(meta, dep_count=1, team_size=2) == "bus-factor-risk"+++def test_classify_bus_factor_unknown_team_size_keeps_behaviour():+ from repowise.server.mcp_server.tool_risk import _classify_risk_type++ assert _classify_risk_type(_bus_factor_meta(), dep_count=1, team_size=None) == "bus-factor-risk"diff --git a/tests/unit/test_git_indexer.py b/tests/unit/test_git_indexer.pyindex cbcf920c3..6f2454067 100644--- a/tests/unit/test_git_indexer.py+++ b/tests/unit/test_git_indexer.py@@ -248,6 +248,128 @@ class TestHotspotClassification:assert 0.0 <= m["churn_percentile"] <= 1.0+class TestHotspotAbsoluteFloors:+ """Issue #361: top-quartile percentile alone must not flag a hotspot on+ a quiet repo — the file also needs absolute recent activity."""++ @staticmethod+ def _quiet_repo(active_meta: dict) -> list[dict]:+ """9 dormant files + the file under test → it always tops the+ percentile ranking, isolating the absolute floors."""+ from repowise.core.ingestion.git_indexer.enrich import compute_percentiles++ metadata_list = [+ {+ "file_path": f"dormant_{i}.py",+ "commit_count_90d": 0,+ "temporal_hotspot_score": 0.0,+ "is_hotspot": False,+ }+ for i in range(9)+ ]+ metadata_list.append({"is_hotspot": False, **active_meta})+ compute_percentiles(metadata_list)+ return metadata_list++ def test_single_drive_by_commit_is_not_a_hotspot(self) -> None:+ """The issue's exact failure mode: one maintenance commit on an+ otherwise-quiet repo made the file a top-quartile 'hotspot'."""+ metas = self._quiet_repo(+ {"file_path": "touched.py", "commit_count_90d": 1, "temporal_hotspot_score": 0.2}+ )+ touched = next(m for m in metas if m["file_path"] == "touched.py")+ assert touched["churn_percentile"] >= 0.75 # top quartile, as before+ assert touched["is_hotspot"] is False # but floors hold it back++ def test_repeated_trivial_commits_are_not_a_hotspot(self) -> None:+ """3 one-line maintenance commits clear the count floor but not the+ decayed-churn floor."""+ metas = self._quiet_repo(+ {"file_path": "config.py", "commit_count_90d": 3, "temporal_hotspot_score": 0.03}+ )+ cfg = next(m for m in metas if m["file_path"] == "config.py")+ assert cfg["is_hotspot"] is False++ def test_real_activity_is_a_hotspot(self) -> None:+ """Repeated commits moving real lines clear both floors."""+ metas = self._quiet_repo(+ {"file_path": "core.py", "commit_count_90d": 4, "temporal_hotspot_score": 1.2}+ )+ core = next(m for m in metas if m["file_path"] == "core.py")+ assert core["is_hotspot"] is True++ def test_high_commit_volume_escape_hatch(self) -> None:+ """8+ commits in 90d is hotspot-grade even with no line counts+ (binary files / missing numstat)."""+ metas = self._quiet_repo(+ {"file_path": "assets.bin", "commit_count_90d": 9, "temporal_hotspot_score": 0.0}+ )+ assets = next(m for m in metas if m["file_path"] == "assets.bin")+ assert assets["is_hotspot"] is True+++class TestCountActiveContributors:+ """count_active_contributors derives the repo's 90-day team size from+ per-author last_commit_ts in top_authors_json."""++ @staticmethod+ def _meta(*authors: tuple[str, int]) -> dict:+ import json as _json++ return {+ "top_authors_json": _json.dumps(+ [+ {"name": n, "email": f"{n}@x", "commit_count": 5, "last_commit_ts": ts}+ for n, ts in authors+ ]+ )+ }++ def test_counts_distinct_recent_authors(self) -> None:+ from repowise.core.ingestion.git_indexer.enrich import count_active_contributors++ anchor = 1_700_000_000+ old = anchor - 200 * 86400 # well outside the 90d window+ metas = [+ self._meta(("Alice", anchor), ("Bob", anchor - 86400)),+ self._meta(("Alice", anchor - 5 * 86400), ("Carol", old)),+ ]+ assert count_active_contributors(metas) == 2 # Alice + Bob; Carol aged out++ def test_bots_are_excluded(self) -> None:+ from repowise.core.ingestion.git_indexer.enrich import count_active_contributors++ anchor = 1_700_000_000+ metas = [self._meta(("Alice", anchor), ("dependabot[bot]", anchor))]+ assert count_active_contributors(metas) == 1++ def test_unknown_when_no_timestamps(self) -> None:+ """Indexes predating per-author last_commit_ts must yield None+ (unknown), never a phantom team size of 0."""+ import json as _json++ from repowise.core.ingestion.git_indexer.enrich import count_active_contributors++ metas = [+ {+ "top_authors_json": _json.dumps(+ [{"name": "Alice", "email": "a@x", "commit_count": 7}]+ )+ }+ ]+ assert count_active_contributors(metas) is None+ assert count_active_contributors([]) is None++ def test_window_anchors_to_most_recent_author(self) -> None:+ """Anchored to the repo's own most recent activity, not wall clock —+ a historical checkout still gets a correct window."""+ from repowise.core.ingestion.git_indexer.enrich import count_active_contributors++ anchor = 900_000_000 # ancient wall-clock-wise; irrelevant+ metas = [self._meta(("Alice", anchor), ("Bob", anchor - 30 * 86400))]+ assert count_active_contributors(metas) == 2++# ---------------------------------------------------------------------------# 4. test_stable_classification# ---------------------------------------------------------------------------