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.

20.8 KB
Raw Blame
"""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

import json
import os
import subprocess
from pathlib import Path

import git
import pytest

from repowise.core.author_identity import identity_kind, is_bot
from repowise.core.ingestion.git_indexer import (
    build_identity_resolver,
    canonicalize_author_email,
)
from repowise.core.ingestion.git_indexer.enrich import (
    count_active_contributors,
    is_significant_commit,
)
from repowise.core.ingestion.git_indexer.identity import author_identity_key
from repowise.core.ingestion.git_indexer.records import capture_repo_totals, count_people
from repowise.core.stats_highlights import build_people
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(
            "[email protected]"
        ) != 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_identity_key(
            "Jane", "[email protected]"
        ) == author_identity_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]"
        )


# ---------------------------------------------------------------------------
# Union-find merge (E3-E5) and its guardrails
# ---------------------------------------------------------------------------

_NR = "@users.noreply.github.com"


def _groups(pairs, evidence=()):
    """The resolver's partition of the given emails, as a set of frozensets."""
    resolve = build_identity_resolver(pairs, evidence)
    out: dict[str, set[str]] = {}
    for name, email in pairs:
        out.setdefault(resolve(name, email), set()).add(email.lower())
    return {frozenset(g) for g in out.values()}, resolve


MERGE_CASES = [
    pytest.param(
        # A handle used as the name on several real emails, and a full name on
        # the login's noreply address: one person (E4 + E2).
        [
            ("Maya Rossi", f"mrossi{_NR}"),
            ("mrossi", f"12381+mrossi{_NR}"),
            ("mrossi", "[email protected]"),
            ("mrossi", "[email protected]"),
        ],
        [{f"mrossi{_NR}", f"12381+mrossi{_NR}", "[email protected]", "[email protected]"}],
        "Maya Rossi",
        id="login-named-real-emails",
    ),
    pytest.param(
        [
            ("Omar Haddad", f"5358+ohdev{_NR}"),
            ("ohdev", f"5358+ohdev{_NR}"),
            ("ohdev", "[email protected]"),
        ],
        [{f"5358+ohdev{_NR}", "[email protected]"}],
        "Omar Haddad",
        id="noreply-full-name-plus-handle-email",
    ),
    pytest.param(
        # Machine-local addresses fold into the one real email of that name (E5).
        [
            ("Lena Park", "[email protected]"),
            ("Lena Park", "[email protected]"),
            ("Lena Park", "[email protected]"),
            ("Lena Park", "lena@(none)"),
        ],
        [
            {
                "[email protected]",
                "[email protected]",
                "[email protected]",
                "lena@(none)",
            }
        ],
        "Lena Park",
        id="machine-local-emails",
    ),
    pytest.param(
        # Same full name on noreply + one real email (E3), a local email (E5).
        [
            ("Tomas Berg", f"144+tberg{_NR}"),
            ("Tomas Berg", "[email protected]"),
            ("Tomas Berg", "[email protected]"),
        ],
        [{f"144+tberg{_NR}", "[email protected]", "[email protected]"}],
        "Tomas Berg",
        id="full-name-noreply-and-local",
    ),
    pytest.param(
        # Two different people called Alex keep their own identities, and so
        # do two real emails under one full name: a name alone never merges.
        [
            ("Alex", "[email protected]"),
            ("Alex", "[email protected]"),
            ("Alex Kim", "[email protected]"),
            ("Alex Kim", "[email protected]"),
        ],
        [{"[email protected]"}, {"[email protected]"}, {"[email protected]"}, {"[email protected]"}],
        None,
        id="two-alexes-stay-apart",
    ),
    pytest.param(
        # A one-word name is too common to bridge a noreply login (E3/E5 need
        # 2+ words); the login is not that email's name either (no E4).
        [
            ("Kirill", f"80+kbast{_NR}"),
            ("Kirill", "[email protected]"),
            ("Kirill", "[email protected]"),
        ],
        [{f"80+kbast{_NR}"}, {"[email protected]"}, {"[email protected]"}],
        None,
        id="one-word-name-does-not-merge",
    ),
    pytest.param(
        # Generic and short logins never bridge by name.
        [
            ("admin", f"9+admin{_NR}"),
            ("admin", "[email protected]"),
            ("ubuntu", f"ubuntu{_NR}"),
            ("ubuntu", "[email protected]"),
            ("jo", f"3+jo{_NR}"),
            ("jo", "[email protected]"),
        ],
        [
            {f"9+admin{_NR}"},
            {"[email protected]"},
            {f"ubuntu{_NR}"},
            {"[email protected]"},
            {f"3+jo{_NR}"},
            {"[email protected]"},
        ],
        None,
        id="generic-login-collision",
    ),
    pytest.param(
        # A login that is the name of more than 3 real emails is a common word.
        [
            ("mike", f"7+mike{_NR}"),
            ("mike", "[email protected]"),
            ("mike", "[email protected]"),
            ("mike", "[email protected]"),
            ("mike", "[email protected]"),
        ],
        [{f"7+mike{_NR}"}, {"[email protected]"}, {"[email protected]"}, {"[email protected]"}, {"[email protected]"}],
        None,
        id="login-naming-too-many-emails",
    ),
    pytest.param(
        # Two different logins would land in one identity: roll the soft edges
        # back rather than guess which login is this person's.
        [
            ("Jane Doe", f"11+janed{_NR}"),
            ("Jane Doe", f"22+jdoe99{_NR}"),
            ("Jane Doe", "[email protected]"),
        ],
        [{f"11+janed{_NR}"}, {f"22+jdoe99{_NR}"}, {"[email protected]"}],
        None,
        id="two-login-conflict-rolls-back",
    ),
    pytest.param(
        # Same conflict reached through E4: two handles name one real email.
        [
            ("Pat Quinn", f"31+pquinn{_NR}"),
            ("Patrick", f"32+patq{_NR}"),
            ("pquinn", "[email protected]"),
            ("patq", "[email protected]"),
        ],
        [{f"31+pquinn{_NR}"}, {f"32+patq{_NR}"}, {"[email protected]"}],
        None,
        id="two-login-conflict-via-handles",
    ),
    pytest.param(
        # One shared alias committed under two people's names must not bridge
        # them: it matches a different real email per name, so it takes neither.
        [
            ("Jane Doe", f"41+shared{_NR}"),
            ("John Smith", f"41+shared{_NR}"),
            ("Jane Doe", "[email protected]"),
            ("John Smith", "[email protected]"),
            ("Jane Doe", "[email protected]"),
            ("John Smith", "[email protected]"),
        ],
        [{f"41+shared{_NR}"}, {"[email protected]"}, {"[email protected]"}, {"[email protected]"}],
        None,
        id="shared-alias-two-names-stays-apart",
    ),
    pytest.param(
        # A GitLab noreply address joins its owner's real email by full name,
        # and is never folded into another account that reused the login.
        [
            ("Jane Doe", "[email protected]"),
            ("Jane Doe", "[email protected]"),
            ("Jim Doe", "[email protected]"),
        ],
        [
            {"[email protected]", "[email protected]"},
            {"[email protected]"},
        ],
        None,
        id="gitlab-noreply-joins-by-name",
    ),
    pytest.param(
        # One login on two GitLab ids or hosts may be two accounts: a shared
        # real email must not bridge them.
        [
            ("john", "[email protected]"),
            ("john", "[email protected]"),
            ("john", "[email protected]"),
        ],
        [
            {"[email protected]"},
            {"[email protected]"},
            {"[email protected]"},
        ],
        None,
        id="gitlab-same-login-two-ids-stays-apart",
    ),
]


