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(commits): count author experience over the whole history, not the update batch (#953)

Raghav Chamadiya90401ce7d2e4
diff --git a/packages/api-client/src/types/git.ts b/packages/api-client/src/types/git.ts
index e53c9b19e..115fb0669 100644
--- a/packages/api-client/src/types/git.ts
+++ b/packages/api-client/src/types/git.ts
@@ -117,6 +117,8 @@ export interface CommitResponse {
top_driver?: string | null;
/** Author's cumulative prior-commit count at commit time. */
author_experience?: number | null;
+ /** Commits by this author across the indexed history (identities folded). */
+ author_commit_count?: number | null;
/** Coding-agent attribution; null for human-authored commits. */
agent_name?: string | null;
/** 1 = near-autonomous bot, 2 = human-driven agent, 3 = assisted. */
diff --git a/packages/core/src/repowise/core/analysis/change_risk/__init__.py b/packages/core/src/repowise/core/analysis/change_risk/__init__.py
index fe9a23ffe..c48d05990 100644
--- a/packages/core/src/repowise/core/analysis/change_risk/__init__.py
+++ b/packages/core/src/repowise/core/analysis/change_risk/__init__.py
@@ -12,6 +12,7 @@ from __future__ import annotations
from .baseline import baseline_scores
from .features import (
ChangeFeatures,
+ change_features_from_stored,
extract_commit_features,
extract_range_features,
features_from_file_changes,
@@ -33,6 +34,7 @@ __all__ = [
"RiskDriver",
"RiskNormalizer",
"baseline_scores",
+ "change_features_from_stored",
"change_risk_payload",
"extract_commit_features",
"extract_range_features",
diff --git a/packages/core/src/repowise/core/analysis/change_risk/features.py b/packages/core/src/repowise/core/analysis/change_risk/features.py
index c3f7fa504..4a05b3e34 100644
--- a/packages/core/src/repowise/core/analysis/change_risk/features.py
+++ b/packages/core/src/repowise/core/analysis/change_risk/features.py
@@ -181,6 +181,44 @@ def features_from_file_changes(
)
+def change_features_from_stored(
+ *,
+ la: int,
+ ld: int,
+ nf: int,
+ nd: int,
+ ns: int,
+ entropy: float,
+ exp: int | None,
+ is_fix: bool = False,
+ author: str = "",
+ subject: str = "",
+ ref: str = "",
+) -> ChangeFeatures:
+ """Rebuild a feature vector from already-computed (persisted) metrics.
+
+ The model ships its constants and is deterministic, so re-scoring these
+ reproduces the score that was stored alongside them. Used wherever a commit
+ has to be re-scored without its diff: the API's per-driver breakdown and the
+ update pass that repairs a stale ``exp``. Shared so both build the vector the
+ same way — a field that drifted between them would make the re-scored
+ breakdown disagree with the stored score.
+ """
+ return ChangeFeatures(
+ la=la or 0,
+ ld=ld or 0,
+ nf=nf or 0,
+ nd=nd or 0,
+ ns=ns or 0,
+ entropy=entropy or 0.0,
+ exp=exp,
+ is_fix=bool(is_fix),
+ author=author or "",
+ subject=subject or "",
+ ref=ref or "",
+ )
+
+
def extract_commit_features(
repo_path: str,
sha: str,
@@ -199,9 +237,7 @@ def extract_commit_features(
numstat = _git(["show", sha, "--numstat", "--format="], repo_path)
la, ld, nf, dirs, subs, per_file = _accumulate_numstat(numstat, extensions, exclude_patterns)
# check=False: a root commit has no parent and that is not an error.
- parent = _git(
- ["rev-parse", "--verify", "--quiet", f"{sha}^"], repo_path, check=False
- ).strip()
+ parent = _git(["rev-parse", "--verify", "--quiet", f"{sha}^"], repo_path, check=False).strip()
exp = _author_experience(repo_path, author, parent or sha)
return ChangeFeatures(
la=la,
diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/commit_rows.py b/packages/core/src/repowise/core/ingestion/git_indexer/commit_rows.py
index c6e1192db..d1522c046 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/commit_rows.py
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/commit_rows.py
@@ -11,31 +11,28 @@ repository. Author experience — the one change-risk feature that costs a
subprocess in the live ``repowise risk`` path — is reconstructed **in memory**
here: walking commits oldest→newest, each author's prior-commit count is the
running tally before their commit. That keeps the whole pass zero-extra-git.
+
+That tally can only see the commits it is handed, which is the whole window on
+a full index but just the new ones on an update. The update path therefore
+re-tallies against the full persisted history afterwards
+(``pipeline.incremental.reconcile_commit_experience``); this module stays pure
+and batch-local on purpose.
"""
from __future__ import annotations
+from collections.abc import Iterable, Mapping
from datetime import UTC, datetime
+from typing import Any
from ._constants import is_fix_commit
-from .identity import canonicalize_author_email
+from .identity import author_identity_key
# Commit subjects are a headline (`%s`); cap defensively against a pathological
# single-line subject so one row can't bloat the table.
_MAX_SUBJECT_LEN = 500
-def _author_key(author_name: str, author_email: str) -> str:
- """Stable identity for the in-memory experience tally.
-
- GitHub ``noreply`` variants of one login are folded together first so a
- person's prior-commit count doesn't reset when their email flips between
- forms.
- """
- canonical = canonicalize_author_email(author_email) or author_email
- return (canonical or author_name or "").strip().lower()
-
-
def _committed_at(ts: int) -> datetime | None:
if not ts or ts <= 0:
return None
@@ -45,6 +42,28 @@ def _committed_at(ts: int) -> datetime | None:
return None
+def author_experience_by_sha(commits: Iterable[Mapping[str, Any]]) -> dict[str, int]:
+ """Map each commit's sha to its author's prior-commit count.
+
+ Walks *commits* oldest→newest (by ``ts``) and returns, per sha, the running
+ tally for that author BEFORE the commit. Ties on the same timestamp are
+ ordered as-given, which is fine for a count. Identities are folded through
+ :func:`_author_key`, so ``noreply`` variants of one person share a tally.
+
+ The count is only ever "prior commits **within this set**". Callers that
+ persist it must therefore hand over the whole history they hold, not a
+ trailing batch — a batch-local tally restarts every author at zero.
+ """
+ ordered = sorted(commits, key=lambda c: c.get("ts", 0) or 0)
+ exp_by_sha: dict[str, int] = {}
+ tally: dict[str, int] = {}
+ for c in ordered:
+ key = author_identity_key(c.get("author_name", ""), c.get("author_email", ""))
+ exp_by_sha[c["sha"]] = tally.get(key, 0)
+ tally[key] = tally.get(key, 0) + 1
+ return exp_by_sha
+
+
def build_commit_rows(parsed_commits: list[dict]) -> list[dict]:
"""Build ``git_commits`` row dicts from sunk commit records.
@@ -62,16 +81,12 @@ def build_commit_rows(parsed_commits: list[dict]) -> list[dict]:
# git_indexer._constants) and matches the codebase's hot-path import style.
from ...analysis.change_risk import features_from_file_changes, score_change
- # --- Author experience: cumulative prior-commit count, oldest→newest. ---
- # Each commit's exp is the author's tally BEFORE this commit (ties on the
- # same timestamp are ordered as-given, which is acceptable for a count).
- ordered = sorted(parsed_commits, key=lambda c: c.get("ts", 0) or 0)
- exp_by_sha: dict[str, int] = {}
- tally: dict[str, int] = {}
- for c in ordered:
- key = _author_key(c.get("author_name", ""), c.get("author_email", ""))
- exp_by_sha[c["sha"]] = tally.get(key, 0)
- tally[key] = tally.get(key, 0) + 1
+ # Author experience: cumulative prior-commit count over THIS batch only.
+ # On the full index that batch is the whole window, so the count lands
+ # right; the incremental path hands over only the new commits, so its rows
+ # are provisional until the update's reconcile pass re-tallies them against
+ # the full persisted history (see ``pipeline.incremental``).
+ exp_by_sha = author_experience_by_sha(parsed_commits)
rows: list[dict] = []
for c in parsed_commits:
diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/identity.py b/packages/core/src/repowise/core/ingestion/git_indexer/identity.py
index 325e80c1d..8f2a0a51f 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/identity.py
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/identity.py
@@ -51,6 +51,19 @@ def canonicalize_author_email(email: str | None) -> str | None:
return lowered
+def author_identity_key(author_name: str | None, author_email: str | None) -> str:
+ """Stable per-person key for counting commits.
+
+ Folds noreply variants onto one login first, falling back to the display
+ name when there is no usable email. Anything that tallies commits per author
+ must key on this, or one person splits across buckets and every count that
+ depends on it (author experience, "is this a new contributor") comes out low
+ for exactly the people who commit through GitHub's web UI.
+ """
+ canonical = canonicalize_author_email(author_email) or author_email
+ return (canonical or author_name or "").strip().lower()
+
+
def _is_github_noreply(canonical_email: str | None) -> bool:
"""True for a ``[email protected]`` identity (not the system
``[email protected]`` author, which lives on a different domain)."""
diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py b/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py
index c7fd1d50d..7f140ab18 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py
@@ -523,6 +523,37 @@ class GitIndexer:
finally:
repo.close()
+ def list_reachable_shas(self) -> set[str] | None:
+ """Shas reachable from HEAD, or ``None`` when that cannot be trusted.
+
+ The commit walk is ``git log --no-merges`` from HEAD, so this is exactly
+ the set a full index would produce. An update run on a feature branch
+ captures that branch's commits; once the branch is squash-merged or
+ rebased those shas stop being reachable, and nothing else prunes them.
+
+ ``None`` means "do not prune": a shallow clone only knows part of its
+ history, so every commit below the graft point would look unreachable
+ and a prune would delete real rows. Any git failure degrades the same
+ way, since dropping rows is not something to guess at.
+ """
+ repo = self._get_repo()
+ if repo is None:
+ return None
+ try:
+ if repo.git.rev_parse("--is-shallow-repository").strip() == "true":
+ return None
+ out = repo.git.rev_list("--no-merges", "HEAD")
+ except Exception as exc:
+ logger.debug("reachable_shas_failed", error=str(exc))
+ return None
+ finally:
+ with contextlib.suppress(Exception):
+ repo.close()
+ shas = {line.strip() for line in out.split("\n") if line.strip()}
+ # An empty result on a repo that has rows is far more likely to be a
+ # broken call than a genuinely empty history.
+ return shas or None
+
def capture_new_fix_events(
self, *, known_shas: set[str] | None = None
) -> tuple[list[dict], int, set[str]]:
diff --git a/packages/core/src/repowise/core/persistence/crud/git.py b/packages/core/src/repowise/core/persistence/crud/git.py
index 51ce99ad3..701a73877 100644
--- a/packages/core/src/repowise/core/persistence/crud/git.py
+++ b/packages/core/src/repowise/core/persistence/crud/git.py
@@ -6,6 +6,7 @@ every public name, so existing imports are unaffected.
from __future__ import annotations
+from collections.abc import Sequence
from datetime import datetime
from sqlalchemy import delete, func, or_, select, text
@@ -270,6 +271,74 @@ async def delete_git_commits(session: AsyncSession, repository_id: str) -> None:
await session.flush()
+async def delete_git_commits_by_sha(
+ session: AsyncSession, repository_id: str, shas: Sequence[str]
+) -> int:
+ """Drop specific per-commit rows. Returns how many were removed."""
+ removed = 0
+ for start in range(0, len(shas), _BATCH_SIZE):
+ chunk = shas[start : start + _BATCH_SIZE]
+ if not chunk:
+ continue
+ result = await session.execute(
+ delete(GitCommit).where(
+ GitCommit.repository_id == repository_id, GitCommit.sha.in_(chunk)
+ )
+ )
+ removed += int(result.rowcount or 0)
+ await session.flush()
+ return removed
+
+
+async def get_commit_experience_inputs(session: AsyncSession, repository_id: str) -> list[dict]:
+ """Every persisted commit's identity, timestamp and stored risk features.
+
+ The input to the update-time reconcile: enough to re-tally author experience
+ across the whole history and re-score each commit without touching git or
+ the diffs. Deliberately column-scoped rather than whole ORM rows, since this
+ loads the full table on every update.
+ """
+ stmt = select(
+ GitCommit.sha,
+ GitCommit.author_name,
+ GitCommit.author_email,
+ GitCommit.committed_at,
+ GitCommit.lines_added,
+ GitCommit.lines_deleted,
+ GitCommit.files_changed,
+ GitCommit.dirs_changed,
+ GitCommit.subsystems_changed,
+ GitCommit.entropy,
+ GitCommit.is_fix,
+ GitCommit.subject,
+ GitCommit.author_experience,
+ GitCommit.change_risk_score,
+ GitCommit.change_risk_level,
+ ).where(GitCommit.repository_id == repository_id)
+ result = await session.execute(stmt)
+ return [dict(row) for row in result.mappings()]
+
+
+async def get_author_commit_counts(session: AsyncSession, repository_id: str) -> list[tuple]:
+ """``(author_name, author_email, count)`` per raw identity in the index.
+
+ Raw because identities are folded by the caller — the canonicalization that
+ decides whether two emails are one person lives in the git-indexer, not in
+ SQL, and splitting it across both would let the two drift.
+ """
+ stmt = (
+ select(
+ GitCommit.author_name,
+ GitCommit.author_email,
+ func.count(),
+ )
+ .where(GitCommit.repository_id == repository_id)
+ .group_by(GitCommit.author_name, GitCommit.author_email)
+ )
+ result = await session.execute(stmt)
+ return [tuple(row) for row in result.all()]
+
+
def _commit_authorship_clause(authorship: str | None):
"""Optional authorship predicate: ``agent`` keeps agent-attributed commits,
``human`` keeps the rest. ``None`` / ``"all"`` means no filtering."""
diff --git a/packages/core/src/repowise/core/pipeline/incremental.py b/packages/core/src/repowise/core/pipeline/incremental.py
index ae21149e8..fac897c55 100644
--- a/packages/core/src/repowise/core/pipeline/incremental.py
+++ b/packages/core/src/repowise/core/pipeline/incremental.py
@@ -573,6 +573,8 @@ async def persist_incremental_commits(session: Any, repo_id: str, repo_path: Any
if rows:
await upsert_git_commits_bulk(session, repo_id, rows)
+ await reconcile_commit_experience(session, repo_id, indexer)
+
# Refresh the repo-level whole-history totals so age / commit / contributor
# counts keep growing between full re-indexes (#730). Cheap git calls, and
# cheap to run every update since they don't touch the bounded sample.
@@ -589,6 +591,139 @@ async def persist_incremental_commits(session: Any, repo_id: str, repo_path: Any
await persist_incremental_fix_events(session, repo_id, indexer)
+async def reconcile_commit_experience(session: Any, repo_id: str, indexer: Any) -> None:
+ """Re-tally author experience across the whole commit table and re-score.
+
+ ``build_commit_rows`` can only count the commits it is handed. On a full
+ index that is the entire window, so the number lands right; on an update it
+ is just the commits newer than the last one persisted, so every author's
+ count restarts at zero and an established author's new commits look like a
+ first-timer's. That is not only a cosmetic badge: ``author_experience`` is a
+ change-risk feature, so the stored ``change_risk_score`` inherits the error
+ and the review queue ranks on it.
+
+ Rather than seed the batch tally, this re-derives experience over the full
+ persisted history after the append. The batch-local pass then has no lasting
+ say, so there is no second code path to keep correct, and rows written by
+ earlier (wrong) updates are repaired on the next one instead of waiting for
+ a re-index.
+
+ Two things have to happen together. Unreachable commits are dropped first:
+ an update run on a feature branch persists that branch's shas, and once it
+ is squash-merged they survive as orphans that no full index would produce
+ and inflate every author's count. Then each surviving commit is re-scored
+ from its stored features, because a corrected experience that leaves the old
+ score in place would just move the inconsistency somewhere less visible.
+
+ Bounded by the commit count and git-free apart from one ``rev-list``, and
+ failure-isolated like the rest of the git-phase refreshes.
+ """
+ from repowise.core.persistence.crud import (
+ delete_git_commits_by_sha,
+ get_commit_experience_inputs,
+ upsert_git_commits_bulk,
+ )
+
+ try:
+ stored = await get_commit_experience_inputs(session, repo_id)
+ if not stored:
+ return
+
+ reachable = await asyncio.to_thread(indexer.list_reachable_shas)
+ if reachable is not None:
+ orphans = [r["sha"] for r in stored if r["sha"] not in reachable]
+ if orphans:
+ await delete_git_commits_by_sha(session, repo_id, orphans)
+ stored = [r for r in stored if r["sha"] in reachable]
+ logger.info("commit_orphans_pruned", repo_id=repo_id, count=len(orphans))
+
+ updates = _recompute_commit_experience(stored)
+ if updates:
+ await upsert_git_commits_bulk(session, repo_id, updates)
+ logger.info("commit_experience_reconciled", repo_id=repo_id, count=len(updates))
+ except Exception as exc:
+ logger.debug("commit_experience_reconcile_failed", error=str(exc))
+
+
+def _committed_ts(committed_at: Any) -> float:
+ """``committed_at`` as a sortable epoch, or 0 when the row has no date.
+
+ SQLite drops tzinfo, so a naive read has to be reinterpreted as UTC — the
+ column is stored tz-aware. Doing that first also keeps ``timestamp()`` off
+ the platform's local-time conversion, which fails outright on Windows for
+ pre-epoch dates.
+ """
+ if committed_at is None:
+ return 0.0
+ from datetime import UTC
+
+ if committed_at.tzinfo is None:
+ committed_at = committed_at.replace(tzinfo=UTC)
+ return committed_at.timestamp()
+
+
+def _recompute_commit_experience(stored: list[dict]) -> list[dict]:
+ """Rows whose experience or risk moved, as partial upserts keyed by sha.
+
+ Pure, so the ordering and re-scoring can be tested without a database.
+ Emits only changed rows: on a settled index that is a handful, which keeps a
+ whole-table read from turning into a whole-table write every update.
+ """
+ from repowise.core.analysis.change_risk import change_features_from_stored, score_change
+ from repowise.core.ingestion.git_indexer.commit_rows import author_experience_by_sha
+
+ exp_by_sha = author_experience_by_sha(
+ [
+ {
+ "sha": r["sha"],
+ "author_name": r["author_name"] or "",
+ "author_email": r["author_email"] or "",
+ # committed_at is the only ordering key the table stores; rows
+ # without one sort oldest, which is where an unknown date least
+ # disturbs everyone else's running count.
+ "ts": _committed_ts(r["committed_at"]),
+ }
+ for r in stored
+ ]
+ )
+
+ updates: list[dict] = []
+ for r in stored:
+ exp = exp_by_sha.get(r["sha"], 0)
+ risk = score_change(
+ change_features_from_stored(
+ la=r["lines_added"],
+ ld=r["lines_deleted"],
+ nf=r["files_changed"],
+ nd=r["dirs_changed"],
+ ns=r["subsystems_changed"],
+ entropy=r["entropy"],
+ exp=exp,
+ is_fix=r["is_fix"],
+ author=r["author_name"],
+ subject=r["subject"],
+ ref=r["sha"],
+ )
+ )
+ unchanged = (
+ r["author_experience"] == exp
+ and r["change_risk_level"] == risk.level
+ and r["change_risk_score"] is not None
+ and abs(r["change_risk_score"] - risk.score) < 1e-9
+ )
+ if unchanged:
+ continue
+ updates.append(
+ {
+ "sha": r["sha"],
+ "author_experience": exp,
+ "change_risk_score": risk.score,
+ "change_risk_level": risk.level,
+ }
+ )
+ return updates
+
+
async def persist_incremental_fix_events(session: Any, repo_id: str, indexer: Any) -> None:
"""Trace + upsert ``fix_events`` for fix commits this index has not seen.
diff --git a/packages/server/src/repowise/server/routers/git.py b/packages/server/src/repowise/server/routers/git.py
index 9b930a9c0..af18a2aa4 100644
--- a/packages/server/src/repowise/server/routers/git.py
+++ b/packages/server/src/repowise/server/routers/git.py
@@ -14,9 +14,9 @@ from sqlalchemy import case, func, select
from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.analysis.change_risk import (
- ChangeFeatures,
RiskNormalizer,
baseline_scores,
+ change_features_from_stored,
extract_range_features,
score_change,
)
@@ -24,6 +24,7 @@ from repowise.core.ingestion.git_indexer._constants import (
EVOLUTION_CATEGORIES,
classify_commit_category,
)
+from repowise.core.ingestion.git_indexer.identity import author_identity_key
from repowise.core.persistence import crud
from repowise.core.persistence.models import GitCommit, GitMetadata, Repository
from repowise.server.deps import get_db_session, verify_api_key
@@ -108,23 +109,38 @@ def _commit_risk(r: GitCommit):
stored ``change_risk_score`` exactly. Returns None for unscored rows."""
if r.change_risk_score is None:
return None
- feats = ChangeFeatures(
- la=r.lines_added or 0,
- ld=r.lines_deleted or 0,
- nf=r.files_changed or 0,
- nd=r.dirs_changed or 0,
- ns=r.subsystems_changed or 0,
- entropy=r.entropy or 0.0,
+ feats = change_features_from_stored(
+ la=r.lines_added,
+ ld=r.lines_deleted,
+ nf=r.files_changed,
+ nd=r.dirs_changed,
+ ns=r.subsystems_changed,
+ entropy=r.entropy,
exp=r.author_experience,
- is_fix=bool(r.is_fix),
- author=r.author_name or "",
- subject=r.subject or "",
+ is_fix=r.is_fix,
+ author=r.author_name,
+ subject=r.subject,
ref=r.sha,
)
return score_change(feats)
-def _commit_fields(r: GitCommit, normalizer: RiskNormalizer) -> dict:
+async def _author_commit_counts(session: AsyncSession, repo_id: str) -> dict[str, int]:
+ """Commits per author in the index, keyed by folded identity.
+
+ One grouped query per request rather than a per-row lookup, and folded in
+ Python so it matches the tally that produced ``author_experience`` exactly.
+ """
+ counts: dict[str, int] = {}
+ for name, email, count in await crud.get_author_commit_counts(session, repo_id):
+ key = author_identity_key(name, email)
+ counts[key] = counts.get(key, 0) + int(count or 0)
+ return counts
+
+
+def _commit_fields(
+ r: GitCommit, normalizer: RiskNormalizer, author_counts: dict[str, int] | None = None
+) -> dict:
"""Shared CommitResponse field map (raw row + repo-relative normalization)."""
risk = _commit_risk(r)
top_driver = risk.top_drivers[0].label if risk and risk.top_drivers else None
@@ -148,17 +164,26 @@ def _commit_fields(r: GitCommit, normalizer: RiskNormalizer) -> dict:
"review_priority": normalizer.priority(r.change_risk_score),
"top_driver": top_driver,
"author_experience": r.author_experience,
+ "author_commit_count": (
+ author_counts.get(author_identity_key(r.author_name, r.author_email))
+ if author_counts is not None
+ else None
+ ),
"agent_name": r.agent_name,
"agent_autonomy_tier": r.agent_autonomy_tier,
"agent_confidence": r.agent_confidence,
}
-def _commit_from_row(r: GitCommit, normalizer: RiskNormalizer) -> CommitResponse:
- return CommitResponse(**_commit_fields(r, normalizer))
+def _commit_from_row(
+ r: GitCommit, normalizer: RiskNormalizer, author_counts: dict[str, int] | None = None
+) -> CommitResponse:
+ return CommitResponse(**_commit_fields(r, normalizer, author_counts))
-def _commit_detail_from_row(r: GitCommit, normalizer: RiskNormalizer) -> CommitDetailResponse:
+def _commit_detail_from_row(
+ r: GitCommit, normalizer: RiskNormalizer, author_counts: dict[str, int] | None = None
+) -> CommitDetailResponse:
"""Map a commit row to its detail view, recomputing the risk-driver
breakdown from the persisted Kamei features + author experience.
@@ -177,7 +202,7 @@ def _commit_detail_from_row(r: GitCommit, normalizer: RiskNormalizer) -> CommitD
for d in (risk.top_drivers if risk else [])
]
return CommitDetailResponse(
- **_commit_fields(r, normalizer),
+ **_commit_fields(r, normalizer, author_counts),
drivers=drivers,
agent_channel=r.agent_channel,
)
@@ -205,7 +230,8 @@ async def get_commits(
session, repo_id, limit=limit, offset=offset, sort=sort, authorship=authorship
)
normalizer = RiskNormalizer.from_scores(await crud.get_commit_risk_scores(session, repo_id))
- items = [_commit_from_row(r, normalizer) for r in rows]
+ author_counts = await _author_commit_counts(session, repo_id)
+ items = [_commit_from_row(r, normalizer, author_counts) for r in rows]
next_offset = offset + limit if offset + limit < total else None
return Paginated[CommitResponse](
items=items,
@@ -426,7 +452,8 @@ async def get_commit(
if row is None:
raise HTTPException(status_code=404, detail="Commit not found")
normalizer = RiskNormalizer.from_scores(await crud.get_commit_risk_scores(session, repo_id))
- return _commit_detail_from_row(row, normalizer)
+ author_counts = await _author_commit_counts(session, repo_id)
+ return _commit_detail_from_row(row, normalizer, author_counts)
@router.get("/{repo_id}/git-metadata", response_model=GitMetadataResponse)
diff --git a/packages/server/src/repowise/server/schemas/git.py b/packages/server/src/repowise/server/schemas/git.py
index e1d240a25..9eb6890f9 100644
--- a/packages/server/src/repowise/server/schemas/git.py
+++ b/packages/server/src/repowise/server/schemas/git.py
@@ -185,9 +185,16 @@ class CommitResponse(BaseModel):
# open every detail sheet. Recomputed deterministically from the stored
# Kamei features; None when the commit was never risk-scored.
top_driver: str | None = None
- # Cumulative prior-commit count at commit time. Low values flag a
- # new-to-this-repo contributor.
+ # Cumulative prior-commit count at commit time, counted over the indexed
+ # history. A change-risk feature, so it is reported as-is; it is not a
+ # verdict on the author, since the window's oldest commits necessarily
+ # start everyone near zero.
author_experience: int | None = None
+ # How many commits this author has in the indexed history, total. Unlike
+ # author_experience this does not depend on where in the window the commit
+ # sits, which is what makes it safe to draw a "new contributor" conclusion
+ # from. Identities are folded, so noreply variants of one person count once.
+ author_commit_count: int | None = None
# Agent provenance (deterministic local-git attribution channels).
# agent_name is None for human-authored commits.
agent_name: str | None = None
diff --git a/packages/types/src/git.ts b/packages/types/src/git.ts
index 6cceb55d2..9a3c69046 100644
--- a/packages/types/src/git.ts
+++ b/packages/types/src/git.ts
@@ -144,6 +144,8 @@ export interface Commit {
/** Author's cumulative prior-commit count at the time of the commit.
* Low values flag a new-to-this-repo contributor. */
author_experience?: number | null;
+ /** Commits by this author across the indexed history (identities folded). */
+ author_commit_count?: number | null;
/** Coding-agent attribution (deterministic local-git channels).
* Null/undefined for human-authored commits. */
agent_name?: string | null;
diff --git a/packages/ui/src/commits/agent-badge.tsx b/packages/ui/src/commits/agent-badge.tsx
index 9c0c2050c..9f0e7d90f 100644
--- a/packages/ui/src/commits/agent-badge.tsx
+++ b/packages/ui/src/commits/agent-badge.tsx
@@ -39,12 +39,29 @@ export function AgentBadge({ agentName, tier, confidence, className }: AgentBadg
);
}
-/** "New contributor" marker — low cumulative prior-commit count at commit time. */
-export function NewContributorBadge({ experience }: { experience: number }) {
+/** At or below this many commits in the index, an author reads as new. */
+const NEW_CONTRIBUTOR_MAX_COMMITS = 2;
+
+/**
+ * Whether a commit's author is new to this repo.
+ *
+ * Keyed on the author's total commits in the index, not on `author_experience`
+ * (their running count at commit time). Experience necessarily starts near zero
+ * for everyone at the old edge of the indexed window, so gating on it labels the
+ * repo's most prolific author a newcomer on their oldest indexed commits. A
+ * total does not move with position in the window. Agent-authored commits are
+ * excluded by the callers, which show provenance instead.
+ */
+export function isNewContributor(commitCount: number | null | undefined): boolean {
+ return commitCount != null && commitCount <= NEW_CONTRIBUTOR_MAX_COMMITS;
+}
+
+/** "New contributor" marker — few commits by this author across the index. */
+export function NewContributorBadge({ commitCount }: { commitCount: number }) {
return (
<span
className="inline-flex shrink-0 items-center rounded-md bg-[var(--color-caution)]/15 px-1.5 py-0.5 text-[10px] font-medium text-[var(--color-caution)]"
- title={`Author had ${experience} prior commit${experience === 1 ? "" : "s"} in this repo at the time`}
+ title={`Author has ${commitCount} commit${commitCount === 1 ? "" : "s"} in the indexed history`}
>
new contributor
</span>
diff --git a/packages/ui/src/commits/commit-detail-card.tsx b/packages/ui/src/commits/commit-detail-card.tsx
index 155eca543..588331af8 100644
--- a/packages/ui/src/commits/commit-detail-card.tsx
+++ b/packages/ui/src/commits/commit-detail-card.tsx
@@ -1,5 +1,5 @@
import { Bug, GitCommitHorizontal, User } from "lucide-react";
-import { AgentBadge, NewContributorBadge } from "./agent-badge";
+import { AgentBadge, NewContributorBadge, isNewContributor } from "./agent-badge";
import { PriorityBadge } from "./priority-badge";
import { RiskDriverBreakdown } from "./risk-driver-breakdown";
import { formatDateTime, formatLOC } from "../lib/format";
@@ -55,7 +55,7 @@ function riskSummary(c: CommitDetail): string {
}
}
- if (c.author_experience != null && c.author_experience < 3) {
+ if (isNewContributor(c.author_commit_count)) {
out += " The author is new to this code.";
}
return out;
@@ -119,11 +119,9 @@ export function CommitDetailCard({ commit, className }: CommitDetailCardProps) {
confidence={c.agent_confidence}
/>
)}
- {!c.agent_name &&
- c.author_experience != null &&
- c.author_experience < 3 && (
- <NewContributorBadge experience={c.author_experience} />
- )}
+ {!c.agent_name && isNewContributor(c.author_commit_count) && (
+ <NewContributorBadge commitCount={c.author_commit_count as number} />
+ )}
{c.committed_at && <span>{formatDateTime(c.committed_at)}</span>}
</div>
{c.agent_name && c.agent_channel && (
@@ -195,7 +193,7 @@ export function CommitDetailCard({ commit, className }: CommitDetailCardProps) {
<Stat
label="Author exp"
value={String(c.author_experience)}
- title="The author's cumulative prior-commit count at the time of this commit"
+ title="The author's prior commits at the time of this commit, counted across the indexed history"
/>
)}
</div>
diff --git a/packages/ui/src/commits/commit-table.tsx b/packages/ui/src/commits/commit-table.tsx
index 1a83cb3a8..41b3de4d0 100644
--- a/packages/ui/src/commits/commit-table.tsx
+++ b/packages/ui/src/commits/commit-table.tsx
@@ -2,7 +2,7 @@
import { useMemo, useState } from "react";
import { Bug, Search } from "lucide-react";
-import { AgentBadge, NewContributorBadge } from "./agent-badge";
+import { AgentBadge, NewContributorBadge, isNewContributor } from "./agent-badge";
import { PriorityBadge } from "./priority-badge";
import { ChurnBar } from "../git/churn-bar";
import { Input } from "../ui/input";
@@ -16,9 +16,6 @@ import type { Commit, ReviewPriority } from "@repowise-dev/types/git";
export type CommitSort = "risk" | "date";
export type CommitAuthorship = "all" | "human" | "agent";
-/** Below this many prior commits the author gets a "new contributor" badge. */
-const NEW_CONTRIBUTOR_THRESHOLD = 3;
-
export interface CommitTableProps {
commits: Commit[];
/** Server-driven ordering. `risk` = review-priority order, `date` = recency. */
@@ -74,11 +71,9 @@ const COLUMNS: ResponsiveColumn<CommitRow>[] = [
<div className="flex items-center gap-1.5 min-w-0 text-xs text-[var(--color-text-secondary)]">
<span className="truncate">{c.author_name || "—"}</span>
{c.agent_name && <AgentBadge agentName={c.agent_name} tier={c.agent_autonomy_tier} />}
- {!c.agent_name &&
- c.author_experience != null &&
- c.author_experience < NEW_CONTRIBUTOR_THRESHOLD && (
- <NewContributorBadge experience={c.author_experience} />
- )}
+ {!c.agent_name && isNewContributor(c.author_commit_count) && (
+ <NewContributorBadge commitCount={c.author_commit_count as number} />
+ )}
</div>
),
mobileRender: (c) => c.author_name || "—",
diff --git a/tests/unit/ingestion/test_author_identity.py b/tests/unit/ingestion/test_author_identity.py
index 8109d3720..86e5df579 100644
--- a/tests/unit/ingestion/test_author_identity.py
+++ b/tests/unit/ingestion/test_author_identity.py
@@ -12,7 +12,7 @@ from repowise.core.ingestion.git_indexer import (
build_identity_resolver,
canonicalize_author_email,
)
-from repowise.core.ingestion.git_indexer.commit_rows import _author_key
+from repowise.core.ingestion.git_indexer.identity import author_identity_key
from repowise.server.services.owner_profile import owner_key
@@ -68,9 +68,9 @@ class TestOwnerKey:
class TestCommitExperienceKey:
def test_noreply_variants_share_an_experience_tally(self) -> None:
- assert _author_key("Jane", "[email protected]") == _author_key(
- "Jane", "[email protected]"
- )
+ assert author_identity_key(
+ "Jane", "[email protected]"
+ ) == author_identity_key("Jane", "[email protected]")
class TestIdentityResolver:
diff --git a/tests/unit/ingestion/test_git_commit_rows_integration.py b/tests/unit/ingestion/test_git_commit_rows_integration.py
index 241f199fe..7e9a73894 100644
--- a/tests/unit/ingestion/test_git_commit_rows_integration.py
+++ b/tests/unit/ingestion/test_git_commit_rows_integration.py
@@ -63,6 +63,48 @@ async def test_index_repo_collects_commit_rows(tmp_path) -> None:
assert fix["files_changed"] == 2
+def test_list_reachable_shas_excludes_abandoned_branch_commits(tmp_path) -> None:
+ """Rows for a squash-merged branch have to be prunable.
+
+ An update run while a feature branch is checked out persists that branch's
+ shas. Once it is squash-merged onto main those commits are unreachable and
+ no full index would ever produce them again, so they have to come back as
+ not-reachable or they inflate every commit-level count forever.
+ """
+ import git as gitpython
+
+ repo = gitpython.Repo.init(tmp_path)
+ _commit(repo, tmp_path / "a.py", "x = 1\n", "feat: add a")
+ main = repo.head.commit.hexsha
+
+ repo.git.checkout("-b", "feature")
+ _commit(repo, tmp_path / "b.py", "y = 2\n", "feat: add b")
+ abandoned = repo.head.commit.hexsha
+ repo.git.checkout(main)
+
+ reachable = GitIndexer(tmp_path).list_reachable_shas()
+
+ assert reachable is not None
+ assert main in reachable
+ assert abandoned not in reachable
+
+
+def test_list_reachable_shas_returns_none_on_a_shallow_clone(tmp_path) -> None:
+ """Unknown history must never be read as "these rows are orphans"."""
+ import git as gitpython
+
+ origin_path = tmp_path / "origin"
+ origin_path.mkdir()
+ origin = gitpython.Repo.init(origin_path)
+ _commit(origin, origin_path / "a.py", "x = 1\n", "feat: add a")
+ _commit(origin, origin_path / "b.py", "y = 2\n", "feat: add b")
+
+ clone_path = tmp_path / "shallow"
+ gitpython.Repo.clone_from(origin_path.as_uri(), clone_path, depth=1)
+
+ assert GitIndexer(clone_path).list_reachable_shas() is None
+
+
@pytest.mark.asyncio
async def test_capture_new_commit_rows_bounds_by_since_ts(tmp_path) -> None:
"""The incremental capture walks the same commit index but drops commits at
diff --git a/tests/unit/persistence/test_commit_experience_reconcile.py b/tests/unit/persistence/test_commit_experience_reconcile.py
new file mode 100644
index 000000000..f739431a6
--- /dev/null
+++ b/tests/unit/persistence/test_commit_experience_reconcile.py
@@ -0,0 +1,227 @@
+"""Update-time repair of persisted ``author_experience`` + change-risk.
+
+The bug these cover: ``build_commit_rows`` tallies author experience over only
+the commits it is handed. An update hands it the commits newer than the last one
+persisted, so every author's count restarts at zero and their commits persist as
+if a first-timer wrote them — including the ``change_risk_score``, which takes
+experience as a feature.
+"""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime
+
+import pytest
+
+from repowise.core.analysis.change_risk import change_features_from_stored, score_change
+from repowise.core.persistence.crud import (
+ get_git_commits,
+ upsert_git_commits_bulk,
+)
+from repowise.core.pipeline.incremental import (
+ _recompute_commit_experience,
+ reconcile_commit_experience,
+)
+from tests.unit.persistence.helpers import insert_repo
+
+
+def _stored(sha: str, *, ts: int, email: str = "ann@x", exp: int | None = 0, **over) -> dict:
+ """A persisted ``git_commits`` row as ``get_commit_experience_inputs`` returns it."""
+ base = {
+ "sha": sha,
+ "author_name": "Ann",
+ "author_email": email,
+ "committed_at": datetime.fromtimestamp(ts, tz=UTC),
+ "subject": f"commit {sha}",
+ "lines_added": 10,
+ "lines_deleted": 2,
+ "files_changed": 3,
+ "dirs_changed": 1,
+ "subsystems_changed": 1,
+ "entropy": 0.5,
+ "is_fix": False,
+ "author_experience": exp,
+ "change_risk_score": 5.0,
+ "change_risk_level": "moderate",
+ }
+ base.update(over)
+ return base
+
+
+def test_batch_local_experience_is_repaired_across_the_whole_history() -> None:
+ """The regression: three updates, each of which restarted the tally at zero."""
+ stored = [
+ # First index: correct within its own batch.
+ _stored("a1", ts=100, exp=0),
+ _stored("a2", ts=200, exp=1),
+ # Second update batch: restarted at zero.
+ _stored("a3", ts=300, exp=0),
+ _stored("a4", ts=400, exp=1),
+ # Third update batch: restarted again.
+ _stored("a5", ts=500, exp=0),
+ ]
+
+ updates = {u["sha"]: u["author_experience"] for u in _recompute_commit_experience(stored)}
+
+ assert updates["a3"] == 2
+ assert updates["a4"] == 3
+ assert updates["a5"] == 4
+
+
+def test_noreply_identities_fold_into_one_tally() -> None:
+ """Both GitHub noreply forms of one login are the same person.
+
+ Squash-merges through the GitHub UI stamp the numeric-id form, so an author
+ whose commits arrive by both routes would otherwise split into two tallies
+ and stay permanently under the "new contributor" line. Folding to a real
+ address is deliberately out of scope (see ``git_indexer.identity``), so
+ ``ann@x`` below is a genuinely separate bucket, not an oversight.
+ """
+ stored = [
+ _stored("n1", ts=100, email="[email protected]"),
+ _stored("n2", ts=200, email="[email protected]"),
+ _stored("n3", ts=300, email="[email protected]"),
+ _stored("plain", ts=400, email="ann@x"),
+ ]
+
+ updates = {u["sha"]: u["author_experience"] for u in _recompute_commit_experience(stored)}
+
+ assert updates["n2"] == 1
+ assert updates["n3"] == 2
+ assert updates["plain"] == 0
+
+
+def test_distinct_authors_keep_separate_tallies() -> None:
+ stored = [
+ _stored("a1", ts=100, email="ann@x"),
+ _stored("b1", ts=200, email="bob@x"),
+ _stored("a2", ts=300, email="ann@x"),
+ _stored("b2", ts=400, email="bob@x"),
+ ]
+
+ updates = {u["sha"]: u["author_experience"] for u in _recompute_commit_experience(stored)}
+
+ assert updates["a2"] == 1
+ assert updates["b2"] == 1
+
+
+def test_risk_score_is_rescored_to_match_the_corrected_experience() -> None:
+ """A corrected experience with a stale score would just hide the error."""
+ stored = [_stored("a1", ts=100, exp=0), _stored("a2", ts=200, exp=0)]
+
+ updates = {u["sha"]: u for u in _recompute_commit_experience(stored)}
+
+ row = stored[1]
+ expected = score_change(
+ change_features_from_stored(
+ la=row["lines_added"],
+ ld=row["lines_deleted"],
+ nf=row["files_changed"],
+ nd=row["dirs_changed"],
+ ns=row["subsystems_changed"],
+ entropy=row["entropy"],
+ exp=1,
+ is_fix=row["is_fix"],
+ author=row["author_name"],
+ subject=row["subject"],
+ ref=row["sha"],
+ )
+ )
+ assert updates["a2"]["change_risk_score"] == expected.score
+ assert updates["a2"]["change_risk_level"] == expected.level
+
+
+def test_settled_index_produces_no_writes() -> None:
+ """A whole-table read must not turn into a whole-table write every update."""
+ stored = [_stored("a1", ts=100, exp=0), _stored("a2", ts=200, exp=1)]
+ # Give both rows the score their features actually imply.
+ for row, exp in ((stored[0], 0), (stored[1], 1)):
+ risk = score_change(
+ change_features_from_stored(
+ la=row["lines_added"],
+ ld=row["lines_deleted"],
+ nf=row["files_changed"],
+ nd=row["dirs_changed"],
+ ns=row["subsystems_changed"],
+ entropy=row["entropy"],
+ exp=exp,
+ is_fix=row["is_fix"],
+ author=row["author_name"],
+ subject=row["subject"],
+ ref=row["sha"],
+ )
+ )
+ row["change_risk_score"] = risk.score
+ row["change_risk_level"] = risk.level
+
+ assert _recompute_commit_experience(stored) == []
+
+
+def test_rows_without_a_timestamp_sort_oldest() -> None:
+ stored = [_stored("dated", ts=100, exp=9), _stored("undated", ts=0, committed_at=None, exp=9)]
+
+ updates = {u["sha"]: u["author_experience"] for u in _recompute_commit_experience(stored)}
+
+ assert updates["undated"] == 0
+ assert updates["dated"] == 1
+
+
+class _FakeIndexer:
+ """Stands in for ``GitIndexer``, whose only role here is reachability."""
+
+ def __init__(self, reachable: set[str] | None) -> None:
+ self._reachable = reachable
+
+ def list_reachable_shas(self) -> set[str] | None:
+ return self._reachable
+
+
+async def test_reconcile_repairs_persisted_rows(async_session) -> None:
+ repo = await insert_repo(async_session)
+ rows = [
+ _stored("a1", ts=100, exp=0),
+ _stored("a2", ts=200, exp=0), # wrong: written by a later update batch
+ _stored("a3", ts=300, exp=1), # wrong for the same reason
+ ]
+ await upsert_git_commits_bulk(async_session, repo.id, rows)
+
+ await reconcile_commit_experience(async_session, repo.id, _FakeIndexer({"a1", "a2", "a3"}))
+
+ stored = {r.sha: r for r in await get_git_commits(async_session, repo.id, sort="date")}
+ assert stored["a1"].author_experience == 0
+ assert stored["a2"].author_experience == 1
+ assert stored["a3"].author_experience == 2
+
+
+async def test_reconcile_prunes_commits_unreachable_from_head(async_session) -> None:
+ """Squash-merged branch commits inflate every count until they are dropped."""
+ repo = await insert_repo(async_session)
+ await upsert_git_commits_bulk(
+ async_session,
+ repo.id,
+ [_stored("keep1", ts=100), _stored("orphan", ts=200), _stored("keep2", ts=300)],
+ )
+
+ await reconcile_commit_experience(async_session, repo.id, _FakeIndexer({"keep1", "keep2"}))
+
+ stored = {r.sha: r for r in await get_git_commits(async_session, repo.id, sort="date")}
+ assert set(stored) == {"keep1", "keep2"}
+ # The orphan must not have contributed to the surviving tally.
+ assert stored["keep2"].author_experience == 1
+
+
+async def test_reconcile_never_prunes_when_reachability_is_unknown(async_session) -> None:
+ """Shallow clone or failed git: repair experience, but delete nothing."""
+ repo = await insert_repo(async_session)
+ await upsert_git_commits_bulk(
+ async_session, repo.id, [_stored("a1", ts=100), _stored("a2", ts=200)]
+ )
+
+ await reconcile_commit_experience(async_session, repo.id, _FakeIndexer(None))
+
+ stored = {r.sha: r for r in await get_git_commits(async_session, repo.id, sort="date")}
+ assert set(stored) == {"a1", "a2"}
+ assert stored["a2"].author_experience == 1
diff --git a/tests/unit/persistence/test_git_commits_crud.py b/tests/unit/persistence/test_git_commits_crud.py
index 3e7edba92..adfb72542 100644
--- a/tests/unit/persistence/test_git_commits_crud.py
+++ b/tests/unit/persistence/test_git_commits_crud.py
@@ -9,6 +9,9 @@ import pytest
from repowise.core.persistence.crud import (
count_git_commits,
delete_git_commits,
+ delete_git_commits_by_sha,
+ get_author_commit_counts,
+ get_commit_experience_inputs,
get_commit_risk_scores,
get_git_commit,
get_git_commits,
@@ -152,6 +155,68 @@ async def test_author_experience_round_trips(async_session) -> None:
assert got.author_experience == 42
+async def test_delete_git_commits_by_sha(async_session) -> None:
+ repo = await insert_repo(async_session)
+ await upsert_git_commits_bulk(
+ async_session,
+ repo.id,
+ [_row(s, risk=1.0, ts=1000) for s in ("keep", "drop1", "drop2")],
+ )
+ await async_session.commit()
+
+ removed = await delete_git_commits_by_sha(async_session, repo.id, ["drop1", "drop2"])
+ await async_session.commit()
+
+ assert removed == 2
+ assert await count_git_commits(async_session, repo.id) == 1
+ assert await get_git_commit(async_session, repo.id, "keep") is not None
+
+
+async def test_get_author_commit_counts_groups_raw_identities(async_session) -> None:
+ """Grouped raw, because the identity fold lives in the git-indexer."""
+ repo = await insert_repo(async_session)
+ await upsert_git_commits_bulk(
+ async_session,
+ repo.id,
+ [
+ _row("a1", risk=1.0, ts=1000),
+ _row("a2", risk=1.0, ts=2000),
+ _row("b1", risk=1.0, ts=3000, author_name="Bob", author_email="bob@x"),
+ ],
+ )
+ await async_session.commit()
+
+ counts = {
+ (name, email): n
+ for name, email, n in await get_author_commit_counts(async_session, repo.id)
+ }
+
+ assert counts[("Ann", "ann@x")] == 2
+ assert counts[("Bob", "bob@x")] == 1
+
+
+async def test_get_commit_experience_inputs_carries_the_scoring_features(async_session) -> None:
+ repo = await insert_repo(async_session)
+ await upsert_git_commits_bulk(
+ async_session, repo.id, [_row("a1", risk=6.0, ts=1000, author_experience=7)]
+ )
+ await async_session.commit()
+
+ rows = await get_commit_experience_inputs(async_session, repo.id)
+
+ assert len(rows) == 1
+ row = rows[0]
+ # Everything score_change needs, so the reconcile never has to touch git.
+ assert row["sha"] == "a1"
+ assert row["author_experience"] == 7
+ assert row["lines_added"] == 10
+ assert row["entropy"] == 0.5
+ assert row["change_risk_score"] == 6.0
+
+
@pytest.mark.asyncio
async def test_delete_git_commits(async_session) -> None:
repo = await insert_repo(async_session)
diff --git a/tests/unit/server/test_git.py b/tests/unit/server/test_git.py
index 6e6a01c96..c1c5aa614 100644
--- a/tests/unit/server/test_git.py
+++ b/tests/unit/server/test_git.py
@@ -271,9 +271,7 @@ async def _insert_agent_commit(session_factory, repo_id: str) -> None:
@pytest.mark.asyncio
-async def test_commits_carry_agent_provenance_and_top_driver(
- client: AsyncClient, app
-) -> None:
+async def test_commits_carry_agent_provenance_and_top_driver(client: AsyncClient, app) -> None:
repo = await create_test_repo(client)
await _insert_git_commits(app.state.session_factory, repo["id"])
await _insert_agent_commit(app.state.session_factory, repo["id"])
@@ -296,22 +294,47 @@ async def test_commits_carry_agent_provenance_and_top_driver(
assert detail.json()["agent_channel"] == "git_footer"
+async def test_commits_carry_the_author_total_behind_the_new_contributor_badge(
+ client: AsyncClient, app
+) -> None:
+ """The badge keys on this, not on ``author_experience``.
+
+ Experience is a running count, so it is near zero for everyone at the old
+ edge of the indexed window; a total does not move with a commit's position
+ in it. Ann's three commits must all report 3, including her earliest.
+ """
+ repo = await create_test_repo(client)
+ await _insert_git_commits(app.state.session_factory, repo["id"])
+ await _insert_agent_commit(app.state.session_factory, repo["id"])
+
+ resp = await client.get(f"/api/repos/{repo['id']}/commits", params={"sort": "date"})
+ assert resp.status_code == 200
+ items = {c["short_sha"]: c for c in resp.json()["items"]}
+
+ assert items["aaaaaaaa"]["author_commit_count"] == 3
+ assert items["bbbbbbbb"]["author_commit_count"] == 3
+ assert items["cccccccc"]["author_commit_count"] == 3
+ # A different author with a single commit is the genuine new contributor.
+ assert items["dddddddd"]["author_commit_count"] == 1
+
+ detail = await client.get(f"/api/repos/{repo['id']}/commits/aaaaaaaa")
+ assert detail.status_code == 200
+ assert detail.json()["author_commit_count"] == 3
+
+
@pytest.mark.asyncio
async def test_commits_authorship_filter(client: AsyncClient, app) -> None:
repo = await create_test_repo(client)
await _insert_git_commits(app.state.session_factory, repo["id"])
await _insert_agent_commit(app.state.session_factory, repo["id"])
- agents = await client.get(
- f"/api/repos/{repo['id']}/commits", params={"authorship": "agent"}
- )
+ agents = await client.get(f"/api/repos/{repo['id']}/commits", params={"authorship": "agent"})
assert agents.status_code == 200
assert agents.json()["total"] == 1
assert agents.json()["items"][0]["agent_name"] == "claude-code"
- humans = await client.get(
- f"/api/repos/{repo['id']}/commits", params={"authorship": "human"}
- )
+ humans = await client.get(f"/api/repos/{repo['id']}/commits", params={"authorship": "human"})
assert humans.json()["total"] == 3
assert all(c["agent_name"] is None for c in humans.json()["items"])
@@ -339,9 +362,7 @@ async def test_commit_stats_risk_histogram(client: AsyncClient, app) -> None:
@pytest.mark.asyncio
-async def test_commit_stats_histogram_empty_without_scores(
- client: AsyncClient, app
-) -> None:
+async def test_commit_stats_histogram_empty_without_scores(client: AsyncClient, app) -> None:
repo = await create_test_repo(client)
resp = await client.get(f"/api/repos/{repo['id']}/commits/stats")