Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(commits): store which files each commit touched (#2459)
Raghav Chamadiya7a300697ef71
diff --git a/packages/api-client/src/types/git.ts b/packages/api-client/src/types/git.tsindex a600ef4c8..8fd9174e9 100644--- a/packages/api-client/src/types/git.ts+++ b/packages/api-client/src/types/git.ts@@ -141,9 +141,19 @@ export interface RiskDriverResponse {label: string;}+/** One file a commit touched, with what it cost and what it carries. */+export interface CommitFileResponse {+ path: string;+ lines_added: number;+ lines_deleted: number;+ /** Bug-fix commits recorded against this path; null when untracked. */+ prior_fixes?: number | null;+}+export interface CommitDetailResponse extends CommitResponse {drivers: RiskDriverResponse[];agent_channel?: string | null;+ files?: CommitFileResponse[];}export interface AgentTrendBucket {diff --git a/packages/core/alembic/versions/0074_git_commit_files.py b/packages/core/alembic/versions/0074_git_commit_files.pynew file mode 100644index 000000000..c70042a92--- /dev/null+++ b/packages/core/alembic/versions/0074_git_commit_files.py@@ -0,0 +1,61 @@+"""``git_commit_files``: one row per commit x file, with that file's churn.++``git_commits`` keeps only the Kamei aggregates the change-risk model reads, so+every per-commit surface had to shell out to git to answer "which files?" — and+a server with no checkout could not answer at all. The rows come free: the+commit walk already parses ``git log --numstat`` per commit and throws the+per-file tuples away once the aggregates are derived.++No change-type column. ``--numstat`` gives paths and line counts only, so+add / modify / delete / rename cannot be separated without a second git pass.++New table only — no existing table is touched, so a pre-0074 wiki.db upgrades+without rewriting anything and reads an empty table until the next index.++Revision ID: 0074+Revises: 0073+Create Date: 2026-09-20+"""++from __future__ import annotations++from collections.abc import Sequence++import sqlalchemy as sa+from alembic import op++# revision identifiers+revision: str = "0074"+down_revision: str | None = "0073"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None+++def upgrade() -> None:+ op.create_table(+ "git_commit_files",+ sa.Column("id", sa.String(32), primary_key=True),+ sa.Column(+ "repository_id",+ sa.String(32),+ sa.ForeignKey("repositories.id", ondelete="CASCADE"),+ nullable=False,+ ),+ sa.Column("sha", sa.String(40), nullable=False),+ sa.Column("file_path", sa.Text, nullable=False),+ sa.Column("lines_added", sa.Integer, nullable=False, server_default="0"),+ sa.Column("lines_deleted", sa.Integer, nullable=False, server_default="0"),+ sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),+ sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),+ sa.UniqueConstraint("repository_id", "sha", "file_path", name="uq_git_commit_file"),+ )+ op.create_index("ix_git_commit_files_repo_sha", "git_commit_files", ["repository_id", "sha"])+ op.create_index(+ "ix_git_commit_files_repo_path", "git_commit_files", ["repository_id", "file_path"]+ )+++def downgrade() -> None:+ op.drop_index("ix_git_commit_files_repo_path", table_name="git_commit_files")+ op.drop_index("ix_git_commit_files_repo_sha", table_name="git_commit_files")+ op.drop_table("git_commit_files")diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/commit_rows.py b/packages/core/src/repowise/core/ingestion/git_indexer/commit_rows.pyindex cdbca277d..86c18b24e 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@@ -134,3 +134,40 @@ def build_commit_rows(parsed_commits: list[dict]) -> list[dict]:})return rows+++def _file_rows_for(sha: str, changes: list) -> list[dict]:+ """One row per distinct path in *changes*.++ numstat can repeat a path (a split rename pair); (sha, path) is the natural+ key, so fold rather than let the upsert pick one arbitrarily.+ """+ seen: set[str] = set()+ rows: list[dict] = []+ for path, added, deleted in changes:+ if not path or path in seen:+ continue+ seen.add(path)+ rows.append(+ {+ "sha": sha,+ "file_path": path,+ "lines_added": max(int(added or 0), 0),+ "lines_deleted": max(int(deleted or 0), 0),+ }+ )+ return rows+++def build_commit_file_rows(parsed_commits: list[dict]) -> list[dict]:+ """Build ``git_commit_files`` rows from the same sunk records.++ The per-file detail ``build_commit_rows`` aggregates away. Same input, same+ walk, so the two must always be built from one batch.+ """+ return [+ row+ for c in parsed_commits+ if c.get("sha")+ for row in _file_rows_for(c["sha"], c.get("changes") or [])+ ]diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py b/packages/core/src/repowise/core/ingestion/git_indexer/indexer.pyindex 18e2f76bb..eda01013e 100644--- a/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py+++ b/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py@@ -425,13 +425,19 @@ class GitIndexer:# in rename-tracking mode (no batched commit index) and failure-isolated# so a change_risk hiccup never breaks file-level git metadata.commit_rows: list[dict] = []+ commit_file_rows: list[dict] = []if commit_sink:try:- from .commit_rows import build_commit_rows+ from .commit_rows import build_commit_file_rows, build_commit_rows- commit_rows = build_commit_rows(commit_sink)+ built = build_commit_rows(commit_sink)+ built_files = build_commit_file_rows(commit_sink)except Exception as exc:logger.debug("commit_rows_build_failed", error=str(exc))+ else:+ # Assigned together: a half-built pair would write commits+ # whose file detail describes a different set.+ commit_rows, commit_file_rows = built, built_filesduration = time.monotonic() - starthotspots = sum(1 for m in results if m.get("is_hotspot", False))@@ -443,6 +449,7 @@ class GitIndexer:stable_files=stable,duration_seconds=duration,commit_rows=commit_rows,+ commit_file_rows=commit_file_rows,fix_event_rows=fix_event_rows,fix_oldest_ts=fix_walk.oldest_fix_ts,fix_events_built=built_ok,@@ -817,9 +824,14 @@ class GitIndexer:out[fp] = {"file_path": fp, **{k: meta[k] for k in DECAY_REFRESH_KEYS}}return out- def capture_new_commit_rows(self, *, since_ts: int | None = None) -> list[dict]:+ def capture_new_commit_rows(+ self, *, since_ts: int | None = None, file_rows_sink: list[dict] | None = None+ ) -> list[dict]:"""Build ``git_commits`` rows for commits newer than *since_ts*.+ *file_rows_sink*, when given, is extended with the matching+ ``git_commit_files`` rows from the same walk.+The incremental counterpart to the ``commit_sink`` capture on``index_repo``: walks the repo-wide commit index (one ``git log`` pass,bounded to commits newer than the newest already-persisted one) and@@ -837,7 +849,7 @@ class GitIndexer:return []from ..git_commit_index import load_commit_index- from .commit_rows import build_commit_rows+ from .commit_rows import build_commit_file_rows, build_commit_rowssink: list[dict] = []# Empty indexable set: we only want the full-footprint sink, not the@@ -850,7 +862,13 @@ class GitIndexer:since_ts=since_ts,provenance_classifier=self._provenance_classifier(),)- return build_commit_rows(sink)+ rows = build_commit_rows(sink)+ files = build_commit_file_rows(sink)+ # Only after both succeed: the sink is the caller's list, and a+ # partial extend would outlive the failure that caused it.+ if file_rows_sink is not None:+ file_rows_sink.extend(files)+ return rowsexcept Exception as exc:logger.debug("incremental_commit_rows_failed", error=str(exc))return []diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/records.py b/packages/core/src/repowise/core/ingestion/git_indexer/records.pyindex df48afd5c..bd906ade1 100644--- a/packages/core/src/repowise/core/ingestion/git_indexer/records.py+++ b/packages/core/src/repowise/core/ingestion/git_indexer/records.py@@ -215,6 +215,8 @@ class GitIndexSummary:# for ``upsert_git_commits_bulk``. Empty in rename-tracking mode (which uses# the per-file walk instead of the batched commit index).commit_rows: list[dict] = field(default_factory=list)+ # One row per (commit, file), from the same walk as ``commit_rows``.+ commit_file_rows: list[dict] = field(default_factory=list)# Per fix-commit x file rows for ``upsert_fix_events_bulk``, plus the# committer time of the oldest fix the walk saw (unix seconds). The cutoff# rides along so the persist step can prune events that have aged out anddiff --git a/packages/core/src/repowise/core/persistence/crud/_shared.py b/packages/core/src/repowise/core/persistence/crud/_shared.pyindex 01a275fff..f23c88b6a 100644--- a/packages/core/src/repowise/core/persistence/crud/_shared.py+++ b/packages/core/src/repowise/core/persistence/crud/_shared.py@@ -13,7 +13,7 @@ from dataclasses import dataclass, fieldfrom datetime import UTC, datetimefrom typing import Any-from sqlalchemy import select+from sqlalchemy import delete, selectfrom sqlalchemy.ext.asyncio import AsyncSession_VALID_JOB_STATUSES = frozenset(@@ -230,3 +230,29 @@ async def _batch_upsert_keyed(session.add(obj)by_key[key] = objawait session.flush()+++async def _batch_delete_in(+ session: AsyncSession,+ model: Any,+ column: Any,+ values: Iterable[str],+ *,+ prefilter: tuple = (),+) -> int:+ """Delete rows whose *column* is in *values*, chunked past SQLite's limit.++ Returns how many were removed.+ """+ items = list(values)+ removed = 0+ for start in range(0, len(items), _BATCH_SIZE):+ chunk = items[start : start + _BATCH_SIZE]+ if not chunk:+ continue+ result = await session.execute(+ delete(model).where(*prefilter, column.in_(chunk))+ )+ removed += int(result.rowcount or 0)+ await session.flush()+ return removeddiff --git a/packages/core/src/repowise/core/persistence/crud/git.py b/packages/core/src/repowise/core/persistence/crud/git.pyindex e9ccec4f8..f08d53b4f 100644--- a/packages/core/src/repowise/core/persistence/crud/git.py+++ b/packages/core/src/repowise/core/persistence/crud/git.py@@ -15,13 +15,14 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom ..models import (FixEvent,GitCommit,+ GitCommitFile,GitFunctionBlame,GitMetadata,_new_uuid,_now_utc,)from ..sql import LIKE_ESCAPE, escape_like-from ._shared import _BATCH_SIZE, _batch_upsert_keyed+from ._shared import _BATCH_SIZE, _batch_delete_in, _batch_upsert_keyed# ---------------------------------------------------------------------------# GitMetadata CRUD@@ -385,6 +386,76 @@ async def upsert_git_commits_bulk()+def _update_git_commit_file(existing: GitCommitFile, row: dict) -> None:+ for key, val in row.items():+ if key not in ("id", "repository_id", "sha", "file_path") and hasattr(existing, key):+ setattr(existing, key, val)+ existing.updated_at = _now_utc()+++async def upsert_git_commit_files_bulk(+ session: AsyncSession,+ repository_id: str,+ rows: list[dict],+) -> None:+ """Bulk upsert per-commit file rows (keyed on ``repository_id`` + sha + path)."""+ await _batch_upsert_keyed(+ session,+ GitCommitFile,+ rows,+ prefilter=(GitCommitFile.repository_id == repository_id,),+ item_key_fn=lambda row: (row.get("sha", ""), row.get("file_path", "")),+ row_key_fn=lambda row: (row.sha, row.file_path),+ update_fn=_update_git_commit_file,+ insert_fn=lambda row: GitCommitFile(+ id=_new_uuid(),+ repository_id=repository_id,+ **{+ k: v+ for k, v in row.items()+ if k not in ("id", "repository_id") and hasattr(GitCommitFile, k)+ },+ ),+ batch_size=_BATCH_SIZE,+ )+++async def get_commit_files(+ session: AsyncSession, repository_id: str, sha: str+) -> list[GitCommitFile]:+ """The files one commit touched, largest churn first."""+ result = await session.execute(+ select(GitCommitFile)+ .where(GitCommitFile.repository_id == repository_id, GitCommitFile.sha == sha)+ .order_by(+ (GitCommitFile.lines_added + GitCommitFile.lines_deleted).desc(),+ GitCommitFile.file_path,+ )+ )+ return list(result.scalars().all())+++async def delete_git_commit_files(session: AsyncSession, repository_id: str) -> None:+ """Remove all per-commit file rows for a repository (before a clean reindex)."""+ await session.execute(+ delete(GitCommitFile).where(GitCommitFile.repository_id == repository_id)+ )+ await session.flush()+++async def delete_git_commit_files_by_sha(+ session: AsyncSession, repository_id: str, shas: Sequence[str]+) -> int:+ """Drop file rows for specific commits, so they leave with their commit."""+ return await _batch_delete_in(+ session,+ GitCommitFile,+ GitCommitFile.sha,+ shas,+ prefilter=(GitCommitFile.repository_id == repository_id,),+ )++async def get_commits_missing_offset(session: AsyncSession, repository_id: str, *, limit: int = 20_000) -> list[str]:@@ -417,19 +488,13 @@ 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+ return await _batch_delete_in(+ session,+ GitCommit,+ GitCommit.sha,+ shas,+ prefilter=(GitCommit.repository_id == repository_id,),+ )async def get_commit_experience_inputs(session: AsyncSession, repository_id: str) -> list[dict]:diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.pyindex a9fd24991..fed6fa919 100644--- a/packages/core/src/repowise/core/persistence/models.py+++ b/packages/core/src/repowise/core/persistence/models.py@@ -766,6 +766,39 @@ class GitCommit(Base):)+class GitCommitFile(Base):+ """One file a commit touched, and the lines it changed there.++ The per-file detail ``GitCommit`` aggregates away. No change type:+ ``--numstat`` gives paths and counts only.+ """++ __tablename__ = "git_commit_files"+ __table_args__ = (+ UniqueConstraint("repository_id", "sha", "file_path", name="uq_git_commit_file"),+ Index("ix_git_commit_files_repo_sha", "repository_id", "sha"),+ Index("ix_git_commit_files_repo_path", "repository_id", "file_path"),+ )++ id: Mapped[str] = mapped_column(String(32), primary_key=True, default=_new_uuid)+ repository_id: Mapped[str] = mapped_column(+ String(32), ForeignKey("repositories.id", ondelete="CASCADE"), nullable=False+ )+ sha: Mapped[str] = mapped_column(String(40), nullable=False)+ file_path: Mapped[str] = mapped_column(Text, nullable=False)++ # 0/0 is a real answer for a binary file, not missing data.+ lines_added: Mapped[int] = mapped_column(Integer, nullable=False, default=0)+ lines_deleted: Mapped[int] = mapped_column(Integer, nullable=False, default=0)++ created_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), nullable=False, default=_now_utc+ )+ updated_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), nullable=False, default=_now_utc, onupdate=_now_utc+ )++class FixEvent(Base):"""One bug-fix commit's effect on one file, with its bug-introducing candidates.diff --git a/packages/core/src/repowise/core/pipeline/incremental.py b/packages/core/src/repowise/core/pipeline/incremental.pyindex 9f63f2026..3301b85fd 100644--- a/packages/core/src/repowise/core/pipeline/incremental.py+++ b/packages/core/src/repowise/core/pipeline/incremental.py@@ -21,6 +21,7 @@ from __future__ import annotationsimport asynciofrom collections.abc import Callable+from functools import partialfrom pathlib import Pathfrom typing import Any@@ -1352,6 +1353,7 @@ async def persist_incremental_commits(get_latest_commit_committed_at,get_repository,update_repo_git_totals,+ upsert_git_commit_files_bulk,upsert_git_commits_bulk,)from repowise.core.repo_config import load_repo_config@@ -1378,9 +1380,19 @@ async def persist_incremental_commits(dt = newest if newest.tzinfo is not None else newest.replace(tzinfo=UTC)since_ts = int(dt.timestamp())with timed(timings, "persist.commits.capture"):- rows = await asyncio.to_thread(indexer.capture_new_commit_rows, since_ts=since_ts)+ # One walk fills both, so they describe the same commit set.+ file_rows: list[dict] = []+ rows = await asyncio.to_thread(+ partial(+ indexer.capture_new_commit_rows,+ since_ts=since_ts,+ file_rows_sink=file_rows,+ )+ )if rows:await upsert_git_commits_bulk(session, repo_id, rows)+ if file_rows:+ await upsert_git_commit_files_bulk(session, repo_id, file_rows)with timed(timings, "persist.commits.experience"):await reconcile_commit_experience(session, repo_id, indexer)@@ -1466,6 +1478,7 @@ async def reconcile_commit_experience(session: Any, repo_id: str, indexer: Any)failure-isolated like the rest of the git-phase refreshes."""from repowise.core.persistence.crud import (+ delete_git_commit_files_by_sha,delete_git_commits_by_sha,get_commit_experience_inputs,upsert_git_commits_bulk,@@ -1481,6 +1494,8 @@ async def reconcile_commit_experience(session: Any, repo_id: str, indexer: Any)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)+ # File rows leave with their commit; nothing cascades them.+ await delete_git_commit_files_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))diff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.pyindex 187820373..8198b0deb 100644--- a/packages/core/src/repowise/core/pipeline/persist.py+++ b/packages/core/src/repowise/core/pipeline/persist.py@@ -1643,6 +1643,7 @@ async def persist_git(result: Any, session: Any, repo_id: str) -> None:prune_fix_events_before,update_repo_git_totals,upsert_fix_events_bulk,+ upsert_git_commit_files_bulk,upsert_git_commits_bulk,upsert_git_metadata_bulk,)@@ -1657,6 +1658,10 @@ async def persist_git(result: Any, session: Any, repo_id: str) -> None:if commit_rows:await upsert_git_commits_bulk(session, repo_id, commit_rows)+ commit_file_rows = getattr(summary, "commit_file_rows", None)+ if commit_file_rows:+ await upsert_git_commit_files_bulk(session, repo_id, commit_file_rows)+# Per fix-commit x file rows (with their SZZ candidates). The prune keeps a# re-index of an already-indexed repo from leaving behind events that have# since aged out of the defect window.@@ -1712,13 +1717,14 @@ async def replace_git_history(from repowise.core.persistence.models import (FixEvent,GitCommit,+ GitCommitFile,GitMetadata,)# Function blame describes the current source tree and is produced by the# health pass, not by persist_git. Preserve it across a history-window# replacement; scope reconciliation prunes entries for excluded files.- for model in (FixEvent, GitCommit, GitMetadata):+ for model in (FixEvent, GitCommit, GitCommitFile, GitMetadata):await session.execute(delete(model).where(model.repository_id == repo_id))await persist_git(SimpleNamespace(diff --git a/packages/server/src/repowise/server/routers/git.py b/packages/server/src/repowise/server/routers/git.pyindex 54609604a..4e1acefa4 100644--- a/packages/server/src/repowise/server/routers/git.py+++ b/packages/server/src/repowise/server/routers/git.py@@ -10,6 +10,7 @@ from datetime import datetime, timedeltafrom fastapi import APIRouter, Depends, HTTPException, Queryfrom sqlalchemy import case, func, select+from sqlalchemy.exc import OperationalError, ProgrammingErrorfrom sqlalchemy.ext.asyncio import AsyncSessionfrom repowise.core.analysis.change_risk import (@@ -37,6 +38,7 @@ from repowise.core.ingestion.git_indexer._constants import (from repowise.core.ingestion.git_indexer.identity import author_identity_keyfrom repowise.core.persistence import crudfrom repowise.core.persistence.models import GitCommit, GitMetadata, Repository+from repowise.core.persistence.sql import is_missing_tablefrom repowise.server.deps import get_db_session, verify_api_keyfrom repowise.server.mcp_server.tool_risk import _check_test_gapfrom repowise.server.schemas import (@@ -47,6 +49,7 @@ from repowise.server.schemas import (CommitDetailResponse,CommitEvolutionBucket,CommitEvolutionResponse,+ CommitFileResponse,CommitResponse,CommitStatsResponse,FixHistoryFileResponse,@@ -193,8 +196,35 @@ def _commit_from_row(return CommitResponse(**_commit_fields(r, normalizer, author_counts))+async def _commit_files(session: AsyncSession, repo_id: str, sha: str) -> list[CommitFileResponse]:+ """The files a commit touched. Stored, so it answers without a checkout."""+ try:+ rows = await crud.get_commit_files(session, repo_id, sha)+ except (OperationalError, ProgrammingError) as exc:+ # An index older than the table: serve the commit without its files+ # rather than failing the whole detail view.+ if not is_missing_table(exc):+ raise+ return []+ if not rows:+ return []+ meta = await crud.get_git_metadata_bulk(session, repo_id, [r.file_path for r in rows])+ return [+ CommitFileResponse(+ path=r.file_path,+ lines_added=r.lines_added,+ lines_deleted=r.lines_deleted,+ prior_fixes=getattr(meta.get(r.file_path), "prior_defect_count", None),+ )+ for r in rows+ ]++def _commit_detail_from_row(- r: GitCommit, normalizer: RiskNormalizer, author_counts: dict[str, int] | None = None+ r: GitCommit,+ normalizer: RiskNormalizer,+ author_counts: dict[str, int] | None = None,+ files: list[CommitFileResponse] | None = None,) -> CommitDetailResponse:"""Map a commit row to its detail view, recomputing the risk-driverbreakdown from the persisted Kamei features + author experience.@@ -217,6 +247,7 @@ def _commit_detail_from_row(**_commit_fields(r, normalizer, author_counts),drivers=drivers,agent_channel=r.agent_channel,+ files=files or [],)@@ -479,7 +510,8 @@ async def get_commit(raise HTTPException(status_code=404, detail="Commit not found")normalizer = RiskNormalizer.from_scores(await crud.get_commit_risk_scores(session, repo_id))author_counts = await _author_commit_counts(session, repo_id)- return _commit_detail_from_row(row, normalizer, author_counts)+ files = await _commit_files(session, repo_id, row.sha)+ return _commit_detail_from_row(row, normalizer, author_counts, files)@router.get("/{repo_id}/git-metadata", response_model=GitMetadataResponse)diff --git a/packages/server/src/repowise/server/schemas/__init__.py b/packages/server/src/repowise/server/schemas/__init__.pyindex 7df9b874e..ed0e4f939 100644--- a/packages/server/src/repowise/server/schemas/__init__.py+++ b/packages/server/src/repowise/server/schemas/__init__.py@@ -124,6 +124,7 @@ from .git import (CommitDetailResponse,CommitEvolutionBucket,CommitEvolutionResponse,+ CommitFileResponse,CommitResponse,CommitStatsResponse,FixHistoryFileResponse,@@ -339,6 +340,7 @@ __all__ = ["CommitDetailResponse","CommitEvolutionBucket","CommitEvolutionResponse",+ "CommitFileResponse","CommitResponse","CommitStatsResponse","CommunityDetailResponse",diff --git a/packages/server/src/repowise/server/schemas/git.py b/packages/server/src/repowise/server/schemas/git.pyindex 384951234..7185b247a 100644--- a/packages/server/src/repowise/server/schemas/git.py+++ b/packages/server/src/repowise/server/schemas/git.py@@ -232,6 +232,9 @@ class CommitDetailResponse(CommitResponse):drivers: list[RiskDriverResponse] = []agent_channel: str | None = None+ #: Files this commit touched, biggest churn first. Empty on an index+ #: written before per-commit files were captured — re-index to fill it.+ files: list[CommitFileResponse] = []class AgentTrendBucket(BaseModel):@@ -297,6 +300,17 @@ class ChangeFeaturesResponse(BaseModel):exp: int | None+class CommitFileResponse(BaseModel):+ """One file a commit touched, with what it cost and what it carries."""++ path: str+ lines_added: int+ lines_deleted: int+ #: Bug-fix commits recorded against this path. ``None`` when the file is no+ #: longer tracked, which is not the same claim as "never fixed".+ prior_fixes: int | None = None++class FixHistoryFileResponse(BaseModel):"""One changed file's recency-weighted bug-fix record."""diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.tsindex 9a5a3e88a..63a22f4c9 100644--- a/packages/types/src/generated/http.ts+++ b/packages/types/src/generated/http.ts@@ -431,6 +431,7 @@ export interface CommitDetailResponse {agent_confidence?: string | null;drivers?: RiskDriverResponse[];agent_channel?: string | null;+ files?: CommitFileResponse[];}/**@@ -464,6 +465,14 @@ export interface CommitEvolutionResponse {last_commit_at?: string | null;}+/** One file a commit touched, with what it cost and what it carries. */+export interface CommitFileResponse {+ path: string;+ lines_added: number;+ lines_deleted: number;+ prior_fixes?: number | null;+}+/*** One per-commit row from the ``git_commits`` table.*diff --git a/packages/types/src/git.ts b/packages/types/src/git.tsindex 4947f7cbe..632e704b6 100644--- a/packages/types/src/git.ts+++ b/packages/types/src/git.ts@@ -170,11 +170,23 @@ export interface RiskDriver {label: string;}+/** One file a commit touched, with what it cost and what it carries. */+export interface CommitFile {+ path: string;+ lines_added: number;+ lines_deleted: number;+ /** Bug-fix commits recorded against this path; null when untracked. */+ prior_fixes?: number | null;+}+export interface CommitDetail extends Commit {/** Per-feature breakdown, strongest contribution first. */drivers: RiskDriver[];/** Which attribution channel identified the agent (e.g. git footer). */agent_channel?: string | null;+ /** Files this commit touched, biggest churn first. Empty on an index written+ * before per-commit files were captured — re-index to fill it. */+ files?: CommitFile[];}/** One month of agent-vs-human commit volume. */diff --git a/packages/ui/__tests__/commits/commit-detail-card.test.tsx b/packages/ui/__tests__/commits/commit-detail-card.test.tsxindex 8579945b6..7056ec18a 100644--- a/packages/ui/__tests__/commits/commit-detail-card.test.tsx+++ b/packages/ui/__tests__/commits/commit-detail-card.test.tsx@@ -27,13 +27,10 @@ const commit: CommitDetail = {],};-const fixHistory = {- percentile: 89.4,- files: [- { path: "cli/commands/update_cmd/command.py", churn: 19, fix_pressure: 28.71 },- { path: "core/workspace/update.py", churn: 4, fix_pressure: 16.2 },- ],-};+const files = [+ { path: "cli/commands/update_cmd/command.py", lines_added: 15, lines_deleted: 4, prior_fixes: 35 },+ { path: "core/workspace/update.py", lines_added: 3, lines_deleted: 0, prior_fixes: null },+];describe("commit detail card", () => {it("leads with the repo-relative percentile, not a raw score", () => {@@ -44,33 +41,35 @@ describe("commit detail card", () => {expect(screen.queryByText(/Supporting diff-size score/)).toBeNull();});- it("names the files and their bug-fix record when git could score them", () => {- render(<CommitDetailCard commit={commit} fixHistory={fixHistory} />);+ it("names the files and their bug-fix record from the stored index", () => {+ render(<CommitDetailCard commit={{ ...commit, files }} />);++ // The shared table keeps a table and a stacked-card tree in the DOM.+ expect(screen.getAllByText("cli/commands/update_cmd/command.py").length).toBeGreaterThan(0);+ expect(screen.getAllByText("35").length).toBeGreaterThan(0);+ });++ it("marks an untracked file as unknown rather than as never fixed", () => {+ render(<CommitDetailCard commit={{ ...commit, files }} />);- expect(screen.getByText("cli/commands/update_cmd/command.py")).toBeInTheDocument();- expect(screen.getByText("28.7")).toBeInTheDocument();+ expect(screen.getAllByText("—").length).toBeGreaterThan(0);});it("says so when diff shape and fix history disagree", () => {- render(<CommitDetailCard commit={commit} fixHistory={fixHistory} />);+ render(<CommitDetailCard commit={commit} fixPercentile={89.4} />);expect(screen.getByText(/heavy fix record/)).toBeInTheDocument();expect(screen.getByText(/89th percentile/)).toBeInTheDocument();});it("stays silent about the disagreement when the two rankings agree", () => {- render(- <CommitDetailCard- commit={commit}- fixHistory={{ ...fixHistory, percentile: 40 }}- />,- );+ render(<CommitDetailCard commit={commit} fixPercentile={40} />);expect(screen.queryByText(/heavy fix record/)).toBeNull();});- it("renders without the fix block on a server with no checkout", () => {- render(<CommitDetailCard commit={commit} fixHistory={null} />);+ it("renders without the file block on an index that predates it", () => {+ render(<CommitDetailCard commit={commit} />);expect(screen.getByText("36th")).toBeInTheDocument();expect(screen.queryByText(/Where this change lands/)).toBeNull();diff --git a/packages/ui/src/commits/commit-detail-card.tsx b/packages/ui/src/commits/commit-detail-card.tsxindex 6a9018126..37b1a82ec 100644--- a/packages/ui/src/commits/commit-detail-card.tsx+++ b/packages/ui/src/commits/commit-detail-card.tsx@@ -3,7 +3,7 @@ import { AskAboutThis } from "../chat/ask-about-this";import { AgentBadge, NewContributorBadge, isNewContributor } from "./agent-badge";import { PriorityBadge } from "./priority-badge";import { RiskDriverBreakdown, describeDriver } from "./risk-driver-breakdown";-import { FixHistoryTable, type FixHistoryRow } from "./fix-history-table";+import { CommitFilesTable } from "./commit-files-table";import { PageLede } from "../shared/page-lede";import { OverviewSection } from "../overview/section";import { formatDateTime } from "../lib/format";@@ -11,12 +11,9 @@ import type { CommitDetail } from "@repowise-dev/types/git";export interface CommitDetailCardProps {commit: CommitDetail;- /**- * Bug-fix record of the files this commit touched, scored live from git.- * Absent on a server with no checkout, where the sheet falls back to the- * diff-shape reading alone.- */- fixHistory?: { files: FixHistoryRow[]; percentile: number | null } | null | undefined;+ /** Rank of this change's fix density against recent commits, when a live+ * scorer supplied one. Drives only the reconciliation sentence. */+ fixPercentile?: number | null | undefined;className?: string;}@@ -29,11 +26,11 @@ export interface CommitDetailCardProps {*/export function CommitDetailCard({commit,- fixHistory,+ fixPercentile,className,}: CommitDetailCardProps) {const c = commit;- const fixFiles = fixHistory?.files ?? [];+ const files = c.files ?? [];return (<div className={className}>@@ -96,19 +93,19 @@ export function CommitDetailCard({badge={<PriorityBadge priority={c.review_priority} />}><p>{riskSentence(c)}</p>- {reconcile(c, fixHistory?.percentile ?? null) && (- <p>{reconcile(c, fixHistory?.percentile ?? null)}</p>+ {reconcile(c, fixPercentile ?? null) && (+ <p>{reconcile(c, fixPercentile ?? null)}</p>)}</PageLede></div>- {fixFiles.length > 0 && (+ {files.length > 0 && (<OverviewSectionclassName="mt-7"title="Where this change lands"description="The files this commit touched, and how much bug-fix history each one carries. Unlike the percentile above, this does not grow with the size of the diff.">- <FixHistoryTable files={fixFiles} />+ <CommitFilesTable files={files} /></OverviewSection>)}diff --git a/packages/ui/src/commits/commit-files-table.tsx b/packages/ui/src/commits/commit-files-table.tsxnew file mode 100644index 000000000..79a7dabf2--- /dev/null+++ b/packages/ui/src/commits/commit-files-table.tsx@@ -0,0 +1,57 @@+import { ResponsiveTable, type ResponsiveColumn } from "../shared/responsive-table";+import { formatLOC } from "../lib/format";+import type { CommitFile } from "@repowise-dev/types/git";++export interface CommitFilesTableProps {+ files: CommitFile[];+ className?: string;+}++const COLUMNS: ResponsiveColumn<CommitFile>[] = [+ {+ key: "path",+ header: "File",+ cellClassName: "font-mono text-[11px] [overflow-wrap:anywhere]",+ render: (f) => f.path,+ },+ {+ key: "lines",+ header: "Lines",+ align: "right",+ headerClassName: "w-28",+ render: (f) => (+ <span className="tabular-nums">+ <span className="text-[var(--color-success)]">+{formatLOC(f.lines_added)}</span>{" "}+ <span className="text-[var(--color-error)]">-{formatLOC(f.lines_deleted)}</span>+ </span>+ ),+ },+ {+ key: "prior_fixes",+ header: "Prior fixes",+ align: "right",+ headerClassName: "w-24",+ // A dash is "the repo no longer tracks this", not zero.+ render: (f) => <span className="tabular-nums">{f.prior_fixes ?? "—"}</span>,+ },+];++/**+ * The files a commit touched, and the fix record each carries. Leads the sheet+ * because, unlike the percentile, it does not grow with the diff.+ */+export function CommitFilesTable({ files, className }: CommitFilesTableProps) {+ if (files.length === 0) return null;++ return (+ <ResponsiveTable+ className={className}+ columns={COLUMNS}+ rows={files}+ rowKey={(f) => f.path}+ caption="Files this commit touched, and how much bug-fix history each carries"+ stacked="sm"+ bare+ />+ );+}diff --git a/packages/ui/src/commits/fix-history-table.tsx b/packages/ui/src/commits/fix-history-table.tsxdeleted file mode 100644index d9838fd1b..000000000--- a/packages/ui/src/commits/fix-history-table.tsx+++ /dev/null@@ -1,73 +0,0 @@-import { cn } from "../lib/cn";-import { formatLOC } from "../lib/format";--export interface FixHistoryRow {- path: string;- churn: number;- fix_pressure: number;-}--export interface FixHistoryTableProps {- files: FixHistoryRow[];- className?: string;-}--/**- * The bug-fix record of the files a commit touched.- *- * This leads the sheet because it is the one signal here that does not grow- * with the diff: one line in a file fixed twenty times outranks a thousand- * lines in files never fixed at all.- */-export function FixHistoryTable({ files, className }: FixHistoryTableProps) {- if (files.length === 0) return null;-- return (- <table className={cn("w-full border-collapse text-xs", className)}>- <caption className="sr-only">- Files this commit touched, and how much bug-fix history each carries- </caption>- <thead>- <tr>- <th- scope="col"- className="border-b border-[var(--color-border-default)] pb-2 pr-3 text-left font-mono text-[10px] font-normal uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]"- >- File- </th>- <th- scope="col"- className="border-b border-[var(--color-border-default)] pb-2 px-3 text-right font-mono text-[10px] font-normal uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]"- >- Lines- </th>- <th- scope="col"- title="Past bug-fix commits on this file, weighted so a fix a year ago counts a half"- className="cursor-help border-b border-[var(--color-border-default)] pb-2 pl-3 text-right font-mono text-[10px] font-normal uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]"- >- Prior fixes- </th>- </tr>- </thead>- <tbody>- {files.map((f) => (- <tr- key={f.path}- className="border-b border-[var(--color-border-default)] last:border-0"- >- <td className="py-2 pr-3 align-middle font-mono text-[11px] text-[var(--color-text-secondary)] [overflow-wrap:anywhere]">- {f.path}- </td>- <td className="whitespace-nowrap py-2 px-3 text-right align-middle tabular-nums text-[var(--color-text-tertiary)]">- {formatLOC(f.churn)}- </td>- <td className="whitespace-nowrap py-2 pl-3 text-right align-middle tabular-nums text-[var(--color-text-primary)]">- {f.fix_pressure.toFixed(1)}- </td>- </tr>- ))}- </tbody>- </table>- );-}diff --git a/packages/web/src/components/commits/commit-detail-sheet.tsx b/packages/web/src/components/commits/commit-detail-sheet.tsxindex 306ed6434..d16d8d2c1 100644--- a/packages/web/src/components/commits/commit-detail-sheet.tsx+++ b/packages/web/src/components/commits/commit-detail-sheet.tsx@@ -33,9 +33,8 @@ export function CommitDetailSheet({ repoId }: { repoId: string }) {{ revalidateOnFocus: false },);- // Scored live from git, because the indexed commit row carries Kamei- // aggregates and no file list. A server with no checkout 404s here and the- // sheet renders without the block rather than failing.+ // Only for the fix-density percentile, which needs live scoring. The file+ // list itself is stored, so a server with no checkout still renders it.const { data: range } = useSWR(selectedSha ? `commit-fixes:${repoId}:${selectedSha}` : null,() =>@@ -72,8 +71,10 @@ export function CommitDetailSheet({ repoId }: { repoId: string }) {</div><CommitDetailCardcommit={detail}- fixHistory={- range?.fix_history?.available ? range.fix_history : null+ fixPercentile={+ range?.fix_history?.available+ ? range.fix_history.percentile+ : null}/></>diff --git a/tests/unit/persistence/test_git_commit_files_crud.py b/tests/unit/persistence/test_git_commit_files_crud.pynew file mode 100644index 000000000..0c2659687--- /dev/null+++ b/tests/unit/persistence/test_git_commit_files_crud.py@@ -0,0 +1,108 @@+"""CRUD round-trip tests for the git_commit_files table."""++from __future__ import annotations++import pytest++from repowise.core.persistence.crud import (+ delete_git_commit_files,+ delete_git_commit_files_by_sha,+ get_commit_files,+ upsert_git_commit_files_bulk,+)+from tests.unit.persistence.helpers import insert_repo+++def _row(sha: str, path: str, added: int = 1, deleted: int = 0) -> dict:+ return {"sha": sha, "file_path": path, "lines_added": added, "lines_deleted": deleted}+++async def test_files_come_back_biggest_churn_first(async_session) -> None:+ repo = await insert_repo(async_session)+ await upsert_git_commit_files_bulk(+ async_session,+ repo.id,+ [+ _row("aaa", "small.py", 1, 1),+ _row("aaa", "big.py", 40, 20),+ _row("aaa", "mid.py", 5, 5),+ ],+ )+ await async_session.commit()++ files = await get_commit_files(async_session, repo.id, "aaa")++ assert [f.file_path for f in files] == ["big.py", "mid.py", "small.py"]+ assert files[0].lines_added == 40+ assert files[0].lines_deleted == 20+++async def test_upsert_is_idempotent_on_sha_and_path(async_session) -> None:+ repo = await insert_repo(async_session)+ await upsert_git_commit_files_bulk(async_session, repo.id, [_row("aaa", "a.py", 1, 1)])+ await async_session.commit()+ await upsert_git_commit_files_bulk(async_session, repo.id, [_row("aaa", "a.py", 9, 3)])+ await async_session.commit()++ files = await get_commit_files(async_session, repo.id, "aaa")++ assert len(files) == 1+ assert (files[0].lines_added, files[0].lines_deleted) == (9, 3)+++async def test_one_path_can_belong_to_many_commits(async_session) -> None:+ """A row is "this commit touched this file", not a file record."""+ repo = await insert_repo(async_session)+ await upsert_git_commit_files_bulk(+ async_session, repo.id, [_row("aaa", "a.py"), _row("bbb", "a.py")]+ )+ await async_session.commit()++ assert len(await get_commit_files(async_session, repo.id, "aaa")) == 1+ assert len(await get_commit_files(async_session, repo.id, "bbb")) == 1+++async def test_rows_leave_with_their_commit(async_session) -> None:+ repo = await insert_repo(async_session)+ await upsert_git_commit_files_bulk(+ async_session, repo.id, [_row("aaa", "a.py"), _row("bbb", "b.py")]+ )+ await async_session.commit()++ removed = await delete_git_commit_files_by_sha(async_session, repo.id, ["aaa"])+ await async_session.commit()++ assert removed == 1+ assert await get_commit_files(async_session, repo.id, "aaa") == []+ assert len(await get_commit_files(async_session, repo.id, "bbb")) == 1+++async def test_a_clean_reindex_clears_the_table(async_session) -> None:+ repo = await insert_repo(async_session)+ await upsert_git_commit_files_bulk(async_session, repo.id, [_row("aaa", "a.py")])+ await async_session.commit()++ await delete_git_commit_files(async_session, repo.id)+ await async_session.commit()++ assert await get_commit_files(async_session, repo.id, "aaa") == []+++async def test_a_full_reindex_wipes_the_file_rows_with_their_commits(async_session) -> None:+ """A rewritten history must not leave rows pointing at vanished shas."""+ from repowise.core.pipeline.persist import replace_git_history++ repo = await insert_repo(async_session)+ await upsert_git_commit_files_bulk(async_session, repo.id, [_row("gone", "a.py")])+ await async_session.commit()++ await replace_git_history(async_session, repo.id, {}, None)+ await async_session.commit()++ assert await get_commit_files(async_session, repo.id, "gone") == []diff --git a/tests/unit/persistence/test_models.py b/tests/unit/persistence/test_models.pyindex 3d864112c..45797810e 100644--- a/tests/unit/persistence/test_models.py+++ b/tests/unit/persistence/test_models.py@@ -301,6 +301,7 @@ def test_base_includes_all_models():"webhook_events","wiki_symbols","git_metadata",+ "git_commit_files","git_commits","git_function_blame","fix_events",diff --git a/tests/unit/server/test_git.py b/tests/unit/server/test_git.pyindex a508f7fc4..37007f302 100644--- a/tests/unit/server/test_git.py+++ b/tests/unit/server/test_git.py@@ -368,6 +368,60 @@ async def test_get_commit_detail_has_drivers(client: AsyncClient, app) -> None:assert feats == {"la", "ld", "entropy", "exp"}+async def test_commit_detail_names_the_files_without_a_checkout(+ client: AsyncClient, app+) -> None:+ """Stored at index time, so hosted answers this too."""+ repo = await create_test_repo(client)+ await _insert_git_commits(app.state.session_factory, repo["id"])+ await _insert_git_metadata(app.state.session_factory, repo["id"])+ async with get_session(app.state.session_factory) as session:+ await crud.upsert_git_commit_files_bulk(+ session,+ repo["id"],+ [+ {+ "sha": "bbbbbbbb22",+ "file_path": "src/main.py",+ "lines_added": 30,+ "lines_deleted": 4,+ },+ {+ "sha": "bbbbbbbb22",+ "file_path": "gone.py",+ "lines_added": 1,+ "lines_deleted": 1,+ },+ ],+ )++ resp = await client.get(f"/api/repos/{repo['id']}/commits/bbbbbbbb")++ assert resp.status_code == 200+ files = resp.json()["files"]+ # Biggest churn first.+ assert [f["path"] for f in files] == ["src/main.py", "gone.py"]+ assert files[0]["lines_added"] == 30+ # Joined from the per-file git rollup.+ assert files[0]["prior_fixes"] == 4+ # An untracked path reports unknown, which is not zero.+ assert files[1]["prior_fixes"] is None+++async def test_commit_detail_is_empty_of_files_on_an_older_index(+ client: AsyncClient, app+) -> None:+ repo = await create_test_repo(client)+ await _insert_git_commits(app.state.session_factory, repo["id"])++ resp = await client.get(f"/api/repos/{repo['id']}/commits/bbbbbbbb")++ assert resp.status_code == 200+ assert resp.json()["files"] == []++@pytest.mark.asyncioasync def test_get_commit_not_found(client: AsyncClient) -> None:repo = await create_test_repo(client)diff --git a/tests/unit/test_git_commit_rows.py b/tests/unit/test_git_commit_rows.pyindex c7ba04f06..831528794 100644--- a/tests/unit/test_git_commit_rows.py+++ b/tests/unit/test_git_commit_rows.py@@ -12,7 +12,10 @@ from datetime import UTC, datetimefrom unittest.mock import MagicMockfrom repowise.core.ingestion.git_commit_index import load_commit_index-from repowise.core.ingestion.git_indexer.commit_rows import build_commit_rows+from repowise.core.ingestion.git_indexer.commit_rows import (+ build_commit_file_rows,+ build_commit_rows,+)def _iso_from_ts(ts: int) -> str:@@ -346,3 +349,46 @@ def test_build_commit_rows_committed_at_parsed() -> None:])assert rows0[0]["committed_at"] is None+++def test_build_commit_file_rows_keeps_the_detail_the_aggregates_drop():+ rows = build_commit_file_rows(+ [{"sha": "a" * 40, "changes": [("pkg/a.py", 10, 2), ("pkg/b.py", 0, 5)]}]+ )++ assert [r["file_path"] for r in rows] == ["pkg/a.py", "pkg/b.py"]+ assert rows[0] == {+ "sha": "a" * 40,+ "file_path": "pkg/a.py",+ "lines_added": 10,+ "lines_deleted": 2,+ }+ # 0/0-style rows are real: a binary file is touched, size unknown.+ assert rows[1]["lines_added"] == 0+++def test_build_commit_file_rows_folds_a_repeated_path():+ """numstat can emit a path twice; (sha, path) is the natural key."""+ rows = build_commit_file_rows(+ [{"sha": "a" * 40, "changes": [("pkg/a.py", 10, 2), ("pkg/a.py", 3, 3)]}]+ )++ assert len(rows) == 1+++def test_build_commit_file_rows_skips_records_without_a_sha():+ rows = build_commit_file_rows([{"changes": [("x.py", 1, 1)]}, {"sha": "", "changes": []}])++ assert rows == []+++def test_build_commit_file_rows_covers_exactly_the_commits_it_was_given():+ commits = [+ {"sha": "a" * 40, "changes": [("a.py", 1, 1)]},+ {"sha": "b" * 40, "changes": [("b.py", 2, 0)]},+ ]++ file_rows = build_commit_file_rows(commits)+ commit_rows = build_commit_rows(commits)++ assert {r["sha"] for r in file_rows} == {r["sha"] for r in commit_rows}