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.

refactor(core): move owner, module health and reviewer rollups into core (#2518)

Raghav Chamadiyac5fec1894cfc
diff --git a/packages/core/src/repowise/core/analysis/health/rows.py b/packages/core/src/repowise/core/analysis/health/rows.py
index edb909ad5..8180a273a 100644
--- a/packages/core/src/repowise/core/analysis/health/rows.py
+++ b/packages/core/src/repowise/core/analysis/health/rows.py
@@ -1,8 +1,8 @@
-"""Reading one health finding whatever shape it arrives in.
+"""Reading one row whatever shape it arrives in.
-A finding reaches this package as an analyzer dataclass before persistence, as
-an ORM row after it, and as a plain dict in tests and fixtures. Everything that
-reads one goes through these two adapters so no consumer has to know which.
+A health finding, git row or decision reaches a fold as an analyzer dataclass,
+an ORM or SQL row, or a plain dict. Everything that reads one goes through
+these adapters so no consumer has to know which.
"""
from __future__ import annotations
@@ -33,4 +33,21 @@ def detail_map(row: Any) -> dict[str, Any]:
return {}
-__all__ = ["detail_map", "field"]
+def json_field(row: Any, name: str, default: Any) -> Any:
+ """A JSON-text column decoded, or the value as given when already decoded.
+
+ *default* stands in for an absent, empty or unparseable cell; valid JSON of
+ another type is returned as is.
+ """
+ value = field(row, name, None)
+ if isinstance(value, (str, bytes)):
+ if not value:
+ return default
+ try:
+ return json.loads(value)
+ except ValueError:
+ return default
+ return default if value is None else value
+
+
+__all__ = ["detail_map", "field", "json_field"]
diff --git a/packages/core/src/repowise/core/analysis/module_health.py b/packages/core/src/repowise/core/analysis/module_health.py
new file mode 100644
index 000000000..245e1f11c
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/module_health.py
@@ -0,0 +1,201 @@
+"""Per-module rollup of ownership, churn, dead code, docs and decisions.
+
+Sync, no I/O, no clock. Rows may be dicts, dataclasses or ORM rows (read
+through :func:`.health.rows.field`); JSON columns may be text or already
+decoded.
+
+A module is the top-level directory of a file path (:func:`module_label`), the
+bucket key every ownership surface uses. It is not ``HealthFileMetric.module``,
+which names the enclosing package boundary.
+"""
+
+from __future__ import annotations
+
+from collections import Counter, defaultdict
+from collections.abc import Iterable
+from dataclasses import dataclass, field
+from statistics import median
+from typing import Any
+
+from repowise.core.analysis.health.aggregation import module_label
+from repowise.core.analysis.health.rows import field as row_field
+from repowise.core.analysis.health.rows import json_field
+
+
+def module_health_score(
+ *,
+ is_silo: bool,
+ hotspot_fraction: float,
+ dead_pct: float,
+ churn_pct: float,
+ doc_pct: float,
+ bus_factor_median: float,
+) -> float:
+ """Composite health, 0-100, higher is better."""
+ score = 100.0
+ if is_silo:
+ score -= 25
+ score -= 20 * hotspot_fraction
+ score -= 25 * dead_pct
+ score -= 15 * (churn_pct / 100.0)
+ score += 15 * doc_pct
+ score += 10 if bus_factor_median >= 2 else -10
+ return max(0.0, min(100.0, score))
+
+
+@dataclass
+class ModuleAccumulator:
+ module_path: str
+ files: list[Any] = field(default_factory=list)
+ symbol_count: int = 0
+ doc_covered_symbols: int = 0
+ dead_code_count: int = 0
+ dead_code_lines: int = 0
+ owners: Counter = field(default_factory=Counter)
+ owner_emails: dict[str, str | None] = field(default_factory=dict)
+ contributors: set[str] = field(default_factory=set)
+ decision_ids: list[str] = field(default_factory=list)
+ top_hotspot_paths: list[tuple[float, str]] = field(default_factory=list)
+
+
+def _score(acc: ModuleAccumulator) -> dict:
+ file_count = len(acc.files)
+ hotspot_count = sum(1 for m in acc.files if row_field(m, "is_hotspot"))
+ dead_pct = (acc.dead_code_count / file_count) if file_count else 0.0
+ doc_pct = acc.doc_covered_symbols / acc.symbol_count if acc.symbol_count else 0.0
+
+ bus_factors = [row_field(m, "bus_factor") or 0 for m in acc.files]
+ med_bus = float(median(bus_factors)) if bus_factors else 0.0
+ min_bus = min(bus_factors) if bus_factors else 0
+ avg_churn = (
+ sum(row_field(m, "churn_percentile") or 0.0 for m in acc.files) / file_count * 100.0
+ if file_count
+ else 0.0
+ )
+
+ primary_owner, primary_pct = None, 0.0
+ if acc.owners:
+ name, cnt = acc.owners.most_common(1)[0]
+ primary_owner = name
+ primary_pct = cnt / file_count if file_count else 0.0
+
+ score = module_health_score(
+ is_silo=primary_pct > 0.8,
+ hotspot_fraction=hotspot_count / file_count if file_count else 0.0,
+ dead_pct=dead_pct,
+ churn_pct=avg_churn,
+ doc_pct=doc_pct,
+ bus_factor_median=med_bus,
+ )
+
+ return {
+ "file_count": file_count,
+ "symbol_count": acc.symbol_count,
+ "hotspot_count": hotspot_count,
+ "dead_code_count": acc.dead_code_count,
+ "dead_code_lines": acc.dead_code_lines,
+ "avg_churn_percentile": avg_churn,
+ "median_bus_factor": med_bus,
+ "min_bus_factor": min_bus,
+ "primary_owner": primary_owner,
+ "primary_owner_pct": primary_pct,
+ "is_silo": primary_pct > 0.8,
+ "decision_count": len(acc.decision_ids),
+ "doc_coverage_pct": doc_pct * 100.0,
+ "health_score": score,
+ }
+
+
+def aggregate_modules(
+ git_rows: Iterable[Any],
+ symbol_rows: Iterable[Any],
+ dead_rows: Iterable[Any],
+ decision_rows: Iterable[Any],
+) -> dict[str, ModuleAccumulator]:
+ """Single pass over each input. O(files + symbols + dead + decisions).
+
+ ``git_rows`` are full ``git_metadata`` rows and define the modules: symbols,
+ dead code (``file_path``, ``lines``) and decisions (``id``,
+ ``affected_modules_json``) that land outside them are dropped.
+ """
+ accs: dict[str, ModuleAccumulator] = defaultdict(lambda: ModuleAccumulator(module_path=""))
+
+ for m in git_rows:
+ file_path = row_field(m, "file_path")
+ mod = module_label(file_path)
+ acc = accs[mod]
+ if not acc.module_path:
+ acc.module_path = mod
+ acc.files.append(m)
+ owner = row_field(m, "primary_owner_name")
+ if owner:
+ acc.owners[owner] += 1
+ acc.owner_emails.setdefault(owner, row_field(m, "primary_owner_email"))
+ for a in json_field(m, "top_authors_json", []):
+ if a.get("name"):
+ acc.contributors.add(a["name"])
+ if row_field(m, "is_hotspot"):
+ acc.top_hotspot_paths.append(
+ ((row_field(m, "temporal_hotspot_score") or 0.0), file_path)
+ )
+
+ for s in symbol_rows:
+ acc = accs.get(module_label(row_field(s, "file_path")))
+ if acc is None:
+ continue
+ acc.symbol_count += 1
+ doc = row_field(s, "docstring")
+ if doc and str(doc).strip():
+ acc.doc_covered_symbols += 1
+
+ for d in dead_rows:
+ acc = accs.get(module_label(row_field(d, "file_path")))
+ if acc is None:
+ continue
+ acc.dead_code_count += 1
+ acc.dead_code_lines += int(row_field(d, "lines") or 0)
+
+ for dec in decision_rows:
+ for mod in json_field(dec, "affected_modules_json", []):
+ acc = accs.get(mod)
+ if acc is not None:
+ acc.decision_ids.append(row_field(dec, "id"))
+
+ return accs
+
+
+def summarize(acc: ModuleAccumulator) -> dict:
+ """Flatten accumulator to summary fields (matches ModuleHealthSummary)."""
+
+ out = _score(acc)
+ out["module_path"] = acc.module_path
+ return out
+
+
+def detail_extras(acc: ModuleAccumulator) -> dict:
+ """Extras only present in ModuleHealthDetail."""
+
+ acc.top_hotspot_paths.sort(reverse=True)
+ return {
+ "owners": [
+ {
+ "name": name,
+ "email": acc.owner_emails.get(name),
+ "file_count": cnt,
+ "pct": cnt / len(acc.files) if acc.files else 0.0,
+ }
+ for name, cnt in acc.owners.most_common(20)
+ ],
+ "top_hotspots": [p for _, p in acc.top_hotspot_paths[:10]],
+ "governing_decisions": acc.decision_ids,
+ "contributor_count": len(acc.contributors),
+ }
+
+
+__all__ = [
+ "ModuleAccumulator",
+ "aggregate_modules",
+ "detail_extras",
+ "module_health_score",
+ "summarize",
+]
diff --git a/packages/core/src/repowise/core/analysis/owners.py b/packages/core/src/repowise/core/analysis/owners.py
new file mode 100644
index 000000000..c2bcdba59
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/owners.py
@@ -0,0 +1,274 @@
+"""Per-contributor rollup, folded from git metadata and dead-code rows.
+
+Sync, no I/O, no clock. Rows may be dicts, dataclasses or ORM rows (read
+through :func:`.health.rows.field`); JSON columns may be text or already
+decoded.
+
+Identity: owners are keyed by email when known (stabler than a display name
+across renames and encodings), else ``name:<name>``. ``top_authors_json`` is
+the authoritative attribution: every (name, email, commit_count) per file,
+capped at 50 by the indexer, so one walk is linear in repo size.
+"""
+
+from __future__ import annotations
+
+from collections import Counter, defaultdict
+from collections.abc import Iterable
+from dataclasses import dataclass, field
+from datetime import UTC, datetime
+from typing import Any
+
+from repowise.core.analysis.health.aggregation import module_label
+from repowise.core.analysis.health.rows import field as row_field
+from repowise.core.analysis.health.rows import json_field
+from repowise.core.author_identity import (
+ build_identity_resolver,
+ canonicalize_author_email,
+)
+
+
+def owner_key(name: str | None, email: str | None) -> str:
+ """Return the canonical key for an (name, email) pair.
+
+ Prefer email; fall back to a ``name:`` prefix so we never collide a
+ name with someone else's email. GitHub ``noreply`` variants of one login
+ are folded to a single email first (see ``canonicalize_author_email``) so
+ the same person doesn't split into two contributor buckets.
+ """
+
+ if email:
+ return (canonicalize_author_email(email) or "").strip().lower()
+ if name:
+ return f"name:{name.strip()}"
+ return ""
+
+
+def as_utc(dt: datetime | str | None) -> datetime | None:
+ """Coerce a stored timestamp to aware UTC; ``None`` when absent or unparseable.
+
+ SQLite hands ``DateTime(timezone=True)`` back naive and artifacts carry ISO
+ text, while per-author times are built aware, so ``min``/``max`` never mix.
+ """
+ if isinstance(dt, str):
+ try:
+ dt = datetime.fromisoformat(dt.replace("Z", "+00:00"))
+ except ValueError:
+ return None
+ if dt is None:
+ return None
+ return dt.replace(tzinfo=UTC) if dt.tzinfo is None else dt.astimezone(UTC)
+
+
+@dataclass
+class OwnerAccumulator:
+ key: str
+ name: str
+ email: str | None = None
+
+ files_owned: int = 0 # files where this person is primary_owner
+ hotspots_owned: int = 0
+ bus_factor_risk_files: int = 0
+ commit_count_90d: int = 0
+ lines_added_90d_est: float = 0.0
+ lines_deleted_90d_est: float = 0.0
+
+ last_commit_at: datetime | None = None
+ first_commit_at: datetime | None = None
+
+ # file_path -> attributed commit count (90d-ish, from top_authors_json)
+ files_touched: dict[str, int] = field(default_factory=dict)
+ # file_path -> the git row as the caller passed it
+ file_meta: dict[str, Any] = field(default_factory=dict)
+
+ # module rollup
+ module_files: dict[str, int] = field(default_factory=lambda: defaultdict(int))
+ module_hotspots: dict[str, int] = field(default_factory=lambda: defaultdict(int))
+
+ commit_categories: Counter[str] = field(default_factory=Counter)
+
+ dead_code_files: set[str] = field(default_factory=set)
+ dead_code_lines: int = 0
+
+ # Agent-provenance rollup across primary-owned files.
+ owned_files_with_agents: int = 0
+ owned_agent_commits: int = 0
+ owned_attributed_commits: int = 0 # total commits on owned files with a rollup
+ owned_agent_tier_counts: Counter[str] = field(default_factory=Counter)
+
+ # co-author tally: other_key -> shared file count
+ coauthor_shared: Counter[str] = field(default_factory=Counter)
+ coauthor_meta: dict[str, tuple[str, str | None]] = field(default_factory=dict)
+
+
+def aggregate_owners(
+ git_rows: Iterable[Any], dead_rows: Iterable[Any]
+) -> tuple[dict[str, OwnerAccumulator], dict[str, int]]:
+ """Walk every git row once, returning per-owner accumulators and files per module.
+
+ ``git_rows`` are one repository's full ``git_metadata`` rows; ``dead_rows``
+ its dead-code findings (``file_path``, ``lines``, ``primary_owner``).
+ """
+ rows = list(git_rows)
+ accs: dict[str, OwnerAccumulator] = {}
+ module_totals: dict[str, int] = defaultdict(int)
+
+ # The resolver folds noreply variants and same-name real+noreply emails to
+ # one bucket, so it needs every (name, email) pair before the main walk.
+ pairs: list[tuple[str | None, str | None]] = []
+ for m in rows:
+ pairs.append((row_field(m, "primary_owner_name"), row_field(m, "primary_owner_email")))
+ for a in json_field(m, "top_authors_json", []):
+ pairs.append((a.get("name"), a.get("email")))
+ resolve = build_identity_resolver(pairs)
+
+ def _ensure(name: str, email: str | None) -> OwnerAccumulator:
+ k = resolve(name, email)
+ if not k:
+ return OwnerAccumulator(key="", name=name or "(unknown)", email=email)
+ acc = accs.get(k)
+ if acc is None:
+ acc = OwnerAccumulator(key=k, name=name or (email or ""), email=email)
+ accs[k] = acc
+ # Promote a richer display name if we learn one later.
+ if name and (not acc.name or acc.name == acc.email):
+ acc.name = name
+ if email and not acc.email:
+ acc.email = email
+ return acc
+
+ # Pass 1: per-file walk.
+ for m in rows:
+ file_path = row_field(m, "file_path")
+ authors = json_field(m, "top_authors_json", [])
+ module = module_label(file_path)
+ module_totals[module] += 1
+ categories = json_field(m, "commit_categories_json", {})
+
+ total_file_commits = sum(int(a.get("commit_count", 0)) for a in authors) or 1
+ added = row_field(m, "lines_added_90d") or 0
+ deleted = row_field(m, "lines_deleted_90d") or 0
+ commits_90d = row_field(m, "commit_count_90d") or 0
+
+ # Everyone who touched this file, for the co-author tally below.
+ touchers: list[OwnerAccumulator] = []
+ for a in authors:
+ name = a.get("name") or ""
+ email = a.get("email") or None
+ cnt = int(a.get("commit_count", 0))
+ acc = _ensure(name, email)
+ if not acc.key:
+ continue
+ share = cnt / total_file_commits
+ acc.files_touched[file_path] = cnt
+ acc.file_meta[file_path] = m
+ acc.commit_count_90d += min(cnt, commits_90d) if commits_90d else 0
+ acc.lines_added_90d_est += added * share
+ acc.lines_deleted_90d_est += deleted * share
+ for cat, n in categories.items():
+ acc.commit_categories[cat] += int(n * share)
+ # Prefer the author's own last/first commit to this file; indexes
+ # without per-author times fall back to the file-level value.
+ a_last_ts = a.get("last_commit_ts")
+ a_last = (
+ datetime.fromtimestamp(a_last_ts, tz=UTC)
+ if a_last_ts
+ else as_utc(row_field(m, "last_commit_at"))
+ )
+ if a_last is not None and (acc.last_commit_at is None or a_last > acc.last_commit_at):
+ acc.last_commit_at = a_last
+
+ a_first_ts = a.get("first_commit_ts")
+ a_first = (
+ datetime.fromtimestamp(a_first_ts, tz=UTC)
+ if a_first_ts
+ else as_utc(row_field(m, "first_commit_at"))
+ )
+ if a_first is not None and (
+ acc.first_commit_at is None or a_first < acc.first_commit_at
+ ):
+ acc.first_commit_at = a_first
+ touchers.append(acc)
+
+ # Primary owner: credit them for files_owned, hotspots and silo risk.
+ primary = _ensure(
+ row_field(m, "primary_owner_name") or "", row_field(m, "primary_owner_email")
+ )
+ if primary.key:
+ primary.files_owned += 1
+ primary.module_files[module] += 1
+ if row_field(m, "is_hotspot"):
+ primary.hotspots_owned += 1
+ primary.module_hotspots[module] += 1
+ if (row_field(m, "bus_factor") or 0) <= 1:
+ primary.bus_factor_risk_files += 1
+ # agent_authored_pct is None on rows indexed before provenance
+ # existed; skip those so the agent share stays honest.
+ if row_field(m, "agent_authored_pct") is not None:
+ primary.owned_attributed_commits += row_field(m, "commit_count_total") or 0
+ agent_commits = row_field(m, "agent_commit_count") or 0
+ if agent_commits > 0:
+ primary.owned_files_with_agents += 1
+ primary.owned_agent_commits += agent_commits
+ for tier, n in json_field(m, "agent_tier_counts_json", {}).items():
+ primary.owned_agent_tier_counts[str(tier)] += int(n)
+
+ # Co-author tally: each pair of distinct touchers shares this file.
+ for i, a in enumerate(touchers):
+ for b in touchers[i + 1 :]:
+ if a.key == b.key:
+ continue
+ a.coauthor_shared[b.key] += 1
+ a.coauthor_meta[b.key] = (b.name, b.email)
+ b.coauthor_shared[a.key] += 1
+ b.coauthor_meta[a.key] = (a.name, a.email)
+
+ # Pass 2: dead-code burden by primary_owner.
+ for d in dead_rows:
+ dead_owner = row_field(d, "primary_owner")
+ if not dead_owner:
+ continue
+ # The finding only carries the display name; fall back to a name match
+ # against accumulators keyed by email (best-effort).
+ acc = accs.get(owner_key(dead_owner, None))
+ if acc is None:
+ for cand in accs.values():
+ if cand.name == dead_owner:
+ acc = cand
+ break
+ if acc is None:
+ continue
+ acc.dead_code_files.add(row_field(d, "file_path"))
+ acc.dead_code_lines += row_field(d, "lines") or 0
+
+ return accs, dict(module_totals)
+
+
+def silo_modules(acc: OwnerAccumulator, module_totals: dict[str, int]) -> int:
+ """Count modules where this owner is >80% of file ownership."""
+
+ siloed = 0
+ for mod, owned in acc.module_files.items():
+ total = module_totals.get(mod, 0)
+ if total > 0 and owned / total > 0.8:
+ siloed += 1
+ return siloed
+
+
+def module_share(acc: OwnerAccumulator, module_totals: dict[str, int]) -> dict[str, float]:
+ """Per-module share of files owned by this person (0–1)."""
+
+ out: dict[str, float] = {}
+ for mod, owned in acc.module_files.items():
+ total = module_totals.get(mod, 0)
+ out[mod] = owned / total if total else 0.0
+ return out
+
+
+__all__ = [
+ "OwnerAccumulator",
+ "aggregate_owners",
+ "as_utc",
+ "module_share",
+ "owner_key",
+ "silo_modules",
+]
diff --git a/packages/core/src/repowise/core/analysis/reviewers.py b/packages/core/src/repowise/core/analysis/reviewers.py
new file mode 100644
index 000000000..901068c59
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/reviewers.py
@@ -0,0 +1,127 @@
+"""Reviewer suggestions for a set of changed files, folded from git metadata rows.
+
+Sync, no I/O, no clock. The composite score blends three signals the indexer
+already computed:
+
+ - Ownership: appearance in ``top_authors_json`` of the touched files,
+ weighted by share of file commits.
+ - Co-change: ownership of files that historically co-change with the
+ touched paths (``co_change_partners_json``).
+ - Recency: weight commit count by the file's 90-day activity so people
+ who *just* worked here outrank people who touched the file in 2018.
+
+Rows may be dicts, dataclasses or ORM rows; JSON columns may be text or
+already decoded.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Iterable
+from typing import Any
+
+from repowise.core.analysis.health.rows import field, json_field
+from repowise.core.co_change import parse_partners
+
+# Tunable weights.
+_W_DIRECT = 1.0
+_W_COCHANGE = 0.5
+_W_RECENT = 0.4
+
+#: Strongest co-change partners followed per touched file, to keep noise low.
+PARTNERS_PER_FILE = 5
+
+
+def cochange_paths(direct_rows: Iterable[Any]) -> set[str]:
+ """Paths whose owners also count: each touched file's strongest partners."""
+ return {
+ p.file_path
+ for m in direct_rows
+ for p in parse_partners(field(m, "co_change_partners_json"))[:PARTNERS_PER_FILE]
+ }
+
+
+def suggest_reviewers(
+ direct_rows: Iterable[Any], cochange_rows: Iterable[Any], *, limit: int = 10
+) -> list[dict[str, Any]]:
+ """Top *limit* reviewers, best first, as ``ReviewerSuggestion``-shaped dicts.
+
+ ``direct_rows`` are the git rows of the touched files; ``cochange_rows``
+ those of :func:`cochange_paths`. Each needs ``file_path``,
+ ``top_authors_json`` and ``commit_count_90d``.
+ """
+ direct_rows, cochange_rows = list(direct_rows), list(cochange_rows)
+ tally: dict[str, dict] = {}
+
+ def _bump(
+ name: str,
+ email: str | None,
+ *,
+ score: float,
+ recent: int,
+ path: str,
+ reason: str,
+ owned: bool,
+ ) -> None:
+ key = (email or "").strip().lower() or f"name:{name.strip()}"
+ slot = tally.setdefault(
+ key,
+ {
+ "name": name,
+ "email": email,
+ "score": 0.0,
+ "recent_commits": 0,
+ "owned_paths": set(),
+ "co_change_paths": set(),
+ "reasons": set(),
+ },
+ )
+ slot["score"] += score
+ slot["recent_commits"] += recent
+ if owned:
+ slot["owned_paths"].add(path)
+ else:
+ slot["co_change_paths"].add(path)
+ slot["reasons"].add(reason)
+
+ def _process(rows: Iterable[Any], *, weight: float, owned: bool, reason: str) -> None:
+ for m in rows:
+ authors = json_field(m, "top_authors_json", [])
+ total = sum(int(a.get("commit_count", 0)) for a in authors) or 1
+ commits_90d = field(m, "commit_count_90d") or 0
+ for a in authors:
+ cnt = int(a.get("commit_count", 0))
+ share = cnt / total
+ # Recency: commits_90d weighted by share is a rough estimate
+ # of how much each author contributed recently.
+ recent = int(commits_90d * share)
+ score = weight * share + _W_RECENT * (recent / max(commits_90d, 1))
+ _bump(
+ a.get("name", ""),
+ a.get("email") or None,
+ score=score,
+ recent=recent,
+ path=field(m, "file_path"),
+ reason=reason,
+ owned=owned,
+ )
+
+ _process(direct_rows, weight=_W_DIRECT, owned=True, reason="touched")
+ _process(cochange_rows, weight=_W_COCHANGE, owned=False, reason="co-change history")
+
+ suggestions = [
+ {
+ "name": slot["name"],
+ "email": slot["email"],
+ "score": round(slot["score"], 4),
+ "recent_commits": slot["recent_commits"],
+ "owned_paths": sorted(slot["owned_paths"])[:10],
+ "co_change_paths": sorted(slot["co_change_paths"])[:10],
+ "reasons": sorted(slot["reasons"]),
+ }
+ for slot in tally.values()
+ ]
+ suggestions.sort(key=lambda s: s["score"], reverse=True)
+ return suggestions[:limit]
+
+
+__all__ = ["PARTNERS_PER_FILE", "cochange_paths", "suggest_reviewers"]
diff --git a/packages/core/src/repowise/core/author_identity.py b/packages/core/src/repowise/core/author_identity.py
new file mode 100644
index 000000000..8f2a0a51f
--- /dev/null
+++ b/packages/core/src/repowise/core/author_identity.py
@@ -0,0 +1,109 @@
+"""Author-identity canonicalization shared across the ingestion + serving paths.
+
+GitHub stamps commits made through its web UI, squash-merges and PR merges with
+a synthetic *noreply* address instead of the author's real email:
+``[email protected]`` (numeric-id prefixed) or the older
+``[email protected]`` form. The numeric id and the exact shape
+vary between commits, so the same person fans out into several contributor
+buckets whenever identity is keyed on the raw email.
+
+:func:`canonicalize_author_email` folds every noreply variant for a login onto
+one stable key so those buckets collapse. It is deliberately the *simple*
+version: it only unifies the noreply forms of a single login. The GitHub
+*system* author ``[email protected]`` (stamped on some merge commits) is left
+untouched on purpose — it stays its own bucket and is never merged into a human
+contributor. Bridging a person's noreply identity to their *real* email when the
+two share only a display name is the thorough version, out of scope here.
+"""
+
+from __future__ import annotations
+
+import re
+from collections.abc import Callable, Iterable
+
+_NOREPLY_DOMAIN = "@users.noreply.github.com"
+
+# ``[email protected]`` or the older ``login@...`` form.
+# The numeric id and the prefix are optional; the login is everything before
+# the ``@`` (minus the ``NNN+`` id). Case-insensitive to match git's casing.
+_GH_NOREPLY_RE = re.compile(
+ r"^(?:\d+\+)?(?P<login>[^@\s+]+)@users\.noreply\.github\.com$",
+ re.IGNORECASE,
+)
+
+
+def canonicalize_author_email(email: str | None) -> str | None:
+ """Return a stable identity email, folding GitHub noreply variants.
+
+ both collapse to ``[email protected]`` (lower-cased) so every
+ noreply variant of one login shares a key. Any other address — including the
+ ``[email protected]`` system author — is returned lower-cased and otherwise
+ unchanged. ``None``/empty passes through unchanged so callers can keep their
+ existing "no email → fall back to name" handling.
+ """
+ if not email:
+ return email
+ lowered = email.strip().lower()
+ m = _GH_NOREPLY_RE.match(lowered)
+ if m:
+ return f"{m.group('login')}{_NOREPLY_DOMAIN}"
+ return lowered
+
+
+def author_identity_key(author_name: str | None, author_email: str | None) -> str:
+ """Stable per-person key for counting commits.
+
+ Folds noreply variants onto one login first, falling back to the display
+ name when there is no usable email. Anything that tallies commits per author
+ must key on this, or one person splits across buckets and every count that
+ depends on it (author experience, "is this a new contributor") comes out low
+ for exactly the people who commit through GitHub's web UI.
+ """
+ canonical = canonicalize_author_email(author_email) or author_email
+ return (canonical or author_name or "").strip().lower()
+
+
+def _is_github_noreply(canonical_email: str | None) -> bool:
+ """True for a ``[email protected]`` identity (not the system
+ ``[email protected]`` author, which lives on a different domain)."""
+ return bool(canonical_email) and canonical_email.endswith(_NOREPLY_DOMAIN)
+
+
+def build_identity_resolver(
+ pairs: Iterable[tuple[str | None, str | None]],
+) -> Callable[[str | None, str | None], str]:
+ """Return ``resolve(name, email) -> identity key`` for a whole repo's authors.
+
+ Canonicalizes each email (folding GitHub noreply *variants* of one login),
+ then does the same-display-name merge the simple dedup calls for: a person
+ who shows up both with a real email and with a ``[email protected]``
+ email under the **same display name** collapses to one identity. Only the
+ noreply side is redirected, and only when that name maps to exactly **one**
+ real email (unambiguous) — so two distinct real emails under one name, or a
+ name<->login bridge across *different* names, are left split on purpose.
+
+ Keys match ``owner_key``'s shape: a lower-cased email, or ``name:<name>``
+ when no email is known.
+ """
+ real_by_name: dict[str, set[str]] = {}
+ for name, email in pairs:
+ canon = canonicalize_author_email(email)
+ if canon and not _is_github_noreply(canon) and name and name.strip():
+ real_by_name.setdefault(name.strip().lower(), set()).add(canon)
+ # Fold only when a display name resolves to a single real email.
+ fold = {n: next(iter(s)) for n, s in real_by_name.items() if len(s) == 1}
+
+ def resolve(name: str | None, email: str | None) -> str:
+ canon = canonicalize_author_email(email)
+ if canon:
+ if _is_github_noreply(canon) and name and name.strip():
+ real = fold.get(name.strip().lower())
+ if real:
+ return real
+ return canon.strip().lower()
+ if name and name.strip():
+ return f"name:{name.strip()}"
+ return ""
+
+ return resolve
diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/identity.py b/packages/core/src/repowise/core/ingestion/git_indexer/identity.py
index 8f2a0a51f..35ba009a7 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/identity.py
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/identity.py
@@ -1,109 +1,12 @@
-"""Author-identity canonicalization shared across the ingestion + serving paths.
-
-GitHub stamps commits made through its web UI, squash-merges and PR merges with
-a synthetic *noreply* address instead of the author's real email:
-``[email protected]`` (numeric-id prefixed) or the older
-``[email protected]`` form. The numeric id and the exact shape
-vary between commits, so the same person fans out into several contributor
-buckets whenever identity is keyed on the raw email.
-
-:func:`canonicalize_author_email` folds every noreply variant for a login onto
-one stable key so those buckets collapse. It is deliberately the *simple*
-version: it only unifies the noreply forms of a single login. The GitHub
-*system* author ``[email protected]`` (stamped on some merge commits) is left
-untouched on purpose — it stays its own bucket and is never merged into a human
-contributor. Bridging a person's noreply identity to their *real* email when the
-two share only a display name is the thorough version, out of scope here.
-"""
+"""Re-export of :mod:`repowise.core.author_identity`, which lives outside the
+ingestion package so pure folds can use it without importing the parser stack."""
from __future__ import annotations
-import re
-from collections.abc import Callable, Iterable
-
-_NOREPLY_DOMAIN = "@users.noreply.github.com"
-
-# ``[email protected]`` or the older ``login@...`` form.
-# The numeric id and the prefix are optional; the login is everything before
-# the ``@`` (minus the ``NNN+`` id). Case-insensitive to match git's casing.
-_GH_NOREPLY_RE = re.compile(
- r"^(?:\d+\+)?(?P<login>[^@\s+]+)@users\.noreply\.github\.com$",
- re.IGNORECASE,
+from repowise.core.author_identity import (
+ author_identity_key,
+ build_identity_resolver,
+ canonicalize_author_email,
)
-
-def canonicalize_author_email(email: str | None) -> str | None:
- """Return a stable identity email, folding GitHub noreply variants.
-
- both collapse to ``[email protected]`` (lower-cased) so every
- noreply variant of one login shares a key. Any other address — including the
- ``[email protected]`` system author — is returned lower-cased and otherwise
- unchanged. ``None``/empty passes through unchanged so callers can keep their
- existing "no email → fall back to name" handling.
- """
- if not email:
- return email
- lowered = email.strip().lower()
- m = _GH_NOREPLY_RE.match(lowered)
- if m:
- return f"{m.group('login')}{_NOREPLY_DOMAIN}"
- return lowered
-
-
-def author_identity_key(author_name: str | None, author_email: str | None) -> str:
- """Stable per-person key for counting commits.
-
- Folds noreply variants onto one login first, falling back to the display
- name when there is no usable email. Anything that tallies commits per author
- must key on this, or one person splits across buckets and every count that
- depends on it (author experience, "is this a new contributor") comes out low
- for exactly the people who commit through GitHub's web UI.
- """
- canonical = canonicalize_author_email(author_email) or author_email
- return (canonical or author_name or "").strip().lower()
-
-
-def _is_github_noreply(canonical_email: str | None) -> bool:
- """True for a ``[email protected]`` identity (not the system
- ``[email protected]`` author, which lives on a different domain)."""
- return bool(canonical_email) and canonical_email.endswith(_NOREPLY_DOMAIN)
-
-
-def build_identity_resolver(
- pairs: Iterable[tuple[str | None, str | None]],
-) -> Callable[[str | None, str | None], str]:
- """Return ``resolve(name, email) -> identity key`` for a whole repo's authors.
-
- Canonicalizes each email (folding GitHub noreply *variants* of one login),
- then does the same-display-name merge the simple dedup calls for: a person
- who shows up both with a real email and with a ``[email protected]``
- email under the **same display name** collapses to one identity. Only the
- noreply side is redirected, and only when that name maps to exactly **one**
- real email (unambiguous) — so two distinct real emails under one name, or a
- name<->login bridge across *different* names, are left split on purpose.
-
- Keys match ``owner_key``'s shape: a lower-cased email, or ``name:<name>``
- when no email is known.
- """
- real_by_name: dict[str, set[str]] = {}
- for name, email in pairs:
- canon = canonicalize_author_email(email)
- if canon and not _is_github_noreply(canon) and name and name.strip():
- real_by_name.setdefault(name.strip().lower(), set()).add(canon)
- # Fold only when a display name resolves to a single real email.
- fold = {n: next(iter(s)) for n, s in real_by_name.items() if len(s) == 1}
-
- def resolve(name: str | None, email: str | None) -> str:
- canon = canonicalize_author_email(email)
- if canon:
- if _is_github_noreply(canon) and name and name.strip():
- real = fold.get(name.strip().lower())
- if real:
- return real
- return canon.strip().lower()
- if name and name.strip():
- return f"name:{name.strip()}"
- return ""
-
- return resolve
+__all__ = ["author_identity_key", "build_identity_resolver", "canonicalize_author_email"]
diff --git a/packages/server/src/repowise/server/services/module_health.py b/packages/server/src/repowise/server/services/module_health.py
index 280243604..08bad915f 100644
--- a/packages/server/src/repowise/server/services/module_health.py
+++ b/packages/server/src/repowise/server/services/module_health.py
@@ -1,30 +1,29 @@
"""Module Health aggregator.
-Per-module rollup combining ownership, churn, dead code, docs, and
-decisions. No core ingestion changes — purely composes existing tables.
-
-A "module" here is the top-level directory of a file path, matching the
-``OwnershipEntry`` convention the ownership surfaces already use. It is
-deliberately not ``HealthFileMetric.module``, which names the enclosing package
-boundary: this value is a rollup bucket key and travels in the URL, so the two
-answer different questions. For nested module views we expose ``module_path``
-as the path prefix the caller passed in, which can be arbitrarily deep.
+Fetches the rows the per-module rollup needs and folds them with
+:mod:`repowise.core.analysis.module_health`, which defines what a module is.
+The module value is a rollup bucket key and travels in the URL; for nested
+views ``module_path`` is the path prefix the caller passed in.
"""
from __future__ import annotations
import json
import sqlite3
-from collections import Counter, defaultdict
-from dataclasses import dataclass, field
from pathlib import Path
-from statistics import median
from sqlalchemy import func as sa_func
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
+from repowise.core.analysis import module_health as _fold
from repowise.core.analysis.health.aggregation import module_label
+from repowise.core.analysis.module_health import (
+ ModuleAccumulator,
+ detail_extras,
+ module_health_score,
+ summarize,
+)
from repowise.core.persistence.models import (
DeadCodeFinding,
DecisionRecord,
@@ -33,164 +32,32 @@ from repowise.core.persistence.models import (
WikiSymbol,
)
-#: The one definition behind every ownership rollup. Not a package boundary --
-#: see the module docstring.
+#: The one definition behind every ownership rollup; not a package boundary
+#: (see :mod:`repowise.core.analysis.module_health`).
top_level_module = module_label
-def _compute_health_score(
- *,
- is_silo: bool,
- hotspot_fraction: float,
- dead_pct: float,
- churn_pct: float,
- doc_pct: float,
- bus_factor_median: float,
-) -> float:
- score = 100.0
- if is_silo:
- score -= 25
- score -= 20 * hotspot_fraction
- score -= 25 * dead_pct
- score -= 15 * (churn_pct / 100.0)
- score += 15 * doc_pct
- score += 10 if bus_factor_median >= 2 else -10
- return max(0.0, min(100.0, score))
-
-
def _under_module(file_path: str, module_path: str) -> bool:
if module_path in ("", "root"):
return "/" not in file_path
return file_path == module_path or file_path.startswith(module_path + "/")
-@dataclass
-class _ModuleAccumulator:
- module_path: str
- files: list[GitMetadata] = field(default_factory=list)
- symbol_count: int = 0
- doc_covered_symbols: int = 0
- dead_code_count: int = 0
- dead_code_lines: int = 0
- owners: Counter = field(default_factory=Counter)
- owner_emails: dict[str, str | None] = field(default_factory=dict)
- contributors: set[str] = field(default_factory=set)
- decision_ids: list[str] = field(default_factory=list)
- top_hotspot_paths: list[tuple[float, str]] = field(default_factory=list)
-
-
-def _score(acc: _ModuleAccumulator) -> dict:
- file_count = len(acc.files)
- hotspot_count = sum(1 for m in acc.files if m.is_hotspot)
- dead_pct = (acc.dead_code_count / file_count) if file_count else 0.0
- doc_pct = (
- acc.doc_covered_symbols / acc.symbol_count if acc.symbol_count else 0.0
- )
-
- bus_factors = [m.bus_factor or 0 for m in acc.files]
- med_bus = float(median(bus_factors)) if bus_factors else 0.0
- min_bus = min(bus_factors) if bus_factors else 0
- avg_churn = (
- sum(m.churn_percentile or 0.0 for m in acc.files) / file_count * 100.0
- if file_count
- else 0.0
- )
-
- primary_owner, primary_pct = None, 0.0
- if acc.owners:
- name, cnt = acc.owners.most_common(1)[0]
- primary_owner = name
- primary_pct = cnt / file_count if file_count else 0.0
-
- # Composite health (0-100). Higher is better. Weighted:
- # -25 if siloed (>80% one owner)
- # -20 * (hotspot_count / file_count)
- # -25 * dead_pct
- # -15 * (avg_churn / 100)
- # +15 * doc_pct
- # +10 if bus_factor >= 2 median, else -10
- score = _compute_health_score(
- is_silo=primary_pct > 0.8,
- hotspot_fraction=hotspot_count / file_count if file_count else 0.0,
- dead_pct=dead_pct,
- churn_pct=avg_churn,
- doc_pct=doc_pct,
- bus_factor_median=med_bus,
- )
-
- return {
- "file_count": file_count,
- "symbol_count": acc.symbol_count,
- "hotspot_count": hotspot_count,
- "dead_code_count": acc.dead_code_count,
- "dead_code_lines": acc.dead_code_lines,
- "avg_churn_percentile": avg_churn,
- "median_bus_factor": med_bus,
- "min_bus_factor": min_bus,
- "primary_owner": primary_owner,
- "primary_owner_pct": primary_pct,
- "is_silo": primary_pct > 0.8,
- "decision_count": len(acc.decision_ids),
- "doc_coverage_pct": doc_pct * 100.0,
- "health_score": score,
- }
-
-
-async def aggregate_modules(
- session: AsyncSession, repo_id: str
-) -> dict[str, _ModuleAccumulator]:
- """Single-pass aggregator. O(files + symbols + dead + decisions)."""
+async def aggregate_modules(session: AsyncSession, repo_id: str) -> dict[str, ModuleAccumulator]:
+ """Fetch the four inputs for *repo_id* and fold them by top-level module."""
files = (
- await session.execute(
- select(GitMetadata).where(GitMetadata.repository_id == repo_id)
- )
- ).scalars().all()
-
- accs: dict[str, _ModuleAccumulator] = defaultdict(
- lambda: _ModuleAccumulator(module_path="")
+ (await session.execute(select(GitMetadata).where(GitMetadata.repository_id == repo_id)))
+ .scalars()
+ .all()
)
-
- for m in files:
- mod = top_level_module(m.file_path)
- acc = accs[mod]
- if not acc.module_path:
- acc.module_path = mod
- acc.files.append(m)
- if m.primary_owner_name:
- acc.owners[m.primary_owner_name] += 1
- acc.owner_emails.setdefault(m.primary_owner_name, m.primary_owner_email)
- # Authors -> contributors set
- try:
- for a in json.loads(m.top_authors_json or "[]"):
- if a.get("name"):
- acc.contributors.add(a["name"])
- except json.JSONDecodeError:
- pass
- if m.is_hotspot:
- acc.top_hotspot_paths.append(
- ((m.temporal_hotspot_score or 0.0), m.file_path)
- )
-
- # Symbols + docs by module.
sym_rows = (
await session.execute(
- select(
- WikiSymbol.file_path,
- WikiSymbol.docstring,
- ).where(WikiSymbol.repository_id == repo_id)
+ select(WikiSymbol.file_path, WikiSymbol.docstring).where(
+ WikiSymbol.repository_id == repo_id
+ )
)
).all()
- for path, doc in sym_rows:
- mod = top_level_module(path)
- acc = accs.get(mod)
- if acc is None:
- continue
- acc.symbol_count += 1
- if doc and str(doc).strip():
- acc.doc_covered_symbols += 1
-
- # Dead-code findings by module.
dead_rows = (
await session.execute(
select(DeadCodeFinding.file_path, DeadCodeFinding.lines).where(
@@ -198,61 +65,14 @@ async def aggregate_modules(
)
)
).all()
- for path, lines in dead_rows:
- mod = top_level_module(path)
- acc = accs.get(mod)
- if acc is None:
- continue
- acc.dead_code_count += 1
- acc.dead_code_lines += int(lines or 0)
-
- # Decisions by affected module.
decisions = (
await session.execute(
- select(
- DecisionRecord.id, DecisionRecord.affected_modules_json
- ).where(DecisionRecord.repository_id == repo_id)
+ select(DecisionRecord.id, DecisionRecord.affected_modules_json).where(
+ DecisionRecord.repository_id == repo_id
+ )
)
).all()
- for did, modules_json in decisions:
- try:
- mods = json.loads(modules_json or "[]")
- except json.JSONDecodeError:
- mods = []
- for mod in mods:
- acc = accs.get(mod)
- if acc is not None:
- acc.decision_ids.append(did)
-
- return accs
-
-
-def summarize(acc: _ModuleAccumulator) -> dict:
- """Flatten accumulator to summary fields (matches ModuleHealthSummary)."""
-
- out = _score(acc)
- out["module_path"] = acc.module_path
- return out
-
-
-def detail_extras(acc: _ModuleAccumulator) -> dict:
- """Extras only present in ModuleHealthDetail."""
-
- acc.top_hotspot_paths.sort(reverse=True)
- return {
- "owners": [
- {
- "name": name,
- "email": acc.owner_emails.get(name),
- "file_count": cnt,
- "pct": cnt / len(acc.files) if acc.files else 0.0,
- }
- for name, cnt in acc.owners.most_common(20)
- ],
- "top_hotspots": [p for _, p in acc.top_hotspot_paths[:10]],
- "governing_decisions": acc.decision_ids,
- "contributor_count": len(acc.contributors),
- }
+ return _fold.aggregate_modules(files, sym_rows, dead_rows, decisions)
def read_repo_health_score(db_path: Path) -> float | None:
@@ -357,11 +177,11 @@ async def build_single_file_health(
doc_coverage_pct = (doc_covered / symbol_count * 100.0) if symbol_count else 0.0
# Composite health score — use health_file_metrics score (0-10 -> 0-100)
- # when available, otherwise derive from the same formula as _score().
+ # when available, otherwise derive from the module formula.
if hfm is not None:
health_score = max(0.0, min(100.0, float(hfm) * 10.0))
else:
- health_score = _compute_health_score(
+ health_score = module_health_score(
is_silo=is_silo,
hotspot_fraction=1.0 if is_hotspot else 0.0,
dead_pct=1.0 if dead_code_count > 0 else 0.0,
@@ -425,3 +245,12 @@ async def build_single_file_health(
}
+__all__ = [
+ "ModuleAccumulator",
+ "aggregate_modules",
+ "build_single_file_health",
+ "detail_extras",
+ "read_repo_health_score",
+ "summarize",
+ "top_level_module",
+]
diff --git a/packages/server/src/repowise/server/services/owner_profile.py b/packages/server/src/repowise/server/services/owner_profile.py
index 836898e62..d48083509 100644
--- a/packages/server/src/repowise/server/services/owner_profile.py
+++ b/packages/server/src/repowise/server/services/owner_profile.py
@@ -1,319 +1,57 @@
"""Owner / contributor aggregation service.
-Composes a "what does this person do in the codebase" picture from existing
-``GitMetadata`` + ``DeadCodeFinding`` rows. Pure aggregation — no schema
-changes to core ingestion.
-
-A few notes on identity:
-- We key owners by *email when known* (much more stable than name across
- rename / unicode / encoding differences) and fall back to ``name:<name>``
- when the GitMetadata row only carries a display name.
-- The exposed ``key`` is URL-safe (we strip ``+`` / ``@`` only at the
- router layer — the service deals with the canonical form).
-- ``top_authors_json`` is the authoritative source of attribution: it lists
- every (name, email, commit_count) per file. Walking it is O(files * 50)
- in the worst case, which is fine for repos in the 10k-file range.
+Fetches ``GitMetadata`` + ``DeadCodeFinding`` rows and folds them with
+:func:`repowise.core.analysis.owners.aggregate_owners`. The exposed ``key`` is
+URL-safe only at the router layer; the fold deals with the canonical form.
"""
from __future__ import annotations
-import contextlib
-import json
-from collections import Counter, defaultdict
-from dataclasses import dataclass, field
-from datetime import UTC, datetime
-
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
-from repowise.core.ingestion.git_indexer import (
- build_identity_resolver,
- canonicalize_author_email,
+from repowise.core.analysis import owners as _fold
+from repowise.core.analysis.owners import (
+ OwnerAccumulator,
+ module_share,
+ owner_key,
+ silo_modules,
)
from repowise.core.persistence.models import DeadCodeFinding, GitMetadata
-from repowise.server.services.module_health import top_level_module
-
-# ---------------------------------------------------------------------------
-# Identity
-# ---------------------------------------------------------------------------
-
-
-def owner_key(name: str | None, email: str | None) -> str:
- """Return the canonical key for an (name, email) pair.
-
- Prefer email; fall back to a ``name:`` prefix so we never collide a
- name with someone else's email. GitHub ``noreply`` variants of one login
- are folded to a single email first (see ``canonicalize_author_email``) so
- the same person doesn't split into two contributor buckets.
- """
-
- if email:
- return (canonicalize_author_email(email) or "").strip().lower()
- if name:
- return f"name:{name.strip()}"
- return ""
-
-
-def _as_utc(dt: datetime | None) -> datetime | None:
- """Coerce a DB datetime to aware-UTC.
-
- ``DateTime(timezone=True)`` round-trips as aware on Postgres but *naive* on
- SQLite. Per-author timestamps are built aware (from a unix epoch); normalize
- the file-level fallback to match so the ``min``/``max`` comparisons below
- never mix naive and aware datetimes.
- """
- if dt is None:
- return None
- return dt.replace(tzinfo=UTC) if dt.tzinfo is None else dt.astimezone(UTC)
-
-
-# ---------------------------------------------------------------------------
-# Per-owner accumulators
-# ---------------------------------------------------------------------------
-
-
-@dataclass
-class _OwnerAccumulator:
- key: str
- name: str
- email: str | None = None
-
- files_owned: int = 0 # files where this person is primary_owner
- hotspots_owned: int = 0
- bus_factor_risk_files: int = 0
- commit_count_90d: int = 0
- lines_added_90d_est: float = 0.0
- lines_deleted_90d_est: float = 0.0
-
- last_commit_at: datetime | None = None
- first_commit_at: datetime | None = None
-
- # file_path -> attributed commit count (90d-ish, from top_authors_json)
- files_touched: dict[str, int] = field(default_factory=dict)
- file_meta: dict[str, GitMetadata] = field(default_factory=dict)
-
- # module rollup
- module_files: dict[str, int] = field(default_factory=lambda: defaultdict(int))
- module_hotspots: dict[str, int] = field(default_factory=lambda: defaultdict(int))
-
- commit_categories: Counter[str] = field(default_factory=Counter)
-
- dead_code_files: set[str] = field(default_factory=set)
- dead_code_lines: int = 0
-
- # Agent-provenance rollup across primary-owned files.
- owned_files_with_agents: int = 0
- owned_agent_commits: int = 0
- owned_attributed_commits: int = 0 # total commits on owned files with a rollup
- owned_agent_tier_counts: Counter[str] = field(default_factory=Counter)
-
- # co-author tally: other_key -> shared file count
- coauthor_shared: Counter[str] = field(default_factory=Counter)
- coauthor_meta: dict[str, tuple[str, str | None]] = field(default_factory=dict)
-
-# ---------------------------------------------------------------------------
-# Public API
-# ---------------------------------------------------------------------------
+_OwnerAccumulator = OwnerAccumulator
async def aggregate_owners(
session: AsyncSession, repo_id: str
-) -> tuple[dict[str, _OwnerAccumulator], dict[str, int]]:
- """Walk all GitMetadata rows once, returning per-owner accumulators.
+) -> tuple[dict[str, OwnerAccumulator], dict[str, int]]:
+ """Per-owner accumulators and files per module for *repo_id*.
- Hot-path: O(files * top_authors_per_file). top_authors is capped at 50
- by the indexer, so this is linear in repo size.
+ Git rows stay ORM entities: ``file_meta`` hands them back to the router.
"""
- rows = (
- await session.execute(
- select(GitMetadata).where(GitMetadata.repository_id == repo_id)
- )
- ).scalars().all()
-
- accs: dict[str, _OwnerAccumulator] = {}
- module_totals: dict[str, int] = defaultdict(int)
-
- # Build a repo-wide identity resolver first so noreply variants and a
- # person's same-display-name real+noreply emails fold to one bucket. Needs
- # every (name, email) pair up front, so collect them in a cheap pre-pass.
- def _pairs() -> list[tuple[str | None, str | None]]:
- out: list[tuple[str | None, str | None]] = []
- for m in rows:
- out.append((m.primary_owner_name, m.primary_owner_email))
- try:
- for a in json.loads(m.top_authors_json or "[]"):
- out.append((a.get("name"), a.get("email")))
- except json.JSONDecodeError:
- continue
- return out
-
- resolve = build_identity_resolver(_pairs())
-
- def _ensure(name: str, email: str | None) -> _OwnerAccumulator:
- k = resolve(name, email)
- if not k:
- return _OwnerAccumulator(key="", name=name or "(unknown)", email=email)
- acc = accs.get(k)
- if acc is None:
- acc = _OwnerAccumulator(key=k, name=name or (email or ""), email=email)
- accs[k] = acc
- # Promote a richer display name if we learn one later.
- if name and (not acc.name or acc.name == acc.email):
- acc.name = name
- if email and not acc.email:
- acc.email = email
- return acc
-
- # Pass 1: per-file walk.
- for m in rows:
- # All authors of this file (capped at 50 by indexer).
- try:
- authors = json.loads(m.top_authors_json or "[]")
- except json.JSONDecodeError:
- authors = []
-
- module = top_level_module(m.file_path)
- module_totals[module] += 1
- categories: dict[str, int] = {}
- with contextlib.suppress(json.JSONDecodeError):
- categories = json.loads(m.commit_categories_json or "{}")
-
- total_file_commits = sum(int(a.get("commit_count", 0)) for a in authors) or 1
- added = m.lines_added_90d or 0
- deleted = m.lines_deleted_90d or 0
- commits_90d = m.commit_count_90d or 0
-
- # Track everyone who touched this file — for co-author tallies we
- # need the full list.
- touchers: list[_OwnerAccumulator] = []
- for a in authors:
- name = a.get("name") or ""
- email = a.get("email") or None
- cnt = int(a.get("commit_count", 0))
- acc = _ensure(name, email)
- if not acc.key:
- continue
- share = cnt / total_file_commits
- acc.files_touched[m.file_path] = cnt
- acc.file_meta[m.file_path] = m
- acc.commit_count_90d += min(cnt, commits_90d) if commits_90d else 0
- acc.lines_added_90d_est += added * share
- acc.lines_deleted_90d_est += deleted * share
- for cat, n in categories.items():
- acc.commit_categories[cat] += int(n * share)
- # Prefer the author's *own* last/first commit to this file (added to
- # top_authors by the git indexer); fall back to the file-level value
- # for indexes built before that field existed.
- a_last_ts = a.get("last_commit_ts")
- a_last = (
- datetime.fromtimestamp(a_last_ts, tz=UTC)
- if a_last_ts
- else _as_utc(m.last_commit_at)
- )
- if a_last is not None and (
- acc.last_commit_at is None or a_last > acc.last_commit_at
- ):
- acc.last_commit_at = a_last
-
- a_first_ts = a.get("first_commit_ts")
- a_first = (
- datetime.fromtimestamp(a_first_ts, tz=UTC)
- if a_first_ts
- else _as_utc(m.first_commit_at)
- )
- if a_first is not None and (
- acc.first_commit_at is None or a_first < acc.first_commit_at
- ):
- acc.first_commit_at = a_first
- touchers.append(acc)
-
- # Primary owner — credit them for "files_owned" / hotspots / silo.
- primary = _ensure(m.primary_owner_name or "", m.primary_owner_email)
- if primary.key:
- primary.files_owned += 1
- primary.module_files[module] += 1
- if m.is_hotspot:
- primary.hotspots_owned += 1
- primary.module_hotspots[module] += 1
- if (m.bus_factor or 0) <= 1:
- primary.bus_factor_risk_files += 1
- # Agent collaboration: how much agent activity lands on the
- # files this person owns. agent_authored_pct is None for rows
- # persisted before the provenance-aware index ran — skip those
- # so the share stays honest.
- if m.agent_authored_pct is not None:
- primary.owned_attributed_commits += m.commit_count_total or 0
- if (m.agent_commit_count or 0) > 0:
- primary.owned_files_with_agents += 1
- primary.owned_agent_commits += m.agent_commit_count or 0
- try:
- tiers = json.loads(m.agent_tier_counts_json or "{}")
- except json.JSONDecodeError:
- tiers = {}
- for tier, n in tiers.items():
- primary.owned_agent_tier_counts[str(tier)] += int(n)
-
- # Co-author tally — each pair of distinct touchers shares this file.
- for i, a in enumerate(touchers):
- for b in touchers[i + 1 :]:
- if a.key == b.key:
- continue
- a.coauthor_shared[b.key] += 1
- a.coauthor_meta[b.key] = (b.name, b.email)
- b.coauthor_shared[a.key] += 1
- b.coauthor_meta[a.key] = (a.name, a.email)
-
- # Pass 2: dead-code burden by primary_owner.
+ git_rows = (
+ (await session.execute(select(GitMetadata).where(GitMetadata.repository_id == repo_id)))
+ .scalars()
+ .all()
+ )
dead_rows = (
await session.execute(
- select(DeadCodeFinding).where(DeadCodeFinding.repository_id == repo_id)
+ select(
+ DeadCodeFinding.primary_owner,
+ DeadCodeFinding.file_path,
+ DeadCodeFinding.lines,
+ ).where(DeadCodeFinding.repository_id == repo_id)
)
- ).scalars().all()
- for d in dead_rows:
- if not d.primary_owner:
- continue
- # DeadCodeFinding.primary_owner only carries the display name.
- acc = accs.get(owner_key(d.primary_owner, None))
- # If no email-keyed bucket exists, also try name lookup against
- # accumulators whose name matches (best-effort).
- if acc is None:
- for cand in accs.values():
- if cand.name == d.primary_owner:
- acc = cand
- break
- if acc is None:
- continue
- acc.dead_code_files.add(d.file_path)
- acc.dead_code_lines += d.lines or 0
-
- return accs, dict(module_totals)
-
-
-# ---------------------------------------------------------------------------
-# Shape helpers — turn accumulators into response models.
-# ---------------------------------------------------------------------------
-
-
-def silo_modules(acc: _OwnerAccumulator, module_totals: dict[str, int]) -> int:
- """Count modules where this owner is >80% of file ownership."""
-
- siloed = 0
- for mod, owned in acc.module_files.items():
- total = module_totals.get(mod, 0)
- if total > 0 and owned / total > 0.8:
- siloed += 1
- return siloed
-
-
-def module_share(
- acc: _OwnerAccumulator, module_totals: dict[str, int]
-) -> dict[str, float]:
- """Per-module share of files owned by this person (0–1)."""
-
- out: dict[str, float] = {}
- for mod, owned in acc.module_files.items():
- total = module_totals.get(mod, 0)
- out[mod] = owned / total if total else 0.0
- return out
+ ).all()
+ return _fold.aggregate_owners(git_rows, dead_rows)
+
+
+__all__ = [
+ "OwnerAccumulator",
+ "_OwnerAccumulator",
+ "aggregate_owners",
+ "module_share",
+ "owner_key",
+ "silo_modules",
+]
diff --git a/packages/server/src/repowise/server/services/reviewer_suggestions.py b/packages/server/src/repowise/server/services/reviewer_suggestions.py
index eed44d43c..7e5e5a2c7 100644
--- a/packages/server/src/repowise/server/services/reviewer_suggestions.py
+++ b/packages/server/src/repowise/server/services/reviewer_suggestions.py
@@ -1,36 +1,20 @@
"""Reviewer suggestion service.
-Given a set of changed file paths, suggest who should review the PR. The
-composite score blends three signals — all already computed during indexing:
-
- - Ownership: appearance in ``top_authors_json`` of the touched files,
- weighted by share of file commits.
- - Co-change: ownership of files that historically co-change with the
- touched paths (``co_change_partners_json``).
- - Recency: weight commit count by the file's 90-day activity so people
- who *just* worked here outrank people who touched the file in 2018.
-
-The output is intentionally short (top 10) — PRs with 30 suggested reviewers
+Fetches the git rows of the changed files and of their co-change partners,
+then ranks authors with :func:`repowise.core.analysis.reviewers.suggest_reviewers`.
+The output is intentionally short (top 10): PRs with 30 suggested reviewers
are no better than zero.
"""
from __future__ import annotations
-import json
-from collections import defaultdict
-
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
-from repowise.core.co_change import parse_partners
+from repowise.core.analysis import reviewers as _fold
from repowise.core.persistence.models import GitMetadata
from repowise.server.schemas import ReviewerSuggestion
-# Tunable weights.
-_W_DIRECT = 1.0
-_W_COCHANGE = 0.5
-_W_RECENT = 0.4
-
async def suggest_reviewers(
session: AsyncSession,
@@ -41,102 +25,36 @@ async def suggest_reviewers(
if not paths:
return []
- # 1) Direct ownership for the touched paths.
direct_rows = (
- await session.execute(
- select(GitMetadata).where(
- GitMetadata.repository_id == repo_id,
- GitMetadata.file_path.in_(paths),
- )
- )
- ).scalars().all()
-
- # 2) For each touched path, look up its co-change partners (cap to 5
- # strongest per file to keep the suggestion noise low) and fetch their
- # GitMetadata as well.
- cochange_paths: set[str] = set()
- cochange_partners: dict[str, list[str]] = defaultdict(list)
- for m in direct_rows:
- for p in parse_partners(m.co_change_partners_json)[:5]:
- cochange_paths.add(p.file_path)
- cochange_partners[p.file_path].append(m.file_path)
-
- cochange_rows = []
- if cochange_paths:
- cochange_rows = (
+ (
await session.execute(
select(GitMetadata).where(
GitMetadata.repository_id == repo_id,
- GitMetadata.file_path.in_(cochange_paths),
+ GitMetadata.file_path.in_(paths),
)
)
- ).scalars().all()
-
- # Per-author tally.
- tally: dict[str, dict] = {}
-
- def _bump(name: str, email: str | None, *, score: float, recent: int, path: str, reason: str, owned: bool) -> None:
- key = (email or "").strip().lower() or f"name:{name.strip()}"
- slot = tally.setdefault(
- key,
- {
- "name": name,
- "email": email,
- "score": 0.0,
- "recent_commits": 0,
- "owned_paths": set(),
- "co_change_paths": set(),
- "reasons": set(),
- },
)
- slot["score"] += score
- slot["recent_commits"] += recent
- if owned:
- slot["owned_paths"].add(path)
- else:
- slot["co_change_paths"].add(path)
- slot["reasons"].add(reason)
+ .scalars()
+ .all()
+ )
- def _process(rows, *, weight: float, owned: bool, reason: str) -> None:
- for m in rows:
- try:
- authors = json.loads(m.top_authors_json or "[]")
- except json.JSONDecodeError:
- continue
- total = sum(int(a.get("commit_count", 0)) for a in authors) or 1
- commits_90d = m.commit_count_90d or 0
- for a in authors:
- cnt = int(a.get("commit_count", 0))
- share = cnt / total
- # Recency: commits_90d weighted by share is a rough estimate
- # of how much each author contributed recently.
- recent = int(commits_90d * share)
- score = weight * share + _W_RECENT * (recent / max(commits_90d, 1))
- _bump(
- a.get("name", ""),
- a.get("email") or None,
- score=score,
- recent=recent,
- path=m.file_path,
- reason=reason,
- owned=owned,
+ partner_paths = _fold.cochange_paths(direct_rows)
+ cochange_rows = []
+ if partner_paths:
+ cochange_rows = (
+ (
+ await session.execute(
+ select(GitMetadata).where(
+ GitMetadata.repository_id == repo_id,
+ GitMetadata.file_path.in_(partner_paths),
+ )
)
-
- _process(direct_rows, weight=_W_DIRECT, owned=True, reason="touched")
- _process(cochange_rows, weight=_W_COCHANGE, owned=False, reason="co-change history")
-
- suggestions = []
- for slot in tally.values():
- suggestions.append(
- ReviewerSuggestion(
- name=slot["name"],
- email=slot["email"],
- score=round(slot["score"], 4),
- recent_commits=slot["recent_commits"],
- owned_paths=sorted(slot["owned_paths"])[:10],
- co_change_paths=sorted(slot["co_change_paths"])[:10],
- reasons=sorted(slot["reasons"]),
)
+ .scalars()
+ .all()
)
- suggestions.sort(key=lambda s: s.score, reverse=True)
- return suggestions[:limit]
+
+ return [
+ ReviewerSuggestion(**s)
+ for s in _fold.suggest_reviewers(direct_rows, cochange_rows, limit=limit)
+ ]
diff --git a/tests/unit/analysis/test_ownership_rollup_folds.py b/tests/unit/analysis/test_ownership_rollup_folds.py
new file mode 100644
index 000000000..ba689b04d
--- /dev/null
+++ b/tests/unit/analysis/test_ownership_rollup_folds.py
@@ -0,0 +1,127 @@
+"""The owner, module and reviewer folds over plain dicts.
+
+A non-SQL producer holds JSON columns already decoded and timestamps as ISO
+text; both must fold exactly like the stored text and datetimes.
+"""
+
+from __future__ import annotations
+
+import json
+from datetime import UTC, datetime
+
+from repowise.core.analysis.health.rows import json_field
+from repowise.core.analysis.module_health import aggregate_modules, detail_extras, summarize
+from repowise.core.analysis.owners import aggregate_owners, as_utc, silo_modules
+from repowise.core.analysis.reviewers import cochange_paths, suggest_reviewers
+
+_ROWS = [
+ {
+ "file_path": "src/core.py",
+ "primary_owner_name": "Alice",
+ "primary_owner_email": "[email protected]",
+ "top_authors": [
+ {"name": "Alice", "email": "[email protected]", "commit_count": 8},
+ {"name": "Bob", "email": "[email protected]", "commit_count": 2},
+ ],
+ "commit_categories": {"fix": 3},
+ "co_change_partners": [{"file_path": "lib/util.py", "co_change_count": 4}],
+ "commit_count_90d": 6,
+ "last_commit_at": datetime(2026, 8, 1, 9, 30),
+ "is_hotspot": True,
+ "bus_factor": 1,
+ "churn_percentile": 0.7,
+ },
+ {
+ "file_path": "lib/util.py",
+ "primary_owner_name": "Bob",
+ "primary_owner_email": "[email protected]",
+ "top_authors": [{"name": "Bob", "email": "[email protected]", "commit_count": 5}],
+ "commit_categories": {},
+ "co_change_partners": [],
+ "commit_count_90d": 1,
+ "last_commit_at": datetime(2026, 9, 1, tzinfo=UTC),
+ "is_hotspot": False,
+ "bus_factor": 2,
+ "churn_percentile": 0.2,
+ },
+]
+
+_JSON = {
+ "top_authors": "top_authors_json",
+ "commit_categories": "commit_categories_json",
+ "co_change_partners": "co_change_partners_json",
+}
+
+
+def _stored(row: dict) -> dict:
+ return {_JSON.get(k, k): (json.dumps(v) if k in _JSON else v) for k, v in row.items()}
+
+
+def _artifact(row: dict) -> dict:
+ out = {_JSON.get(k, k): v for k, v in row.items()}
+ out["last_commit_at"] = row["last_commit_at"].isoformat().replace("+00:00", "Z")
+ return out
+
+
+_DEAD = [{"file_path": "src/core.py", "lines": 4, "primary_owner": "Alice"}]
+_SYMBOLS = [{"file_path": "src/core.py", "docstring": "Doc."}]
+
+
+def test_json_field_reads_text_decoded_and_bad_cells() -> None:
+ assert json_field({"x": "[1]"}, "x", []) == [1]
+ assert json_field({"x": [1]}, "x", []) == [1]
+ assert json_field({"x": ""}, "x", []) == []
+ assert json_field({"x": "{bad"}, "x", {}) == {}
+ assert json_field({}, "x", {}) == {}
+
+
+def test_as_utc_reads_naive_aware_and_iso_text() -> None:
+ aware = datetime(2026, 8, 1, 9, 30, tzinfo=UTC)
+ assert as_utc(datetime(2026, 8, 1, 9, 30)) == aware
+ assert as_utc("2026-08-01T09:30:00Z") == aware
+ assert as_utc("not a date") is None
+
+
+def test_owner_fold_is_the_same_over_stored_and_decoded_rows() -> None:
+ def fold(rows):
+ accs, totals = aggregate_owners(rows, _DEAD)
+ return {k: {**vars(a), "file_meta": None} for k, a in accs.items()}, totals
+
+ stored = fold([_stored(r) for r in _ROWS])
+ assert stored == fold([_artifact(r) for r in _ROWS])
+ accs, totals = stored
+ assert totals == {"src": 1, "lib": 1}
+ assert accs["[email protected]"]["dead_code_lines"] == 4
+ assert accs["[email protected]"]["commit_categories"] == {"fix": 2}
+
+
+def test_module_fold_is_the_same_over_stored_and_decoded_rows() -> None:
+ decisions_text = [{"id": "d1", "affected_modules_json": json.dumps(["src"])}]
+ decisions_list = [{"id": "d1", "affected_modules_json": ["src"]}]
+
+ def fold(rows, decisions):
+ accs = aggregate_modules(rows, _SYMBOLS, _DEAD, decisions)
+ return {m: {**summarize(a), **detail_extras(a)} for m, a in accs.items()}
+
+ stored = fold([_stored(r) for r in _ROWS], decisions_text)
+ assert stored == fold([_artifact(r) for r in _ROWS], decisions_list)
+ assert stored["src"]["governing_decisions"] == ["d1"]
+ assert stored["src"]["doc_coverage_pct"] == 100.0
+
+
+def test_reviewer_fold_is_the_same_over_stored_and_decoded_rows() -> None:
+ for shape in (_stored, _artifact):
+ rows = [shape(r) for r in _ROWS]
+ assert cochange_paths(rows[:1]) == {"lib/util.py"}
+ out = suggest_reviewers(rows[:1], rows[1:], limit=5)
+ assert [s["name"] for s in out] == ["Bob", "Alice"]
+ assert out[0]["co_change_paths"] == ["lib/util.py"]
+
+
+def test_a_sole_owner_is_a_silo_in_both_rollups() -> None:
+ rows = [_stored(r) for r in _ROWS]
+ accs, totals = aggregate_owners(rows, [])
+ assert silo_modules(accs["[email protected]"], totals) == 1
+ modules = aggregate_modules(rows, [], [], [])
+ assert summarize(modules["src"])["is_silo"] is True
+ assert summarize(modules["src"])["health_score"] == 34.5
diff --git a/tests/unit/health/test_lightweight_health_imports.py b/tests/unit/health/test_lightweight_health_imports.py
index e5420243f..741cc1001 100644
--- a/tests/unit/health/test_lightweight_health_imports.py
+++ b/tests/unit/health/test_lightweight_health_imports.py
@@ -8,8 +8,8 @@ cycle from closing.
The engine now binds on first attribute access, and ``scoring`` keeps its one
biomarker import behind a ``TYPE_CHECKING`` gate. A consumer that only wants the
-ranking, the folds or the trend arithmetic pays for none of it: the seven modules
-below reach fewer than ten repowise modules between them, against the 419 and a
+ranking, the folds or the trend arithmetic pays for none of it: the modules
+below each reach about ten repowise modules, against the 419 and a
full set of tree-sitter grammars before. This is a guard, not a benchmark: it
fails when someone reintroduces an eager import, and says nothing about speed.
"""
@@ -31,6 +31,9 @@ _LIGHTWEIGHT = (
"repowise.core.analysis.health.grading",
"repowise.core.analysis.health.suggestions",
"repowise.core.analysis.health.defect_accuracy",
+ "repowise.core.analysis.module_health",
+ "repowise.core.analysis.owners",
+ "repowise.core.analysis.reviewers",
)
# Loading any of these means the seam stopped being portable: a downstream
diff --git a/tests/unit/server/golden/ownership_rollups.json b/tests/unit/server/golden/ownership_rollups.json
new file mode 100644
index 000000000..94baa64b7
--- /dev/null
+++ b/tests/unit/server/golden/ownership_rollups.json
@@ -0,0 +1,693 @@
+{
+ "owners": {
+ "items": [
+ {
+ "key": "[email protected]",
+ "name": "Alice",
+ "email": "[email protected]",
+ "files_owned": 2,
+ "hotspots_owned": 1,
+ "silo_modules": 0,
+ "dead_code_files_owned": 1,
+ "dead_code_lines_owned": 12,
+ "commit_count_90d": 25,
+ "last_commit_at": "2026-07-01T00:00:00Z",
+ "bus_factor_risk_files": 1
+ },
+ {
+ "key": "[email protected]",
+ "name": "Bob",
+ "email": "[email protected]",
+ "files_owned": 2,
+ "hotspots_owned": 1,
+ "silo_modules": 0,
+ "dead_code_files_owned": 0,
+ "dead_code_lines_owned": 0,
+ "commit_count_90d": 18,
+ "last_commit_at": "2026-08-01T12:00:00Z",
+ "bus_factor_risk_files": 1
+ },
+ {
+ "key": "name:Carol",
+ "name": "Carol",
+ "email": null,
+ "files_owned": 1,
+ "hotspots_owned": 0,
+ "silo_modules": 0,
+ "dead_code_files_owned": 1,
+ "dead_code_lines_owned": 30,
+ "commit_count_90d": 5,
+ "last_commit_at": "2026-08-01T12:00:00Z",
+ "bus_factor_risk_files": 1
+ }
+ ],
+ "total": 3,
+ "has_more": false,
+ "next_offset": null
+ },
+ "owners_by_commits": {
+ "items": [
+ {
+ "key": "[email protected]",
+ "name": "Alice",
+ "email": "[email protected]",
+ "files_owned": 2,
+ "hotspots_owned": 1,
+ "silo_modules": 0,
+ "dead_code_files_owned": 1,
+ "dead_code_lines_owned": 12,
+ "commit_count_90d": 25,
+ "last_commit_at": "2026-07-01T00:00:00Z",
+ "bus_factor_risk_files": 1
+ },
+ {
+ "key": "[email protected]",
+ "name": "Bob",
+ "email": "[email protected]",
+ "files_owned": 2,
+ "hotspots_owned": 1,
+ "silo_modules": 0,
+ "dead_code_files_owned": 0,
+ "dead_code_lines_owned": 0,
+ "commit_count_90d": 18,
+ "last_commit_at": "2026-08-01T12:00:00Z",
+ "bus_factor_risk_files": 1
+ },
+ {
+ "key": "name:Carol",
+ "name": "Carol",
+ "email": null,
+ "files_owned": 1,
+ "hotspots_owned": 0,
+ "silo_modules": 0,
+ "dead_code_files_owned": 1,
+ "dead_code_lines_owned": 30,
+ "commit_count_90d": 5,
+ "last_commit_at": "2026-08-01T12:00:00Z",
+ "bus_factor_risk_files": 1
+ }
+ ],
+ "total": 3,
+ "has_more": false,
+ "next_offset": null
+ },
+ "owner_profiles": {
+ "key": "[email protected]",
+ "name": "Alice",
+ "email": "[email protected]",
+ "files_owned": 2,
+ "hotspots_owned": 1,
+ "silo_modules": 0,
+ "dead_code_files_owned": 1,
+ "dead_code_lines_owned": 12,
+ "commit_count_90d": 25,
+ "last_commit_at": "2026-07-01T00:00:00Z",
+ "first_commit_at": "2025-01-02T03:04:05Z",
+ "bus_factor_risk_files": 1,
+ "lines_added_90d_est": 218,
+ "lines_deleted_90d_est": 70,
+ "modules": [
+ {
+ "module_path": "src",
+ "file_count": 1,
+ "hotspot_count": 1,
+ "dominant_pct": 0.3333333333333333
+ },
+ {
+ "module_path": "lib",
+ "file_count": 1,
+ "hotspot_count": 0,
+ "dominant_pct": 0.5
+ }
+ ],
+ "top_files": [
+ {
+ "file_path": "src/core.py",
+ "commit_count_90d": 35,
+ "churn_percentile": 95.0,
+ "bus_factor": 1,
+ "is_hotspot": true,
+ "last_commit_at": "2026-08-01T12:00:00",
+ "primary_owner_commit_pct": 0.7
+ },
+ {
+ "file_path": "lib/util.py",
+ "commit_count_90d": 4,
+ "churn_percentile": 40.0,
+ "bus_factor": 2,
+ "is_hotspot": false,
+ "last_commit_at": null,
+ "primary_owner_commit_pct": 0.6
+ },
+ {
+ "file_path": "src/api.py",
+ "commit_count_90d": 2,
+ "churn_percentile": 60.0,
+ "bus_factor": 1,
+ "is_hotspot": true,
+ "last_commit_at": "2026-07-01T00:00:00",
+ "primary_owner_commit_pct": 0.9
+ }
+ ],
+ "files_touched_total": 3,
+ "co_authors": [
+ {
+ "name": "Bob",
+ "email": "[email protected]",
+ "shared_files": 3,
+ "co_change_strength": 1.0
+ },
+ {
+ "name": "Carol",
+ "email": null,
+ "shared_files": 1,
+ "co_change_strength": 0.3333333333333333
+ }
+ ],
+ "co_authors_total": 2,
+ "commit_categories": {
+ "fix": 2,
+ "feature": 4
+ },
+ "agent_collab": {
+ "files_with_agent_commits": 1,
+ "agent_commit_count": 10,
+ "agent_share_pct": 20.0,
+ "tier_counts": {
+ "confirmed": 6,
+ "likely": 4
+ }
+ }
+ },
+ "key": "[email protected]",
+ "name": "Bob",
+ "email": "[email protected]",
+ "files_owned": 2,
+ "hotspots_owned": 1,
+ "silo_modules": 0,
+ "dead_code_files_owned": 0,
+ "dead_code_lines_owned": 0,
+ "commit_count_90d": 18,
+ "last_commit_at": "2026-08-01T12:00:00Z",
+ "first_commit_at": "2025-01-02T03:04:05Z",
+ "bus_factor_risk_files": 1,
+ "lines_added_90d_est": 132,
+ "lines_deleted_90d_est": 20,
+ "modules": [
+ {
+ "module_path": "src",
+ "file_count": 1,
+ "hotspot_count": 1,
+ "dominant_pct": 0.3333333333333333
+ },
+ {
+ "module_path": "lib",
+ "file_count": 1,
+ "hotspot_count": 0,
+ "dominant_pct": 0.5
+ }
+ ],
+ "top_files": [
+ {
+ "file_path": "src/api.py",
+ "commit_count_90d": 18,
+ "churn_percentile": 60.0,
+ "bus_factor": 1,
+ "is_hotspot": true,
+ "last_commit_at": "2026-07-01T00:00:00",
+ "primary_owner_commit_pct": 0.9
+ },
+ {
+ "file_path": "src/core.py",
+ "commit_count_90d": 10,
+ "churn_percentile": 95.0,
+ "bus_factor": 1,
+ "is_hotspot": true,
+ "last_commit_at": "2026-08-01T12:00:00",
+ "primary_owner_commit_pct": 0.7
+ },
+ {
+ "file_path": "lib/util.py",
+ "commit_count_90d": 6,
+ "churn_percentile": 40.0,
+ "bus_factor": 2,
+ "is_hotspot": false,
+ "last_commit_at": null,
+ "primary_owner_commit_pct": 0.6
+ }
+ ],
+ "files_touched_total": 3,
+ "co_authors": [
+ {
+ "name": "Alice",
+ "email": "[email protected]",
+ "shared_files": 3,
+ "co_change_strength": 1.0
+ },
+ {
+ "name": "Carol",
+ "email": null,
+ "shared_files": 1,
+ "co_change_strength": 0.3333333333333333
+ }
+ ],
+ "co_authors_total": 2,
+ "commit_categories": {
+ "fix": 0,
+ "feature": 1
+ },
+ "agent_collab": {
+ "files_with_agent_commits": 0,
+ "agent_commit_count": 0,
+ "agent_share_pct": 0.0,
+ "tier_counts": {}
+ }
+ },
+ "name:Carol": {
+ "key": "name:Carol",
+ "name": "Carol",
+ "email": null,
+ "files_owned": 1,
+ "hotspots_owned": 0,
+ "silo_modules": 0,
+ "dead_code_files_owned": 1,
+ "dead_code_lines_owned": 30,
+ "commit_count_90d": 5,
+ "last_commit_at": "2026-08-01T12:00:00Z",
+ "first_commit_at": "2019-03-03T00:00:00Z",
+ "bus_factor_risk_files": 1,
+ "lines_added_90d_est": 30,
+ "lines_deleted_90d_est": 10,
+ "modules": [
+ {
+ "module_path": "src",
+ "file_count": 1,
+ "hotspot_count": 0,
+ "dominant_pct": 0.3333333333333333
+ }
+ ],
+ "top_files": [
+ {
+ "file_path": "src/legacy.py",
+ "commit_count_90d": 7,
+ "churn_percentile": 10.0,
+ "bus_factor": 1,
+ "is_hotspot": false,
+ "last_commit_at": "2020-03-03T00:00:00",
+ "primary_owner_commit_pct": 1.0
+ },
+ {
+ "file_path": "src/core.py",
+ "commit_count_90d": 5,
+ "churn_percentile": 95.0,
+ "bus_factor": 1,
+ "is_hotspot": true,
+ "last_commit_at": "2026-08-01T12:00:00",
+ "primary_owner_commit_pct": 0.7
+ }
+ ],
+ "files_touched_total": 2,
+ "co_authors": [
+ {
+ "name": "Alice",
+ "email": "[email protected]",
+ "shared_files": 1,
+ "co_change_strength": 0.5
+ },
+ {
+ "name": "Bob",
+ "email": "[email protected]",
+ "shared_files": 1,
+ "co_change_strength": 0.5
+ }
+ ],
+ "co_authors_total": 2,
+ "commit_categories": {
+ "fix": 0,
+ "feature": 0
+ },
+ "agent_collab": null
+ }
+ },
+ "modules": {
+ "items": [
+ {
+ "module_path": "src",
+ "file_count": 3,
+ "symbol_count": 3,
+ "hotspot_count": 2,
+ "dead_code_count": 2,
+ "dead_code_lines": 42,
+ "avg_churn_percentile": 54.99999999999999,
+ "median_bus_factor": 1.0,
+ "min_bus_factor": 1,
+ "primary_owner": "Bob",
+ "primary_owner_pct": 0.3333333333333333,
+ "is_silo": false,
+ "decision_count": 2,
+ "doc_coverage_pct": 33.33333333333333,
+ "health_score": 56.75
+ },
+ {
+ "module_path": "root",
+ "file_count": 1,
+ "symbol_count": 0,
+ "hotspot_count": 0,
+ "dead_code_count": 0,
+ "dead_code_lines": 0,
+ "avg_churn_percentile": 0.0,
+ "median_bus_factor": 0.0,
+ "min_bus_factor": 0,
+ "primary_owner": null,
+ "primary_owner_pct": 0.0,
+ "is_silo": false,
+ "decision_count": 0,
+ "doc_coverage_pct": 0.0,
+ "health_score": 90.0
+ },
+ {
+ "module_path": "lib",
+ "file_count": 2,
+ "symbol_count": 1,
+ "hotspot_count": 0,
+ "dead_code_count": 1,
+ "dead_code_lines": 0,
+ "avg_churn_percentile": 30.000000000000004,
+ "median_bus_factor": 2.5,
+ "min_bus_factor": 2,
+ "primary_owner": "Alice",
+ "primary_owner_pct": 0.5,
+ "is_silo": false,
+ "decision_count": 1,
+ "doc_coverage_pct": 100.0,
+ "health_score": 100.0
+ }
+ ],
+ "total": 3,
+ "has_more": false,
+ "next_offset": null
+ },
+ "module_details": {
+ "src": {
+ "module_path": "src",
+ "file_count": 3,
+ "symbol_count": 3,
+ "hotspot_count": 2,
+ "dead_code_count": 2,
+ "dead_code_lines": 42,
+ "avg_churn_percentile": 54.99999999999999,
+ "median_bus_factor": 1.0,
+ "min_bus_factor": 1,
+ "primary_owner": "Bob",
+ "primary_owner_pct": 0.3333333333333333,
+ "is_silo": false,
+ "decision_count": 2,
+ "doc_coverage_pct": 33.33333333333333,
+ "health_score": 56.75,
+ "owners": [
+ {
+ "name": "Bob",
+ "email": "[email protected]",
+ "file_count": 1,
+ "pct": 0.3333333333333333
+ },
+ {
+ "name": "Alice",
+ "email": "[email protected]",
+ "file_count": 1,
+ "pct": 0.3333333333333333
+ },
+ {
+ "name": "Carol",
+ "email": null,
+ "file_count": 1,
+ "pct": 0.3333333333333333
+ }
+ ],
+ "top_hotspots": [
+ "src/core.py",
+ "src/api.py"
+ ],
+ "governing_decisions": [
+ {
+ "id": "dec-src",
+ "title": "Keep src flat",
+ "status": "active"
+ },
+ {
+ "id": "dec-both",
+ "title": "Share one util",
+ "status": "active"
+ }
+ ],
+ "contributor_count": 3
+ },
+ "lib": {
+ "module_path": "lib",
+ "file_count": 2,
+ "symbol_count": 1,
+ "hotspot_count": 0,
+ "dead_code_count": 1,
+ "dead_code_lines": 0,
+ "avg_churn_percentile": 30.000000000000004,
+ "median_bus_factor": 2.5,
+ "min_bus_factor": 2,
+ "primary_owner": "Alice",
+ "primary_owner_pct": 0.5,
+ "is_silo": false,
+ "decision_count": 1,
+ "doc_coverage_pct": 100.0,
+ "health_score": 100.0,
+ "owners": [
+ {
+ "name": "Alice",
+ "email": "[email protected]",
+ "file_count": 1,
+ "pct": 0.5
+ },
+ {
+ "name": "Bob",
+ "email": "[email protected]",
+ "file_count": 1,
+ "pct": 0.5
+ }
+ ],
+ "top_hotspots": [],
+ "governing_decisions": [
+ {
+ "id": "dec-both",
+ "title": "Share one util",
+ "status": "active"
+ }
+ ],
+ "contributor_count": 2
+ },
+ "root": {
+ "module_path": "root",
+ "file_count": 1,
+ "symbol_count": 0,
+ "hotspot_count": 0,
+ "dead_code_count": 0,
+ "dead_code_lines": 0,
+ "avg_churn_percentile": 0.0,
+ "median_bus_factor": 0.0,
+ "min_bus_factor": 0,
+ "primary_owner": null,
+ "primary_owner_pct": 0.0,
+ "is_silo": false,
+ "decision_count": 0,
+ "doc_coverage_pct": 0.0,
+ "health_score": 90.0,
+ "owners": [],
+ "top_hotspots": [],
+ "governing_decisions": [],
+ "contributor_count": 0
+ },
+ "src/api.py": {
+ "module_path": "src/api.py",
+ "file_count": 1,
+ "symbol_count": 1,
+ "hotspot_count": 1,
+ "dead_code_count": 0,
+ "dead_code_lines": 0,
+ "avg_churn_percentile": 60.0,
+ "median_bus_factor": 1.0,
+ "min_bus_factor": 1,
+ "primary_owner": "Bob",
+ "primary_owner_pct": 0.9,
+ "is_silo": true,
+ "decision_count": 0,
+ "doc_coverage_pct": 0.0,
+ "health_score": 36.0,
+ "owners": [
+ {
+ "name": "Bob",
+ "email": "[email protected]",
+ "file_count": 1,
+ "pct": 0.9
+ },
+ {
+ "name": "Alice",
+ "email": "[email protected]",
+ "file_count": 1,
+ "pct": 0.0
+ }
+ ],
+ "top_hotspots": [
+ "src/api.py"
+ ],
+ "governing_decisions": [],
+ "contributor_count": 2
+ },
+ "src/nested/missing.py": {
+ "module_path": "src",
+ "file_count": 3,
+ "symbol_count": 3,
+ "hotspot_count": 2,
+ "dead_code_count": 2,
+ "dead_code_lines": 42,
+ "avg_churn_percentile": 54.99999999999999,
+ "median_bus_factor": 1.0,
+ "min_bus_factor": 1,
+ "primary_owner": "Bob",
+ "primary_owner_pct": 0.3333333333333333,
+ "is_silo": false,
+ "decision_count": 2,
+ "doc_coverage_pct": 33.33333333333333,
+ "health_score": 56.75,
+ "owners": [
+ {
+ "name": "Bob",
+ "email": "[email protected]",
+ "file_count": 1,
+ "pct": 0.3333333333333333
+ },
+ {
+ "name": "Alice",
+ "email": "[email protected]",
+ "file_count": 1,
+ "pct": 0.3333333333333333
+ },
+ {
+ "name": "Carol",
+ "email": null,
+ "file_count": 1,
+ "pct": 0.3333333333333333
+ }
+ ],
+ "top_hotspots": [
+ "src/core.py",
+ "src/api.py"
+ ],
+ "governing_decisions": [
+ {
+ "id": "dec-src",
+ "title": "Keep src flat",
+ "status": "active"
+ },
+ {
+ "id": "dec-both",
+ "title": "Share one util",
+ "status": "active"
+ }
+ ],
+ "contributor_count": 3
+ }
+ },
+ "reviewers": {
+ "paths": [
+ "src/core.py",
+ "src/api.py"
+ ],
+ "suggestions": [
+ {
+ "name": "Bob",
+ "email": "[email protected]",
+ "score": 1.99,
+ "recent_commits": 8,
+ "owned_paths": [
+ "src/api.py"
+ ],
+ "co_change_paths": [
+ "src/api.py"
+ ],
+ "reasons": [
+ "co-change history",
+ "touched"
+ ]
+ },
+ {
+ "name": "Alice",
+ "email": "[email protected]",
+ "score": 1.4633,
+ "recent_commits": 15,
+ "owned_paths": [
+ "src/api.py",
+ "src/core.py"
+ ],
+ "co_change_paths": [
+ "lib/util.py",
+ "src/api.py"
+ ],
+ "reasons": [
+ "co-change history",
+ "touched"
+ ]
+ },
+ {
+ "name": "Bob",
+ "email": "[email protected]",
+ "score": 0.7133,
+ "recent_commits": 5,
+ "owned_paths": [
+ "src/core.py"
+ ],
+ "co_change_paths": [
+ "lib/util.py"
+ ],
+ "reasons": [
+ "co-change history",
+ "touched"
+ ]
+ },
+ {
+ "name": "Carol",
+ "email": null,
+ "score": 0.14,
+ "recent_commits": 2,
+ "owned_paths": [
+ "src/core.py"
+ ],
+ "co_change_paths": [],
+ "reasons": [
+ "touched"
+ ]
+ }
+ ]
+ },
+ "reviewers_limited": {
+ "paths": [
+ "lib/util.py"
+ ],
+ "suggestions": [
+ {
+ "name": "Alice",
+ "email": "[email protected]",
+ "score": 1.1633,
+ "recent_commits": 15,
+ "owned_paths": [
+ "lib/util.py"
+ ],
+ "co_change_paths": [
+ "src/core.py"
+ ],
+ "reasons": [
+ "co-change history",
+ "touched"
+ ]
+ }
+ ]
+ }
+}
diff --git a/tests/unit/server/test_ownership_rollups_golden.py b/tests/unit/server/test_ownership_rollups_golden.py
new file mode 100644
index 000000000..e30ce3d10
--- /dev/null
+++ b/tests/unit/server/test_ownership_rollups_golden.py
@@ -0,0 +1,234 @@
+"""Golden output of the owners, module-health and reviewer endpoints.
+
+Pins every field and order these three rollups serve over one seeded repo, so
+moving the folds between packages cannot change the wire. Rewrite with
+``REPOWISE_REWRITE_GOLDEN=1`` only for an intended behaviour change.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+from datetime import datetime
+from pathlib import Path
+from urllib.parse import quote
+
+import pytest
+from httpx import AsyncClient
+
+from repowise.core.persistence import crud
+from repowise.core.persistence.database import get_session
+from repowise.core.persistence.models import DeadCodeFinding, DecisionRecord, WikiSymbol
+from tests.unit.server.conftest import create_test_repo
+
+GOLDEN = Path(__file__).parent / "golden" / "ownership_rollups.json"
+
+_ALICE = {"name": "Alice", "email": "[email protected]"}
+_BOB = {"name": "Bob", "email": "[email protected]"}
+_BOB_NOREPLY = {"name": "Bob", "email": "[email protected]"}
+_CAROL = {"name": "Carol", "email": None}
+
+
+def _authors(*rows: tuple[dict, int, int | None]) -> str:
+ return json.dumps(
+ [
+ {**who, "commit_count": n, **({"last_commit_ts": ts} if ts else {})}
+ for who, n, ts in rows
+ ]
+ )
+
+
+# Naive on purpose: SQLite hands them back naive, which the fold must coerce.
+_GIT = {
+ "src/core.py": dict(
+ primary_owner_name="Alice",
+ primary_owner_email="[email protected]",
+ primary_owner_commit_pct=0.7,
+ top_authors_json=_authors((_ALICE, 35, 1_780_000_000), (_BOB, 10, None), (_CAROL, 5, None)),
+ commit_count_total=50,
+ commit_count_90d=20,
+ lines_added_90d=300,
+ lines_deleted_90d=100,
+ commit_categories_json=json.dumps({"fix": 4, "feature": 6}),
+ first_commit_at=datetime(2025, 1, 2, 3, 4, 5),
+ last_commit_at=datetime(2026, 8, 1, 12, 0, 0),
+ is_hotspot=True,
+ temporal_hotspot_score=0.9,
+ churn_percentile=0.95,
+ bus_factor=1,
+ agent_authored_pct=0.2,
+ agent_commit_count=10,
+ agent_tier_counts_json=json.dumps({"confirmed": 6, "likely": 4}),
+ co_change_partners_json=json.dumps(
+ [
+ {"file_path": "lib/util.py", "co_change_count": 9},
+ {"file_path": "src/api.py", "co_change_count": 4},
+ ]
+ ),
+ ),
+ "src/api.py": dict(
+ primary_owner_name="Bob",
+ primary_owner_email="[email protected]",
+ primary_owner_commit_pct=0.9,
+ top_authors_json=_authors((_BOB_NOREPLY, 18, 1_785_000_000), (_ALICE, 2, None)),
+ commit_count_total=20,
+ commit_count_90d=5,
+ lines_added_90d=80,
+ first_commit_at=datetime(2025, 6, 1),
+ last_commit_at=datetime(2026, 7, 1),
+ is_hotspot=True,
+ temporal_hotspot_score=0.4,
+ churn_percentile=0.6,
+ bus_factor=1,
+ agent_authored_pct=0.0,
+ agent_commit_count=0,
+ ),
+ "src/legacy.py": dict(
+ primary_owner_name="Carol",
+ primary_owner_email=None,
+ primary_owner_commit_pct=1.0,
+ top_authors_json=_authors((_CAROL, 7, None)),
+ commit_count_total=7,
+ first_commit_at=datetime(2019, 3, 3),
+ last_commit_at=datetime(2020, 3, 3),
+ churn_percentile=0.1,
+ bus_factor=1,
+ ),
+ "lib/util.py": dict(
+ primary_owner_name="Bob",
+ primary_owner_email="[email protected]",
+ primary_owner_commit_pct=0.6,
+ top_authors_json=_authors((_BOB, 6, None), (_ALICE, 4, 1_770_000_000)),
+ commit_count_total=10,
+ commit_count_90d=3,
+ commit_categories_json="{not json",
+ churn_percentile=0.4,
+ bus_factor=2,
+ co_change_partners_json=json.dumps([{"file_path": "src/core.py", "co_change_count": 9}]),
+ ),
+ "lib/broken.py": dict(
+ primary_owner_name="Alice",
+ primary_owner_email="[email protected]",
+ primary_owner_commit_pct=0.5,
+ top_authors_json="not json",
+ churn_percentile=0.2,
+ bus_factor=3,
+ ),
+ "setup.py": dict(
+ primary_owner_name=None,
+ primary_owner_email=None,
+ top_authors_json="[]",
+ bus_factor=0,
+ ),
+}
+
+
+async def _seed(session_factory, repo_id: str) -> None:
+ async with get_session(session_factory) as session:
+ for path, fields in _GIT.items():
+ await crud.upsert_git_metadata(
+ session, repository_id=repo_id, file_path=path, **fields
+ )
+ session.add_all(
+ [
+ WikiSymbol(
+ id=f"sym{i}",
+ repository_id=repo_id,
+ file_path=path,
+ symbol_id=f"{path}::f{i}",
+ name=f"f{i}",
+ qualified_name=f"f{i}",
+ kind="function",
+ docstring=doc,
+ )
+ for i, (path, doc) in enumerate(
+ [
+ ("src/core.py", "Does the thing."),
+ ("src/core.py", " "),
+ ("src/api.py", None),
+ ("lib/util.py", "Helps."),
+ ("orphan/x.py", "No git row, so no module."),
+ ]
+ )
+ ]
+ )
+ session.add_all(
+ [
+ DeadCodeFinding(
+ id=f"dead{i}",
+ repository_id=repo_id,
+ kind="unused_export",
+ file_path=path,
+ symbol_name="old",
+ symbol_kind="function",
+ confidence=0.9,
+ lines=lines,
+ safe_to_delete=True,
+ primary_owner=owner,
+ )
+ for i, (path, lines, owner) in enumerate(
+ [
+ ("src/core.py", 12, "Alice"),
+ ("src/legacy.py", 30, "Carol"),
+ ("lib/util.py", None, "Nobody"),
+ ("orphan/x.py", 5, None),
+ ]
+ )
+ ]
+ )
+ session.add_all(
+ [
+ DecisionRecord(
+ id=did,
+ repository_id=repo_id,
+ title=title,
+ status="active",
+ affected_modules_json=modules,
+ )
+ for did, title, modules in [
+ ("dec-src", "Keep src flat", json.dumps(["src"])),
+ ("dec-both", "Share one util", json.dumps(["lib", "src", "gone"])),
+ ("dec-bad", "Malformed scope", "{oops"),
+ ]
+ ]
+ )
+ await session.commit()
+
+
+async def test_ownership_rollups_match_the_golden(client: AsyncClient, session_factory) -> None:
+ repo = await create_test_repo(client)
+ await _seed(session_factory, repo["id"])
+ base = f"/api/repos/{repo['id']}"
+
+ async def get(url: str, params=None):
+ resp = await client.get(base + url, params=params)
+ assert resp.status_code == 200, url
+ return resp.json()
+
+ owners = await get("/owners")
+ result = {
+ "owners": owners,
+ "owners_by_commits": await get("/owners", {"sort": "commit_count_90d"}),
+ "owner_profiles": {
+ o["key"]: await get(f"/owners/{quote(o['key'], safe='')}") for o in owners["items"]
+ },
+ "modules": await get("/modules/health"),
+ "module_details": {
+ path: await get(f"/modules/health/{quote(path)}")
+ for path in ("src", "lib", "root", "src/api.py", "src/nested/missing.py")
+ },
+ "reviewers": await get(
+ "/reviewer-suggestions", [("paths", "src/core.py"), ("paths", "src/api.py")]
+ ),
+ "reviewers_limited": await get(
+ "/reviewer-suggestions", [("paths", "lib/util.py"), ("limit", "1")]
+ ),
+ }
+
+ if os.environ.get("REPOWISE_REWRITE_GOLDEN"):
+ GOLDEN.parent.mkdir(exist_ok=True)
+ GOLDEN.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8", newline="\n")
+ pytest.skip("golden rewritten")
+ golden = json.loads(GOLDEN.read_text(encoding="utf-8"))
+ assert result == golden