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.

fix(git): count non-merge commits everywhere and keep merges apart (#2683)

Swati Ahuja4f4433cc7c7d
diff --git a/packages/api-client/src/types/ownership.ts b/packages/api-client/src/types/ownership.ts
index b732cf697..dc331fffb 100644
--- a/packages/api-client/src/types/ownership.ts
+++ b/packages/api-client/src/types/ownership.ts
@@ -11,7 +11,7 @@ export interface OwnerListEntry {
silo_modules: number;
dead_code_files_owned: number;
dead_code_lines_owned: number;
- commit_count_90d: number;
+ commit_count_90d: number | null;
last_commit_at: string | null;
bus_factor_risk_files: number;
}
@@ -49,7 +49,7 @@ export interface OwnerProfileResponse {
silo_modules: number;
dead_code_files_owned: number;
dead_code_lines_owned: number;
- commit_count_90d: number;
+ commit_count_90d: number | null;
last_commit_at: string | null;
first_commit_at: string | null;
bus_factor_risk_files: number;
diff --git a/packages/core/alembic/versions/0087_repo_merge_commit_count.py b/packages/core/alembic/versions/0087_repo_merge_commit_count.py
new file mode 100644
index 000000000..53b57b41e
--- /dev/null
+++ b/packages/core/alembic/versions/0087_repo_merge_commit_count.py
@@ -0,0 +1,41 @@
+"""repositories: merge commits counted apart from ``total_commit_count``.
+
+``total_commit_count`` was ``git rev-list --count HEAD``, merges included,
+while every per-commit walk runs ``--no-merges``. On a repo that merges, the
+stats page then read a 5,000-commit sample against a larger merge-inclusive
+total and called a complete sample truncated. ``total_commit_count`` now means
+non-merge commits reachable from HEAD, like every other commit count, and the
+merges live in this column.
+
+NULL until the next index writes it. ``init_db``'s additive schema reconciler
+picks the column up from the model for local SQLite stores that never run
+Alembic; this migration covers the managed Postgres ones.
+
+Revision ID: 0087
+Revises: 0086
+Create Date: 2026-09-29
+"""
+
+from __future__ import annotations
+
+from collections.abc import Sequence
+
+import sqlalchemy as sa
+from alembic import op
+
+# revision identifiers
+revision: str = "0087"
+down_revision: str | None = "0086"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+
+def upgrade() -> None:
+ op.add_column(
+ "repositories",
+ sa.Column("total_merge_commit_count", sa.Integer(), nullable=True),
+ )
+
+
+def downgrade() -> None:
+ op.drop_column("repositories", "total_merge_commit_count")
diff --git a/packages/core/alembic/versions/0088_git_owner_line_pct.py b/packages/core/alembic/versions/0088_git_owner_line_pct.py
new file mode 100644
index 000000000..937d343df
--- /dev/null
+++ b/packages/core/alembic/versions/0088_git_owner_line_pct.py
@@ -0,0 +1,44 @@
+"""git_metadata: the primary owner's line share, apart from their commit share.
+
+With blame, the indexer made the top blame author the primary owner and then
+overwrote ``primary_owner_commit_pct`` with that author's share of current
+lines, so pages read "X, at 51% of commits" where 51% was a line share.
+``primary_owner_commit_pct`` goes back to the owner's own share of commits and
+the blame share moves to ``primary_owner_line_pct``.
+
+NULL without blame. Existing rows blame wrote are moved here by
+``split_blame_line_shares``, since a file with no new commits is never
+re-walked. The additive schema reconciler adds the column and runs the same
+step for local SQLite stores; this migration covers managed Postgres.
+
+Revision ID: 0088
+Revises: 0087
+Create Date: 2026-09-29
+"""
+
+from __future__ import annotations
+
+from collections.abc import Sequence
+
+import sqlalchemy as sa
+from alembic import op
+
+from repowise.core.persistence.crud.git import split_blame_line_shares
+
+# revision identifiers
+revision: str = "0088"
+down_revision: str | None = "0087"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+
+def upgrade() -> None:
+ op.add_column(
+ "git_metadata",
+ sa.Column("primary_owner_line_pct", sa.Float(), nullable=True),
+ )
+ split_blame_line_shares(op.get_bind())
+
+
+def downgrade() -> None:
+ op.drop_column("git_metadata", "primary_owner_line_pct")
diff --git a/packages/core/src/repowise/core/analysis/owners.py b/packages/core/src/repowise/core/analysis/owners.py
index c2bcdba59..2d7e38730 100644
--- a/packages/core/src/repowise/core/analysis/owners.py
+++ b/packages/core/src/repowise/core/analysis/owners.py
@@ -8,6 +8,11 @@ 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.
+
+Activity is not read from those per-file counts: a commit touching ten files
+appears in ten rows, and ``commit_count`` there is all-time. ``commit_count_90d``
+and ``last_commit_at`` come from the per-commit rows instead, counting distinct
+SHAs in the 90 days before the newest commit (HEAD time, not the wall clock).
"""
from __future__ import annotations
@@ -15,7 +20,7 @@ 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 datetime import UTC, datetime, timedelta
from typing import Any
from repowise.core.analysis.health.aggregation import module_label
@@ -68,7 +73,9 @@ class OwnerAccumulator:
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
+ # Distinct commits in the 90 days before HEAD; None when the commit rows
+ # are missing or do not reach back across the whole window.
+ commit_count_90d: int | None = None
lines_added_90d_est: float = 0.0
lines_deleted_90d_est: float = 0.0
@@ -100,15 +107,26 @@ class OwnerAccumulator:
coauthor_meta: dict[str, tuple[str, str | None]] = field(default_factory=dict)
+ACTIVITY_WINDOW_DAYS = 90
+
+
def aggregate_owners(
- git_rows: Iterable[Any], dead_rows: Iterable[Any]
+ git_rows: Iterable[Any],
+ dead_rows: Iterable[Any],
+ commit_rows: Iterable[Any] | None = None,
+ total_commits: int | None = None,
) -> 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``).
+ ``commit_rows`` are its per-commit rows (``sha``, ``author_name``,
+ ``author_email``, ``committed_at``), newest non-merge commits from HEAD;
+ ``total_commits`` the repo's non-merge total, which says whether a sample
+ that stops inside the window is nonetheless the whole history.
"""
rows = list(git_rows)
+ commits = list(commit_rows or [])
accs: dict[str, OwnerAccumulator] = {}
module_totals: dict[str, int] = defaultdict(int)
@@ -119,6 +137,8 @@ def aggregate_owners(
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")))
+ for c in commits:
+ pairs.append((row_field(c, "author_name"), row_field(c, "author_email")))
resolve = build_identity_resolver(pairs)
def _ensure(name: str, email: str | None) -> OwnerAccumulator:
@@ -147,7 +167,6 @@ def aggregate_owners(
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] = []
@@ -161,7 +180,6 @@ def aggregate_owners(
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():
@@ -222,6 +240,8 @@ def aggregate_owners(
b.coauthor_shared[a.key] += 1
b.coauthor_meta[a.key] = (a.name, a.email)
+ _apply_commit_activity(accs, resolve, commits, total_commits)
+
# Pass 2: dead-code burden by primary_owner.
for d in dead_rows:
dead_owner = row_field(d, "primary_owner")
@@ -243,6 +263,52 @@ def aggregate_owners(
return accs, dict(module_totals)
+def _apply_commit_activity(
+ accs: dict[str, OwnerAccumulator],
+ resolve: Any,
+ commits: list[Any],
+ total_commits: int | None,
+) -> None:
+ """Set each owner's 90-day commit count and last commit from the commit rows.
+
+ Counts distinct SHAs per identity with ``committed_at`` at or after HEAD
+ time minus 90 days, so a commit touching many files counts once and the
+ sum over owners never exceeds the repo's non-merge commits in the window.
+ Each owner's ``last_commit_at`` is the newest of their own commits; an
+ owner with no row keeps the per-file value. The count stays ``None`` when
+ there are no rows, or when the rows stop short of the window start and
+ are not the whole history (a capped sample would undercount).
+ """
+ stamped: list[tuple[str, str, datetime]] = []
+ for c in commits:
+ sha = row_field(c, "sha")
+ at = as_utc(row_field(c, "committed_at"))
+ key = resolve(row_field(c, "author_name") or "", row_field(c, "author_email") or None)
+ if sha and at is not None and key:
+ stamped.append((key, sha, at))
+ if not stamped:
+ return
+
+ head = max(at for _, _, at in stamped)
+ since = head - timedelta(days=ACTIVITY_WINDOW_DAYS)
+ whole_history = total_commits is not None and len({s for _, s, _ in stamped}) >= total_commits
+ covers_window = whole_history or min(at for _, _, at in stamped) <= since
+
+ recent: dict[str, set[str]] = defaultdict(set)
+ last: dict[str, datetime] = {}
+ for key, sha, at in stamped:
+ if at >= since:
+ recent[key].add(sha)
+ if key not in last or at > last[key]:
+ last[key] = at
+
+ for key, acc in accs.items():
+ if covers_window:
+ acc.commit_count_90d = len(recent.get(key, ()))
+ if key in last:
+ acc.last_commit_at = last[key]
+
+
def silo_modules(acc: OwnerAccumulator, module_totals: dict[str, int]) -> int:
"""Count modules where this owner is >80% of file ownership."""
diff --git a/packages/core/src/repowise/core/generation/page_generator/structural.py b/packages/core/src/repowise/core/generation/page_generator/structural.py
index 16ec5dfdf..24570fa1f 100644
--- a/packages/core/src/repowise/core/generation/page_generator/structural.py
+++ b/packages/core/src/repowise/core/generation/page_generator/structural.py
@@ -45,7 +45,7 @@ log = structlog.get_logger(__name__)
# output without changing any template's bytes: new context fields, a changed
# helper, a reordered section. Template edits are picked up automatically
# (their source is hashed), so this is only for the cases hashing cannot see.
-STRUCTURAL_GENERATION_VERSION = "2"
+STRUCTURAL_GENERATION_VERSION = "3"
# Keyless stub templates live one directory down so their filenames can match
# the prompt templates they stand in for.
diff --git a/packages/core/src/repowise/core/generation/structural_labels.py b/packages/core/src/repowise/core/generation/structural_labels.py
index fe73cc9aa..5c2005689 100644
--- a/packages/core/src/repowise/core/generation/structural_labels.py
+++ b/packages/core/src/repowise/core/generation/structural_labels.py
@@ -81,7 +81,12 @@ ENGLISH_LABELS: dict[str, str] = {
"history": "History",
"history_commits": "{total} {commit_word} in its history, {recent} in the last 90 days.",
"history_last_commit": "The last landed on {date}.",
+ # ``history_owner`` when only commit shares are known (no blame);
+ # ``history_owner_lines`` when blame chose the owner, naming both shares
+ # because the top blame author need not be the top committer.
"history_owner": "**{owner}** is its primary maintainer, at {pct}% of commits.",
+ "history_owner_lines": "**{owner}** wrote {line}% of its current lines ({commit}% of commits).",
+ "history_owner_lines_only": "**{owner}** wrote {line}% of its current lines.",
"history_fixes": "{count} of those commits fixed a bug.",
"history_hotspot": "It is one of the repository's change hotspots.",
"history_stable": "It has been stable: nothing has changed it lately.",
@@ -225,6 +230,10 @@ LOCALIZED_LABELS: dict[str, dict[str, str]] = {
),
"history_last_commit": "Der letzte stammt vom {date}.",
"history_owner": "**{owner}** betreut sie hauptsächlich, mit {pct}% der Commits.",
+ "history_owner_lines": (
+ "**{owner}** hat {line}% ihrer aktuellen Zeilen geschrieben ({commit}% der Commits)."
+ ),
+ "history_owner_lines_only": "**{owner}** hat {line}% ihrer aktuellen Zeilen geschrieben.",
"history_fixes": "{count} dieser Commits haben einen Fehler behoben.",
"history_hotspot": "Sie gehört zu den Änderungs-Hotspots des Repositorys.",
"history_stable": "Sie ist stabil: zuletzt hat sich nichts an ihr geändert.",
diff --git a/packages/core/src/repowise/core/generation/templates/file_page.j2 b/packages/core/src/repowise/core/generation/templates/file_page.j2
index b1b3e3d5a..0b4afb924 100644
--- a/packages/core/src/repowise/core/generation/templates/file_page.j2
+++ b/packages/core/src/repowise/core/generation/templates/file_page.j2
@@ -56,8 +56,16 @@
{#- The column is written on either scale depending on the producer, the
same normalisation ``health/biomarkers/developer_congestion.py`` applies.
Unnormalised, a 0-100 source renders "at 8500% of commits". -#}
-{%- if git.get("primary_owner_name") and git.get("primary_owner_commit_pct") -%}
+{#- With blame the owner is the top author of current lines, so the line share
+ leads and the commit share is named as such; without blame both the owner
+ and the share come from commits. -#}
{%- set owner_pct = git.get("primary_owner_commit_pct") -%}
+{%- set line_pct = git.get("primary_owner_line_pct") -%}
+{%- if git.get("primary_owner_name") and line_pct and owner_pct -%}
+{%- set _ = history.append(labels.history_owner_lines.format(owner=git.get("primary_owner_name"), line=(line_pct if line_pct > 1.0 else line_pct * 100) | round | int, commit=(owner_pct if owner_pct > 1.0 else owner_pct * 100) | round | int)) -%}
+{%- elif git.get("primary_owner_name") and line_pct -%}
+{%- set _ = history.append(labels.history_owner_lines_only.format(owner=git.get("primary_owner_name"), line=(line_pct if line_pct > 1.0 else line_pct * 100) | round | int)) -%}
+{%- elif git.get("primary_owner_name") and owner_pct -%}
{%- set _ = history.append(labels.history_owner.format(owner=git.get("primary_owner_name"), pct=(owner_pct if owner_pct > 1.0 else owner_pct * 100) | round | int)) -%}
{%- endif -%}
{#- Suppressed when it exceeds the commit total: the two are counted over
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.py
index 4bc07d17e..17fc00233 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
@@ -97,7 +97,11 @@ def new_meta(file_path: str) -> dict[str, Any]:
"last_commit_at": None,
"primary_owner_name": None,
"primary_owner_email": None,
+ # The primary owner's share of the file's commits, and (FULL tier) of
+ # its current lines by blame. The owner is the blame owner when blame
+ # ran, so the two can rank different people first.
"primary_owner_commit_pct": None,
+ "primary_owner_line_pct": None,
"top_authors_json": "[]",
"significant_commits_json": "[]",
"co_change_partners_json": "[]",
@@ -203,12 +207,21 @@ def _parse_per_file_log(
def _per_file_log_args(file_path: str, commit_limit: int, follow_renames: bool) -> list[str]:
- walk = [f"-{commit_limit}", "--numstat", f"--format={_LOG_FORMAT}", "--", file_path]
+ # No merges in any lane: "commits" means non-merge commits everywhere, so a
+ # file's count means the same thing whichever lane produced it.
+ walk = [
+ "--no-merges",
+ f"-{commit_limit}",
+ "--numstat",
+ f"--format={_LOG_FORMAT}",
+ "--",
+ file_path,
+ ]
if follow_renames:
return ["--follow", *walk]
- # The repo-wide lanes' contract: no merges, and the full diff for churn and
+ # The repo-wide lanes' contract also carries the full diff for churn and
# changed paths, so a file moving between lanes keeps the same history.
- return ["--no-merges", "--full-diff", *walk]
+ return ["--full-diff", *walk]
def _known_paths(
@@ -345,7 +358,7 @@ def index_file(
meta["temporal_hotspot_score"] = _temporal_hotspot_score(commits, now)
_add_ownership(meta, authors)
if include_blame:
- _add_blame_ownership(meta, repo, repo_path, now)
+ _add_blame_ownership(meta, repo, repo_path, now, authors)
_add_commit_messages(meta, commits)
# Only the per-file ``--follow`` walk reports an original path.
if orig_path:
@@ -509,9 +522,16 @@ def _bus_factor(author_counts: Counter[str], total_commits: int) -> int:
return bus
-def _add_blame_ownership(meta: dict[str, Any], repo: Any, repo_path: Path, now: datetime) -> None:
+def _add_blame_ownership(
+ meta: dict[str, Any], repo: Any, repo_path: Path, now: datetime, authors: _Authors
+) -> None:
"""Blame ownership plus the per-line ``BlameIndex`` (FULL tier), best effort.
+ The blame owner becomes the primary owner; ``primary_owner_line_pct`` is
+ their share of current lines and ``primary_owner_commit_pct`` their own
+ share of the file's commits (``None`` when they made none of the indexed
+ commits, e.g. every commit of theirs is older than the walked depth).
+
One ``git blame --line-porcelain`` pass serves both the primary-owner
signal and the index ``function_hotspot`` / ``code_age_volatility`` read.
Files over the size cap are skipped: blame is O(lines) and can block the
@@ -531,7 +551,12 @@ def _add_blame_ownership(meta: dict[str, Any], repo: Any, repo_path: Path, now:
if blame_name:
meta["primary_owner_name"] = blame_name
meta["primary_owner_email"] = blame_email
- meta["primary_owner_commit_pct"] = blame_pct
+ meta["primary_owner_line_pct"] = blame_pct
+ total_commits = sum(authors.counts.values())
+ own_commits = authors.counts.get(blame_name, 0)
+ meta["primary_owner_commit_pct"] = (
+ own_commits / total_commits if own_commits and total_commits else None
+ )
except Exception:
pass # blame is best-effort
diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/records.py b/packages/core/src/repowise/core/ingestion/git_indexer/records.py
index 01dffb0de..ff5c1f4a3 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/records.py
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/records.py
@@ -322,7 +322,12 @@ class RepoTotals:
persists what succeeded. See :func:`capture_repo_totals`.
"""
+ # Non-merge commits reachable from HEAD: the one definition of "commits"
+ # every surface uses, matching the ``--no-merges`` walks that fill the
+ # per-commit table. Merges are counted apart so nothing reads a larger
+ # merge-inclusive total against a non-merge sample and calls it truncated.
total_commit_count: int | None = None
+ total_merge_commit_count: int | None = None
first_commit_at: datetime | None = None
total_contributor_count: int | None = None
first_commit_author: str | None = None
@@ -407,6 +412,9 @@ def _folded_churn(
therefore holds only when nothing was dropped and nothing appeared
underneath: a rebase, a force-push, a branch swap and an ``--unshallow``
all break it. That is why the check is on counts and not just on ancestry.
+ Every count here is non-merge, like the stored total; the argument holds
+ for that subset unchanged, and a total stored before merges were excluded
+ simply fails the equality once and forces a full walk.
*The anchor is still an ancestor.* ``merge-base --is-ancestor`` runs first
because it is cheaper than the count, it rejects an anchor whose object git
@@ -442,7 +450,9 @@ def _folded_churn(
# Raises (non-zero exit) when the anchor is not an ancestor, which is
# the answer we want rather than an error.
repo.git.merge_base("--is-ancestor", anchor, head_sha)
- since_count = int(repo.git.rev_list("--count", f"{anchor}..{head_sha}").strip())
+ since_count = int(
+ repo.git.rev_list("--count", "--no-merges", f"{anchor}..{head_sha}").strip()
+ )
except Exception:
return None
@@ -512,7 +522,8 @@ def capture_repo_totals(repo: Any, prior: RepoTotals | None = None) -> RepoTotal
the indexer's ``commit_limit``, so they stay cheap no matter how deep the
history is:
- - ``git rev-list --count`` — the true total commit count.
+ - ``git rev-list --count --no-merges`` — the true total commit count, and
+ ``--merges`` for the merge count kept beside it.
- the root commit(s) — earliest committed date (project age), the founding
author's name, and that commit's subject. Multiple roots (merged
histories) use the earliest root.
@@ -536,7 +547,9 @@ def capture_repo_totals(repo: Any, prior: RepoTotals | None = None) -> RepoTotal
rev = head_sha or "HEAD"
with contextlib.suppress(Exception):
- totals.total_commit_count = int(repo.git.rev_list("--count", rev).strip())
+ totals.total_commit_count = int(repo.git.rev_list("--count", "--no-merges", rev).strip())
+ with contextlib.suppress(Exception):
+ totals.total_merge_commit_count = int(repo.git.rev_list("--count", "--merges", rev).strip())
try:
roots = repo.git.rev_list("--max-parents=0", rev).split()
diff --git a/packages/core/src/repowise/core/persistence/crud/git.py b/packages/core/src/repowise/core/persistence/crud/git.py
index 8e4c961b5..c87c2dece 100644
--- a/packages/core/src/repowise/core/persistence/crud/git.py
+++ b/packages/core/src/repowise/core/persistence/crud/git.py
@@ -6,10 +6,12 @@ every public name, so existing imports are unaffected.
from __future__ import annotations
+import json
from collections.abc import Sequence
from datetime import UTC, datetime
from sqlalchemy import delete, func, or_, select, text
+from sqlalchemy.engine import Connection
from sqlalchemy.ext.asyncio import AsyncSession
from ..models import (
@@ -252,6 +254,50 @@ async def upsert_git_metadata_bulk(
)
+def split_blame_line_shares(connection: Connection) -> int:
+ """Move blame line shares stored as commit shares into ``primary_owner_line_pct``.
+
+ Before that column existed, blame overwrote ``primary_owner_commit_pct``
+ with the blame owner's share of current lines, and a file without new
+ commits is never re-walked to fix it. Such a row is recognisable from its
+ own stored data: the value is not the owner's share of the file's commits
+ per ``top_authors_json`` / ``commit_count_total``. Those rows get the value
+ as their line share and the owner's commit share (None when they have no
+ counted commits); every other row, including all commit-only rows, is left
+ alone. Sync so both Alembic and the SQLite schema reconciler can run it,
+ once, when the column is added. Returns the number of rows moved.
+ """
+ rows = connection.execute(
+ text(
+ "SELECT id, primary_owner_name, primary_owner_commit_pct, commit_count_total, "
+ "top_authors_json FROM git_metadata "
+ "WHERE primary_owner_commit_pct IS NOT NULL AND primary_owner_line_pct IS NULL"
+ )
+ ).all()
+ moves: list[dict] = []
+ for row_id, owner, stored_pct, total, authors_json in rows:
+ try:
+ authors = json.loads(authors_json or "[]")
+ except ValueError:
+ continue
+ if not authors or not total:
+ continue # nothing to check the value against
+ own = next((a.get("commit_count", 0) for a in authors if a.get("name") == owner), 0)
+ commit_pct = own / total if own else None
+ if commit_pct is not None and abs(commit_pct - stored_pct) < 1e-9:
+ continue
+ moves.append({"id": row_id, "line_pct": stored_pct, "commit_pct": commit_pct})
+ if moves:
+ connection.execute(
+ text(
+ "UPDATE git_metadata SET primary_owner_line_pct = :line_pct, "
+ "primary_owner_commit_pct = :commit_pct WHERE id = :id"
+ ),
+ moves,
+ )
+ return len(moves)
+
+
async def recompute_git_percentiles(
session: AsyncSession,
repository_id: str,
diff --git a/packages/core/src/repowise/core/persistence/crud/repository.py b/packages/core/src/repowise/core/persistence/crud/repository.py
index b9192716e..303bcd65d 100644
--- a/packages/core/src/repowise/core/persistence/crud/repository.py
+++ b/packages/core/src/repowise/core/persistence/crud/repository.py
@@ -147,6 +147,7 @@ async def update_repo_git_totals(
repo_id: str,
*,
total_commit_count: int | None = None,
+ total_merge_commit_count: int | None = None,
first_commit_at: datetime | None = None,
total_contributor_count: int | None = None,
first_commit_author: str | None = None,
@@ -165,6 +166,7 @@ async def update_repo_git_totals(
"""
updates = {
"total_commit_count": total_commit_count,
+ "total_merge_commit_count": total_merge_commit_count,
"first_commit_at": first_commit_at,
"total_contributor_count": total_contributor_count,
"first_commit_author": first_commit_author,
diff --git a/packages/core/src/repowise/core/persistence/database.py b/packages/core/src/repowise/core/persistence/database.py
index 315d12385..f28f84fd0 100644
--- a/packages/core/src/repowise/core/persistence/database.py
+++ b/packages/core/src/repowise/core/persistence/database.py
@@ -380,6 +380,20 @@ def _add_column_ddl(column: object, dialect: object) -> str:
return " ".join(parts)
+def _split_blame_line_shares(connection: object) -> int:
+ from repowise.core.persistence.crud.git import split_blame_line_shares
+
+ return split_blame_line_shares(connection) # type: ignore[arg-type]
+
+
+#: One-time data fixes that must run when the reconciler adds a column, for
+#: rows the new column changes the meaning of. Alembic runs the same step in
+#: the column's migration for managed Postgres. Keyed ``table.column``.
+_DATA_STEPS_ON_ADD: dict[str, Callable[[object], object]] = {
+ "git_metadata.primary_owner_line_pct": _split_blame_line_shares,
+}
+
+
def _reconcile_schema(connection: object) -> None:
"""Bring an existing database up to ``Base.metadata`` (additive only).
@@ -440,9 +454,11 @@ def _reconcile_schema(connection: object) -> None:
# ``build`` renders the statement as well as running it, because
# compiling a column's type can fail on its own and that failure has
# to strand no more than compiling it successfully and failing to
- # execute it would.
+ # execute it would. A data step runs itself and returns None.
try:
- connection.execute(build()) # type: ignore[attr-defined]
+ statement = build()
+ if statement is not None:
+ connection.execute(statement) # type: ignore[attr-defined]
except Exception as exc: # re-raised below, once the walk is done
if not continue_past_failure:
raise
@@ -470,12 +486,16 @@ def _reconcile_schema(connection: object) -> None:
for column in table.columns:
if column.name in db_cols:
continue
+ what = f"{table.name}.{column.name}"
_run(
- f"{table.name}.{column.name}",
+ what,
lambda table=table, column=column: text(
f'ALTER TABLE "{table.name}" ADD COLUMN {_add_column_ddl(column, dialect)}'
),
)
+ data_step = _DATA_STEPS_ON_ADD.get(what)
+ if data_step is not None and not any(name == what for name, _ in failures):
+ _run(f"{what}:data", lambda data_step=data_step: data_step(connection) and None)
# --- Indexes ---------------------------------------------------
# Only model-declared indexes (i.e. ``Index(...)`` on the table
diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.py
index baaa2dec8..4613a9095 100644
--- a/packages/core/src/repowise/core/persistence/models.py
+++ b/packages/core/src/repowise/core/persistence/models.py
@@ -100,6 +100,9 @@ class Repository(Base):
# from that sample — otherwise a multi-year repo reads as a few months old
# (issue #730). NULL until the first index writes them / for non-git repos.
total_commit_count: Mapped[int | None] = mapped_column(Integer, nullable=True)
+ # ``total_commit_count`` is non-merge commits reachable from HEAD, the one
+ # meaning "commits" has everywhere; merges are counted here instead.
+ total_merge_commit_count: Mapped[int | None] = mapped_column(Integer, nullable=True)
first_commit_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
# All-time unique authors (mailmap-folded) and the founding author's name.
# Contributor count shares the #730 bug when read off the bounded sample;
@@ -577,7 +580,11 @@ class GitMetadata(Base):
# Ownership
primary_owner_name: Mapped[str | None] = mapped_column(String(255), nullable=True)
primary_owner_email: Mapped[str | None] = mapped_column(String(255), nullable=True)
+ # The primary owner is the blame owner when blame ran. commit_pct is their
+ # share of the file's commits, line_pct their share of current lines (NULL
+ # without blame); the two can rank different people first.
primary_owner_commit_pct: Mapped[float | None] = mapped_column(Float, nullable=True)
+ primary_owner_line_pct: Mapped[float | None] = mapped_column(Float, nullable=True)
# JSON fields (stored as Text, parsed/serialized in CRUD layer)
top_authors_json: Mapped[str] = mapped_column(Text, nullable=False, default="[]")
diff --git a/packages/core/src/repowise/core/pipeline/incremental.py b/packages/core/src/repowise/core/pipeline/incremental.py
index 8f72791bf..dff882847 100644
--- a/packages/core/src/repowise/core/pipeline/incremental.py
+++ b/packages/core/src/repowise/core/pipeline/incremental.py
@@ -1454,6 +1454,7 @@ async def persist_incremental_commits(
session,
repo_id,
total_commit_count=totals.total_commit_count,
+ total_merge_commit_count=totals.total_merge_commit_count,
first_commit_at=totals.first_commit_at,
total_contributor_count=totals.total_contributor_count,
first_commit_author=totals.first_commit_author,
diff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.py
index 900c73125..683e356d2 100644
--- a/packages/core/src/repowise/core/pipeline/persist.py
+++ b/packages/core/src/repowise/core/pipeline/persist.py
@@ -1676,6 +1676,7 @@ async def persist_git(result: Any, session: Any, repo_id: str) -> None:
session,
repo_id,
total_commit_count=totals.total_commit_count,
+ total_merge_commit_count=getattr(totals, "total_merge_commit_count", None),
first_commit_at=totals.first_commit_at,
total_contributor_count=totals.total_contributor_count,
first_commit_author=totals.first_commit_author,
diff --git a/packages/core/src/repowise/core/stats_highlights.py b/packages/core/src/repowise/core/stats_highlights.py
index a186fdecf..40ecae644 100644
--- a/packages/core/src/repowise/core/stats_highlights.py
+++ b/packages/core/src/repowise/core/stats_highlights.py
@@ -377,13 +377,17 @@ def _sample_complete(
) -> bool:
"""Whether the commit sample reaches the root commit.
- Decided by date where the root is known: the sample walk skips merge
- commits and the whole-history count does not, so the counts never match on
- a repo that merges.
+ The sample and the whole-history total both count non-merge commits, so a
+ sample as large as the total is complete; the sample reaching the root's
+ date proves the same thing. Truncated only when neither holds. A total
+ stored before merges were excluded is too large, and the date keeps it from
+ calling a complete sample truncated until the next index corrects it.
"""
+ if true_total is not None and total >= int(true_total):
+ return True
if true_first is not None:
return first_at is not None and first_at <= true_first + timedelta(seconds=60)
- return true_total is None or total >= int(true_total)
+ return true_total is None
def _most_common(counter: Counter[Any]) -> tuple[Any, int] | None:
@@ -466,6 +470,7 @@ def _origin(
first = parse_dt(totals.get("first_commit_at")) or first_at
true_total = totals.get("total_commit_count")
true_people = totals.get("total_contributor_count")
+ merges = totals.get("total_merge_commit_count")
return {
"first_commit_at": _iso(first),
"first_commit_author": totals.get("first_commit_author"),
@@ -473,6 +478,8 @@ def _origin(
"last_commit_at": _iso(last_at),
"age_days": (last_at - first).days if (first and last_at) else None,
"total_commits": int(true_total) if true_total is not None else sampled,
+ # Merges are counted apart: "commits" is non-merge everywhere.
+ "total_merge_commits": int(merges) if merges is not None else None,
"contributor_count": int(true_people) if true_people is not None else people,
}
diff --git a/packages/server/src/repowise/server/mcp_server/_helpers.py b/packages/server/src/repowise/server/mcp_server/_helpers.py
index ab3627690..8f158c2bb 100644
--- a/packages/server/src/repowise/server/mcp_server/_helpers.py
+++ b/packages/server/src/repowise/server/mcp_server/_helpers.py
@@ -429,6 +429,7 @@ def _build_origin_story(
"available": True,
"primary_author": primary,
"author_commit_pct": git_meta.primary_owner_commit_pct,
+ "author_line_pct": getattr(git_meta, "primary_owner_line_pct", None),
"contributors": authors,
"total_commits": total,
"first_commit": first_date,
diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/targets.py b/packages/server/src/repowise/server/mcp_server/tool_context/targets.py
index 011f512aa..3f4da4465 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_context/targets.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_context/targets.py
@@ -905,7 +905,10 @@ async def _resolve_one_target(
meta = res.scalar_one_or_none()
if meta:
ownership["primary_owner"] = meta.primary_owner_name
+ # owner_pct is the owner's share of commits; owner_line_pct
+ # their share of current lines by blame (None without blame).
ownership["owner_pct"] = meta.primary_owner_commit_pct
+ ownership["owner_line_pct"] = getattr(meta, "primary_owner_line_pct", None)
ownership["contributor_count"] = getattr(meta, "contributor_count", 0) or len(
json.loads(meta.top_authors_json)
)
diff --git a/packages/server/src/repowise/server/mcp_server/tool_risk/assessment.py b/packages/server/src/repowise/server/mcp_server/tool_risk/assessment.py
index cba26e87b..e006677bf 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_risk/assessment.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_risk/assessment.py
@@ -713,6 +713,7 @@ async def _assess_one_target(
owner = meta.primary_owner_name or "unknown"
pct = meta.primary_owner_commit_pct or 0.0
+ line_pct = getattr(meta, "primary_owner_line_pct", None)
# --- Risk velocity (trend) ---
trend = _compute_trend(meta)
@@ -753,6 +754,7 @@ async def _assess_one_target(
}
result_data["primary_owner"] = owner
result_data["owner_pct"] = pct
+ result_data["owner_line_pct"] = line_pct
result_data["recent_owner"] = getattr(meta, "recent_owner_name", None)
result_data["recent_owner_pct"] = getattr(meta, "recent_owner_commit_pct", None)
result_data["bus_factor"] = bus_factor
@@ -798,8 +800,20 @@ async def _assess_one_target(
f"{target} — {_fix_clause(defect_profile)}"
f"hotspot score {hotspot_score:.0%} ({trend}), "
f"{dep_count} direct dependents, {risk_type}, {change_pattern}, "
- f"{co_changes_total} co-change partners, owned {pct:.0%} by {owner}"
+ f"{co_changes_total} co-change partners, {_owner_clause(owner, pct, line_pct)}"
f"{bus_note}{capped_note}"
)
return result_data
+
+
+def _owner_clause(owner: str, commit_pct: float, line_pct: float | None) -> str:
+ """Name the owner with the share each figure actually measures.
+
+ With blame, the owner is the top author of current lines, which need not
+ be the top committer, so both shares are stated and neither is called the
+ other.
+ """
+ if line_pct is None:
+ return f"primary owner {owner} ({commit_pct:.0%} of commits)"
+ return f"{owner} wrote {line_pct:.0%} of current lines ({commit_pct:.0%} of commits)"
diff --git a/packages/server/src/repowise/server/routers/owners.py b/packages/server/src/repowise/server/routers/owners.py
index 13d1d064b..3c5651a30 100644
--- a/packages/server/src/repowise/server/routers/owners.py
+++ b/packages/server/src/repowise/server/routers/owners.py
@@ -182,7 +182,7 @@ async def list_owners(
sort_key = {
"files_owned": lambda e: e.files_owned,
"hotspots_owned": lambda e: e.hotspots_owned,
- "commit_count_90d": lambda e: e.commit_count_90d,
+ "commit_count_90d": lambda e: e.commit_count_90d or 0,
"dead_code_lines_owned": lambda e: e.dead_code_lines_owned,
"bus_factor_risk_files": lambda e: e.bus_factor_risk_files,
}.get(sort, lambda e: e.files_owned)
diff --git a/packages/server/src/repowise/server/routers/stats.py b/packages/server/src/repowise/server/routers/stats.py
index 1c492483d..2e8034958 100644
--- a/packages/server/src/repowise/server/routers/stats.py
+++ b/packages/server/src/repowise/server/routers/stats.py
@@ -164,6 +164,7 @@ async def stats_highlights(
totals = {
"total_commit_count": repo.total_commit_count,
+ "total_merge_commit_count": repo.total_merge_commit_count,
"first_commit_at": repo.first_commit_at,
"total_contributor_count": repo.total_contributor_count,
"first_commit_author": repo.first_commit_author,
diff --git a/packages/server/src/repowise/server/schemas/git.py b/packages/server/src/repowise/server/schemas/git.py
index 6f78664c9..94dc37b11 100644
--- a/packages/server/src/repowise/server/schemas/git.py
+++ b/packages/server/src/repowise/server/schemas/git.py
@@ -22,6 +22,8 @@ class GitMetadataResponse(BaseModel):
primary_owner_name: str | None
primary_owner_email: str | None
primary_owner_commit_pct: float | None
+ # The primary (blame) owner's share of current lines; None without blame.
+ primary_owner_line_pct: float | None = None
recent_owner_name: str | None
recent_owner_commit_pct: float | None
top_authors: list[dict]
@@ -76,6 +78,7 @@ class GitMetadataResponse(BaseModel):
primary_owner_name=obj.primary_owner_name, # type: ignore[attr-defined]
primary_owner_email=obj.primary_owner_email, # type: ignore[attr-defined]
primary_owner_commit_pct=obj.primary_owner_commit_pct, # type: ignore[attr-defined]
+ primary_owner_line_pct=getattr(obj, "primary_owner_line_pct", None),
recent_owner_name=obj.recent_owner_name, # type: ignore[attr-defined]
recent_owner_commit_pct=obj.recent_owner_commit_pct, # type: ignore[attr-defined]
top_authors=json.loads(obj.top_authors_json), # type: ignore[attr-defined]
diff --git a/packages/server/src/repowise/server/schemas/ownership.py b/packages/server/src/repowise/server/schemas/ownership.py
index a11ebcce5..c3e7e2cec 100644
--- a/packages/server/src/repowise/server/schemas/ownership.py
+++ b/packages/server/src/repowise/server/schemas/ownership.py
@@ -43,7 +43,9 @@ class OwnerListEntry(BaseModel):
silo_modules: int # modules where this owner is >80%
dead_code_files_owned: int
dead_code_lines_owned: int
- commit_count_90d: int # sum of per-file 90d commits attributed to this person
+ # Distinct commits by this person in the 90 days before HEAD; None when the
+ # indexed commits do not cover the window.
+ commit_count_90d: int | None
last_commit_at: datetime | None
bus_factor_risk_files: int # files they own where bus_factor <= 1
@@ -99,7 +101,7 @@ class OwnerProfileResponse(BaseModel):
silo_modules: int
dead_code_files_owned: int
dead_code_lines_owned: int
- commit_count_90d: int
+ commit_count_90d: int | None
last_commit_at: datetime | None
first_commit_at: datetime | None
bus_factor_risk_files: int
diff --git a/packages/server/src/repowise/server/services/owner_profile.py b/packages/server/src/repowise/server/services/owner_profile.py
index d48083509..3bdee0f8b 100644
--- a/packages/server/src/repowise/server/services/owner_profile.py
+++ b/packages/server/src/repowise/server/services/owner_profile.py
@@ -1,6 +1,6 @@
"""Owner / contributor aggregation service.
-Fetches ``GitMetadata`` + ``DeadCodeFinding`` rows and folds them with
+Fetches ``GitMetadata``, ``DeadCodeFinding`` and ``GitCommit`` 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.
"""
@@ -17,7 +17,12 @@ from repowise.core.analysis.owners import (
owner_key,
silo_modules,
)
-from repowise.core.persistence.models import DeadCodeFinding, GitMetadata
+from repowise.core.persistence.models import (
+ DeadCodeFinding,
+ GitCommit,
+ GitMetadata,
+ Repository,
+)
_OwnerAccumulator = OwnerAccumulator
@@ -44,7 +49,20 @@ async def aggregate_owners(
).where(DeadCodeFinding.repository_id == repo_id)
)
).all()
- return _fold.aggregate_owners(git_rows, dead_rows)
+ commit_rows = (
+ await session.execute(
+ select(
+ GitCommit.sha,
+ GitCommit.author_name,
+ GitCommit.author_email,
+ GitCommit.committed_at,
+ ).where(GitCommit.repository_id == repo_id)
+ )
+ ).all()
+ total_commits = await session.scalar(
+ select(Repository.total_commit_count).where(Repository.id == repo_id)
+ )
+ return _fold.aggregate_owners(git_rows, dead_rows, commit_rows, total_commits)
__all__ = [
diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.ts
index ea48e0562..6c5469b41 100644
--- a/packages/types/src/generated/http.ts
+++ b/packages/types/src/generated/http.ts
@@ -1604,6 +1604,7 @@ export interface GitMetadataResponse {
primary_owner_name: string | null;
primary_owner_email: string | null;
primary_owner_commit_pct: number | null;
+ primary_owner_line_pct?: number | null;
recent_owner_name: string | null;
recent_owner_commit_pct: number | null;
top_authors: Record<string, unknown>[];
@@ -2156,7 +2157,7 @@ export interface OwnerListEntry {
silo_modules: number;
dead_code_files_owned: number;
dead_code_lines_owned: number;
- commit_count_90d: number;
+ commit_count_90d: number | null;
last_commit_at: string | null;
bus_factor_risk_files: number;
}
@@ -2177,7 +2178,7 @@ export interface OwnerProfileResponse {
silo_modules: number;
dead_code_files_owned: number;
dead_code_lines_owned: number;
- commit_count_90d: number;
+ commit_count_90d: number | null;
last_commit_at: string | null;
first_commit_at: string | null;
bus_factor_risk_files: number;
diff --git a/packages/types/src/git.ts b/packages/types/src/git.ts
index c3f8bd23b..6f6e42c8d 100644
--- a/packages/types/src/git.ts
+++ b/packages/types/src/git.ts
@@ -38,7 +38,10 @@ export interface GitMetadata {
last_commit_at: string | null;
primary_owner_name: string | null;
primary_owner_email: string | null;
+ /** The primary owner's own share of the file's commits, 0–1. */
primary_owner_commit_pct: number | null;
+ /** The primary (blame) owner's share of current lines, 0–1. Null without blame. */
+ primary_owner_line_pct?: number | null;
recent_owner_name: string | null;
recent_owner_commit_pct: number | null;
top_authors: FileAuthor[];
diff --git a/packages/types/src/owners.ts b/packages/types/src/owners.ts
index dc8568c12..b708c29c5 100644
--- a/packages/types/src/owners.ts
+++ b/packages/types/src/owners.ts
@@ -13,7 +13,8 @@ export interface OwnerListEntry {
silo_modules: number;
dead_code_files_owned: number;
dead_code_lines_owned: number;
- commit_count_90d: number;
+ /** Distinct commits in the 90 days before HEAD; null when the indexed commits do not cover the window. */
+ commit_count_90d: number | null;
last_commit_at: string | null;
bus_factor_risk_files: number;
}
@@ -54,7 +55,8 @@ export interface OwnerProfile {
silo_modules: number;
dead_code_files_owned: number;
dead_code_lines_owned: number;
- commit_count_90d: number;
+ /** Distinct commits in the 90 days before HEAD; null when the indexed commits do not cover the window. */
+ commit_count_90d: number | null;
last_commit_at: string | null;
first_commit_at: string | null;
bus_factor_risk_files: number;
diff --git a/packages/types/src/stats.ts b/packages/types/src/stats.ts
index 405aec991..3ca19e225 100644
--- a/packages/types/src/stats.ts
+++ b/packages/types/src/stats.ts
@@ -46,7 +46,10 @@ export interface StatsOrigin {
first_commit_subject: string | null;
last_commit_at: string | null;
age_days: number | null;
+ /** Non-merge commits reachable from HEAD, the meaning "commits" has everywhere. */
total_commits: number;
+ /** Merge commits, counted apart. Null until an index captures it. */
+ total_merge_commits?: number | null;
contributor_count: number;
}
diff --git a/packages/ui/src/owners/owner-directory.tsx b/packages/ui/src/owners/owner-directory.tsx
index 6f70e64e7..c9c0c875b 100644
--- a/packages/ui/src/owners/owner-directory.tsx
+++ b/packages/ui/src/owners/owner-directory.tsx
@@ -98,9 +98,12 @@ export function OwnerDirectory({
const deadLines = sorted.reduce((s, o) => s + o.dead_code_lines_owned, 0);
const deadOwners = sorted.filter((o) => o.dead_code_lines_owned > 0).length;
const deadFiles = sorted.reduce((s, o) => s + o.dead_code_files_owned, 0);
- const active = sorted.filter((o) => o.commit_count_90d > 0).length;
+ // Null when the indexed commits do not cover the last 90 days: unknown, not zero.
+ const active = sorted.some((o) => o.commit_count_90d != null)
+ ? sorted.filter((o) => (o.commit_count_90d ?? 0) > 0).length
+ : null;
const hotspots = sorted.reduce((s, o) => s + o.hotspots_owned, 0);
- const commits90d = sorted.reduce((s, o) => s + o.commit_count_90d, 0);
+ const commits90d = sorted.reduce((s, o) => s + (o.commit_count_90d ?? 0), 0);
return {
deadFiles,
hotspots,
@@ -149,14 +152,16 @@ export function OwnerDirectory({
href: base ? `${base}/modules` : "#",
});
}
- reads.push({
- key: "active",
- label: "Active this quarter",
- value: summary.active.toLocaleString(),
- unit: `of ${total.toLocaleString()}`,
- why: `Committed in the last ${INACTIVE_DAYS} days. The rest are history, not staffing.`,
- href: base ? `${base}/commits` : "#",
- });
+ if (summary.active != null) {
+ reads.push({
+ key: "active",
+ label: "Active this quarter",
+ value: summary.active.toLocaleString(),
+ unit: `of ${total.toLocaleString()}`,
+ why: `Committed in the last ${INACTIVE_DAYS} days. The rest are history, not staffing.`,
+ href: base ? `${base}/commits` : "#",
+ });
+ }
if (summary.deadLines > 0) {
reads.push({
key: "dead",
diff --git a/packages/ui/src/owners/owner-profile.tsx b/packages/ui/src/owners/owner-profile.tsx
index 4340fb6bf..b40ea9798 100644
--- a/packages/ui/src/owners/owner-profile.tsx
+++ b/packages/ui/src/owners/owner-profile.tsx
@@ -158,7 +158,8 @@ export function OwnerProfileView({
// section below. The two line counts are the payload's `_est` fields, so an
// exact six-digit figure would claim a precision the number does not have.
const ribbon: RibbonStat[] = [
- { label: "Commits, 90d", value: owner.commit_count_90d.toLocaleString() },
+ // Null when the indexed commits do not reach back 90 days: not a zero.
+ { label: "Commits, 90d", value: owner.commit_count_90d?.toLocaleString() ?? "—" },
{
label: "Lines added",
value: formatCompact(owner.lines_added_90d_est),
diff --git a/packages/ui/src/owners/owner-table.tsx b/packages/ui/src/owners/owner-table.tsx
index 327e4813a..7a24d7fa9 100644
--- a/packages/ui/src/owners/owner-table.tsx
+++ b/packages/ui/src/owners/owner-table.tsx
@@ -185,7 +185,7 @@ function Num({
marker,
markerTitle,
}: {
- value: number;
+ value: number | null;
emphasis?: boolean;
marker?: boolean;
markerTitle?: string;
@@ -196,7 +196,7 @@ function Num({
emphasis ? "font-semibold text-[var(--color-text-primary)]" : ""
}`}
>
- {value > 0 ? value.toLocaleString() : <span className="text-[var(--color-text-tertiary)]">—</span>}
+ {value != null && value > 0 ? value.toLocaleString() : <span className="text-[var(--color-text-tertiary)]">—</span>}
{marker && (
<span
title={markerTitle}
diff --git a/tests/unit/analysis/test_owner_activity_from_commits.py b/tests/unit/analysis/test_owner_activity_from_commits.py
new file mode 100644
index 000000000..c3e661151
--- /dev/null
+++ b/tests/unit/analysis/test_owner_activity_from_commits.py
@@ -0,0 +1,128 @@
+"""An owner's "commits in the last 90 days" counts distinct commits, anchored to HEAD.
+
+Summing per-file counts credited a commit once per file it touched, and used
+the author's all-time count on each file, so the directory showed several
+times the repo's real commit volume and nearly everyone as active. The count
+now comes from the per-commit rows.
+"""
+
+from __future__ import annotations
+
+import os
+import subprocess
+from datetime import UTC, datetime, timedelta
+from pathlib import Path
+
+import pytest
+
+from repowise.core.analysis.owners import aggregate_owners
+from repowise.core.ingestion.git_indexer import GitIndexer, GitIndexTier
+
+# Fixed in the past so HEAD time, not the wall clock, must anchor the window.
+_HEAD = datetime(2025, 3, 1, 12, 0, tzinfo=UTC)
+_FILES = ("a.py", "b.py", "c.py")
+
+
+def _commit(cwd: Path, who: str, when: datetime, n: int) -> None:
+ for name in _FILES:
+ (cwd / name).write_text(f"# {who} {n}\n")
+ subprocess.run(["git", "add", *_FILES], cwd=cwd, check=True)
+ stamp = when.isoformat()
+ env = {
+ **os.environ,
+ "GIT_AUTHOR_DATE": stamp,
+ "GIT_COMMITTER_DATE": stamp,
+ "GIT_AUTHOR_NAME": who,
+ "GIT_AUTHOR_EMAIL": f"{who.lower()}@example.com",
+ "GIT_COMMITTER_NAME": who,
+ "GIT_COMMITTER_EMAIL": f"{who.lower()}@example.com",
+ }
+ subprocess.run(["git", "commit", "-q", "-m", f"change {n}"], cwd=cwd, check=True, env=env)
+
+
+def three_author_repo(tmp_path: Path) -> Path:
+ """Carol stopped 150 days before HEAD; Ada and Bob are active.
+
+ Every commit touches all three files, so per-file sums triple-count.
+ """
+ subprocess.run(["git", "init", "-q"], cwd=tmp_path, check=True)
+ plan = [
+ ("Carol", 400),
+ ("Carol", 300),
+ ("Carol", 150),
+ ("Ada", 200),
+ ("Bob", 120),
+ ("Ada", 60),
+ ("Bob", 40),
+ ("Ada", 20),
+ ("Ada", 0),
+ ]
+ for n, (who, days_before_head) in enumerate(plan):
+ _commit(tmp_path, who, _HEAD - timedelta(days=days_before_head), n)
+ return tmp_path
+
+
+async def _index(repo: Path, commit_limit: int | None = None):
+ summary, results = await GitIndexer(
+ repo, tier=GitIndexTier.FULL, commit_limit=commit_limit
+ ).index_repo("r")
+ return summary, results
+
+
+def _window_commits(repo: Path) -> int:
+ since = (_HEAD - timedelta(days=90)).isoformat()
+ out = subprocess.run(
+ ["git", "rev-list", "--count", "--no-merges", f"--since={since}", "HEAD"],
+ cwd=repo,
+ check=True,
+ capture_output=True,
+ text=True,
+ )
+ return int(out.stdout)
+
+
+async def test_counts_distinct_commits_in_the_window_before_head(three_author_repo: Path) -> None:
+ summary, results = await _index(three_author_repo)
+ accs, _ = aggregate_owners(
+ results, [], summary.commit_rows, summary.repo_totals.total_commit_count
+ )
+ ada, bob, carol = (accs[f"{n}@example.com"] for n in ("ada", "bob", "carol"))
+
+ assert (ada.commit_count_90d, bob.commit_count_90d, carol.commit_count_90d) == (3, 1, 0)
+ # The inactive author is not active, and their last commit is their own.
+ assert carol.last_commit_at == _HEAD - timedelta(days=150)
+ assert ada.last_commit_at == _HEAD
+ # Invariant: the owners never add up to more commits than the repo made.
+ total = sum(a.commit_count_90d for a in accs.values() if a.key)
+ assert total <= _window_commits(three_author_repo) == 4
+
+
+async def test_no_commit_rows_means_unknown_not_zero(three_author_repo: Path) -> None:
+ _summary, results = await _index(three_author_repo)
+ accs, _ = aggregate_owners(results, [])
+ assert {a.commit_count_90d for a in accs.values() if a.key} == {None}
+
+
+async def test_a_sample_that_stops_inside_the_window_is_unknown(three_author_repo: Path) -> None:
+ # Two rows reach back only 20 days; the window is 90 and history is deeper.
+ summary, results = await _index(three_author_repo, commit_limit=2)
+ accs, _ = aggregate_owners(
+ results, [], summary.commit_rows, summary.repo_totals.total_commit_count
+ )
+ assert {a.commit_count_90d for a in accs.values() if a.key} == {None}
+
+
+async def test_a_short_history_inside_the_window_is_complete(tmp_path: Path) -> None:
+ subprocess.run(["git", "init", "-q"], cwd=tmp_path, check=True)
+ _commit(tmp_path, "Ada", _HEAD - timedelta(days=10), 0)
+ _commit(tmp_path, "Ada", _HEAD, 1)
+ summary, results = await _index(tmp_path)
+ accs, _ = aggregate_owners(
+ results, [], summary.commit_rows, summary.repo_totals.total_commit_count
+ )
+ assert accs["[email protected]"].commit_count_90d == 2
diff --git a/tests/unit/generation/test_structural_pages_read_like_a_wiki.py b/tests/unit/generation/test_structural_pages_read_like_a_wiki.py
index e5f04a66a..0e2c866cc 100644
--- a/tests/unit/generation/test_structural_pages_read_like_a_wiki.py
+++ b/tests/unit/generation/test_structural_pages_read_like_a_wiki.py
@@ -111,6 +111,20 @@ class TestHistory:
assert "12 of those commits fixed a bug." in page
assert "change hotspots" in page
+ def test_a_blame_owner_is_credited_with_lines_not_commits(self, generator):
+ git = {**GIT, "primary_owner_commit_pct": 0.25, "primary_owner_line_pct": 0.7}
+ page = render(generator, _context(git_metadata=git))
+
+ assert "**Ada Lovelace** wrote 70% of its current lines (25% of commits)." in page
+ assert "70% of commits" not in page
+
+ def test_a_blame_owner_with_no_indexed_commits_gets_the_line_share_alone(self, generator):
+ git = {**GIT, "primary_owner_commit_pct": None, "primary_owner_line_pct": 0.7}
+ page = render(generator, _context(git_metadata=git))
+
+ assert "**Ada Lovelace** wrote 70% of its current lines." in page
+ assert "of commits" not in page
+
def test_the_date_is_absolute_so_the_page_does_not_move_on_its_own(self, generator):
# The rendered bytes are this page's reuse key. "three days ago" would
# restate every page in the wiki every day.
diff --git a/tests/unit/ingestion/test_blame_ownership_single_pass.py b/tests/unit/ingestion/test_blame_ownership_single_pass.py
index a555fba47..f0eed9db2 100644
--- a/tests/unit/ingestion/test_blame_ownership_single_pass.py
+++ b/tests/unit/ingestion/test_blame_ownership_single_pass.py
@@ -71,7 +71,10 @@ class TestSingleBlamePassOwnership:
)
assert meta["primary_owner_name"] == "Alice"
assert meta["primary_owner_email"] == "[email protected]"
- assert meta["primary_owner_commit_pct"] == pytest.approx(0.75)
+ # Blame picks the owner by lines (3 of 4); the commit share stays
+ # Alice's own share of the file's commits (1 of 2).
+ assert meta["primary_owner_line_pct"] == pytest.approx(0.75)
+ assert meta["primary_owner_commit_pct"] == pytest.approx(0.5)
assert "blame_index" not in meta
def test_hot_file_retains_blame_index(self, repo) -> None:
diff --git a/tests/unit/ingestion/test_commit_totals_merges.py b/tests/unit/ingestion/test_commit_totals_merges.py
new file mode 100644
index 000000000..f3f8a084a
--- /dev/null
+++ b/tests/unit/ingestion/test_commit_totals_merges.py
@@ -0,0 +1,122 @@
+""" "Commits" means non-merge commits reachable from HEAD on every surface.
+
+A merge-inclusive whole-history total read against the ``--no-merges`` commit
+sample made a complete sample look truncated ("5000 of 5498"). These tests
+build a repo with merge commits and check every surface that reports a commit
+total agrees, with merges counted apart.
+"""
+
+from __future__ import annotations
+
+import subprocess
+from pathlib import Path
+
+import pytest
+
+from repowise.core.ingestion.git_commit_index import _count_non_merge_commits
+from repowise.core.ingestion.git_indexer import GitIndexer, GitIndexTier
+from repowise.core.ingestion.git_indexer.file_history import _per_file_log_args
+from repowise.core.stats_highlights import build_commit_pass
+
+
+def _git(cwd: Path, *args: str) -> str:
+ return subprocess.run(
+ ["git", *args], cwd=cwd, check=True, capture_output=True, text=True
+ ).stdout
+
+
+def _commit(cwd: Path, path: str, content: str, message: str) -> None:
+ (cwd / path).write_text(content)
+ _git(cwd, "add", path)
+ _git(cwd, "commit", "-q", "-m", message)
+
+
+def merge_repo(tmp_path: Path) -> Path:
+ """Six non-merge commits and two ``--no-ff`` merges, one of them an evil merge."""
+ _git(tmp_path, "init", "-q", "-b", "main")
+ _git(tmp_path, "config", "user.name", "Ada")
+ _git(tmp_path, "config", "user.email", "[email protected]")
+ _commit(tmp_path, "a.py", "a = 1\n", "feat: add a")
+ _git(tmp_path, "checkout", "-q", "-b", "topic")
+ _commit(tmp_path, "b.py", "b = 1\n", "feat: add b")
+ _commit(tmp_path, "a.py", "a = 2\n", "feat: bump a on topic")
+ _git(tmp_path, "checkout", "-q", "main")
+ _commit(tmp_path, "c.py", "c = 1\n", "feat: add c")
+ _git(tmp_path, "merge", "-q", "--no-ff", "--no-commit", "topic")
+ # An evil merge: the merge itself changes a.py beyond either parent.
+ (tmp_path / "a.py").write_text("a = 3\n")
+ _git(tmp_path, "add", "a.py")
+ _git(tmp_path, "commit", "-q", "-m", "Merge branch 'topic'")
+ _git(tmp_path, "checkout", "-q", "-b", "second")
+ _commit(tmp_path, "d.py", "d = 1\n", "feat: add d")
+ _git(tmp_path, "checkout", "-q", "main")
+ _commit(tmp_path, "e.py", "e = 1\n", "feat: add e")
+ _git(tmp_path, "merge", "-q", "--no-ff", "-m", "Merge branch 'second'", "second")
+ _commit(tmp_path, "a.py", "a = 4\n", "fix: a")
+ return tmp_path
+
+
+def test_capture_counts_non_merge_and_merges_apart(merge_repo: Path) -> None:
+ totals = GitIndexer(merge_repo, tier=GitIndexTier.FULL).capture_repo_totals()
+ assert totals.total_commit_count == 7
+ assert totals.total_merge_commit_count == 2
+ assert int(_git(merge_repo, "rev-list", "--count", "HEAD")) == 9
+
+
+async def test_every_surface_reports_the_same_total(merge_repo: Path) -> None:
+ import git as gitpython
+
+ summary, _results = await GitIndexer(merge_repo, tier=GitIndexTier.FULL).index_repo("r")
+ totals = summary.repo_totals
+ assert totals is not None
+ rows = summary.commit_rows
+ stored = {
+ "total_commit_count": totals.total_commit_count,
+ "total_merge_commit_count": totals.total_merge_commit_count,
+ "first_commit_at": totals.first_commit_at,
+ }
+ stats = build_commit_pass(rows, stored)
+
+ surfaces = {
+ "repo_totals": totals.total_commit_count,
+ "commit_rows": len(rows),
+ "history_walk_total": _count_non_merge_commits(gitpython.Repo(merge_repo)),
+ "stats_origin": stats["origin"]["total_commits"],
+ "stats_window": stats["rhythm"]["window"]["commits"],
+ }
+ assert set(surfaces.values()) == {7}, surfaces
+ assert stats["origin"]["total_merge_commits"] == 2
+ # The sample holds every non-merge commit, so it is not truncated.
+ assert stats["rhythm"]["window"]["complete"] is True
+
+
+async def test_truncated_only_when_non_merge_total_exceeds_depth(merge_repo: Path) -> None:
+ summary, _results = await GitIndexer(
+ merge_repo, tier=GitIndexTier.FULL, commit_limit=3
+ ).index_repo("r")
+ totals = summary.repo_totals
+ stats = build_commit_pass(
+ summary.commit_rows, {"total_commit_count": totals.total_commit_count}
+ )
+ assert len(summary.commit_rows) == 3
+ assert stats["origin"]["total_commits"] == 7
+ assert stats["rhythm"]["window"]["complete"] is False
+
+
+def test_every_per_file_lane_skips_merges() -> None:
+ for follow in (True, False):
+ assert "--no-merges" in _per_file_log_args("a.py", 10, follow)
+
+
+async def test_follow_lane_counts_match_non_merge_log(merge_repo: Path) -> None:
+ _summary, results = await GitIndexer(
+ merge_repo, tier=GitIndexTier.FULL, follow_renames=True
+ ).index_repo("r")
+ by_path = {r["file_path"]: r for r in results}
+ expected = int(_git(merge_repo, "rev-list", "--count", "--no-merges", "HEAD", "--", "a.py"))
+ assert by_path["a.py"]["commit_count_total"] == expected == 3
+ assert by_path["a.py"]["merge_commit_count_90d"] == 0
diff --git a/tests/unit/ingestion/test_owner_line_share.py b/tests/unit/ingestion/test_owner_line_share.py
new file mode 100644
index 000000000..c127ba9f2
--- /dev/null
+++ b/tests/unit/ingestion/test_owner_line_share.py
@@ -0,0 +1,78 @@
+"""The primary owner's line share and commit share are two different numbers.
+
+With blame, the top author of current lines becomes the primary owner. That
+person need not be the top committer, so their share of lines must not be
+reported as a share of commits.
+"""
+
+from __future__ import annotations
+
+import json
+import subprocess
+from pathlib import Path
+
+import git as gitpython
+
+from repowise.core.ingestion.git_indexer.file_history import index_file
+
+
+def _init(cwd: Path) -> None:
+ subprocess.run(["git", "init", "-q"], cwd=cwd, check=True)
+ subprocess.run(["git", "config", "user.name", "Setup"], cwd=cwd, check=True)
+ subprocess.run(["git", "config", "user.email", "[email protected]"], cwd=cwd, check=True)
+
+
+def _commit(cwd: Path, author: str, content: str, message: str) -> None:
+ (cwd / "mod.py").write_text(content)
+ subprocess.run(["git", "add", "mod.py"], cwd=cwd, check=True)
+ subprocess.run(
+ ["git", "commit", "-q", "-m", message, f"--author={author} <{author.lower()}@example.com>"],
+ cwd=cwd,
+ check=True,
+ )
+
+
+def test_top_blame_author_differs_from_top_commit_author(tmp_path: Path) -> None:
+ _init(tmp_path)
+ lines = [f"v{i} = {i}\n" for i in range(10)]
+ # Ada writes all ten lines in one commit; Bob then edits one line three times.
+ _commit(tmp_path, "Ada", "".join(lines), "feat: add mod")
+ for n in range(3):
+ lines[n] = f"v{n} = {n + 100}\n"
+ _commit(tmp_path, "Bob", "".join(lines), f"fix: tweak v{n}")
+
+ meta = index_file(
+ gitpython.Repo(tmp_path),
+ "mod.py",
+ repo_path=tmp_path,
+ commit_limit=100,
+ follow_renames=False,
+ include_blame=True,
+ )
+
+ # Bob made 3 of the 4 commits, but Ada still wrote 7 of the 10 lines.
+ assert meta["primary_owner_name"] == "Ada"
+ assert meta["primary_owner_line_pct"] == 0.7
+ assert meta["primary_owner_commit_pct"] == 0.25
+ top_committer = max(json.loads(meta["top_authors_json"]), key=lambda a: a["commit_count"])
+ assert top_committer["name"] == "Bob"
+
+
+def test_without_blame_the_owner_and_share_come_from_commits(tmp_path: Path) -> None:
+ _init(tmp_path)
+ _commit(tmp_path, "Ada", "a = 1\nb = 2\n", "feat: add mod")
+ _commit(tmp_path, "Bob", "a = 1\nb = 3\n", "fix: b")
+ _commit(tmp_path, "Bob", "a = 1\nb = 4\n", "fix: b again")
+
+ meta = index_file(
+ gitpython.Repo(tmp_path),
+ "mod.py",
+ repo_path=tmp_path,
+ commit_limit=100,
+ follow_renames=False,
+ include_blame=False,
+ )
+
+ assert meta["primary_owner_name"] == "Bob"
+ assert meta["primary_owner_commit_pct"] == 2 / 3
+ assert meta["primary_owner_line_pct"] is None
diff --git a/tests/unit/persistence/test_schema_reconciliation.py b/tests/unit/persistence/test_schema_reconciliation.py
index 34476efc4..5a91abc25 100644
--- a/tests/unit/persistence/test_schema_reconciliation.py
+++ b/tests/unit/persistence/test_schema_reconciliation.py
@@ -480,3 +480,72 @@ async def test_reconciler_handles_arbitrary_new_column(tmp_path: Path) -> None:
await engine.dispose()
assert target_column in _table_columns(db_path, target_table)
+
+
+async def test_adding_owner_line_pct_moves_stale_blame_line_shares(tmp_path: Path) -> None:
+ """Before ``primary_owner_line_pct`` existed, blame stored the owner's line
+ share as ``primary_owner_commit_pct``. Upgrading must not leave that value
+ labelled a commit share on files no update re-walks."""
+ import json
+
+ from repowise.core.persistence import create_session_factory, crud, get_session
+
+ db_path = tmp_path / "wiki.db"
+ engine = create_engine(f"sqlite+aiosqlite:///{db_path}")
+ authors = json.dumps(
+ [{"name": "Bob", "commit_count": 3}, {"name": "Ada", "commit_count": 1}]
+ )
+ rows = {
+ # blame owner Ada: 70% of lines, 1 of 4 commits
+ "blame.py": ("Ada", 0.7),
+ # no blame: the top committer and their commit share, already right
+ "commits.py": ("Bob", 0.75),
+ # blame owner with no counted commits
+ "old.py": ("Cy", 0.6),
+ }
+ try:
+ await init_db(engine)
+ async with get_session(create_session_factory(engine)) as session:
+ repo = await crud.upsert_repository(session, name="r", local_path=str(tmp_path))
+ await crud.upsert_git_metadata_bulk(
+ session,
+ repo.id,
+ [
+ {
+ "file_path": path,
+ "commit_count_total": 4,
+ "top_authors_json": authors,
+ "primary_owner_name": owner,
+ "primary_owner_commit_pct": pct,
+ }
+ for path, (owner, pct) in rows.items()
+ ],
+ )
+ finally:
+ await engine.dispose()
+
+ try:
+ _execute(db_path, 'ALTER TABLE "git_metadata" DROP COLUMN "primary_owner_line_pct"')
+ except sqlite3.OperationalError as exc:
+ pytest.skip(f"SQLite build doesn't support DROP COLUMN: {exc}")
+
+ engine = create_engine(f"sqlite+aiosqlite:///{db_path}")
+ try:
+ await init_db(engine)
+ finally:
+ await engine.dispose()
+
+ got = {
+ path: (commit_pct, line_pct)
+ for path, commit_pct, line_pct in _fetchall(
+ db_path,
+ "SELECT file_path, primary_owner_commit_pct, primary_owner_line_pct "
+ "FROM git_metadata",
+ )
+ }
+ assert got == {
+ "blame.py": (0.25, 0.7),
+ "commits.py": (0.75, None),
+ "old.py": (None, 0.6),
+ }
diff --git a/tests/unit/server/golden/ownership_rollups.json b/tests/unit/server/golden/ownership_rollups.json
index 94baa64b7..4c79fcbdc 100644
--- a/tests/unit/server/golden/ownership_rollups.json
+++ b/tests/unit/server/golden/ownership_rollups.json
@@ -10,8 +10,8 @@
"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",
+ "commit_count_90d": 2,
+ "last_commit_at": "2026-08-01T12:00:00Z",
"bus_factor_risk_files": 1
},
{
@@ -23,8 +23,8 @@
"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",
+ "commit_count_90d": 1,
+ "last_commit_at": "2026-07-01T00:00:00Z",
"bus_factor_risk_files": 1
},
{
@@ -36,8 +36,8 @@
"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",
+ "commit_count_90d": 0,
+ "last_commit_at": "2020-03-03T00:00:00Z",
"bus_factor_risk_files": 1
}
],
@@ -56,8 +56,8 @@
"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",
+ "commit_count_90d": 2,
+ "last_commit_at": "2026-08-01T12:00:00Z",
"bus_factor_risk_files": 1
},
{
@@ -69,8 +69,8 @@
"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",
+ "commit_count_90d": 1,
+ "last_commit_at": "2026-07-01T00:00:00Z",
"bus_factor_risk_files": 1
},
{
@@ -82,8 +82,8 @@
"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",
+ "commit_count_90d": 0,
+ "last_commit_at": "2020-03-03T00:00:00Z",
"bus_factor_risk_files": 1
}
],
@@ -101,8 +101,8 @@
"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",
+ "commit_count_90d": 2,
+ "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": 218,
@@ -189,8 +189,8 @@
"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",
+ "commit_count_90d": 1,
+ "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": 132,
@@ -274,8 +274,8 @@
"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",
+ "commit_count_90d": 0,
+ "last_commit_at": "2020-03-03T00:00:00Z",
"first_commit_at": "2019-03-03T00:00:00Z",
"bus_factor_risk_files": 1,
"lines_added_90d_est": 30,
diff --git a/tests/unit/server/test_owners.py b/tests/unit/server/test_owners.py
index 09eb4e6ec..775ceb300 100644
--- a/tests/unit/server/test_owners.py
+++ b/tests/unit/server/test_owners.py
@@ -254,3 +254,37 @@ async def test_get_owner_profile_not_found(client: AsyncClient) -> None:
repo = await create_test_repo(client)
resp = await client.get(f"/api/repos/{repo['id']}/owners/ghost@nowhere")
assert resp.status_code == 404
+
+
+async def test_commits_90d_counts_the_owners_own_commits(client: AsyncClient, app) -> None:
+ """The directory's 90-day count is distinct commits from the commit table,
+ anchored to the newest commit, and unknown (null) without that table."""
+ repo = await create_test_repo(client)
+ await _seed(app.state.session_factory, repo["id"])
+
+ resp = await client.get(f"/api/repos/{repo['id']}/owners")
+ assert {i["commit_count_90d"] for i in resp.json()["items"]} == {None}
+
+ head = datetime(2025, 3, 1, tzinfo=UTC)
+ rows = [
+ ("a1", "Alice", "[email protected]", head),
+ ("a2", "Alice", "[email protected]", head.replace(month=2)),
+ ("b1", "Bob", "[email protected]", head.replace(year=2024)),
+ ]
+ async with get_session(app.state.session_factory) as session:
+ await crud.upsert_git_commits_bulk(
+ session,
+ repo["id"],
+ [
+ {"sha": sha, "author_name": name, "author_email": email, "committed_at": at}
+ for sha, name, email, at in rows
+ ],
+ )
+ await crud.update_repo_git_totals(session, repo["id"], total_commit_count=3)
+
+ resp = await client.get(f"/api/repos/{repo['id']}/owners")
+ by_name = {i["name"]: i for i in resp.json()["items"]}
+ assert by_name["Alice"]["commit_count_90d"] == 2
+ assert by_name["Bob"]["commit_count_90d"] == 0
+ assert by_name["Bob"]["last_commit_at"].startswith("2024-03-01")
diff --git a/tests/unit/server/test_ownership_rollups_golden.py b/tests/unit/server/test_ownership_rollups_golden.py
index e30ce3d10..a38e60a1c 100644
--- a/tests/unit/server/test_ownership_rollups_golden.py
+++ b/tests/unit/server/test_ownership_rollups_golden.py
@@ -129,6 +129,29 @@ async def _seed(session_factory, repo_id: str) -> None:
await crud.upsert_git_metadata(
session, repository_id=repo_id, file_path=path, **fields
)
+ # The per-commit rows the owners' 90-day activity is counted from:
+ # distinct commits before the newest one, a noreply alias folding into
+ # Bob, and Carol inactive for years.
+ await crud.upsert_git_commits_bulk(
+ session,
+ repo_id,
+ [
+ {
+ "sha": sha,
+ "author_name": who["name"],
+ "author_email": who["email"] or "",
+ "committed_at": at,
+ }
+ for sha, who, at in [
+ ("c1", _ALICE, datetime(2026, 8, 1, 12, 0, 0)),
+ ("c2", _ALICE, datetime(2026, 7, 20)),
+ ("c3", _BOB_NOREPLY, datetime(2026, 7, 1)),
+ ("c4", _BOB, datetime(2026, 1, 5)),
+ ("c5", _CAROL, datetime(2020, 3, 3)),
+ ]
+ ],
+ )
+ await crud.update_repo_git_totals(session, repo_id, total_commit_count=5)
session.add_all(
[
WikiSymbol(