@pytest.mark.parametrize(("pairs", "expected", "display"), MERGE_CASES)
def test_identity_merge_table(pairs, expected, display) -> None:
    groups, resolve = _groups(pairs)
    assert groups == {frozenset(g) for g in expected}
    if display is not None:
        (key,) = {resolve(n, e) for n, e in pairs}
        assert resolve.display_name(key) == display


def test_bots_never_merge_and_are_not_people() -> None:
    pairs = [
        ("dependabot[bot]", f"49699333+dependabot[bot]{_NR}"),
        ("dependabot[bot]", f"dependabot[bot]{_NR}"),
        ("github-actions", "[email protected]"),
        ("Dana White", "[email protected]"),
    ]
    resolve = build_identity_resolver(pairs)
    bot = resolve("dependabot[bot]", f"49699333+dependabot[bot]{_NR}")
    assert resolve.is_bot(bot)
    assert resolve.is_bot(resolve("github-actions", "[email protected]"))
    assert resolve.people() == {"[email protected]"}


KIND_CASES = [
    ("copilot-swe-agent[bot]", "[email protected]", "agent"),
    ("devin-ai-integration[bot]", "158243242+devin-ai-integration[bot]@users.noreply.github.com", "agent"),
    ("Cursor Agent", "[email protected]", "agent"),
    ("Claude", "[email protected]", "agent"),
    ("Claude", "", "agent"),
    ("dependabot[bot]", f"49699333+dependabot[bot]{_NR}", "bot"),
    ("github-actions", "[email protected]", "bot"),
    ("renovate", "", "bot"),
    ("Deploy Bot", "[email protected]", "bot"),
    ("deploy token", "[email protected]", "bot"),
    ("Project Collection Build Service (contoso)", "[email protected]", "bot"),
    ("bitbucket-pipelines", "[email protected]", "bot"),
    ("Dana White", "[email protected]", "human"),
    # Near misses stay people: no loose substring or first-name rules.
    ("Claudette Moreau", "[email protected]", "human"),
    ("Netlify Johnson", "[email protected]", "human"),
    ("Aiden Coplin", "[email protected]", "human"),
    ("renovate-fan", "[email protected]", "human"),
]


