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(contributors): fold GitHub noreply emails so one person isn't two contributors (#701)
Swati Ahujade2a63029494
diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/__init__.py b/packages/core/src/repowise/core/ingestion/git_indexer/__init__.pyindex 2546ec4e6..9456ec986 100644--- a/packages/core/src/repowise/core/ingestion/git_indexer/__init__.py+++ b/packages/core/src/repowise/core/ingestion/git_indexer/__init__.py@@ -36,6 +36,7 @@ from .enrich import (meets_hotspot_floors,)from .file_history import index_file+from .identity import build_identity_resolver, canonicalize_author_emailfrom .indexer import GitIndexerfrom .prior_defects import compute_prior_defectsfrom .records import (@@ -67,6 +68,8 @@ __all__ = ["_parse_commit_record","_should_skip_index","backfill_full_tier",+ "build_identity_resolver",+ "canonicalize_author_email","classifier_from_repo_config","compute_co_changes","compute_co_changes_and_entropy",diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/commit_rows.py b/packages/core/src/repowise/core/ingestion/git_indexer/commit_rows.pyindex 1ce3cedbd..1b345f5e6 100644--- a/packages/core/src/repowise/core/ingestion/git_indexer/commit_rows.py+++ b/packages/core/src/repowise/core/ingestion/git_indexer/commit_rows.py@@ -18,6 +18,7 @@ from __future__ import annotationsfrom datetime import UTC, datetimefrom ._constants import is_fix_commit+from .identity import canonicalize_author_email# Commit subjects are a headline (`%s`); cap defensively against a pathological# single-line subject so one row can't bloat the table.@@ -25,8 +26,14 @@ _MAX_SUBJECT_LEN = 500def _author_key(author_name: str, author_email: str) -> str:- """Stable identity for the in-memory experience tally."""- return (author_email or author_name or "").strip().lower()+ """Stable identity for the in-memory experience tally.++ GitHub ``noreply`` variants of one login are folded together first so a+ person's prior-commit count doesn't reset when their email flips between+ forms.+ """+ canonical = canonicalize_author_email(author_email) or author_email+ return (canonical or author_name or "").strip().lower()def _committed_at(ts: int) -> datetime | None:diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/file_history.py b/packages/core/src/repowise/core/ingestion/git_indexer/file_history.pyindex 54a581713..7328be5d5 100644--- a/packages/core/src/repowise/core/ingestion/git_indexer/file_history.py+++ b/packages/core/src/repowise/core/ingestion/git_indexer/file_history.py@@ -36,6 +36,7 @@ from .function_blame import (build_blame_index,ownership_from_blame,)+from .identity import canonicalize_author_emailfrom .records import (_LOG_FORMAT,_RECORD_SEP,@@ -300,8 +301,18 @@ def index_file(if c.ts >= thirty_days_ago_ts:meta["commit_count_30d"] += 1author_counts[c.author_name] += 1- if c.author_name not in author_emails and c.author_email:- author_emails[c.author_name] = c.author_email+ if c.author_email:+ # Group by name, but pick a stable email per person: fold GitHub+ # noreply variants together and prefer a real address over a+ # noreply one, so a contributor who committed both ways doesn't+ # split into two buckets downstream (owner_profile keys on email).+ canon = canonicalize_author_email(c.author_email) or c.author_email+ existing = author_emails.get(c.author_name)+ if existing is None or (+ existing.endswith("@users.noreply.github.com")+ and not canon.endswith("@users.noreply.github.com")+ ):+ author_emails[c.author_name] = canonif c.ts > 0:prev_last = author_last_ts.get(c.author_name)if prev_last is None or c.ts > prev_last:diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/identity.py b/packages/core/src/repowise/core/ingestion/git_indexer/identity.pynew file mode 100644index 000000000..325e80c1d--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/git_indexer/identity.py@@ -0,0 +1,96 @@+"""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.++ ``[email protected]`` and ``[email protected]``+ 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 _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 resolvediff --git a/packages/server/src/repowise/server/routers/stats.py b/packages/server/src/repowise/server/routers/stats.pyindex 1c066a588..3e4fcae4a 100644--- a/packages/server/src/repowise/server/routers/stats.py+++ b/packages/server/src/repowise/server/routers/stats.py@@ -20,6 +20,7 @@ from fastapi import APIRouter, Depends, HTTPExceptionfrom sqlalchemy import func, selectfrom sqlalchemy.ext.asyncio import AsyncSession+from repowise.core.ingestion.git_indexer import build_identity_resolverfrom repowise.core.persistence import crudfrom repowise.core.persistence.models import (DecisionRecord,@@ -127,6 +128,7 @@ async def _activity(session: AsyncSession, repo_id: str) -> dict[str, Any]:await session.execute(select(GitCommit.committed_at,+ GitCommit.author_name,GitCommit.author_email,GitCommit.agent_name,GitCommit.is_fix,@@ -134,6 +136,10 @@ async def _activity(session: AsyncSession, repo_id: str) -> dict[str, Any]:)).all()+ # Fold GitHub noreply variants and same-name real+noreply emails to one+ # identity so the same person isn't counted as several contributors.+ resolve = build_identity_resolver([(name, email) for _, name, email, _, _ in rows])+total = 0agent_total = 0fix_total = 0@@ -143,10 +149,12 @@ async def _activity(session: AsyncSession, repo_id: str) -> dict[str, Any]:first_at: Any = Nonelast_at: Any = None- for committed_at, author_email, agent_name, is_fix in rows:+ for committed_at, author_name, author_email, agent_name, is_fix in rows:total += 1- if author_email:- contributors.add(author_email.lower())+ if author_email or author_name:+ key = resolve(author_name, author_email)+ if key:+ contributors.add(key)if is_fix:fix_total += 1if agent_name:diff --git a/packages/server/src/repowise/server/services/owner_profile.py b/packages/server/src/repowise/server/services/owner_profile.pyindex 66925a9aa..6a51f9959 100644--- a/packages/server/src/repowise/server/services/owner_profile.py+++ b/packages/server/src/repowise/server/services/owner_profile.py@@ -25,6 +25,10 @@ from datetime import UTC, datetimefrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession+from repowise.core.ingestion.git_indexer import (+ build_identity_resolver,+ canonicalize_author_email,+)from repowise.core.persistence.models import DeadCodeFinding, GitMetadata@@ -37,11 +41,13 @@ 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.+ 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 email.strip().lower()+ return (canonicalize_author_email(email) or "").strip().lower()if name:return f"name:{name.strip()}"return ""@@ -133,8 +139,24 @@ async def aggregate_owners(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 = owner_key(name, email)+ k = resolve(name, email)if not k:return _OwnerAccumulator(key="", name=name or "(unknown)", email=email)acc = accs.get(k)diff --git a/tests/unit/ingestion/test_author_identity.py b/tests/unit/ingestion/test_author_identity.pynew file mode 100644index 000000000..8109d3720--- /dev/null+++ b/tests/unit/ingestion/test_author_identity.py@@ -0,0 +1,122 @@+"""Tests for GitHub noreply author-identity canonicalization.++Covers the identity chokepoints that split one person into several contributor+buckets: the shared ``canonicalize_author_email`` helper, the ``owner_key``+that keys the contributor directory, the commit-experience tally key, and the+per-file author-email selection in ``index_file``.+"""++from __future__ import annotations++from repowise.core.ingestion.git_indexer import (+ build_identity_resolver,+ canonicalize_author_email,+)+from repowise.core.ingestion.git_indexer.commit_rows import _author_key+from repowise.server.services.owner_profile import owner_key+++class TestCanonicalizeAuthorEmail:+ def test_numeric_prefixed_noreply_folds_to_login(self) -> None:+ assert (+ canonicalize_author_email("[email protected]")+ == "[email protected]"+ )++ def test_all_noreply_variants_of_one_login_share_a_key(self) -> None:+ # Old (no numeric id) and new (numeric id) forms, plus a re-issued id,+ # all collapse to the same canonical identity.+ variants = [+ "[email protected]",+ "[email protected]",+ "[email protected]",+ "[email protected]", # casing varies too+ ]+ keys = {canonicalize_author_email(v) for v in variants}+ assert keys == {"[email protected]"}++ def test_different_logins_stay_distinct(self) -> None:+ assert canonicalize_author_email(+ ) != canonicalize_author_email("[email protected]")++ def test_real_email_is_lowercased_but_unchanged(self) -> None:+ assert canonicalize_author_email("[email protected]") == "[email protected]"++ def test_github_system_author_is_not_folded_into_a_person(self) -> None:+ # [email protected] is the GitHub *system* author on some merge commits;+ # it must stay its own bucket, never merged onto a human login.+ assert canonicalize_author_email("[email protected]") == "[email protected]"++ def test_empty_and_none_pass_through(self) -> None:+ assert canonicalize_author_email("") == ""+ assert canonicalize_author_email(None) is None+++class TestOwnerKey:+ def test_noreply_variants_key_to_one_contributor(self) -> None:+ a = owner_key("Jane", "[email protected]")+ b = owner_key("Jane", "[email protected]")+ assert a == b == "[email protected]"++ def test_name_fallback_when_no_email(self) -> None:+ assert owner_key("Jane Doe", None) == "name:Jane Doe"++ def test_real_email_preferred_and_lowercased(self) -> None:+ assert owner_key("Jane", "[email protected]") == "[email protected]"+++class TestCommitExperienceKey:+ def test_noreply_variants_share_an_experience_tally(self) -> None:+ assert _author_key("Jane", "[email protected]") == _author_key(+ "Jane", "[email protected]"+ )+++class TestIdentityResolver:+ def test_same_name_real_and_noreply_collapse_to_the_real_email(self) -> None:+ # The DoD case: one real-email commit + one noreply commit, same display+ # name, spread across records -> a single contributor keyed on the real+ # email.+ resolve = build_identity_resolver(+ [+ ("Jane Doe", "[email protected]"),+ ("Jane Doe", "[email protected]"),+ ]+ )+ assert resolve("Jane Doe", "[email protected]") == "[email protected]"+ assert resolve("Jane Doe", "[email protected]") == "[email protected]"++ def test_noreply_only_person_keeps_the_noreply_identity(self) -> None:+ resolve = build_identity_resolver([("Ghost", "[email protected]")])+ assert (+ resolve("Ghost", "[email protected]") == "[email protected]"+ )++ def test_ambiguous_name_with_two_real_emails_is_not_folded(self) -> None:+ # A display name that maps to two different real emails is left split —+ # we can't safely guess which the noreply commit belongs to.+ resolve = build_identity_resolver(+ [+ ("Admin", "[email protected]"),+ ("Admin", "[email protected]"),+ ("Admin", "[email protected]"),+ ]+ )+ assert (+ resolve("Admin", "[email protected]") == "[email protected]"+ )++ def test_different_names_are_not_bridged(self) -> None:+ # Real email under one name, noreply under another -> stays split (the+ # name<->login bridge is out of scope for the simple version).+ resolve = build_identity_resolver(+ [+ ("Jane Doe", "[email protected]"),+ ("jdoe", "[email protected]"),+ ]+ )+ assert (+ resolve("jdoe", "[email protected]")+ == "[email protected]"+ )diff --git a/tests/unit/server/test_owners.py b/tests/unit/server/test_owners.pyindex 5417db196..09eb4e6ec 100644--- a/tests/unit/server/test_owners.py+++ b/tests/unit/server/test_owners.py@@ -190,6 +190,65 @@ async def test_last_commit_uses_authors_own_timestamp(client: AsyncClient, app)assert bob.last_commit_at == file_last+async def test_noreply_and_real_email_collapse_to_one_contributor(+ client: AsyncClient, app+) -> None:+ """One person who committed with a real email on one file and a GitHub+ noreply email on another (same display name) is a single contributor —+ not two."""+ repo = await create_test_repo(client)+ async with get_session(app.state.session_factory) as session:+ # File A: Jane with her real email.+ await crud.upsert_git_metadata(+ session,+ repository_id=repo["id"],+ file_path="src/a.py",+ commit_count_total=10,+ primary_owner_name="Jane Doe",+ primary_owner_email="[email protected]",+ top_authors_json=json.dumps(+ [{"name": "Jane Doe", "email": "[email protected]", "commit_count": 10}]+ ),+ contributor_count=1,+ )+ # File B: same Jane, but a squash-merge stamped a noreply email.+ await crud.upsert_git_metadata(+ session,+ repository_id=repo["id"],+ file_path="src/b.py",+ commit_count_total=4,+ primary_owner_name="Jane Doe",+ primary_owner_email="[email protected]",+ top_authors_json=json.dumps(+ [+ {+ "name": "Jane Doe",+ "email": "[email protected]",+ "commit_count": 4,+ }+ ]+ ),+ contributor_count=1,+ )++ async with get_session(app.state.session_factory) as session:+ accs, _ = await aggregate_owners(session, repo["id"])++ # Exactly one bucket, keyed on the real email, crediting both files.+ people = [a for a in accs.values() if a.key]+ assert len(people) == 1+ jane = people[0]+ assert jane.key == "[email protected]"+ assert jane.name == "Jane Doe"+ assert set(jane.files_touched) == {"src/a.py", "src/b.py"}++ # The directory endpoint agrees: one contributor.+ resp = await client.get(f"/api/repos/{repo['id']}/owners")+ assert resp.status_code == 200+ assert resp.json()["total"] == 1++@pytest.mark.asyncioasync def test_get_owner_profile_not_found(client: AsyncClient) -> None:repo = await create_test_repo(client)diff --git a/tests/unit/server/test_stats_contributors.py b/tests/unit/server/test_stats_contributors.pynew file mode 100644index 000000000..38474f57e--- /dev/null+++ b/tests/unit/server/test_stats_contributors.py@@ -0,0 +1,58 @@+"""Contributor-count dedup on the /stats/highlights activity payload.++The "By the Numbers" contributor count keys on commit author identity; GitHub+noreply variants and a person's same-name real+noreply emails must fold to one+person so the headline count isn't inflated.+"""++from __future__ import annotations++from datetime import UTC, datetime++import pytest+from httpx import AsyncClient++from repowise.core.persistence.crud import upsert_git_commits_bulk+from repowise.core.persistence.database import get_session+from repowise.server.routers.stats import _activity+from tests.unit.server.conftest import create_test_repo+++def _commit(sha: str, name: str, email: str, ts: int) -> dict:+ return {+ "sha": sha,+ "author_name": name,+ "author_email": email,+ "committed_at": datetime.fromtimestamp(ts, tz=UTC),+ "subject": f"commit {sha}",+ "lines_added": 5,+ "lines_deleted": 1,+ "files_changed": 1,+ "dirs_changed": 1,+ "subsystems_changed": 1,+ "entropy": 0.1,+ "is_fix": False,+ "change_risk_score": 1.0,+ "change_risk_level": "low",+ }+++async def test_contributor_count_folds_noreply_and_same_name(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ rows = [+ # Jane: real email + two noreply variants (numeric id changed) — one person.+ _commit("a1", "Jane Doe", "[email protected]", 1000),+ _commit("a2", "Jane Doe", "[email protected]", 1100),+ _commit("a3", "Jane Doe", "[email protected]", 1200),+ # Bob: a genuinely separate contributor.+ _commit("b1", "Bob", "[email protected]", 1300),+ ]+ async with get_session(app.state.session_factory) as session:+ await upsert_git_commits_bulk(session, repo["id"], rows)++ async with get_session(app.state.session_factory) as session:+ activity = await _activity(session, repo["id"])++ assert activity["total_commits"] == 4+ assert activity["contributor_count"] == 2 # Jane + Bob, not 4