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(git): make "last touched" the contributor's own last commit + honor .mailmap (#349)
Raghav Chamadiyaa57d7958aa55
diff --git a/.mailmap b/.mailmapnew file mode 100644index 000000000..fafb77eff--- /dev/null+++ b/.mailmap@@ -0,0 +1,13 @@+# Coalesce contributor identities that git records under more than one+# name/email (personal vs. GitHub noreply, differing name spellings).+# Format: Canonical Name <canonical-email> <other-email> (or with a name).+# repowise reads author identity through git's mailmap (%aN/%aE), so entries+# here merge split contributor buckets in ownership / "last touched".++Raghav Chamadiya <[email protected]> <[email protected]>+Raghav Chamadiya <[email protected]> RaghavChamadiya <[email protected]>++Swati Ahuja <[email protected]> <[email protected]>+Swati Ahuja <[email protected]> swati510 <[email protected]>++joptimus <[email protected]> <[email protected]>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 5a37f949a..9f50dd7f6 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@@ -259,6 +259,12 @@ def index_file(author_counts: Counter[str] = Counter()author_emails: dict[str, str] = {}recent_author_counts: Counter[str] = Counter()+ # Per-author commit timestamps so a contributor's "last touched" reflects+ # *their own* last commit to this file — not the file's last commit by+ # anyone (which would credit you whenever a co-owner touches a shared+ # file). Consumed downstream by the owner-profile aggregator.+ author_last_ts: dict[str, int] = {}+ author_first_ts: dict[str, int] = {}for c in commits:if c.ts >= ninety_days_ago_ts:@@ -273,6 +279,13 @@ def index_file(author_counts[c.author_name] += 1if c.author_name not in author_emails and c.author_email:author_emails[c.author_name] = c.author_email+ if c.ts > 0:+ prev_last = author_last_ts.get(c.author_name)+ if prev_last is None or c.ts > prev_last:+ author_last_ts[c.author_name] = c.ts+ prev_first = author_first_ts.get(c.author_name)+ if prev_first is None or c.ts < prev_first:+ author_first_ts[c.author_name] = c.tsc90 = meta["commit_count_90d"]total_churn = meta["lines_added_90d"] + meta["lines_deleted_90d"]@@ -306,13 +319,16 @@ def index_file(# full contributor surface for a file.top_authors = []for name, count in author_counts.most_common(_MAX_TOP_AUTHORS):- top_authors.append(- {- "name": name,- "email": author_emails.get(name, ""),- "commit_count": count,- }- )+ entry: dict[str, Any] = {+ "name": name,+ "email": author_emails.get(name, ""),+ "commit_count": count,+ }+ if name in author_last_ts:+ entry["last_commit_ts"] = author_last_ts[name]+ if name in author_first_ts:+ entry["first_commit_ts"] = author_first_ts[name]+ top_authors.append(entry)meta["top_authors_json"] = json.dumps(top_authors)if top_authors:diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/records.py b/packages/core/src/repowise/core/ingestion/git_indexer/records.pyindex 1b9e21eb3..420d3fda4 100644--- a/packages/core/src/repowise/core/ingestion/git_indexer/records.py+++ b/packages/core/src/repowise/core/ingestion/git_indexer/records.py@@ -34,7 +34,12 @@ _FIELD_SEP = "\x1f"# output, which is what :func:`_parse_commit_record` then splits on. The body# (``%b``) is captured last because it is the only multi-line field; everything# after the 6th field separator is "body + numstat" and is disentangled there.-_LOG_FORMAT = "%x00%H%x1f%an%x1f%ae%x1f%ct%x1f%P%x1f%s%x1f%b"+# Author name/email use the mailmap-canonical ``%aN``/``%aE`` (not raw+# ``%an``/``%ae``) so a repo's ``.mailmap`` folds a contributor's multiple+# names/emails — personal vs. GitHub ``noreply``, a second machine's git config —+# into one identity. Without this, ownership and "last touched" split one human+# across several contributor buckets.+_LOG_FORMAT = "%x00%H%x1f%aN%x1f%aE%x1f%ct%x1f%P%x1f%s%x1f%b"# A git ``--numstat`` line: ``<added>\t<deleted>\t<path>`` where added/deleted# are decimal counts or ``-`` for binary files. Used to split the trailingdiff --git a/packages/server/src/repowise/server/services/owner_profile.py b/packages/server/src/repowise/server/services/owner_profile.pyindex 7ea596f55..929118277 100644--- a/packages/server/src/repowise/server/services/owner_profile.py+++ b/packages/server/src/repowise/server/services/owner_profile.py@@ -20,7 +20,7 @@ from __future__ import annotationsimport jsonfrom collections import Counter, defaultdictfrom dataclasses import dataclass, field-from datetime import datetime+from datetime import UTC, datetimefrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession@@ -52,6 +52,19 @@ def _module_of(file_path: str) -> str:return parts[0] if len(parts) > 1 else "root"+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# ---------------------------------------------------------------------------@@ -168,12 +181,30 @@ async def aggregate_owners(acc.lines_deleted_90d_est += deleted * sharefor cat, n in categories.items():acc.commit_categories[cat] += int(n * share)- if m.last_commit_at:- if acc.last_commit_at is None or m.last_commit_at > acc.last_commit_at:- acc.last_commit_at = m.last_commit_at- if m.first_commit_at:- if acc.first_commit_at is None or m.first_commit_at < acc.first_commit_at:- acc.first_commit_at = m.first_commit_at+ # 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_firsttouchers.append(acc)# Primary owner — credit them for "files_owned" / hotspots / silo.diff --git a/tests/unit/server/test_owners.py b/tests/unit/server/test_owners.pyindex a39f40794..c54e61a5e 100644--- a/tests/unit/server/test_owners.py+++ b/tests/unit/server/test_owners.py@@ -3,6 +3,7 @@from __future__ import annotationsimport json+from datetime import UTC, datetimefrom urllib.parse import quoteimport pytest@@ -10,6 +11,7 @@ from httpx import AsyncClientfrom repowise.core.persistence import crudfrom repowise.core.persistence.database import get_session+from repowise.server.services.owner_profile import aggregate_ownersfrom tests.unit.server.conftest import create_test_repo@@ -103,6 +105,55 @@ async def test_get_owner_profile(client: AsyncClient, app) -> None:assert "Bob" in coauthors+async def test_last_commit_uses_authors_own_timestamp(client: AsyncClient, app) -> None:+ """A contributor's last_commit_at is their *own* last commit to a file,+ not the file's last commit by a co-owner."""+ repo = await create_test_repo(client)+ alice_last = datetime(2026, 1, 10, tzinfo=UTC)+ file_last = datetime(2026, 1, 30, tzinfo=UTC) # Bob's later commit++ async with get_session(app.state.session_factory) as session:+ await crud.upsert_git_metadata(+ session,+ repository_id=repo["id"],+ file_path="src/shared.py",+ commit_count_total=20,+ first_commit_at=datetime(2025, 1, 1, tzinfo=UTC),+ last_commit_at=file_last,+ primary_owner_name="Bob",+ primary_owner_email="[email protected]",+ top_authors_json=json.dumps(+ [+ {+ "name": "Bob",+ "email": "[email protected]",+ "commit_count": 15,+ "last_commit_ts": int(file_last.timestamp()),+ "first_commit_ts": int(datetime(2025, 6, 1, tzinfo=UTC).timestamp()),+ },+ {+ "name": "Alice",+ "email": "[email protected]",+ "commit_count": 5,+ "last_commit_ts": int(alice_last.timestamp()),+ "first_commit_ts": int(datetime(2025, 1, 1, tzinfo=UTC).timestamp()),+ },+ ]+ ),+ contributor_count=2,+ )++ async with get_session(app.state.session_factory) as session:+ accs, _ = await aggregate_owners(session, repo["id"])++ alice = accs["[email protected]"]+ bob = accs["[email protected]"]+ # Alice must NOT inherit Bob's later commit to the shared file.+ assert alice.last_commit_at == alice_last+ assert bob.last_commit_at == file_last++@pytest.mark.asyncioasync def test_get_owner_profile_not_found(client: AsyncClient) -> None:repo = await create_test_repo(client)diff --git a/tests/unit/test_git_indexer.py b/tests/unit/test_git_indexer.pyindex 9974a4e8f..cbcf920c3 100644--- a/tests/unit/test_git_indexer.py+++ b/tests/unit/test_git_indexer.py@@ -279,6 +279,40 @@ class TestStableClassification:assert meta["commit_count_90d"] == 0assert meta["is_stable"] is True+ def test_top_authors_carry_per_author_timestamps(self) -> None:+ """Each top-author entry records that author's own first/last commit ts+ so the owner aggregator doesn't credit one author for another's commit."""+ import json++ indexer = GitIndexer("/tmp/repo")+ mock_repo = MagicMock()++ base = datetime.now(UTC) - timedelta(days=200)+ # Alice: days 0 and 5 (older). Bob: day 40 (most recent on this file).+ specs = [+ ("Alice", "[email protected]", base),+ ("Alice", "[email protected]", base + timedelta(days=5)),+ ("Bob", "[email protected]", base + timedelta(days=40)),+ ]+ log_lines = []+ for i, (name, email, when) in enumerate(specs):+ ts = int(when.timestamp())+ log_lines.append(+ f"\x00sha{i:04d}\x1f{name}\x1f{email}\x1f{ts}\x1f\x1ffeat: c{i}\x1f"+ )+ mock_repo.git.log.return_value = "\n".join(log_lines)++ meta = indexer._index_file("shared.py", mock_repo)+ authors = {a["name"]: a for a in json.loads(meta["top_authors_json"])}++ alice_last = int((base + timedelta(days=5)).timestamp())+ bob_last = int((base + timedelta(days=40)).timestamp())+ assert authors["Alice"]["last_commit_ts"] == alice_last+ assert authors["Alice"]["first_commit_ts"] == int(base.timestamp())+ # Alice's last must NOT be bumped to Bob's later commit on the same file.+ assert authors["Alice"]["last_commit_ts"] < authors["Bob"]["last_commit_ts"]+ assert authors["Bob"]["last_commit_ts"] == bob_last+class TestGitWindowAnchor:"""REPOWISE_GIT_WINDOW_ANCHOR anchors recency windows to the repo's most