@pytest.mark.parametrize(("name", "email", "kind"), KIND_CASES)
def test_identity_kind_table(name, email, kind) -> None:
    assert identity_kind(name, email) == kind
    # is_bot keeps meaning "automation of any kind".
    assert is_bot(name, email) is (kind != "human")


def test_resolver_kinds_and_agent_label() -> None:
    pairs = [
        ("Cursor Agent", "[email protected]"),
        ("dependabot[bot]", f"49699333+dependabot[bot]{_NR}"),
        ("Dana White", "[email protected]"),
    ]
    resolve = build_identity_resolver(pairs)
    agent = resolve("Cursor Agent", "[email protected]")
    bot = resolve("dependabot[bot]", f"49699333+dependabot[bot]{_NR}")
    assert resolve.kind(agent) == "agent"
    assert resolve.agent_of(agent) == "cursor"
    assert resolve.kind(bot) == "bot"
    assert resolve.agent_of(bot) is None
    assert resolve.kind("[email protected]") == "human"
    assert resolve.agent_of("[email protected]") is None
    # An unknown key is a person, as before.
    assert resolve.kind("[email protected]") == "human"
    assert resolve.people() == {"[email protected]"}
    assert resolve.is_bot(agent) and resolve.is_bot(bot)


def test_kind_vote_ties() -> None:
    # One email seen as a person once and as automation once: a tie stays human.
    shared = "[email protected]"
    resolve = build_identity_resolver([("Ops Team", shared), ("ops-bot", shared)])
    assert resolve.kind(shared) == "human"
    assert not resolve.is_bot(shared)
    # Automation wins a majority, and an agent/bot tie goes to the agent.
    resolve = build_identity_resolver(
        [("Claude", shared), ("ops-bot", shared), ("Claude", shared), ("ops-bot", shared)]
    )
    assert resolve.kind(shared) == "agent"
    assert resolve.agent_of(shared) == "claude"
    resolve = build_identity_resolver([("ops-bot", shared)] * 2 + [("Claude", shared)])
    assert resolve.kind(shared) == "bot"
    assert resolve.agent_of(shared) is None


def test_significance_skips_bots_but_keeps_agent_commits() -> None:
    msg = "refactor: migrate the cache to a write-through store"
    assert is_significant_commit(msg, "dependabot[bot]") is False
    assert is_significant_commit(msg, "Deploy Bot") is False
    assert is_significant_commit(msg, "Ada Lovelace") is True
    assert is_significant_commit(msg, "Cursor Agent", "[email protected]") is True


def test_active_contributors_count_people_only() -> None:
    ts = 1_700_000_000
    authors = [
        {"name": "Dana White", "email": "[email protected]", "last_commit_ts": ts},
        {"name": "Cursor Agent", "email": "[email protected]", "last_commit_ts": ts},
        {"name": "github-actions[bot]", "email": "", "last_commit_ts": ts},
        {"name": "Lee Park", "email": "[email protected]", "last_commit_ts": ts - 86400},
    ]
    assert count_active_contributors([{"top_authors_json": json.dumps(authors)}]) == 2


