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.

feat(git): add commits change-risk page, per-function blame, coverage-gradient breakdown (#319)

Raghav Chamadiya1ae19dac192f
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd.py b/packages/cli/src/repowise/cli/commands/update_cmd.py
index 65ffdee70..014537e1e 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import asyncio
import time
from typing import Any
@@ -117,6 +118,47 @@ async def _persist_partial_health(session: Any, repo_id: str, report: Any) -> No
await upsert_health_findings(
session, repo_id, list(report.findings or []), file_paths=changed_paths
)
+ # Per-function blame rollup for the changed files (keeps git_function_blame
+ # current between full indexes; FULL git tier only — empty otherwise).
+ fn_blame_rows = getattr(report, "function_blame_rows", None)
+ if fn_blame_rows:
+ from repowise.core.persistence.crud import upsert_git_function_blame_bulk
+
+ await upsert_git_function_blame_bulk(session, repo_id, fn_blame_rows)
+
+
+async def _persist_incremental_commits(session: Any, repo_id: str, repo_path: Any) -> None:
+ """Capture + upsert ``git_commits`` rows for commits new since the last index.
+
+ Foundation 1 only populated the per-commit table on the full orchestrator
+ index; without this, the commits/change-risk surface goes stale between full
+ re-indexes. Bounds the walk to commits newer than the newest persisted
+ ``committed_at`` (one ``git log`` pass) and upserts (idempotent on sha).
+ """
+ from repowise.core.ingestion.git_indexer import GitIndexer
+ from repowise.core.persistence.crud import (
+ get_latest_commit_committed_at,
+ upsert_git_commits_bulk,
+ )
+
+ cfg = load_config(repo_path)
+ indexer = GitIndexer(
+ repo_path,
+ commit_limit=cfg.get("commit_limit"),
+ follow_renames=cfg.get("follow_renames", False),
+ )
+ newest = await get_latest_commit_committed_at(session, repo_id)
+ since_ts: int | None = None
+ if newest is not None:
+ # SQLite drops tzinfo, so a naive read must be interpreted as UTC (the
+ # column is stored tz-aware) rather than local time.
+ from datetime import UTC
+
+ dt = newest if newest.tzinfo is not None else newest.replace(tzinfo=UTC)
+ since_ts = int(dt.timestamp())
+ rows = await asyncio.to_thread(indexer.capture_new_commit_rows, since_ts=since_ts)
+ if rows:
+ await upsert_git_commits_bulk(session, repo_id, rows)
# ---------------------------------------------------------------------------
@@ -404,6 +446,11 @@ def _persist_index_only_update(
except Exception as exc:
console.print(f"[yellow]Git persist skipped: {exc}[/yellow]")
+ try:
+ await _persist_incremental_commits(session, repo_id, repo_path)
+ except Exception as exc:
+ console.print(f"[yellow]Commit capture skipped: {exc}[/yellow]")
+
if dead_code_report is not None:
try:
from repowise.core.persistence.crud import (
@@ -987,6 +1034,7 @@ def update_command(
list(git_meta_map.values()),
)
await recompute_git_percentiles(session, repo_id)
+ await _persist_incremental_commits(session, repo_id, repo_path)
except Exception:
pass # git persistence is best-effort
diff --git a/packages/cli/src/repowise/cli/commands/upgrade_flow.py b/packages/cli/src/repowise/cli/commands/upgrade_flow.py
index 0615a82b6..8b2ce0c18 100644
--- a/packages/cli/src/repowise/cli/commands/upgrade_flow.py
+++ b/packages/cli/src/repowise/cli/commands/upgrade_flow.py
@@ -91,6 +91,7 @@ async def _backfill_git(
from repowise.core.persistence import get_session
from repowise.core.persistence.crud import (
recompute_git_percentiles,
+ upsert_git_commits_bulk,
upsert_git_metadata_bulk,
)
from repowise.core.persistence.stores.sql_job_store import SqlJobStore
@@ -115,6 +116,11 @@ async def _backfill_git(
if git_results:
await upsert_git_metadata_bulk(session, repo_id, git_results)
await recompute_git_percentiles(session, repo_id)
+ # Persist the per-commit rows captured during the FULL-tier walk so the
+ # commits/change-risk surface lands on an ESSENTIAL→FULL promotion too
+ # (Foundation 1 only wrote them on the full orchestrator index).
+ if summary.commit_rows:
+ await upsert_git_commits_bulk(session, repo_id, summary.commit_rows)
console.print(
f"Git tier upgraded to FULL: [cyan]{summary.files_indexed}[/cyan] files "
diff --git a/packages/core/alembic/versions/0028_git_commit_author_experience.py b/packages/core/alembic/versions/0028_git_commit_author_experience.py
new file mode 100644
index 000000000..d2c5fa698
--- /dev/null
+++ b/packages/core/alembic/versions/0028_git_commit_author_experience.py
@@ -0,0 +1,36 @@
+"""Add author_experience to git_commits.
+
+The author's cumulative prior-commit count at the time of each commit — the one
+change-risk feature not derivable from the diff alone (reconstructed in-memory
+during the commit-index walk, no extra git pass). Persisted so the per-commit
+risk breakdown can reproduce the stored change_risk_score exactly. Nullable;
+back-populated on the next index.
+
+Revision ID: 0028
+Revises: 0027
+Create Date: 2026-05-30
+"""
+
+from __future__ import annotations
+
+from collections.abc import Sequence
+
+import sqlalchemy as sa
+from alembic import op
+
+# revision identifiers
+revision: str = "0028"
+down_revision: str | None = "0027"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+
+def upgrade() -> None:
+ op.add_column(
+ "git_commits",
+ sa.Column("author_experience", sa.Integer, nullable=True),
+ )
+
+
+def downgrade() -> None:
+ op.drop_column("git_commits", "author_experience")
diff --git a/packages/core/alembic/versions/0029_git_function_blame.py b/packages/core/alembic/versions/0029_git_function_blame.py
new file mode 100644
index 000000000..8a78c3621
--- /dev/null
+++ b/packages/core/alembic/versions/0029_git_function_blame.py
@@ -0,0 +1,58 @@
+"""Create git_function_blame table for the per-function blame rollup.
+
+Persists the function-granular git signals derived from the per-line blame
+index during FULL-tier health analysis (modification count, median line age,
+recent-modification count, blame owner) — previously computed and discarded.
+Bounded by the number of modified functions; raw per-line blame is not stored.
+
+Revision ID: 0029
+Revises: 0028
+Create Date: 2026-05-30
+"""
+
+from __future__ import annotations
+
+from collections.abc import Sequence
+
+import sqlalchemy as sa
+from alembic import op
+
+# revision identifiers
+revision: str = "0029"
+down_revision: str | None = "0028"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+
+def upgrade() -> None:
+ op.create_table(
+ "git_function_blame",
+ sa.Column("id", sa.String(32), primary_key=True),
+ sa.Column("repository_id", sa.String(32), nullable=False),
+ sa.Column("symbol_id", sa.String(512), nullable=False),
+ sa.Column("file_path", sa.Text, nullable=False, server_default=""),
+ sa.Column("function_name", sa.Text, nullable=False, server_default=""),
+ sa.Column("start_line", sa.Integer, nullable=False, server_default="0"),
+ sa.Column("end_line", sa.Integer, nullable=False, server_default="0"),
+ sa.Column("line_count", sa.Integer, nullable=False, server_default="0"),
+ sa.Column("mod_count", sa.Integer, nullable=False, server_default="0"),
+ sa.Column("recent_mod_count", sa.Integer, nullable=False, server_default="0"),
+ sa.Column("median_author_time", sa.Integer, nullable=True),
+ sa.Column("owner_name", sa.String(255), nullable=True),
+ sa.Column("owner_email", sa.String(255), nullable=True),
+ sa.Column("owner_line_pct", sa.Float, nullable=True),
+ sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
+ sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
+ sa.ForeignKeyConstraint(["repository_id"], ["repositories.id"], ondelete="CASCADE"),
+ sa.UniqueConstraint("repository_id", "symbol_id", name="uq_git_function_blame"),
+ )
+ op.create_index(
+ "ix_git_function_blame_repo_mods",
+ "git_function_blame",
+ ["repository_id", "mod_count"],
+ )
+
+
+def downgrade() -> None:
+ op.drop_index("ix_git_function_blame_repo_mods", table_name="git_function_blame")
+ op.drop_table("git_function_blame")
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 792a0fa02..48386cb75 100644
--- a/packages/core/src/repowise/core/analysis/change_risk/__init__.py
+++ b/packages/core/src/repowise/core/analysis/change_risk/__init__.py
@@ -16,11 +16,13 @@ from .features import (
features_from_file_changes,
)
from .model import ChangeRisk, RiskDriver, score_change
+from .normalize import RiskNormalizer
__all__ = [
"ChangeFeatures",
"ChangeRisk",
"RiskDriver",
+ "RiskNormalizer",
"extract_commit_features",
"extract_range_features",
"features_from_file_changes",
diff --git a/packages/core/src/repowise/core/analysis/change_risk/normalize.py b/packages/core/src/repowise/core/analysis/change_risk/normalize.py
new file mode 100644
index 000000000..3529d777a
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/change_risk/normalize.py
@@ -0,0 +1,74 @@
+"""Repo-relative normalization of change-risk scores.
+
+The raw :func:`change_risk.score_change` value is a calibrated absolute
+probability, anchored to the offline calibration corpus — which makes its
+high/moderate/low *banding* portable only across repos whose typical commit
+resembles that corpus. On a repo whose median commit is large, the diff-size
+feature (``la``) dominates and the absolute band skews high (two-thirds of
+commits reading "high" was measured on this very repo). The *ranking* is sound;
+the absolute band is not.
+
+This module normalizes a score **against the repo's own distribution** so the
+surface can show a portable, honest signal: where a commit sits relative to the
+rest of the repo's history. The raw score stays the stored source of truth; we
+re-bucket only for display.
+"""
+
+from __future__ import annotations
+
+from bisect import bisect_left, bisect_right
+from dataclasses import dataclass
+
+# Tercile cut points on the repo-relative percentile (0-100). A commit in the
+# top third of its repo's risk distribution is the review-priority tier.
+_HIGH_PCT = 200.0 / 3.0 # ≈ 66.67
+_MODERATE_PCT = 100.0 / 3.0 # ≈ 33.33
+
+
+@dataclass
+class RiskNormalizer:
+ """Maps a raw change-risk score to its rank within one repo's distribution.
+
+ Built once per request from the repo's full set of stored commit scores
+ (bounded by the indexer's ``commit_limit``, so cheap to hold in memory).
+ """
+
+ scores: list[float] # sorted ascending, ``None``/missing dropped
+
+ @classmethod
+ def from_scores(cls, scores: list[float | None]) -> RiskNormalizer:
+ clean = sorted(float(s) for s in scores if s is not None)
+ return cls(scores=clean)
+
+ @property
+ def count(self) -> int:
+ return len(self.scores)
+
+ def percentile(self, score: float | None) -> float:
+ """Mid-rank percentile (0-100) of *score* within the repo distribution.
+
+ Ties share the average rank, so identical scores get one percentile and
+ the busiest repos don't pin every commit to 100. Returns 0.0 when there
+ is no distribution to rank against.
+ """
+ n = len(self.scores)
+ if n == 0 or score is None:
+ return 0.0
+ below = bisect_left(self.scores, score)
+ equal = bisect_right(self.scores, score) - below
+ return 100.0 * (below + 0.5 * equal) / n
+
+ def priority(self, score: float | None) -> str:
+ """Repo-relative review priority: ``high`` | ``moderate`` | ``low``.
+
+ Derived from the repo-relative percentile (terciles), NOT the absolute
+ calibrated band — so two-thirds of commits can never all read "high".
+ """
+ if score is None or not self.scores:
+ return "low"
+ pct = self.percentile(score)
+ if pct >= _HIGH_PCT:
+ return "high"
+ if pct >= _MODERATE_PCT:
+ return "moderate"
+ return "low"
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/coverage_gradient.py b/packages/core/src/repowise/core/analysis/health/biomarkers/coverage_gradient.py
index 468ccbb8e..75d71ad7e 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/coverage_gradient.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/coverage_gradient.py
@@ -93,6 +93,10 @@ class CoverageGradientDetector:
"line_coverage_pct": cov,
"branch_coverage_pct": ctx.branch_coverage_pct,
"uncovered_fraction": round(uncovered_fraction, 4),
+ # The continuous base deduction (pre-weight, pre-cap). Stored
+ # so the score-breakdown API can show the gradient instead of
+ # recomputing a severity-band proxy.
+ "deduction": round(deduction, 4),
},
reason=(
f"{uncovered_pct}% of lines uncovered ({cov:.0f}% line coverage) - "
diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.py
index 7f900bc09..3e81151b4 100644
--- a/packages/core/src/repowise/core/analysis/health/engine.py
+++ b/packages/core/src/repowise/core/analysis/health/engine.py
@@ -19,6 +19,7 @@ from __future__ import annotations
import asyncio
import os
+import time
from datetime import UTC, datetime
from pathlib import Path
from typing import Any
@@ -327,6 +328,7 @@ class HealthAnalyzer:
findings=findings,
metrics=metrics,
kpis=kpis,
+ function_blame_rows=self._function_blame_rows(walked),
)
async def analyze_async(
@@ -440,12 +442,31 @@ class HealthAnalyzer:
findings=findings,
metrics=metrics,
kpis=kpis,
+ function_blame_rows=self._function_blame_rows(walked),
)
# ------------------------------------------------------------------
# Helpers
# ------------------------------------------------------------------
+ def _function_blame_rows(self, walked: list[tuple[Any, FileComplexity]]) -> list[dict]:
+ """Build the per-function blame rollup from the walked files + the
+ FULL-tier blame indexes attached to ``git_meta_map``.
+
+ Cheap (reads the already-materialised blame index; no extra git) and
+ failure-isolated so a rollup hiccup never breaks the health report.
+ Returns an empty list on the ESSENTIAL tier (no blame indexes).
+ """
+ try:
+ from .function_blame_rollup import build_function_blame_rows
+
+ return build_function_blame_rows(
+ list(walked), self.git_meta_map, now_ts=int(time.time())
+ )
+ except Exception as exc:
+ log.debug("function_blame_rollup_failed", error=str(exc))
+ return []
+
def _walk(self, pf: Any) -> FileComplexity:
path = pf.file_info.abs_path
language = pf.file_info.language
diff --git a/packages/core/src/repowise/core/analysis/health/function_blame_rollup.py b/packages/core/src/repowise/core/analysis/health/function_blame_rollup.py
new file mode 100644
index 000000000..9213e27d2
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/function_blame_rollup.py
@@ -0,0 +1,82 @@
+"""Per-function blame rollup → ``git_function_blame`` rows.
+
+Turns the in-memory per-line :class:`BlameIndex` (built once per file during
+FULL-tier health analysis) plus the walker's per-function line ranges into one
+persisted rollup row per *modified* function. The biomarkers
+(``function_hotspot``/``code_age_volatility``) already project the same blame
+index onto each function's range and then discard it; this captures that work so
+a function-level health surface can read it without re-blaming.
+
+The transform is pure (no git, no I/O) — it only reads the already-materialised
+blame index and the walker output — so it is cheap and unit-testable. Only
+functions with ``mod_count > 0`` are emitted, bounding the table to genuinely
+churned functions (the "no signal" convention used by the biomarkers).
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from ...ingestion.git_indexer.function_blame import (
+ BlameIndex,
+ distinct_commits_in_range,
+ median_author_time_in_range,
+ owner_in_range,
+ recent_commits_in_range,
+)
+
+# Recent-modification window for the rollup. Broader than the 30-day window
+# ``code_age_volatility`` uses for its finding gate — the persisted row is a
+# general-purpose signal, so a 90-day window matches the rest of the git data.
+_RECENT_WINDOW_DAYS = 90
+
+
+def build_function_blame_rows(
+ walked: list[tuple[Any, Any]],
+ git_meta_map: dict[str, dict],
+ *,
+ now_ts: int,
+ recent_window_days: int = _RECENT_WINDOW_DAYS,
+) -> list[dict]:
+ """Build ``git_function_blame`` row dicts from walked files + blame indexes.
+
+ *walked* is the engine's ``[(parsed_file, FileComplexity)]`` list; each
+ file's blame index is looked up in *git_meta_map* under ``"blame_index"``
+ (the FULL-tier git tier attaches it there). *now_ts* anchors the recent
+ window (unix seconds) — pass the index-time clock.
+ """
+ since = now_ts - recent_window_days * 86400
+ rows: list[dict] = []
+
+ for pf, fcx in walked:
+ path = pf.file_info.path
+ meta = git_meta_map.get(path) or {}
+ idx = meta.get("blame_index")
+ if not isinstance(idx, BlameIndex) or not idx.lines:
+ continue
+ for fc in fcx.functions:
+ start, end = fc.start_line, fc.end_line
+ mod_count = len(distinct_commits_in_range(idx, start, end))
+ if mod_count == 0:
+ # No blame coverage / unmodified — the "no signal" outcome.
+ continue
+ recent_mod = len(recent_commits_in_range(idx, start, end, since_unix_ts=since))
+ median_ts = median_author_time_in_range(idx, start, end)
+ owner_name, owner_email, owner_pct = owner_in_range(idx, start, end)
+ rows.append(
+ {
+ "symbol_id": f"{path}::{fc.name}",
+ "file_path": path,
+ "function_name": fc.name,
+ "start_line": start,
+ "end_line": end,
+ "line_count": max(0, end - start + 1),
+ "mod_count": mod_count,
+ "recent_mod_count": recent_mod,
+ "median_author_time": median_ts,
+ "owner_name": owner_name,
+ "owner_email": owner_email,
+ "owner_line_pct": owner_pct,
+ }
+ )
+ return rows
diff --git a/packages/core/src/repowise/core/analysis/health/models.py b/packages/core/src/repowise/core/analysis/health/models.py
index f3e40ca94..cd30e5ba1 100644
--- a/packages/core/src/repowise/core/analysis/health/models.py
+++ b/packages/core/src/repowise/core/analysis/health/models.py
@@ -59,3 +59,6 @@ class HealthReport:
metrics: list[HealthFileMetricData] = field(default_factory=list)
# Repo-level KPIs computed by ``scoring.compute_kpis``.
kpis: dict[str, Any] = field(default_factory=dict)
+ # Per-function blame rollup rows (``git_function_blame``), derived from the
+ # FULL-tier blame index. Empty on ESSENTIAL tier / when blame is absent.
+ function_blame_rows: list[dict] = field(default_factory=list)
diff --git a/packages/core/src/repowise/core/ingestion/git_commit_index.py b/packages/core/src/repowise/core/ingestion/git_commit_index.py
index fda370793..01719a3f0 100644
--- a/packages/core/src/repowise/core/ingestion/git_commit_index.py
+++ b/packages/core/src/repowise/core/ingestion/git_commit_index.py
@@ -35,6 +35,7 @@ def load_commit_index(
indexable_files: set[str],
*,
commit_sink: list[dict] | None = None,
+ since_ts: int | None = None,
) -> dict[str, list[_CommitRec]]:
"""Bucket every commit in the recent history by the files it touched.
@@ -59,6 +60,12 @@ def load_commit_index(
(see :mod:`git_indexer.commit_rows`). The default (``None``) leaves the
return value and behaviour unchanged.
+ When *since_ts* is supplied (unix seconds), commits at or before it are
+ skipped — used by the incremental path to capture only commits newer than
+ the newest already-persisted one, so the commits surface stays current
+ without re-walking the full window. Default (``None``) processes the whole
+ depth.
+
Failures (git unavailable, corrupt log output, etc.) return an
empty dict so the caller can fall back to per-file indexing.
"""
@@ -99,6 +106,12 @@ def load_commit_index(
if parsed is None:
continue
header, numstat_lines = parsed
+
+ # Incremental bound: drop commits at/older than the newest already
+ # persisted (newest-first walk, but author/commit-time can be slightly
+ # out of order, so skip rather than break to stay correct).
+ if since_ts is not None and header["ts"] <= since_ts:
+ continue
commits_parsed += 1
# Full change footprint of this commit (every file, not just the
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 15f1f7977..d49a2b7d3 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
@@ -71,9 +71,10 @@ def build_commit_rows(parsed_commits: list[dict]) -> list[dict]:
sha = c["sha"]
subject = (c.get("subject") or "")[:_MAX_SUBJECT_LEN]
changes = c.get("changes") or []
+ exp = exp_by_sha.get(sha, 0)
feats = features_from_file_changes(
changes,
- exp=exp_by_sha.get(sha, 0),
+ exp=exp,
is_fix=is_fix_commit(subject),
author=c.get("author_name", ""),
subject=subject,
@@ -94,6 +95,7 @@ def build_commit_rows(parsed_commits: list[dict]) -> list[dict]:
"subsystems_changed": feats.ns,
"entropy": feats.entropy,
"is_fix": feats.is_fix,
+ "author_experience": exp,
"change_risk_score": risk.score,
"change_risk_level": risk.level,
}
diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/function_blame.py b/packages/core/src/repowise/core/ingestion/git_indexer/function_blame.py
index 8ca37190b..1b26c03de 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/function_blame.py
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/function_blame.py
@@ -35,6 +35,7 @@ __all__ = [
"build_blame_index",
"distinct_commits_in_range",
"median_author_time_in_range",
+ "owner_in_range",
"recent_commits_in_range",
]
@@ -87,6 +88,39 @@ def ownership_from_blame(idx: BlameIndex) -> tuple[str | None, str | None, float
return top_name, top_email, top_count / total if total else None
+def owner_in_range(
+ idx: BlameIndex, start_line: int, end_line: int
+) -> tuple[str | None, str | None, float | None]:
+ """Top blame author over ``[start_line, end_line]`` (inclusive).
+
+ Returns ``(name, email, share)`` where ``share`` is the fraction of blamed
+ lines in the range authored by the top author. ``None``s when the range has
+ no blame coverage. Scoped variant of :func:`ownership_from_blame`, reused by
+ the per-function blame rollup.
+ """
+ if not idx.lines or start_line > end_line:
+ return None, None, None
+ from collections import Counter
+
+ counts: Counter[str] = Counter()
+ for ln in range(start_line, end_line + 1):
+ entry = idx.lines.get(ln)
+ if entry is None:
+ continue
+ name = idx.authors.get(entry[0], ("unknown", ""))[0]
+ counts[name] += 1
+ if not counts:
+ return None, None, None
+ total = sum(counts.values())
+ top_name, top_count = counts.most_common(1)[0]
+ top_email = ""
+ for _sha, (name, email) in idx.authors.items():
+ if name == top_name and email:
+ top_email = email
+ break
+ return top_name, top_email or None, (top_count / total if total else None)
+
+
def _parse_porcelain(
raw: str,
) -> tuple[dict[int, tuple[str, int]], dict[str, tuple[str, str]]]:
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 1017f80aa..f5e2cf454 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py
@@ -345,6 +345,38 @@ class GitIndexer:
repo.close()
return results
+ def capture_new_commit_rows(self, *, since_ts: int | None = None) -> list[dict]:
+ """Build ``git_commits`` rows for commits newer than *since_ts*.
+
+ 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
+ turns the sunk commits into rows via :func:`build_commit_rows`. Empty in
+ rename-tracking mode (no batched commit index — same limitation as the
+ full index). Failure-isolated: returns ``[]`` on any error.
+ """
+ if self.follow_renames:
+ return []
+ repo = self._get_repo()
+ if repo is None:
+ return []
+ try:
+ from ..git_commit_index import load_commit_index
+ from .commit_rows import build_commit_rows
+
+ sink: list[dict] = []
+ # Empty indexable set: we only want the full-footprint sink, not the
+ # per-file bucket (which the incremental file pass already rebuilt).
+ load_commit_index(
+ repo, self.commit_limit, set(), commit_sink=sink, since_ts=since_ts
+ )
+ return build_commit_rows(sink)
+ except Exception as exc:
+ logger.debug("incremental_commit_rows_failed", error=str(exc))
+ return []
+ finally:
+ repo.close()
+
# ------------------------------------------------------------------
# Internal methods
# ------------------------------------------------------------------
diff --git a/packages/core/src/repowise/core/persistence/crud/git.py b/packages/core/src/repowise/core/persistence/crud/git.py
index 8a5310f43..9d14b6b38 100644
--- a/packages/core/src/repowise/core/persistence/crud/git.py
+++ b/packages/core/src/repowise/core/persistence/crud/git.py
@@ -11,6 +11,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from ..models import (
GitCommit,
+ GitFunctionBlame,
GitMetadata,
_new_uuid,
_now_utc,
@@ -233,6 +234,20 @@ async def count_git_commits(session: AsyncSession, repository_id: str) -> int:
return int(result.scalar_one() or 0)
+async def get_latest_commit_committed_at(session: AsyncSession, repository_id: str):
+ """Return the newest persisted ``committed_at`` for a repo, or None.
+
+ Bounds the incremental commit-row walk: only commits newer than this need
+ capturing on a ``repowise update``.
+ """
+ result = await session.execute(
+ select(func.max(GitCommit.committed_at)).where(
+ GitCommit.repository_id == repository_id
+ )
+ )
+ return result.scalar_one_or_none()
+
+
async def get_git_commit(session: AsyncSession, repository_id: str, sha: str) -> GitCommit | None:
"""Return one commit by sha (or a unique prefix), or None."""
result = await session.execute(
@@ -244,6 +259,23 @@ async def get_git_commit(session: AsyncSession, repository_id: str, sha: str) ->
return result.scalars().first()
+async def get_commit_risk_scores(session: AsyncSession, repository_id: str) -> list[float]:
+ """Return every persisted ``change_risk_score`` for a repository (unsorted).
+
+ Used to build a repo-relative :class:`~repowise.core.analysis.change_risk.
+ RiskNormalizer` so the commits surface can rank a commit against its own
+ repo's distribution rather than the absolute calibration band. Bounded by
+ the indexer's ``commit_limit``, so the full pull is cheap.
+ """
+ result = await session.execute(
+ select(GitCommit.change_risk_score).where(
+ GitCommit.repository_id == repository_id,
+ GitCommit.change_risk_score.is_not(None),
+ )
+ )
+ return [float(s) for s in result.scalars().all() if s is not None]
+
+
async def get_git_commits(
session: AsyncSession,
repository_id: str,
@@ -266,3 +298,95 @@ async def get_git_commits(
.offset(offset)
)
return list(result.scalars().all())
+
+
+# ---------------------------------------------------------------------------
+# GitFunctionBlame CRUD (per-function blame rollup)
+# ---------------------------------------------------------------------------
+
+
+def _update_git_function_blame(existing: GitFunctionBlame, row: dict) -> None:
+ for key, val in row.items():
+ # ``symbol_id`` is the natural key — never reassign it on update.
+ if key not in ("id", "repository_id", "symbol_id") and hasattr(existing, key):
+ setattr(existing, key, val)
+ existing.updated_at = _now_utc()
+
+
+async def upsert_git_function_blame_bulk(
+ session: AsyncSession,
+ repository_id: str,
+ rows: list[dict],
+) -> None:
+ """Bulk upsert per-function blame rows (keyed ``repository_id`` + ``symbol_id``)."""
+ await _batch_upsert(
+ session,
+ GitFunctionBlame,
+ rows,
+ key_fn=lambda row: (
+ GitFunctionBlame.repository_id == repository_id,
+ GitFunctionBlame.symbol_id == row.get("symbol_id", ""),
+ ),
+ update_fn=_update_git_function_blame,
+ insert_fn=lambda row: GitFunctionBlame(
+ id=_new_uuid(),
+ repository_id=repository_id,
+ **{
+ k: v
+ for k, v in row.items()
+ if k not in ("id", "repository_id") and hasattr(GitFunctionBlame, k)
+ },
+ ),
+ batch_size=_BATCH_SIZE,
+ )
+
+
+async def delete_git_function_blame(session: AsyncSession, repository_id: str) -> None:
+ """Remove all per-function blame rows for a repository (clean reindex)."""
+ await session.execute(
+ delete(GitFunctionBlame).where(GitFunctionBlame.repository_id == repository_id)
+ )
+ await session.flush()
+
+
+async def count_git_function_blame(session: AsyncSession, repository_id: str) -> int:
+ """Count persisted per-function blame rows for a repository."""
+ result = await session.execute(
+ select(func.count())
+ .select_from(GitFunctionBlame)
+ .where(GitFunctionBlame.repository_id == repository_id)
+ )
+ return int(result.scalar_one() or 0)
+
+
+async def get_git_function_blame(
+ session: AsyncSession, repository_id: str, symbol_id: str
+) -> GitFunctionBlame | None:
+ """Return one per-function blame row by exact ``symbol_id``, or None."""
+ result = await session.execute(
+ select(GitFunctionBlame).where(
+ GitFunctionBlame.repository_id == repository_id,
+ GitFunctionBlame.symbol_id == symbol_id,
+ )
+ )
+ return result.scalar_one_or_none()
+
+
+async def get_git_function_blames(
+ session: AsyncSession,
+ repository_id: str,
+ *,
+ file_path: str | None = None,
+ limit: int = 50,
+ offset: int = 0,
+) -> list[GitFunctionBlame]:
+ """Return a page of per-function blame rows, hottest (most-modified) first.
+
+ Optionally scoped to a single ``file_path`` (the per-file drill-down).
+ """
+ q = select(GitFunctionBlame).where(GitFunctionBlame.repository_id == repository_id)
+ if file_path is not None:
+ q = q.where(GitFunctionBlame.file_path == file_path)
+ q = q.order_by(GitFunctionBlame.mod_count.desc()).limit(limit).offset(offset)
+ result = await session.execute(q)
+ return list(result.scalars().all())
diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.py
index 50e86ad39..69edaeceb 100644
--- a/packages/core/src/repowise/core/persistence/models.py
+++ b/packages/core/src/repowise/core/persistence/models.py
@@ -450,6 +450,12 @@ class GitCommit(Base):
entropy: Mapped[float] = mapped_column(Float, nullable=False, default=0.0)
is_fix: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
+ # Author experience at the time of the commit: the author's cumulative prior
+ # commit count, reconstructed in-memory over the walk (no extra git pass).
+ # The one change-risk feature not derivable from the diff alone — persisted
+ # so the per-commit risk breakdown reproduces the stored score exactly.
+ author_experience: Mapped[int | None] = mapped_column(Integer, nullable=True)
+
# Just-in-time change-risk: 0-10 score + level ("low"/"moderate"/"high")
# from the calibrated linear ``change_risk`` model. Author experience is
# computed in-memory across the walk (cumulative prior-commit count); the
@@ -465,6 +471,63 @@ class GitCommit(Base):
)
+class GitFunctionBlame(Base):
+ """Per-function blame rollup: function-granular git signals derived from the
+ per-line ``BlameIndex`` during FULL-tier health analysis.
+
+ The blame index is built once per file (one ``git blame`` call) and was
+ previously consumed in-memory by the ``function_hotspot`` /
+ ``code_age_volatility`` biomarkers and then discarded. This table persists
+ the cheap per-function rollup (bounded by the number of *modified*
+ functions) so a function-level health surface can read it without
+ re-blaming: modification count, median line age, recent-modification count,
+ and the blame owner over the function's line range. Raw per-line blame is
+ NOT persisted (size ~ LOC x history; recomputable).
+
+ Keyed ``(repository_id, symbol_id)`` where ``symbol_id = "{path}::{name}"``
+ mirrors :class:`WikiSymbol.symbol_id`, so callers can join straight to the
+ symbol graph.
+ """
+
+ __tablename__ = "git_function_blame"
+ __table_args__ = (
+ UniqueConstraint("repository_id", "symbol_id", name="uq_git_function_blame"),
+ Index("ix_git_function_blame_repo_mods", "repository_id", "mod_count"),
+ )
+
+ 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
+ )
+ # "{path}::{name}" — mirrors WikiSymbol.symbol_id.
+ symbol_id: Mapped[str] = mapped_column(String(512), nullable=False)
+ file_path: Mapped[str] = mapped_column(Text, nullable=False, default="")
+ function_name: Mapped[str] = mapped_column(Text, nullable=False, default="")
+ start_line: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
+ end_line: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
+ line_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
+
+ # Distinct commits touching the function's line range (its churn).
+ mod_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
+ # Distinct commits touching the range within the recent window.
+ recent_mod_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
+ # Median author time (unix seconds) over the range — a line-age proxy that
+ # ages naturally; the UI derives "median age" relative to display time.
+ median_author_time: Mapped[int | None] = mapped_column(Integer, nullable=True)
+
+ # Blame owner over the function's lines.
+ owner_name: Mapped[str | None] = mapped_column(String(255), nullable=True)
+ owner_email: Mapped[str | None] = mapped_column(String(255), nullable=True)
+ owner_line_pct: Mapped[float | None] = mapped_column(Float, nullable=True)
+
+ 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 DecisionRecord(Base):
"""An architectural decision record captured from inline markers, git
archaeology, README mining, or manual CLI entry."""
diff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.py
index 159662886..80401ed73 100644
--- a/packages/core/src/repowise/core/pipeline/persist.py
+++ b/packages/core/src/repowise/core/pipeline/persist.py
@@ -147,6 +147,7 @@ async def persist_pipeline_result(
save_health_metrics,
save_health_snapshot,
upsert_git_commits_bulk,
+ upsert_git_function_blame_bulk,
upsert_git_metadata_bulk,
)
@@ -242,6 +243,10 @@ async def persist_pipeline_result(
await save_health_metrics(session, repo_id, hr.metrics or [])
if hr.findings:
await save_health_findings(session, repo_id, hr.findings)
+ # Per-function blame rollup (FULL tier only; empty otherwise).
+ fn_blame_rows = getattr(hr, "function_blame_rows", None)
+ if fn_blame_rows:
+ await upsert_git_function_blame_bulk(session, repo_id, fn_blame_rows)
# Snapshot the run for trend tracking (rolling delete inside).
kpis = hr.kpis or {}
try:
diff --git a/packages/server/src/repowise/server/routers/code_health.py b/packages/server/src/repowise/server/routers/code_health.py
index 125ca202b..2dc95ea49 100644
--- a/packages/server/src/repowise/server/routers/code_health.py
+++ b/packages/server/src/repowise/server/routers/code_health.py
@@ -19,6 +19,7 @@ from repowise.core.analysis.health.models import Severity
from repowise.core.analysis.health.scoring import (
CATEGORY_CAPS,
biomarker_category,
+ biomarker_weight,
severity_deduction,
)
from repowise.core.analysis.health.suggestions import suggestion_for as _suggestion_for
@@ -275,50 +276,92 @@ async def list_health_files(
}
-def _score_breakdown_from_findings(findings: list[Any]) -> dict:
- """Recompute per-category deductions from open findings of one file.
+def _finding_details(f: Any) -> dict:
+ """Return a finding's details as a dict, from either a live ``details``
+ attr (tests) or the stored ``details_json`` column (the ORM row)."""
+ d = getattr(f, "details", None)
+ if isinstance(d, dict):
+ return d
+ raw = getattr(f, "details_json", None)
+ if raw:
+ try:
+ parsed = json.loads(raw)
+ return parsed if isinstance(parsed, dict) else {}
+ except Exception:
+ return {}
+ return {}
+
+
+def _finding_base_deduction(f: Any) -> float:
+ """The pre-cap, pre-weight base deduction for one stored finding.
+
+ Mirrors ``scoring.score_file``: a continuous ``deduction`` override (e.g.
+ coverage scaled by the uncovered fraction, recorded in the finding's
+ ``details``) takes the place of the discrete severity table. Reading the
+ override here — instead of always recomputing from the severity band — is
+ what lets the breakdown show the continuous coverage gradient rather than a
+ band proxy.
+ """
+ override = _finding_details(f).get("deduction")
+ if isinstance(override, (int, float)):
+ return float(override)
+ sev = Severity(f.severity) if not isinstance(f.severity, Severity) else f.severity
+ return severity_deduction(sev)
+
- Mirrors ``scoring.score_file`` so the dashboard can show how a file's
- score was built up — even though the scoring math runs at index time,
- not at request time.
+def _score_breakdown_from_findings(findings: list[Any]) -> dict:
+ """Reconstruct per-category deductions from open findings of one file.
+
+ The applied per-finding impact is read from the **stored**
+ ``health_impact`` (the exact, already-weighted-and-capped value computed by
+ ``scoring.score_file`` at index time), so the breakdown reproduces the
+ file's score and surfaces continuous signals (the coverage gradient) instead
+ of a severity-band proxy. The raw (pre-cap) figure is reconstructed with the
+ same ``base x weight`` formula scoring uses, so a capped category is honest
+ about how much it shed.
"""
- raw_per_cat: dict[str, list[tuple[Any, float]]] = {}
+ per_cat: dict[str, list[Any]] = {}
for f in findings:
- sev = Severity(f.severity) if not isinstance(f.severity, Severity) else f.severity
- d = severity_deduction(sev)
- cat = biomarker_category(f.biomarker_type)
- raw_per_cat.setdefault(cat, []).append((f, d))
+ per_cat.setdefault(biomarker_category(f.biomarker_type), []).append(f)
categories: list[dict] = []
total_deduction = 0.0
for cat, cap in CATEGORY_CAPS.items():
- entries = raw_per_cat.get(cat, [])
- raw_sum = sum(d for _, d in entries)
- capped = min(raw_sum, cap)
- scale = (cap / raw_sum) if raw_sum > cap and raw_sum > 0 else 1.0
+ entries = per_cat.get(cat, [])
+ if not entries:
+ continue
+ raw_per_finding = [
+ _finding_base_deduction(f) * biomarker_weight(f.biomarker_type) for f in entries
+ ]
+ applied_per_finding = [float(f.health_impact or 0.0) for f in entries]
+ raw_sum = sum(raw_per_finding)
+ applied_sum = sum(applied_per_finding)
categories.append(
{
"category": cat,
"cap": round(cap, 2),
"raw_deduction": round(raw_sum, 3),
- "applied_deduction": round(capped, 3),
- "capped": raw_sum > cap,
+ "applied_deduction": round(applied_sum, 3),
+ # Category shed weight iff its applied total is held at the cap.
+ "capped": applied_sum < raw_sum - 1e-6,
"finding_count": len(entries),
"findings": [
{
"id": f.id,
"biomarker_type": f.biomarker_type,
"severity": f.severity,
- "raw_impact": round(d, 3),
- "applied_impact": round(d * scale, 3),
+ "raw_impact": round(raw, 3),
+ "applied_impact": round(applied, 3),
"function_name": f.function_name,
"reason": f.reason,
}
- for f, d in entries
+ for f, raw, applied in zip(
+ entries, raw_per_finding, applied_per_finding, strict=True
+ )
],
}
)
- total_deduction += capped
+ total_deduction += applied_sum
score = max(1.0, min(10.0, 10.0 - total_deduction))
return {
"score": round(score, 2),
@@ -345,9 +388,7 @@ async def file_score_breakdown(
"metric": _metric_to_dict(metric) if metric else None,
"breakdown": breakdown,
"findings": [_finding_to_dict(f) for f in findings],
- "suggestions": {
- b: _suggestion_for(b) for b in {f.biomarker_type for f in findings}
- },
+ "suggestions": {b: _suggestion_for(b) for b in {f.biomarker_type for f in findings}},
}
@@ -380,9 +421,7 @@ async def health_trend(
d = round(float(after) - float(before), 2)
if d == 0:
continue
- file_deltas.append(
- {"file_path": p, "before": before, "after": after, "delta": d}
- )
+ file_deltas.append({"file_path": p, "before": before, "after": after, "delta": d})
file_deltas.sort(key=lambda r: r["delta"])
return {
@@ -426,7 +465,9 @@ async def update_finding_status(
session: AsyncSession = Depends(get_db_session), # noqa: B008
) -> dict:
if payload.status not in _ALLOWED_STATUSES:
- raise HTTPException(status_code=400, detail=f"status must be one of {sorted(_ALLOWED_STATUSES)}")
+ raise HTTPException(
+ status_code=400, detail=f"status must be one of {sorted(_ALLOWED_STATUSES)}"
+ )
f = await crud.update_health_finding_status(session, finding_id, payload.status)
if f is None:
raise HTTPException(status_code=404, detail="Finding not found")
@@ -542,7 +583,9 @@ async def refactoring_targets(
biomarker: str | None = Query(None, description="Filter to one biomarker type"),
min_severity: str | None = Query(None),
max_effort: str | None = Query(None, description="S | M | L | XL"),
- sort: str = Query("impact_per_effort", pattern="^(impact_per_effort|total_impact|score|finding_count)$"),
+ sort: str = Query(
+ "impact_per_effort", pattern="^(impact_per_effort|total_impact|score|finding_count)$"
+ ),
session: AsyncSession = Depends(get_db_session), # noqa: B008
) -> dict:
"""Refactoring candidates ranked by impact / effort."""
diff --git a/packages/server/src/repowise/server/routers/git.py b/packages/server/src/repowise/server/routers/git.py
index a18db135d..edcfc9d02 100644
--- a/packages/server/src/repowise/server/routers/git.py
+++ b/packages/server/src/repowise/server/routers/git.py
@@ -4,21 +4,29 @@ from __future__ import annotations
import json
+from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
-from fastapi import APIRouter, Depends, HTTPException, Query
+from repowise.core.analysis.change_risk import (
+ ChangeFeatures,
+ RiskNormalizer,
+ score_change,
+)
from repowise.core.persistence import crud
-from repowise.core.persistence.models import GitMetadata
+from repowise.core.persistence.models import GitCommit, GitMetadata
from repowise.server.deps import get_db_session, verify_api_key
from repowise.server.mcp_server.tool_risk import _check_test_gap
from repowise.server.schemas import (
+ CommitDetailResponse,
+ CommitResponse,
GitMetadataResponse,
GitSummaryResponse,
HotspotResponse,
OwnershipEntry,
Paginated,
ReviewerSuggestionsResponse,
+ RiskDriverResponse,
)
from repowise.server.services.reviewer_suggestions import suggest_reviewers
@@ -72,6 +80,113 @@ def _hotspot_from_row(r: GitMetadata) -> HotspotResponse:
)
+def _commit_fields(r: GitCommit, normalizer: RiskNormalizer) -> dict:
+ """Shared CommitResponse field map (raw row + repo-relative normalization)."""
+ return {
+ "sha": r.sha,
+ "short_sha": r.sha[:8],
+ "author_name": r.author_name or "",
+ "author_email": r.author_email or "",
+ "committed_at": r.committed_at,
+ "subject": r.subject or "",
+ "lines_added": r.lines_added or 0,
+ "lines_deleted": r.lines_deleted or 0,
+ "files_changed": r.files_changed or 0,
+ "dirs_changed": r.dirs_changed or 0,
+ "subsystems_changed": r.subsystems_changed or 0,
+ "entropy": r.entropy or 0.0,
+ "is_fix": bool(r.is_fix),
+ "change_risk_score": r.change_risk_score,
+ "change_risk_level": r.change_risk_level,
+ "risk_percentile": normalizer.percentile(r.change_risk_score),
+ "review_priority": normalizer.priority(r.change_risk_score),
+ }
+
+
+def _commit_from_row(r: GitCommit, normalizer: RiskNormalizer) -> CommitResponse:
+ return CommitResponse(**_commit_fields(r, normalizer))
+
+
+def _commit_detail_from_row(r: GitCommit, normalizer: RiskNormalizer) -> CommitDetailResponse:
+ """Map a commit row to its detail view, recomputing the risk-driver
+ breakdown from the persisted Kamei features + author experience.
+
+ The model is deterministic and ships its constants, so re-scoring the
+ stored features reproduces the persisted ``change_risk_score`` exactly —
+ no need to persist the per-driver breakdown.
+ """
+ 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,
+ exp=r.author_experience,
+ is_fix=bool(r.is_fix),
+ author=r.author_name or "",
+ subject=r.subject or "",
+ ref=r.sha,
+ )
+ risk = score_change(feats)
+ drivers = [
+ RiskDriverResponse(
+ feature=d.feature,
+ value=None if d.value != d.value else d.value, # drop NaN (unknown feature)
+ contribution=d.contribution,
+ label=d.label,
+ )
+ for d in risk.top_drivers
+ ]
+ return CommitDetailResponse(
+ **_commit_fields(r, normalizer),
+ author_experience=r.author_experience,
+ drivers=drivers,
+ )
+
+
[email protected]("/{repo_id}/commits", response_model=Paginated[CommitResponse])
+async def get_commits(
+ repo_id: str,
+ sort: str = Query("risk", pattern="^(risk|date)$"),
+ limit: int = Query(50, ge=1, le=200),
+ offset: int = Query(0, ge=0),
+ session: AsyncSession = Depends(get_db_session), # noqa: B008
+) -> Paginated[CommitResponse]:
+ """Per-commit change-risk feed — the review-priority queue.
+
+ ``sort=risk`` (default) orders by raw change-risk score descending (the
+ review-priority order); ``sort=date`` orders by recency. Each commit also
+ carries a **repo-relative** ``risk_percentile`` + ``review_priority`` so the
+ ranking is portable across repos (the absolute calibration band is not).
+ """
+ total = await crud.count_git_commits(session, repo_id)
+ rows = await crud.get_git_commits(session, repo_id, limit=limit, offset=offset, sort=sort)
+ normalizer = RiskNormalizer.from_scores(await crud.get_commit_risk_scores(session, repo_id))
+ items = [_commit_from_row(r, normalizer) for r in rows]
+ next_offset = offset + limit if offset + limit < total else None
+ return Paginated[CommitResponse](
+ items=items,
+ total=total,
+ has_more=next_offset is not None,
+ next_offset=next_offset,
+ )
+
+
[email protected]("/{repo_id}/commits/{sha}", response_model=CommitDetailResponse)
+async def get_commit(
+ repo_id: str,
+ sha: str,
+ session: AsyncSession = Depends(get_db_session), # noqa: B008
+) -> CommitDetailResponse:
+ """A single commit (by full sha or unique prefix) with its risk breakdown."""
+ row = await crud.get_git_commit(session, repo_id, sha)
+ 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)
+
+
@router.get("/{repo_id}/git-metadata", response_model=GitMetadataResponse)
async def get_git_metadata(
repo_id: str,
@@ -108,10 +223,14 @@ async def get_hotspots(
)
total = await session.scalar(select(func.count()).select_from(base.subquery())) or 0
- paged = base.order_by(
- GitMetadata.temporal_hotspot_score.desc().nulls_last(),
- GitMetadata.churn_percentile.desc(),
- ).limit(limit).offset(offset)
+ paged = (
+ base.order_by(
+ GitMetadata.temporal_hotspot_score.desc().nulls_last(),
+ GitMetadata.churn_percentile.desc(),
+ )
+ .limit(limit)
+ .offset(offset)
+ )
rows = (await session.execute(paged)).scalars().all()
items = [_hotspot_from_row(r) for r in rows]
next_offset = offset + limit if offset + limit < total else None
@@ -254,9 +373,7 @@ async def get_git_summary(
stable_count = sum(1 for m in all_meta if m.is_stable)
# Normalize to 0–100 to match the rest of the HTTP API contract.
avg_churn = (
- sum(m.churn_percentile for m in all_meta) / len(all_meta) * 100.0
- if all_meta
- else 0.0
+ sum(m.churn_percentile for m in all_meta) / len(all_meta) * 100.0 if all_meta else 0.0
)
owners: dict[str, int] = {}
diff --git a/packages/server/src/repowise/server/schemas/__init__.py b/packages/server/src/repowise/server/schemas/__init__.py
index cfb6e7b14..25d2f092a 100644
--- a/packages/server/src/repowise/server/schemas/__init__.py
+++ b/packages/server/src/repowise/server/schemas/__init__.py
@@ -57,10 +57,13 @@ from .decisions import (
DecisionStatusUpdate,
)
from .git import (
+ CommitDetailResponse,
+ CommitResponse,
GitMetadataResponse,
GitSummaryResponse,
HotspotResponse,
OwnershipEntry,
+ RiskDriverResponse,
)
from .graph import (
ArchitectureEdgeResponse,
@@ -179,6 +182,8 @@ __all__ = [
"ChatMessageResponse",
"ChatRequest",
"CochangeWarning",
+ "CommitDetailResponse",
+ "CommitResponse",
"CommunityDetailResponse",
"CommunityMember",
"CommunitySummaryItem",
@@ -243,6 +248,7 @@ __all__ = [
"ReviewerEntry",
"ReviewerSuggestion",
"ReviewerSuggestionsResponse",
+ "RiskDriverResponse",
"SearchRequest",
"SearchResultResponse",
"SecurityFindingResponse",
diff --git a/packages/server/src/repowise/server/schemas/git.py b/packages/server/src/repowise/server/schemas/git.py
index 12d92a5a5..0637dfc12 100644
--- a/packages/server/src/repowise/server/schemas/git.py
+++ b/packages/server/src/repowise/server/schemas/git.py
@@ -130,3 +130,49 @@ class GitSummaryResponse(BaseModel):
stable_count: int
average_churn_percentile: float
top_owners: list[dict]
+
+
+class CommitResponse(BaseModel):
+ """One per-commit row from the ``git_commits`` table.
+
+ Carries the stored raw change-risk plus a **repo-relative** normalization
+ (``risk_percentile`` + ``review_priority``). The raw ``change_risk_level``
+ is the absolute calibration band — kept for transparency but de-emphasized
+ in the UI, because it skews high on repos with large typical commits. The
+ review-priority queue ranks on ``risk_percentile`` instead.
+ """
+
+ sha: str
+ short_sha: str
+ author_name: str
+ author_email: str
+ committed_at: datetime | None
+ subject: str
+ lines_added: int
+ lines_deleted: int
+ files_changed: int
+ dirs_changed: int
+ subsystems_changed: int
+ entropy: float
+ is_fix: bool
+ change_risk_score: float | None
+ change_risk_level: str | None
+ # Repo-relative normalization (the portable signal).
+ risk_percentile: float
+ review_priority: str
+
+
+class RiskDriverResponse(BaseModel):
+ """One feature's signed contribution to a commit's change-risk logit."""
+
+ feature: str
+ value: float | None
+ contribution: float
+ label: str
+
+
+class CommitDetailResponse(CommitResponse):
+ """A single commit with its full, attributable risk-driver breakdown."""
+
+ author_experience: int | None = None
+ drivers: list[RiskDriverResponse] = []
diff --git a/packages/types/src/git.ts b/packages/types/src/git.ts
index 7d1dc2bb5..37176b602 100644
--- a/packages/types/src/git.ts
+++ b/packages/types/src/git.ts
@@ -103,6 +103,51 @@ export interface Hotspot {
original_path?: string | null;
}
+/** Repo-relative review priority derived from the score's percentile within
+ * its own repo (terciles) — portable, unlike the absolute calibration band. */
+export type ReviewPriority = "low" | "moderate" | "high";
+
+export interface Commit {
+ sha: string;
+ short_sha: string;
+ author_name: string;
+ author_email: string;
+ committed_at: string | null;
+ subject: string;
+ lines_added: number;
+ lines_deleted: number;
+ files_changed: number;
+ dirs_changed: number;
+ subsystems_changed: number;
+ entropy: number;
+ is_fix: boolean;
+ /** Raw 0–10 change-risk score from the calibrated model (stored). */
+ change_risk_score: number | null;
+ /** Absolute calibration band — kept for transparency, but skews high on
+ * repos with large typical commits; prefer {@link review_priority}. */
+ change_risk_level: ReviewPriority | null;
+ /** Where this commit's score sits within its repo's distribution, 0–100. */
+ risk_percentile: number;
+ /** Repo-relative review priority (the portable ranking signal). */
+ review_priority: ReviewPriority;
+}
+
+/** One feature's signed contribution to a commit's change-risk logit. */
+export interface RiskDriver {
+ feature: string;
+ value: number | null;
+ /** Signed push on the logit; positive raises risk, negative lowers it. */
+ contribution: number;
+ label: string;
+}
+
+export interface CommitDetail extends Commit {
+ /** Author's cumulative prior-commit count at the time of the commit. */
+ author_experience?: number | null;
+ /** Per-feature breakdown, strongest contribution first. */
+ drivers: RiskDriver[];
+}
+
export interface OwnershipEntry {
module_path: string;
primary_owner: string | null;
diff --git a/packages/ui/package.json b/packages/ui/package.json
index ec29db4d8..df072b013 100644
--- a/packages/ui/package.json
+++ b/packages/ui/package.json
@@ -22,6 +22,8 @@
"./graph/*": "./src/graph/*.tsx",
"./git": "./src/git/index.ts",
"./git/*": "./src/git/*.tsx",
+ "./commits": "./src/commits/index.ts",
+ "./commits/*": "./src/commits/*.tsx",
"./dead-code": "./src/dead-code/index.ts",
"./dead-code/*": "./src/dead-code/*.tsx",
"./health": "./src/health/index.ts",
diff --git a/packages/ui/src/commits/commit-detail-card.tsx b/packages/ui/src/commits/commit-detail-card.tsx
new file mode 100644
index 000000000..3b1ec8517
--- /dev/null
+++ b/packages/ui/src/commits/commit-detail-card.tsx
@@ -0,0 +1,118 @@
+import { Bug, GitCommitHorizontal, User } from "lucide-react";
+import { PriorityBadge } from "./priority-badge.js";
+import { RiskDriverBreakdown } from "./risk-driver-breakdown.js";
+import { formatDateTime, formatLOC } from "../lib/format.js";
+import type { CommitDetail } from "@repowise-dev/types/git";
+
+export interface CommitDetailCardProps {
+ commit: CommitDetail;
+ className?: string;
+}
+
+function Stat({ label, value, title }: { label: string; value: string; title?: string }) {
+ return (
+ <div title={title}>
+ <div className="text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">
+ {label}
+ </div>
+ <div className="text-sm tabular-nums text-[var(--color-text-primary)]">{value}</div>
+ </div>
+ );
+}
+
+/**
+ * Drill-down for one commit: header, repo-relative risk summary, the Kamei
+ * change features, and the exact per-feature risk-driver breakdown.
+ */
+export function CommitDetailCard({ commit, className }: CommitDetailCardProps) {
+ const c = commit;
+ return (
+ <div className={className}>
+ {/* Header */}
+ <div className="mb-4 space-y-1.5">
+ <div className="flex items-center gap-2">
+ <GitCommitHorizontal className="h-4 w-4 text-[var(--color-text-tertiary)]" />
+ <span className="font-mono text-xs text-[var(--color-text-secondary)]">
+ {c.short_sha}
+ </span>
+ {c.is_fix && (
+ <span className="inline-flex items-center gap-1 text-xs text-red-400">
+ <Bug className="h-3 w-3" />
+ fix
+ </span>
+ )}
+ </div>
+ <p className="text-sm font-medium text-[var(--color-text-primary)] break-words">
+ {c.subject || "(no subject)"}
+ </p>
+ <div className="flex items-center gap-3 text-xs text-[var(--color-text-tertiary)]">
+ <span className="inline-flex items-center gap-1">
+ <User className="h-3 w-3" />
+ {c.author_name || "unknown"}
+ </span>
+ {c.committed_at && <span>{formatDateTime(c.committed_at)}</span>}
+ </div>
+ </div>
+
+ {/* Risk summary */}
+ <div className="mb-4 flex items-center gap-4 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-3">
+ <div className="text-center">
+ <div className="text-2xl font-semibold tabular-nums text-[var(--color-text-primary)]">
+ {c.risk_percentile.toFixed(0)}
+ <span className="text-sm text-[var(--color-text-tertiary)]">%ile</span>
+ </div>
+ <div className="mt-0.5">
+ <PriorityBadge priority={c.review_priority} />
+ </div>
+ </div>
+ <div className="flex-1 text-xs text-[var(--color-text-secondary)]">
+ Riskier than{" "}
+ <span className="font-medium text-[var(--color-text-primary)] tabular-nums">
+ {c.risk_percentile.toFixed(0)}%
+ </span>{" "}
+ of this repo&apos;s commits.
+ {c.change_risk_score != null && (
+ <span
+ className="ml-1 text-[var(--color-text-tertiary)]"
+ title="Raw calibrated score (0–10). Anchored to the calibration corpus, so it skews high on repos with large typical commits — use the repo-relative percentile above for review order."
+ >
+ (raw {c.change_risk_score.toFixed(1)}/10)
+ </span>
+ )}
+ </div>
+ </div>
+
+ {/* Kamei change features */}
+ <div className="mb-4 grid grid-cols-3 gap-3 sm:grid-cols-4">
+ <Stat label="Lines" value={`+${formatLOC(c.lines_added)} -${formatLOC(c.lines_deleted)}`} />
+ <Stat label="Files" value={String(c.files_changed)} />
+ <Stat label="Dirs" value={String(c.dirs_changed)} title="Distinct directories touched" />
+ <Stat
+ label="Subsystems"
+ value={String(c.subsystems_changed)}
+ title="Distinct top-level subsystems touched"
+ />
+ <Stat
+ label="Entropy"
+ value={c.entropy.toFixed(2)}
+ title="Shannon entropy of the per-file churn distribution — how scattered the change is"
+ />
+ {c.author_experience != null && (
+ <Stat
+ label="Author exp"
+ value={String(c.author_experience)}
+ title="The author's cumulative prior-commit count at the time of this commit"
+ />
+ )}
+ </div>
+
+ {/* Risk drivers */}
+ <div>
+ <p className="mb-2 text-xs font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">
+ Why this score
+ </p>
+ <RiskDriverBreakdown drivers={c.drivers} />
+ </div>
+ </div>
+ );
+}
diff --git a/packages/ui/src/commits/commit-table.tsx b/packages/ui/src/commits/commit-table.tsx
new file mode 100644
index 000000000..495bd26d1
--- /dev/null
+++ b/packages/ui/src/commits/commit-table.tsx
@@ -0,0 +1,228 @@
+"use client";
+
+import { useMemo, useState } from "react";
+import { Bug, Search } from "lucide-react";
+import { PriorityBadge } from "./priority-badge.js";
+import { ChurnBar } from "../git/churn-bar.js";
+import { Input } from "../ui/input.js";
+import { EmptyState } from "../shared/empty-state.js";
+import { ResultsFooter } from "../shared/results-footer.js";
+import { formatLOC, formatRelativeTime } from "../lib/format.js";
+import { cn } from "../lib/cn.js";
+import type { Commit, ReviewPriority } from "@repowise-dev/types/git";
+
+export type CommitSort = "risk" | "date";
+
+export interface CommitTableProps {
+ commits: Commit[];
+ /** Server-driven ordering. `risk` = review-priority order, `date` = recency. */
+ sort: CommitSort;
+ onSortChange?: (sort: CommitSort) => void;
+ onSelect?: (commit: Commit) => void;
+ total?: number;
+ hasMore?: boolean;
+ loadingMore?: boolean;
+ onLoadMore?: () => void;
+}
+
+type Filter = "all" | "high" | "fixes";
+
+/**
+ * The review-priority queue: per-commit change-risk, ranked. Ordering is
+ * server-driven (risk vs date); search + priority filters are client-side over
+ * the loaded page. Risk is shown as a **repo-relative** percentile + priority,
+ * so the column is portable across repos.
+ */
+export function CommitTable({
+ commits,
+ sort,
+ onSortChange,
+ onSelect,
+ total,
+ hasMore,
+ loadingMore,
+ onLoadMore,
+}: CommitTableProps) {
+ const [search, setSearch] = useState("");
+ const [filter, setFilter] = useState<Filter>("all");
+
+ const filtered = useMemo(() => {
+ let items = commits;
+ if (search) {
+ const q = search.toLowerCase();
+ items = items.filter(
+ (c) =>
+ c.subject.toLowerCase().includes(q) ||
+ c.author_name.toLowerCase().includes(q) ||
+ c.sha.toLowerCase().includes(q),
+ );
+ }
+ if (filter === "high") items = items.filter((c) => c.review_priority === "high");
+ else if (filter === "fixes") items = items.filter((c) => c.is_fix);
+ return items;
+ }, [commits, search, filter]);
+
+ if (commits.length === 0) {
+ return (
+ <EmptyState
+ title="No commits indexed"
+ description="Per-commit change-risk is captured on the next full index of this repo."
+ />
+ );
+ }
+
+ const filters: { key: Filter; label: string; count: number }[] = [
+ { key: "all", label: "All", count: commits.length },
+ {
+ key: "high",
+ label: "High priority",
+ count: commits.filter((c) => c.review_priority === "high").length,
+ },
+ { key: "fixes", label: "Fixes", count: commits.filter((c) => c.is_fix).length },
+ ];
+
+ const sorts: { key: CommitSort; label: string }[] = [
+ { key: "risk", label: "Review priority" },
+ { key: "date", label: "Most recent" },
+ ];
+
+ return (
+ <div className="space-y-3">
+ <div className="flex flex-wrap items-center gap-2">
+ <div className="relative">
+ <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-[var(--color-text-tertiary)]" />
+ <Input
+ placeholder="Search commits or authors…"
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ className="pl-8 h-8 w-full sm:w-56 text-xs"
+ />
+ </div>
+ <div className="flex flex-wrap rounded-md border border-[var(--color-border-default)] overflow-hidden text-xs">
+ {filters.map((f) => (
+ <button
+ key={f.key}
+ onClick={() => setFilter(f.key)}
+ className={cn(
+ "px-2.5 py-1.5 font-medium transition-colors",
+ filter === f.key
+ ? "bg-[var(--color-accent-primary)] text-[var(--color-text-inverse)]"
+ : "bg-transparent text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)]",
+ )}
+ >
+ {f.label}
+ <span className="ml-1 text-[10px] opacity-70">({f.count})</span>
+ </button>
+ ))}
+ </div>
+ <div className="ml-auto flex rounded-md border border-[var(--color-border-default)] overflow-hidden text-xs">
+ {sorts.map((s) => (
+ <button
+ key={s.key}
+ onClick={() => onSortChange?.(s.key)}
+ aria-pressed={sort === s.key}
+ className={cn(
+ "px-2.5 py-1.5 font-medium transition-colors",
+ sort === s.key
+ ? "bg-[var(--color-bg-elevated)] text-[var(--color-text-primary)]"
+ : "bg-transparent text-[var(--color-text-tertiary)] hover:bg-[var(--color-bg-elevated)]",
+ )}
+ >
+ {s.label}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ {filtered.length === 0 ? (
+ <EmptyState title="No matches" description="Try adjusting your search or filters." />
+ ) : (
+ <div className="rounded-lg border border-[var(--color-border-default)] overflow-x-auto">
+ <table className="w-full min-w-[720px] text-sm">
+ <thead className="sticky top-0 z-10 bg-[var(--color-bg-elevated)]">
+ <tr className="border-b border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]">
+ <th className="px-3 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider w-8">
+ #
+ </th>
+ <th className="px-3 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider">
+ Commit
+ </th>
+ <th className="px-3 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider hidden md:table-cell">
+ Author
+ </th>
+ <th className="px-3 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider w-24 hidden lg:table-cell">
+ When
+ </th>
+ <th className="px-3 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider w-24 hidden lg:table-cell">
+ Lines
+ </th>
+ <th className="px-3 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider w-40">
+ Risk
+ </th>
+ </tr>
+ </thead>
+ <tbody>
+ {filtered.map((c, i) => (
+ <tr
+ key={c.sha}
+ onClick={onSelect ? () => onSelect(c) : undefined}
+ className={cn(
+ "border-b border-[var(--color-border-default)] last:border-0 hover:bg-[var(--color-bg-elevated)] transition-colors",
+ onSelect && "cursor-pointer",
+ )}
+ >
+ <td className="px-3 py-2.5 text-[var(--color-text-tertiary)] tabular-nums text-xs">
+ {i + 1}
+ </td>
+ <td className="px-3 py-2.5 min-w-[200px] max-w-[460px]">
+ <div className="flex items-center gap-2">
+ <span className="font-mono text-[11px] text-[var(--color-text-tertiary)] shrink-0">
+ {c.short_sha}
+ </span>
+ {c.is_fix && <Bug className="h-3 w-3 shrink-0 text-red-400" />}
+ <span
+ className="truncate text-xs text-[var(--color-text-primary)]"
+ title={c.subject}
+ >
+ {c.subject || "(no subject)"}
+ </span>
+ </div>
+ </td>
+ <td className="px-3 py-2.5 text-xs text-[var(--color-text-secondary)] hidden md:table-cell truncate max-w-[140px]">
+ {c.author_name || "—"}
+ </td>
+ <td className="px-3 py-2.5 text-xs text-[var(--color-text-tertiary)] tabular-nums hidden lg:table-cell">
+ {c.committed_at ? formatRelativeTime(c.committed_at) : "—"}
+ </td>
+ <td className="px-3 py-2.5 text-xs tabular-nums hidden lg:table-cell">
+ <span className="text-green-400">+{formatLOC(c.lines_added)}</span>{" "}
+ <span className="text-red-400">-{formatLOC(c.lines_deleted)}</span>
+ </td>
+ <td className="px-3 py-2.5">
+ <div className="flex items-center gap-2">
+ <ChurnBar percentile={c.risk_percentile} className="w-16" />
+ <span className="text-xs text-[var(--color-text-tertiary)] tabular-nums w-8">
+ {Math.round(c.risk_percentile)}%
+ </span>
+ <PriorityBadge priority={c.review_priority as ReviewPriority} />
+ </div>
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ {total != null && (
+ <ResultsFooter
+ shown={filtered.length}
+ total={total}
+ hasMore={!!hasMore}
+ loading={loadingMore}
+ onLoadMore={onLoadMore}
+ noun="commits"
+ />
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/packages/ui/src/commits/credibility-strip.tsx b/packages/ui/src/commits/credibility-strip.tsx
new file mode 100644
index 000000000..b8900ea98
--- /dev/null
+++ b/packages/ui/src/commits/credibility-strip.tsx
@@ -0,0 +1,32 @@
+import { ShieldCheck } from "lucide-react";
+import { cn } from "../lib/cn.js";
+
+/**
+ * Honest credibility note for the change-risk model. The numbers are the
+ * backtested leave-one-repo-out result from `docs/CHANGE_RISK.md` — we show
+ * them rather than imply the score is infallible. The model edges churn-only
+ * on average and is stronger on some repos; it is a ranking aid, not a verdict.
+ */
+export function CredibilityStrip({ className }: { className?: string }) {
+ return (
+ <div
+ className={cn(
+ "flex items-start gap-2 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-3 text-xs text-[var(--color-text-secondary)]",
+ className,
+ )}
+ >
+ <ShieldCheck className="mt-0.5 h-3.5 w-3.5 shrink-0 text-[var(--color-text-tertiary)]" />
+ <p>
+ Change-risk is a calibrated linear model over each commit&apos;s diff shape
+ (size, diffusion, author experience). Backtested leave-one-repo-out it scores{" "}
+ <span className="font-medium text-[var(--color-text-primary)] tabular-nums">
+ 0.772 AUC
+ </span>{" "}
+ vs{" "}
+ <span className="tabular-nums">0.766</span> for a churn-only baseline — a
+ ranking aid for review order, not a verdict. Priority is{" "}
+ <span className="font-medium">relative to this repo&apos;s own distribution</span>.
+ </p>
+ </div>
+ );
+}
diff --git a/packages/ui/src/commits/index.ts b/packages/ui/src/commits/index.ts
new file mode 100644
index 000000000..d2eb647c8
--- /dev/null
+++ b/packages/ui/src/commits/index.ts
@@ -0,0 +1,5 @@
+export * from "./commit-table.js";
+export * from "./commit-detail-card.js";
+export * from "./risk-driver-breakdown.js";
+export * from "./priority-badge.js";
+export * from "./credibility-strip.js";
diff --git a/packages/ui/src/commits/priority-badge.tsx b/packages/ui/src/commits/priority-badge.tsx
new file mode 100644
index 000000000..c026f7048
--- /dev/null
+++ b/packages/ui/src/commits/priority-badge.tsx
@@ -0,0 +1,40 @@
+import { cn } from "../lib/cn.js";
+import type { ReviewPriority } from "@repowise-dev/types/git";
+
+const STYLES: Record<ReviewPriority, string> = {
+ high: "bg-red-500/15 text-red-400 border-red-500/25",
+ moderate: "bg-yellow-500/15 text-yellow-400 border-yellow-500/25",
+ low: "bg-green-500/15 text-green-400 border-green-500/25",
+};
+
+const LABELS: Record<ReviewPriority, string> = {
+ high: "High",
+ moderate: "Moderate",
+ low: "Low",
+};
+
+/**
+ * Review-priority pill. The priority is **repo-relative** (where the commit
+ * sits in its own repo's risk distribution), not the absolute calibration band
+ * — so it stays meaningful on repos whose typical commit is large.
+ */
+export function PriorityBadge({
+ priority,
+ className,
+}: {
+ priority: ReviewPriority;
+ className?: string;
+}) {
+ return (
+ <span
+ className={cn(
+ "inline-flex items-center rounded border px-1.5 py-0.5 text-xs font-medium tabular-nums",
+ STYLES[priority],
+ className,
+ )}
+ title="Review priority relative to this repo's own commit-risk distribution"
+ >
+ {LABELS[priority]}
+ </span>
+ );
+}
diff --git a/packages/ui/src/commits/risk-driver-breakdown.tsx b/packages/ui/src/commits/risk-driver-breakdown.tsx
new file mode 100644
index 000000000..8dd05e4bf
--- /dev/null
+++ b/packages/ui/src/commits/risk-driver-breakdown.tsx
@@ -0,0 +1,63 @@
+import { cn } from "../lib/cn.js";
+import type { RiskDriver } from "@repowise-dev/types/git";
+
+export interface RiskDriverBreakdownProps {
+ drivers: RiskDriver[];
+ className?: string;
+}
+
+/**
+ * Per-feature change-risk attribution. The model is a linear logistic, so each
+ * driver's signed contribution is exact: positive (red, right) pushed risk up,
+ * negative (green, left) pulled it down. Bars are scaled to the strongest
+ * contribution in the set. NaN-valued (unknown) features are skipped.
+ */
+export function RiskDriverBreakdown({ drivers, className }: RiskDriverBreakdownProps) {
+ const shown = drivers.filter((d) => d.value !== null);
+ if (shown.length === 0) return null;
+
+ const maxAbs = Math.max(...shown.map((d) => Math.abs(d.contribution)), 1e-6);
+
+ return (
+ <div className={cn("space-y-1.5", className)}>
+ {shown.map((d) => {
+ const pct = (Math.abs(d.contribution) / maxAbs) * 50; // half-width per side
+ const raises = d.contribution >= 0;
+ return (
+ <div key={d.feature} className="flex items-center gap-2 text-xs">
+ <span
+ className="w-28 shrink-0 truncate text-[var(--color-text-secondary)]"
+ title={d.label}
+ >
+ {d.label}
+ </span>
+ {/* Diverging bar centered on a zero baseline. */}
+ <div className="relative h-3 flex-1 rounded bg-[var(--color-bg-elevated)]">
+ <div className="absolute inset-y-0 left-1/2 w-px bg-[var(--color-border-default)]" />
+ <div
+ className={cn(
+ "absolute inset-y-0 rounded",
+ raises ? "bg-red-500/60" : "bg-green-500/60",
+ )}
+ style={
+ raises
+ ? { left: "50%", width: `${pct}%` }
+ : { right: "50%", width: `${pct}%` }
+ }
+ />
+ </div>
+ <span
+ className={cn(
+ "w-12 shrink-0 text-right tabular-nums",
+ raises ? "text-red-400" : "text-green-400",
+ )}
+ >
+ {raises ? "+" : ""}
+ {d.contribution.toFixed(2)}
+ </span>
+ </div>
+ );
+ })}
+ </div>
+ );
+}
diff --git a/packages/ui/src/health/biomarker-glossary.ts b/packages/ui/src/health/biomarker-glossary.ts
index 41ef97378..c9253830d 100644
--- a/packages/ui/src/health/biomarker-glossary.ts
+++ b/packages/ui/src/health/biomarker-glossary.ts
@@ -12,6 +12,7 @@ export type BiomarkerCategory =
| "size_and_complexity"
| "duplication"
| "test_coverage"
+ | "test_coverage_gradient"
| "organizational";
export interface BiomarkerInfo {
@@ -25,6 +26,7 @@ export const CATEGORY_LABEL: Record<BiomarkerCategory, string> = {
size_and_complexity: "Size & complexity",
duplication: "Duplication",
test_coverage: "Test coverage",
+ test_coverage_gradient: "Coverage gradient",
organizational: "Organizational",
};
@@ -32,6 +34,7 @@ export const CATEGORY_CAP: Record<BiomarkerCategory, number> = {
organizational: 3.5,
structural_complexity: 2.5,
test_coverage: 2.0,
+ test_coverage_gradient: 2.0,
size_and_complexity: 1.5,
duplication: 1.0,
};
@@ -91,6 +94,12 @@ export const BIOMARKER_GLOSSARY: Record<string, BiomarkerInfo> = {
description:
"Specific uncovered lines in a file. Surfaced when a coverage report has been ingested.",
},
+ coverage_gradient: {
+ label: "Coverage gradient",
+ category: "test_coverage_gradient",
+ description:
+ "A continuous coverage penalty proportional to the uncovered fraction — keeps the score sensitive to coverage even on well-tested files where the binary gates never fire.",
+ },
developer_congestion: {
label: "Developer congestion",
category: "organizational",
diff --git a/packages/web/src/app/repos/[id]/commits/loading.tsx b/packages/web/src/app/repos/[id]/commits/loading.tsx
new file mode 100644
index 000000000..4946a1025
--- /dev/null
+++ b/packages/web/src/app/repos/[id]/commits/loading.tsx
@@ -0,0 +1,19 @@
+import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
+
+export default function CommitsLoading() {
+ return (
+ <div className="p-4 sm:p-6 space-y-6 max-w-[1600px]">
+ <div>
+ <Skeleton className="h-7 w-32" />
+ <Skeleton className="h-4 w-72 mt-1.5" />
+ </div>
+ <Skeleton className="h-14 w-full rounded-lg" />
+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
+ {Array.from({ length: 4 }).map((_, i) => (
+ <Skeleton key={i} className="h-20 rounded-lg" />
+ ))}
+ </div>
+ <Skeleton className="h-[400px] w-full rounded-lg" />
+ </div>
+ );
+}
diff --git a/packages/web/src/app/repos/[id]/commits/page.tsx b/packages/web/src/app/repos/[id]/commits/page.tsx
new file mode 100644
index 000000000..65ae5c218
--- /dev/null
+++ b/packages/web/src/app/repos/[id]/commits/page.tsx
@@ -0,0 +1,30 @@
+import type { Metadata } from "next";
+import { GitCommitHorizontal } from "lucide-react";
+import { CommitsExplorer } from "@/components/commits/commits-explorer";
+
+export const metadata: Metadata = { title: "Commits" };
+
+export default async function CommitsPage({
+ params,
+}: {
+ params: Promise<{ id: string }>;
+}) {
+ const { id } = await params;
+
+ return (
+ <div className="p-4 sm:p-6 space-y-6 max-w-[1600px]">
+ <div>
+ <h1 className="text-xl font-semibold text-[var(--color-text-primary)] mb-1 flex items-center gap-2">
+ <GitCommitHorizontal className="h-5 w-5 text-[var(--color-accent-primary)]" />
+ Commits
+ </h1>
+ <p className="text-sm text-[var(--color-text-secondary)]">
+ A review-priority queue — every indexed commit scored for change-risk and ranked
+ relative to this repo&apos;s own history. Open a commit for its per-feature breakdown.
+ </p>
+ </div>
+
+ <CommitsExplorer repoId={id} />
+ </div>
+ );
+}
diff --git a/packages/web/src/components/commits/commits-explorer.tsx b/packages/web/src/components/commits/commits-explorer.tsx
new file mode 100644
index 000000000..e4c07c3a9
--- /dev/null
+++ b/packages/web/src/components/commits/commits-explorer.tsx
@@ -0,0 +1,131 @@
+"use client";
+
+import { useState } from "react";
+import useSWR from "swr";
+import { AlertTriangle, Bug, GitCommitHorizontal } from "lucide-react";
+import { StatCard } from "@repowise-dev/ui/shared/stat-card";
+import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
+import {
+ Sheet,
+ SheetContent,
+ SheetHeader,
+ SheetTitle,
+} from "@repowise-dev/ui/ui/sheet";
+import { CommitTable, type CommitSort } from "@repowise-dev/ui/commits/commit-table";
+import { CommitDetailCard } from "@repowise-dev/ui/commits/commit-detail-card";
+import { CredibilityStrip } from "@repowise-dev/ui/commits/credibility-strip";
+import { getCommit, getCommitsPage } from "@/lib/api/git";
+import type { CommitResponse, Paginated } from "@/lib/api/types";
+
+const PAGE_SIZE = 50;
+
+export function CommitsExplorer({ repoId }: { repoId: string }) {
+ const [sort, setSort] = useState<CommitSort>("risk");
+ const [limit, setLimit] = useState(PAGE_SIZE);
+ const [selectedSha, setSelectedSha] = useState<string | null>(null);
+
+ const { data, isLoading, isValidating, error } = useSWR<Paginated<CommitResponse>>(
+ `commits:${repoId}:${sort}:${limit}`,
+ () => getCommitsPage(repoId, { sort, limit }),
+ { revalidateOnFocus: false, keepPreviousData: true },
+ );
+
+ const { data: detail, isLoading: detailLoading } = useSWR(
+ selectedSha ? `commit:${repoId}:${selectedSha}` : null,
+ () => getCommit(repoId, selectedSha as string),
+ { revalidateOnFocus: false },
+ );
+
+ const list = data?.items ?? [];
+ const total = data?.total ?? list.length;
+ const hasMore = data?.has_more ?? false;
+
+ const highCount = list.filter((c) => c.review_priority === "high").length;
+ const fixCount = list.filter((c) => c.is_fix).length;
+ const avgEntropy =
+ list.length > 0
+ ? list.reduce((s, c) => s + (c.entropy || 0), 0) / list.length
+ : 0;
+
+ if (isLoading && list.length === 0) {
+ return (
+ <div className="space-y-4">
+ <Skeleton className="h-20 w-full" />
+ <Skeleton className="h-96 w-full" />
+ </div>
+ );
+ }
+
+ if (error && list.length === 0) {
+ return (
+ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-4 text-sm text-[var(--color-text-secondary)]">
+ Couldn&apos;t load commits. Per-commit change-risk is captured on the next full index —
+ try running a sync first.
+ </div>
+ );
+ }
+
+ return (
+ <div className="space-y-6">
+ <CredibilityStrip />
+
+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
+ <StatCard
+ label="Commits"
+ value={total}
+ description="with change-risk"
+ icon={<GitCommitHorizontal className="h-4 w-4 text-[var(--color-text-tertiary)]" />}
+ />
+ <StatCard
+ label="High priority"
+ value={highCount}
+ description="top tercile (loaded)"
+ icon={<AlertTriangle className="h-4 w-4 text-red-400" />}
+ />
+ <StatCard
+ label="Fix commits"
+ value={fixCount}
+ description="bug-fix subjects"
+ icon={<Bug className="h-4 w-4 text-orange-400" />}
+ />
+ <StatCard
+ label="Avg entropy"
+ value={avgEntropy.toFixed(2)}
+ description="change diffusion"
+ />
+ </div>
+
+ <CommitTable
+ commits={list}
+ sort={sort}
+ onSortChange={(s) => {
+ setSort(s);
+ setLimit(PAGE_SIZE);
+ }}
+ onSelect={(c) => setSelectedSha(c.sha)}
+ total={total}
+ hasMore={hasMore}
+ loadingMore={isValidating && !isLoading}
+ onLoadMore={() => setLimit((n) => Math.min(n + PAGE_SIZE, 200))}
+ />
+
+ <Sheet open={selectedSha !== null} onOpenChange={(open) => !open && setSelectedSha(null)}>
+ <SheetContent side="right" className="w-[440px] max-w-[92vw] sm:w-[560px]">
+ <SheetHeader>
+ <SheetTitle>Commit change-risk</SheetTitle>
+ </SheetHeader>
+ <div className="flex-1 overflow-y-auto px-4 pb-6">
+ {detailLoading || !detail ? (
+ <div className="space-y-3 pt-2">
+ <Skeleton className="h-24 w-full" />
+ <Skeleton className="h-40 w-full" />
+ </div>
+ ) : (
+ <CommitDetailCard commit={detail} />
+ )}
+ </div>
+ </SheetContent>
+ </Sheet>
+ </div>
+ );
+}
diff --git a/packages/web/src/components/layout/mobile-nav.tsx b/packages/web/src/components/layout/mobile-nav.tsx
index 1611376dc..5737ca932 100644
--- a/packages/web/src/components/layout/mobile-nav.tsx
+++ b/packages/web/src/components/layout/mobile-nav.tsx
@@ -17,6 +17,7 @@ import {
Code2,
Users,
Flame,
+ GitCommitHorizontal,
Trash2,
Radar,
ChevronDown,
@@ -50,6 +51,7 @@ function repoNavItems(repoId: string) {
{ label: "Symbols", href: `/repos/${repoId}/symbols`, icon: Code2 },
{ label: "Ownership", href: `/repos/${repoId}/ownership`, icon: Users },
{ label: "Hotspots", href: `/repos/${repoId}/hotspots`, icon: Flame },
+ { label: "Commits", href: `/repos/${repoId}/commits`, icon: GitCommitHorizontal },
{ label: "Dead Code", href: `/repos/${repoId}/dead-code`, icon: Trash2 },
{ label: "Blast Radius", href: `/repos/${repoId}/blast-radius`, icon: Radar },
{ label: "Decisions", href: `/repos/${repoId}/decisions`, icon: Lightbulb },
diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsx
index f5f61de74..6b0ebc591 100644
--- a/packages/web/src/components/layout/sidebar.tsx
+++ b/packages/web/src/components/layout/sidebar.tsx
@@ -13,6 +13,7 @@ import {
MessageSquare,
Code2,
ShieldAlert,
+ GitCommitHorizontal,
DollarSign,
Settings,
ChevronDown,
@@ -58,6 +59,7 @@ function repoNavItems(repoId: string): NavItem[] {
{ label: "Chat", href: `/repos/${repoId}`, icon: MessageSquare, exact: true },
{ label: "Wiki", href: `/repos/${repoId}/docs`, icon: BookOpen },
{ label: "Risk", href: `/repos/${repoId}/risk`, icon: ShieldAlert },
+ { label: "Commits", href: `/repos/${repoId}/commits`, icon: GitCommitHorizontal },
{ label: "Health", href: `/repos/${repoId}/health`, icon: HeartPulse, exact: true },
{ label: "Graph", href: `/repos/${repoId}/graph`, icon: GitBranch },
{ label: "Knowledge Graph", href: `/repos/${repoId}/c4`, icon: Boxes },
diff --git a/packages/web/src/lib/api/git.ts b/packages/web/src/lib/api/git.ts
index b80e1513b..47f0200ca 100644
--- a/packages/web/src/lib/api/git.ts
+++ b/packages/web/src/lib/api/git.ts
@@ -1,5 +1,7 @@
import { apiGet } from "./client";
import type {
+ CommitDetailResponse,
+ CommitResponse,
GitMetadataResponse,
GitSummaryResponse,
HotspotResponse,
@@ -105,3 +107,27 @@ export async function getGitSummary(
const params = topOwnersLimit ? { top_owners_limit: topOwnersLimit } : undefined;
return apiGet<GitSummaryResponse>(`/api/repos/${repoId}/git-summary`, params);
}
+
+/**
+ * Paginated per-commit change-risk feed — the review-priority queue. `sort`
+ * defaults to `risk` (review-priority order); `date` orders by recency. Each
+ * commit carries a repo-relative `risk_percentile` + `review_priority`.
+ */
+export async function getCommitsPage(
+ repoId: string,
+ options: { sort?: "risk" | "date"; limit?: number; offset?: number } = {},
+): Promise<Paginated<CommitResponse>> {
+ const { sort = "risk", limit = 50, offset = 0 } = options;
+ return apiGet<Paginated<CommitResponse>>(`/api/repos/${repoId}/commits`, {
+ sort,
+ limit,
+ offset,
+ });
+}
+
+export async function getCommit(
+ repoId: string,
+ sha: string,
+): Promise<CommitDetailResponse> {
+ return apiGet<CommitDetailResponse>(`/api/repos/${repoId}/commits/${sha}`);
+}
diff --git a/packages/web/src/lib/api/types/git.ts b/packages/web/src/lib/api/types/git.ts
index 6b13ff782..9a851286c 100644
--- a/packages/web/src/lib/api/types/git.ts
+++ b/packages/web/src/lib/api/types/git.ts
@@ -81,3 +81,37 @@ export interface GitSummaryResponse {
average_churn_percentile: number;
top_owners: Array<{ name: string; email?: string; file_count: number; pct: number }>;
}
+
+export type ReviewPriority = "low" | "moderate" | "high";
+
+export interface CommitResponse {
+ sha: string;
+ short_sha: string;
+ author_name: string;
+ author_email: string;
+ committed_at: string | null;
+ subject: string;
+ lines_added: number;
+ lines_deleted: number;
+ files_changed: number;
+ dirs_changed: number;
+ subsystems_changed: number;
+ entropy: number;
+ is_fix: boolean;
+ change_risk_score: number | null;
+ change_risk_level: ReviewPriority | null;
+ risk_percentile: number;
+ review_priority: ReviewPriority;
+}
+
+export interface RiskDriverResponse {
+ feature: string;
+ value: number | null;
+ contribution: number;
+ label: string;
+}
+
+export interface CommitDetailResponse extends CommitResponse {
+ author_experience?: number | null;
+ drivers: RiskDriverResponse[];
+}
diff --git a/tests/unit/analysis/test_change_risk_normalize.py b/tests/unit/analysis/test_change_risk_normalize.py
new file mode 100644
index 000000000..6c4d15693
--- /dev/null
+++ b/tests/unit/analysis/test_change_risk_normalize.py
@@ -0,0 +1,55 @@
+"""Repo-relative change-risk normalization (RiskNormalizer)."""
+
+from __future__ import annotations
+
+from repowise.core.analysis.change_risk import RiskNormalizer
+
+
+def test_empty_distribution_is_low_zero() -> None:
+ n = RiskNormalizer.from_scores([])
+ assert n.count == 0
+ assert n.percentile(5.0) == 0.0
+ assert n.priority(5.0) == "low"
+
+
+def test_none_score_is_neutral() -> None:
+ n = RiskNormalizer.from_scores([1.0, 2.0, 3.0])
+ assert n.percentile(None) == 0.0
+ assert n.priority(None) == "low"
+
+
+def test_none_values_dropped_from_distribution() -> None:
+ n = RiskNormalizer.from_scores([1.0, None, 3.0, None])
+ assert n.count == 2
+
+
+def test_midrank_percentile_orders_monotonically() -> None:
+ n = RiskNormalizer.from_scores([0.0, 2.0, 4.0, 6.0, 8.0, 10.0])
+ # The lowest score sits below the middle; the top score near the ceiling.
+ assert n.percentile(0.0) < n.percentile(6.0) < n.percentile(10.0)
+ assert n.percentile(10.0) > 90.0
+ assert n.percentile(0.0) < 10.0
+
+
+def test_ties_share_one_percentile() -> None:
+ # Heavy clustering (the skew case): everything equal -> all mid-ranked at 50,
+ # so the absolute "high" band can't fire on the whole repo.
+ n = RiskNormalizer.from_scores([7.0] * 10)
+ assert n.percentile(7.0) == 50.0
+ assert n.priority(7.0) == "moderate"
+
+
+def test_priority_terciles() -> None:
+ n = RiskNormalizer.from_scores([float(i) for i in range(1, 10)]) # 1..9
+ # Bottom third low, middle moderate, top third high.
+ assert n.priority(1.0) == "low"
+ assert n.priority(5.0) == "moderate"
+ assert n.priority(9.0) == "high"
+
+
+def test_priority_is_repo_relative_not_absolute() -> None:
+ # A repo whose commits are ALL high-absolute-risk: the top still reads
+ # "high" but the bottom reads "low" — the band is portable.
+ n = RiskNormalizer.from_scores([8.0, 8.2, 8.4, 8.6, 8.8, 9.0])
+ assert n.priority(8.0) == "low"
+ assert n.priority(9.0) == "high"
diff --git a/tests/unit/ingestion/test_git_commit_rows_integration.py b/tests/unit/ingestion/test_git_commit_rows_integration.py
index c0ffe5990..7393b22a0 100644
--- a/tests/unit/ingestion/test_git_commit_rows_integration.py
+++ b/tests/unit/ingestion/test_git_commit_rows_integration.py
@@ -63,6 +63,40 @@ async def test_index_repo_collects_commit_rows(tmp_path) -> None:
assert fix["files_changed"] == 2
+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
+ or older than *since_ts* — only genuinely new commits are returned."""
+ import git as gitpython
+
+ repo = gitpython.Repo.init(tmp_path)
+ _commit(repo, tmp_path / "a.py", "x = 1\n", "feat: add a")
+ _commit(repo, tmp_path / "b.py", "y = 2\n", "feat: add b")
+ _commit(repo, tmp_path / "c.py", "w = 4\n", "feat: add c")
+
+ idx = GitIndexer(tmp_path, tier=GitIndexTier.FULL)
+
+ # No bound → all three commits captured.
+ all_rows = idx.capture_new_commit_rows()
+ assert len(all_rows) == 3
+
+ # Bound at/after the newest → nothing new. (Commits made in the same second
+ # share a timestamp at 1s git resolution, so a far-future bound is the
+ # robust assertion; the precise boundary is covered by the unit test.)
+ newest_ts = max(r["committed_at"].timestamp() for r in all_rows)
+ assert idx.capture_new_commit_rows(since_ts=int(newest_ts)) == []
+
+
+async def test_capture_new_commit_rows_empty_in_rename_mode(tmp_path) -> None:
+ import git as gitpython
+
+ repo = gitpython.Repo.init(tmp_path)
+ _commit(repo, tmp_path / "a.py", "x = 1\n", "feat: add a")
+ idx = GitIndexer(tmp_path, tier=GitIndexTier.FULL, follow_renames=True)
+ assert idx.capture_new_commit_rows() == []
+
+
@pytest.mark.asyncio
async def test_index_repo_commit_rows_empty_in_rename_mode(tmp_path) -> None:
"""Rename-tracking mode uses the per-file walk (no batched commit index),
diff --git a/tests/unit/persistence/test_git_commits_crud.py b/tests/unit/persistence/test_git_commits_crud.py
index 213bc89ec..3e7edba92 100644
--- a/tests/unit/persistence/test_git_commits_crud.py
+++ b/tests/unit/persistence/test_git_commits_crud.py
@@ -9,8 +9,10 @@ import pytest
from repowise.core.persistence.crud import (
count_git_commits,
delete_git_commits,
+ get_commit_risk_scores,
get_git_commit,
get_git_commits,
+ get_latest_commit_committed_at,
upsert_git_commits_bulk,
)
from tests.unit.persistence.helpers import insert_repo
@@ -100,6 +102,56 @@ async def test_upsert_is_idempotent_on_sha(async_session) -> None:
assert got.change_risk_level == "high"
+async def test_get_commit_risk_scores(async_session) -> None:
+ repo = await insert_repo(async_session)
+ rows = [
+ _row("aaa", risk=2.0, ts=3000),
+ _row("bbb", risk=8.5, ts=1000),
+ _row("ccc", risk=5.0, ts=2000, change_risk_score=None, change_risk_level=None),
+ ]
+ await upsert_git_commits_bulk(async_session, repo.id, rows)
+ await async_session.commit()
+
+ scores = await get_commit_risk_scores(async_session, repo.id)
+ # Null-scored commits are excluded; order is unspecified, so compare as a set.
+ assert sorted(scores) == [2.0, 8.5]
+
+
+async def test_get_latest_commit_committed_at(async_session) -> None:
+ repo = await insert_repo(async_session)
+ assert await get_latest_commit_committed_at(async_session, repo.id) is None
+ base = 1_700_000_000
+ await upsert_git_commits_bulk(
+ async_session,
+ repo.id,
+ [
+ _row("aaa", risk=2.0, ts=base + 300),
+ _row("bbb", risk=8.5, ts=base + 100),
+ _row("ccc", risk=5.0, ts=base + 200),
+ ],
+ )
+ await async_session.commit()
+ latest = await get_latest_commit_committed_at(async_session, repo.id)
+ assert latest is not None
+ # SQLite may return naive; interpret as UTC for the comparison.
+ dt = latest if latest.tzinfo is not None else latest.replace(tzinfo=UTC)
+ assert int(dt.timestamp()) == base + 300
+
+
+async def test_author_experience_round_trips(async_session) -> None:
+ repo = await insert_repo(async_session)
+ await upsert_git_commits_bulk(
+ async_session, repo.id, [_row("exp1", risk=3.0, ts=1000, author_experience=42)]
+ )
+ await async_session.commit()
+ got = await get_git_commit(async_session, repo.id, "exp1")
+ assert got is not None
+ assert got.author_experience == 42
+
+
@pytest.mark.asyncio
async def test_delete_git_commits(async_session) -> None:
repo = await insert_repo(async_session)
diff --git a/tests/unit/persistence/test_git_function_blame_crud.py b/tests/unit/persistence/test_git_function_blame_crud.py
new file mode 100644
index 000000000..9a8ac400f
--- /dev/null
+++ b/tests/unit/persistence/test_git_function_blame_crud.py
@@ -0,0 +1,96 @@
+"""CRUD round-trip tests for the git_function_blame table."""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.persistence.crud import (
+ count_git_function_blame,
+ delete_git_function_blame,
+ get_git_function_blame,
+ get_git_function_blames,
+ upsert_git_function_blame_bulk,
+)
+from tests.unit.persistence.helpers import insert_repo
+
+
+def _row(symbol_id: str, *, mods: int, **over) -> dict:
+ path, _, name = symbol_id.partition("::")
+ base = {
+ "symbol_id": symbol_id,
+ "file_path": path,
+ "function_name": name,
+ "start_line": 1,
+ "end_line": 10,
+ "line_count": 10,
+ "mod_count": mods,
+ "recent_mod_count": 1,
+ "median_author_time": 1_700_000_000,
+ "owner_name": "Ann",
+ "owner_email": "ann@x",
+ "owner_line_pct": 0.7,
+ }
+ base.update(over)
+ return base
+
+
+async def test_upsert_and_rank_by_mods(async_session) -> None:
+ repo = await insert_repo(async_session)
+ await upsert_git_function_blame_bulk(
+ async_session,
+ repo.id,
+ [
+ _row("a.py::foo", mods=2),
+ _row("a.py::bar", mods=9),
+ _row("b.py::baz", mods=5),
+ ],
+ )
+ await async_session.commit()
+
+ assert await count_git_function_blame(async_session, repo.id) == 3
+ ranked = await get_git_function_blames(async_session, repo.id)
+ # Hottest (most-modified) first.
+ assert [r.symbol_id for r in ranked] == ["a.py::bar", "b.py::baz", "a.py::foo"]
+
+
+async def test_scope_by_file_path(async_session) -> None:
+ repo = await insert_repo(async_session)
+ await upsert_git_function_blame_bulk(
+ async_session,
+ repo.id,
+ [_row("a.py::foo", mods=2), _row("a.py::bar", mods=3), _row("b.py::baz", mods=5)],
+ )
+ await async_session.commit()
+
+ only_a = await get_git_function_blames(async_session, repo.id, file_path="a.py")
+ assert {r.symbol_id for r in only_a} == {"a.py::foo", "a.py::bar"}
+
+
+async def test_get_by_symbol_id_and_idempotent_upsert(async_session) -> None:
+ repo = await insert_repo(async_session)
+ await upsert_git_function_blame_bulk(async_session, repo.id, [_row("a.py::foo", mods=2)])
+ await async_session.commit()
+ # Re-upsert same symbol with new mods → update, not duplicate.
+ await upsert_git_function_blame_bulk(
+ async_session, repo.id, [_row("a.py::foo", mods=7, owner_name="Bob")]
+ )
+ await async_session.commit()
+
+ assert await count_git_function_blame(async_session, repo.id) == 1
+ got = await get_git_function_blame(async_session, repo.id, "a.py::foo")
+ assert got is not None
+ assert got.mod_count == 7
+ assert got.owner_name == "Bob"
+
+
+async def test_delete_git_function_blame(async_session) -> None:
+ repo = await insert_repo(async_session)
+ await upsert_git_function_blame_bulk(async_session, repo.id, [_row("a.py::foo", mods=2)])
+ await async_session.commit()
+ await delete_git_function_blame(async_session, repo.id)
+ await async_session.commit()
+ assert await count_git_function_blame(async_session, repo.id) == 0
diff --git a/tests/unit/persistence/test_models.py b/tests/unit/persistence/test_models.py
index 445d8b0a7..9f08f7b6a 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():
"wiki_symbols",
"git_metadata",
"git_commits",
+ "git_function_blame",
"dead_code_findings",
"decision_records",
"decision_evidence",
diff --git a/tests/unit/server/test_git.py b/tests/unit/server/test_git.py
index e94c7f0c7..e3a245ef6 100644
--- a/tests/unit/server/test_git.py
+++ b/tests/unit/server/test_git.py
@@ -144,6 +144,99 @@ async def test_get_co_changes(client: AsyncClient, app) -> None:
assert data["co_change_partners"][0]["file_path"] == "src/utils.py"
+async def _insert_git_commits(session_factory, repo_id: str) -> None:
+ """Insert a small spread of commits with distinct risk scores."""
+ from datetime import UTC, datetime
+
+ def _row(sha: str, risk: float, ts: int, **over) -> dict:
+ base = {
+ "sha": sha,
+ "author_name": "Ann",
+ "author_email": "[email protected]",
+ "committed_at": datetime.fromtimestamp(ts, tz=UTC),
+ "subject": f"commit {sha}",
+ "lines_added": 40,
+ "lines_deleted": 5,
+ "files_changed": 4,
+ "dirs_changed": 2,
+ "subsystems_changed": 1,
+ "entropy": 1.2,
+ "is_fix": False,
+ "author_experience": 3,
+ "change_risk_score": risk,
+ "change_risk_level": "high" if risk >= 7 else "moderate" if risk >= 4 else "low",
+ }
+ base.update(over)
+ return base
+
+ async with get_session(session_factory) as session:
+ await crud.upsert_git_commits_bulk(
+ session,
+ repo_id,
+ [
+ _row("aaaaaaaa11", 2.0, 3000),
+ _row("bbbbbbbb22", 8.5, 1000),
+ _row("cccccccc33", 5.0, 2000),
+ ],
+ )
+
+
+async def test_get_commits_sorted_by_risk(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", params={"sort": "risk"})
+ assert resp.status_code == 200
+ payload = resp.json()
+ assert payload["total"] == 3
+ items = payload["items"]
+ # Risk-descending review-priority order.
+ assert [c["short_sha"] for c in items] == ["bbbbbbbb", "cccccccc", "aaaaaaaa"]
+ top = items[0]
+ assert top["change_risk_score"] == 8.5
+ # Repo-relative normalization: the top commit is the highest percentile and
+ # falls in the top tercile (portable, not the absolute calibration band).
+ assert top["risk_percentile"] > items[-1]["risk_percentile"]
+ assert top["review_priority"] == "high"
+ assert items[-1]["review_priority"] == "low"
+
+
+async def test_get_commits_sorted_by_date(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", params={"sort": "date"})
+ assert resp.status_code == 200
+ items = resp.json()["items"]
+ assert [c["short_sha"] for c in items] == ["aaaaaaaa", "cccccccc", "bbbbbbbb"]
+
+
+async def test_get_commit_detail_has_drivers(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
+ data = resp.json()
+ assert data["sha"] == "bbbbbbbb22"
+ assert data["author_experience"] == 3
+ # Re-scoring the stored features reproduces the persisted score exactly.
+ assert data["change_risk_score"] == 8.5
+ assert len(data["drivers"]) == 7 # la, ld, nf, nd, ns, entropy, exp
+ feats = {d["feature"] for d in data["drivers"]}
+ assert {"la", "exp", "entropy"} <= feats
+
+
+async def test_get_commit_not_found(client: AsyncClient) -> None:
+ repo = await create_test_repo(client)
+ resp = await client.get(f"/api/repos/{repo['id']}/commits/deadbeef")
+ assert resp.status_code == 404
+
+
@pytest.mark.asyncio
async def test_get_git_summary(client: AsyncClient, app) -> None:
repo = await create_test_repo(client)
diff --git a/tests/unit/server/test_health_breakdown.py b/tests/unit/server/test_health_breakdown.py
new file mode 100644
index 000000000..cda6907c3
--- /dev/null
+++ b/tests/unit/server/test_health_breakdown.py
@@ -0,0 +1,76 @@
+"""Unit tests for the score-breakdown helper in the code-health router.
+
+Pins the Task-12.5 fix: the breakdown reads each finding's STORED
+``health_impact`` (the continuous, already-weighted-and-capped value) rather
+than recomputing from the severity band, so the coverage gradient is surfaced
+faithfully and the breakdown reproduces the file's score.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+from repowise.core.analysis.health.models import Severity
+from repowise.core.analysis.health.scoring import biomarker_weight, severity_deduction
+from repowise.server.routers.code_health import (
+ _finding_base_deduction,
+ _score_breakdown_from_findings,
+)
+
+
+def _finding(biomarker_type, severity, health_impact, *, details=None, fid="x"):
+ return SimpleNamespace(
+ id=fid,
+ biomarker_type=biomarker_type,
+ severity=severity,
+ health_impact=health_impact,
+ function_name=None,
+ reason="",
+ details=details or {},
+ )
+
+
+def test_base_deduction_prefers_continuous_override() -> None:
+ # coverage_gradient records its continuous base in details["deduction"].
+ f = _finding("coverage_gradient", Severity.MEDIUM, 1.2, details={"deduction": 1.6})
+ assert _finding_base_deduction(f) == 1.6
+ # Without an override, falls back to the severity band.
+ g = _finding("complex_method", Severity.HIGH, 0.5)
+ assert _finding_base_deduction(g) == severity_deduction(Severity.HIGH)
+
+
+def test_breakdown_uses_stored_impact_and_reproduces_score() -> None:
+ findings = [
+ _finding("coverage_gradient", Severity.MEDIUM, 1.2, details={"deduction": 1.6}, fid="a"),
+ _finding("complex_method", Severity.HIGH, 0.8, fid="b"),
+ ]
+ out = _score_breakdown_from_findings(findings)
+
+ # total = sum of stored impacts; score = 10 - total.
+ assert abs(out["total_deduction"] - 2.0) < 1e-6
+ assert abs(out["score"] - 8.0) < 1e-6
+
+ cats = {c["category"]: c for c in out["categories"]}
+ # The continuous gradient category is present and applied == stored impact.
+ grad = cats["test_coverage_gradient"]
+ assert abs(grad["applied_deduction"] - 1.2) < 1e-6
+ gf = grad["findings"][0]
+ assert abs(gf["applied_impact"] - 1.2) < 1e-6
+ # Raw = continuous base x biomarker weight (NOT a severity-band proxy).
+ assert abs(gf["raw_impact"] - 1.6 * biomarker_weight("coverage_gradient")) < 1e-6
+ # Empty categories are omitted.
+ assert all(c["finding_count"] > 0 for c in out["categories"])
+
+
+def test_breakdown_flags_capped_category() -> None:
+ # Two organizational findings whose raw weighted sum exceeds the 3.5 cap,
+ # but the stored applied impacts are held at the cap.
+ findings = [
+ _finding("co_change_scatter", Severity.CRITICAL, 1.75, fid="a"),
+ _finding("change_entropy", Severity.CRITICAL, 1.75, fid="b"),
+ ]
+ out = _score_breakdown_from_findings(findings)
+ org = next(c for c in out["categories"] if c["category"] == "organizational")
+ # raw (uncapped) should exceed applied (held at cap) → capped flag set.
+ assert org["raw_deduction"] > org["applied_deduction"]
+ assert org["capped"] is True
diff --git a/tests/unit/test_function_blame_rollup.py b/tests/unit/test_function_blame_rollup.py
new file mode 100644
index 000000000..3536975ac
--- /dev/null
+++ b/tests/unit/test_function_blame_rollup.py
@@ -0,0 +1,99 @@
+"""Unit tests for the per-function blame rollup (pure builder)."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+from repowise.core.analysis.health.function_blame_rollup import build_function_blame_rows
+from repowise.core.ingestion.git_indexer.function_blame import BlameIndex
+
+
+@dataclass
+class _Fn:
+ name: str
+ start_line: int
+ end_line: int
+
+
+@dataclass
+class _Fcx:
+ functions: list
+
+
+class _FileInfo:
+ def __init__(self, path: str) -> None:
+ self.path = path
+
+
+class _Pf:
+ def __init__(self, path: str) -> None:
+ self.file_info = _FileInfo(path)
+
+
+_NOW = 1_700_000_000
+_DAY = 86400
+
+
+def _walked_and_meta():
+ # foo: lines 1-3 (Ann, Ann, Bob); bar: lines 5-6 (Carol, recent).
+ idx = BlameIndex(
+ lines={
+ 1: ("s1", _NOW - 400 * _DAY),
+ 2: ("s1", _NOW - 400 * _DAY),
+ 3: ("s2", _NOW - 300 * _DAY),
+ 5: ("s3", _NOW - 10 * _DAY),
+ 6: ("s3", _NOW - 10 * _DAY),
+ },
+ authors={
+ "s1": ("Ann", "ann@x"),
+ "s2": ("Bob", "bob@x"),
+ "s3": ("Carol", "carol@x"),
+ },
+ )
+ pf = _Pf("a.py")
+ fcx = _Fcx(functions=[_Fn("foo", 1, 3), _Fn("bar", 5, 6), _Fn("dead", 8, 9)])
+ return [(pf, fcx)], {"a.py": {"blame_index": idx}}
+
+
+def test_rollup_emits_only_modified_functions() -> None:
+ walked, meta = _walked_and_meta()
+ rows = build_function_blame_rows(walked, meta, now_ts=_NOW)
+ # "dead" (lines 8-9) has no blame coverage → not emitted.
+ assert {r["function_name"] for r in rows} == {"foo", "bar"}
+
+
+def test_rollup_foo_signals() -> None:
+ walked, meta = _walked_and_meta()
+ rows = {r["function_name"]: r for r in build_function_blame_rows(walked, meta, now_ts=_NOW)}
+ foo = rows["foo"]
+ assert foo["symbol_id"] == "a.py::foo"
+ assert foo["mod_count"] == 2 # s1, s2
+ assert foo["line_count"] == 3
+ assert foo["owner_name"] == "Ann" # 2 of 3 lines
+ assert foo["owner_email"] == "ann@x"
+ assert abs(foo["owner_line_pct"] - 2 / 3) < 1e-9
+ # No commit within the last 90 days → recent_mod_count 0.
+ assert foo["recent_mod_count"] == 0
+ assert foo["median_author_time"] is not None
+
+
+def test_rollup_recent_window() -> None:
+ walked, meta = _walked_and_meta()
+ rows = {r["function_name"]: r for r in build_function_blame_rows(walked, meta, now_ts=_NOW)}
+ # bar's only commit is 10 days old → inside the 90-day recent window.
+ assert rows["bar"]["recent_mod_count"] == 1
+ assert rows["bar"]["mod_count"] == 1
+
+
+def test_rollup_empty_when_no_blame() -> None:
+ pf = _Pf("a.py")
+ fcx = _Fcx(functions=[_Fn("foo", 1, 3)])
+ # No blame_index in meta → ESSENTIAL-tier no-op.
+ assert build_function_blame_rows([(pf, fcx)], {"a.py": {}}, now_ts=_NOW) == []
+ # Empty blame index also yields nothing.
+ assert (
+ build_function_blame_rows(
+ [(pf, fcx)], {"a.py": {"blame_index": BlameIndex()}}, now_ts=_NOW
+ )
+ == []
+ )
diff --git a/tests/unit/test_git_commit_rows.py b/tests/unit/test_git_commit_rows.py
index a8967971b..f8d0b5ed5 100644
--- a/tests/unit/test_git_commit_rows.py
+++ b/tests/unit/test_git_commit_rows.py
@@ -78,6 +78,32 @@ def test_commit_sink_collects_full_footprint_including_non_indexable() -> None:
]
+def test_commit_sink_since_ts_drops_old_commits() -> None:
+ """``since_ts`` filters the sink to commits strictly newer than the bound —
+ the incremental capture path's freshness guarantee."""
+ raw = _build_log(
+ [
+ {"sha": "new", "an": "A", "ae": "a@x", "ct": 3000, "subj": "new",
+ "files": [(1, 0, "src/a.py")]},
+ {"sha": "mid", "an": "A", "ae": "a@x", "ct": 2000, "subj": "mid",
+ "files": [(1, 0, "src/a.py")]},
+ {"sha": "old", "an": "A", "ae": "a@x", "ct": 1000, "subj": "old",
+ "files": [(1, 0, "src/a.py")]},
+ ]
+ )
+ repo = MagicMock()
+ repo.git.log.return_value = raw
+
+ sink: list[dict] = []
+ load_commit_index(repo, 100, {"src/a.py"}, commit_sink=sink, since_ts=1500)
+ # Only commits with ts > 1500 survive (3000, 2000).
+ assert sorted(c["sha"] for c in sink) == ["mid", "new"]
+
+ sink2: list[dict] = []
+ load_commit_index(repo, 100, {"src/a.py"}, commit_sink=sink2, since_ts=3000)
+ assert sink2 == []
+
+
def test_commit_sink_default_none_is_noop() -> None:
"""Without a sink the return value and behaviour are unchanged."""
raw = _build_log(
@@ -179,14 +205,14 @@ def test_build_commit_rows_author_experience_is_cumulative() -> None:
},
]
rows = build_commit_rows(parsed)
- # Re-derive exp via the change features by re-scoring would be indirect;
- # instead assert the monotonic relationship through risk's exp driver is
- # consistent — simplest: rebuild and check the experience tally by proxy.
- # Ann's three commits have exp 0,1,2 in time order; Bob's single commit 0.
- # We can't read exp off the row directly, so assert via a fresh computation
- # mirroring the implementation contract: the earliest Ann commit must score
- # at least as risky (lower exp ⇒ higher risk, exp coef is protective).
by_sha = {r["sha"]: r for r in rows}
+ # Ann's three commits have exp 0,1,2 in time order; Bob's single commit 0.
+ # The persisted author_experience is the in-memory cumulative prior count.
+ assert by_sha["c1"]["author_experience"] == 0
+ assert by_sha["c2"]["author_experience"] == 1
+ assert by_sha["c3"]["author_experience"] == 2
+ assert by_sha["b1"]["author_experience"] == 0
+ # Lower experience ⇒ higher risk (exp coefficient is protective).
assert by_sha["c1"]["change_risk_score"] >= by_sha["c3"]["change_risk_score"]