def test_co_author_trailer_alone_never_merges() -> None:
    # Only a trailer names the real email with the handle, so E4 has no author
    # row to stand on and the two stay apart. The trailer's name still counts
    # for the display name of the identity it points at.
    pairs = [("Ana Lima", "[email protected]"), ("ana-l", f"7+ana-l{_NR}")]
    groups, resolve = _groups(pairs, evidence=[("ana-l", "[email protected]"), ("Ana M. Lima", "[email protected]")])
    assert groups == {frozenset({"[email protected]"}), frozenset({f"7+ana-l{_NR}"})}
    assert resolve.display_name("[email protected]") == "Ana Lima"


def test_display_name_prefers_a_full_name() -> None:
    resolve = build_identity_resolver([("mrossi", "[email protected]")] * 5 + [("Maya Rossi", "[email protected]")])
    assert resolve.display_name("[email protected]") == "Maya Rossi"


# ---------------------------------------------------------------------------
# Whole-repo: one git log pass, trailers, and the truck factor
# ---------------------------------------------------------------------------


def _git_commit(repo: Path, author: str, message: str) -> None:
    (repo / "f.txt").write_text(f"{author}\n{message}\n")
    subprocess.run(["git", "add", "f.txt"], cwd=repo, check=True)
    env = {**os.environ, "GIT_COMMITTER_NAME": "Committer", "GIT_COMMITTER_EMAIL": "[email protected]"}
    subprocess.run(
        ["git", "commit", "-q", f"--author={author}", "-m", message],
        cwd=repo,
        check=True,
        env=env,
    )


def test_contributor_count_from_one_log_pass(tmp_path: Path) -> None:
    subprocess.run(["git", "init", "-q"], cwd=tmp_path, check=True)
    authors = [
        f"Maya Rossi <12381+mrossi{_NR}>",
        "mrossi <[email protected]>",
        "Lena Park <[email protected]>",
        "Lena Park <[email protected]>",
        "Alex <[email protected]>",
        "Alex <[email protected]>",
        f"dependabot[bot] <49699333+dependabot[bot]{_NR}>",
        "Ana Lima <[email protected]>",
    ]
    for n, author in enumerate(authors):
        _git_commit(tmp_path, author, f"change {n}")
    # The trailer pairs the handle with Ana's real email; it must not merge.
    _git_commit(tmp_path, f"ana-l <7+ana-l{_NR}>", "pair work\n\nCo-authored-by: ana-l <[email protected]>")

    repo = git.Repo(tmp_path)
    shortlog = repo.git.shortlog("-sn", "HEAD").splitlines()
    # shortlog groups by name: it splits Maya and merges the two Alexes.
    assert len(shortlog) == 7
    # Maya, Lena, two Alexes, Ana, ana-l; the bot is not a person.
    assert count_people(repo, "HEAD") == 6
    assert capture_repo_totals(repo).total_contributor_count == 6


def test_truck_factor_counts_people_not_names() -> None:
    def meta(path: str, name: str, email: str) -> dict:
        return {
            "file_path": path,
            "primary_owner_name": name,
            "primary_owner_email": email,
            "bus_factor": 1,
        }

    rows = (
        [meta(f"a/{i}.py", "Maya Rossi", f"12381+mrossi{_NR}") for i in range(4)]
        + [meta(f"b/{i}.py", "Omar Haddad", "[email protected]") for i in range(3)]
        + [meta(f"c/{i}.py", "mrossi", "[email protected]") for i in range(3)]
        + [meta(f"d/{i}.py", "Lena Park", "[email protected]") for i in range(2)]
        + [meta(f"e/{i}.py", "Ivan Petrov", "[email protected]") for i in range(2)]
    )
    # Keyed by name it takes 3 owners (4 + 3 + 3) to pass half of 14 files;
    # as people Maya owns 7 and Omar 3, so 2 do.
    assert build_people(rows)["truck_factor"] == 2
    bots = [meta(f"z/{i}.py", "dependabot[bot]", f"1+dependabot[bot]{_NR}") for i in range(9)]
    people = build_people(rows + bots)
    # Automation owns nothing: the bot's 9 files neither count nor move the factor.
    assert people["owner_count"] == 4
    assert people["truck_factor"] == 2