Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(commits): show what a commit did to code health (#2463)
Raghav Chamadiya6e1cf6e7529c
diff --git a/packages/api-client/src/types/git.ts b/packages/api-client/src/types/git.tsindex 8fd9174e9..0995f4dbb 100644--- a/packages/api-client/src/types/git.ts+++ b/packages/api-client/src/types/git.ts@@ -150,10 +150,49 @@ export interface CommitFileResponse {prior_fixes?: number | null;}+/** One thing a commit introduced or worsened. */+export interface CommitHealthFindingResponse {+ change_kind: string;+ dimension: string;+ biomarker_type: string;+ severity: string;+ /** Only set on `worsened`: what the severity was before the commit. */+ severity_before?: string | null;+ path: string;+ symbol?: string | null;+ line_start?: number | null;+ line_end?: number | null;+ /** How directly the commit is responsible, from `added_lines` down to+ * `unknown`. Separates what a change wrote from what it merely touched. */+ attribution_basis: string;+ reason: string;+}++/** What a commit did to code health, computed at index time.+ *+ * Absent rather than empty when the commit was never scanned: the scan is+ * bounded, so older commits routinely have none, and that is not the same+ * claim as "changed nothing". */+export interface CommitHealthResponse {+ /** `available` when every changed file was compared, `partial` when some+ * were skipped (unsupported language, binary, unreadable). */+ status: string;+ introduced_count: number;+ worsened_count: number;+ resolved_count: number;+ files_analyzed: number;+ files_skipped: number;+ /** Worst first, capped. `introduced_count + worsened_count` is the true+ * total, so a shorter list means the rest was not stored. */+ findings: CommitHealthFindingResponse[];+}+export interface CommitDetailResponse extends CommitResponse {drivers: RiskDriverResponse[];agent_channel?: string | null;files?: CommitFileResponse[];+ /** What the commit did to health; null when it was never scanned. */+ health?: CommitHealthResponse | null;}export interface AgentTrendBucket {diff --git a/packages/core/alembic/versions/0076_git_commit_health.py b/packages/core/alembic/versions/0076_git_commit_health.pynew file mode 100644index 000000000..444d6b3aa--- /dev/null+++ b/packages/core/alembic/versions/0076_git_commit_health.py@@ -0,0 +1,103 @@+"""``git_commit_health_deltas`` / ``git_commit_health_findings``: what each commit did to health.++The base-versus-head comparison needs both sides of every changed file and a+working tree, so a hosted read path could never run it. These tables hold the+answer computed at index time.++Two tables rather than one: without a per-commit status row, "no findings" and+"never scanned" are the same empty result, and the scan is deliberately bounded+so unscanned commits are normal rather than exceptional.++The three version columns pin each row to the analyzer that produced it. A+reader treats a mismatch as absent, so a bumped analyzer version invalidates+rows without a migration and the next index refills them.++New tables only — no existing table is touched, so a pre-0076 wiki.db upgrades+without rewriting anything and reads empty tables until the next index.++Revision ID: 0076+Revises: 0075+Create Date: 2026-09-20+"""++from __future__ import annotations++from collections.abc import Sequence++import sqlalchemy as sa+from alembic import op++# revision identifiers+revision: str = "0076"+down_revision: str | None = "0075"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None+++def _repository_fk() -> sa.Column:+ return sa.Column(+ "repository_id",+ sa.String(32),+ sa.ForeignKey("repositories.id", ondelete="CASCADE"),+ nullable=False,+ )+++def upgrade() -> None:+ op.create_table(+ "git_commit_health_deltas",+ sa.Column("id", sa.String(32), primary_key=True),+ _repository_fk(),+ sa.Column("sha", sa.String(40), nullable=False),+ sa.Column("status", sa.String(16), nullable=False, server_default="available"),+ sa.Column("analyzer_version", sa.Integer, nullable=False, server_default="0"),+ sa.Column("rules_fingerprint", sa.String(64), nullable=False, server_default=""),+ sa.Column("performance_model_version", sa.Integer, nullable=False, server_default="0"),+ sa.Column("introduced_count", sa.Integer, nullable=False, server_default="0"),+ sa.Column("worsened_count", sa.Integer, nullable=False, server_default="0"),+ sa.Column("resolved_count", sa.Integer, nullable=False, server_default="0"),+ sa.Column("files_analyzed", sa.Integer, nullable=False, server_default="0"),+ sa.Column("files_skipped", sa.Integer, nullable=False, server_default="0"),+ sa.Column("findings_stored", sa.Integer, nullable=False, server_default="0"),+ sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),+ sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),+ sa.UniqueConstraint("repository_id", "sha", name="uq_git_commit_health_delta"),+ )+ op.create_table(+ "git_commit_health_findings",+ sa.Column("id", sa.String(32), primary_key=True),+ _repository_fk(),+ sa.Column("sha", sa.String(40), nullable=False),+ sa.Column("change_finding_id", sa.String(64), nullable=False),+ sa.Column("position", sa.Integer, nullable=False, server_default="0"),+ sa.Column("change_kind", sa.String(16), nullable=False),+ sa.Column("dimension", sa.String(32), nullable=False),+ sa.Column("biomarker_type", sa.String(64), nullable=False),+ sa.Column("severity", sa.String(16), nullable=False),+ sa.Column("severity_before", sa.String(16), nullable=True),+ sa.Column("file_path", sa.Text, nullable=False),+ sa.Column("symbol", sa.Text, nullable=True),+ sa.Column("line_start", sa.Integer, nullable=True),+ sa.Column("line_end", sa.Integer, nullable=True),+ sa.Column("attribution_basis", sa.String(24), nullable=False, server_default="unknown"),+ sa.Column("health_impact", sa.Float, nullable=False, server_default="0"),+ sa.Column("reason", sa.Text, nullable=False, server_default=""),+ sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),+ sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),+ sa.UniqueConstraint(+ "repository_id", "sha", "change_finding_id", name="uq_git_commit_health_finding"+ ),+ )+ op.create_index(+ "ix_git_commit_health_findings_repo_sha",+ "git_commit_health_findings",+ ["repository_id", "sha"],+ )+++def downgrade() -> None:+ op.drop_index(+ "ix_git_commit_health_findings_repo_sha", table_name="git_commit_health_findings"+ )+ op.drop_table("git_commit_health_findings")+ op.drop_table("git_commit_health_deltas")diff --git a/packages/core/src/repowise/core/analysis/change_health/commit_scan.py b/packages/core/src/repowise/core/analysis/change_health/commit_scan.pynew file mode 100644index 000000000..6cc1d7fae--- /dev/null+++ b/packages/core/src/repowise/core/analysis/change_health/commit_scan.py@@ -0,0 +1,149 @@+"""Run the base-versus-head comparison over a list of commits, for storage.++Turns shas into the rows ``git_commit_health_deltas`` and+``git_commit_health_findings`` hold, so a host with no working tree can answer+for a commit the viewer picks at random.++Serial by measurement: ~0.19s per analysed file single-threaded, but 0.41s+across a thread pool, because the analyzer is GIL-bound. So it bounds itself+by a wall clock instead, leaving older commits unscanned.+"""++from __future__ import annotations++import time+from dataclasses import dataclass, field+from typing import Any++from repowise.core.repo_config import health_rules_fingerprint++from .models import ChangeFinding, ChangeHealthDelta+from .service import ChangeHealthDeltaService, DeltaRequest++#: Findings kept per commit. The delta row carries the true totals, so a+#: capped commit still reports honestly how much it is not showing.+MAX_FINDINGS_PER_COMMIT = 50++#: Statuses worth a row. A comparison that could not run is not a clean+#: commit, and storing it would make "no findings" ambiguous forever.+_STORED_STATUSES = frozenset({"available", "partial"})+++@dataclass(slots=True)+class CommitHealthScan:+ """Rows for the commits that were scanned, and how far the scan got."""++ delta_rows: list[dict] = field(default_factory=list)+ finding_rows: list[dict] = field(default_factory=list)+ scanned: int = 0+ skipped: int = 0+ exhausted_budget: bool = False+++def _delta_row(sha: str, delta: ChangeHealthDelta, kept: int) -> dict:+ fp = delta.fingerprint+ return {+ "sha": sha,+ "status": delta.status,+ "analyzer_version": fp.analyzer_version if fp else 0,+ "rules_fingerprint": fp.rules_fingerprint if fp else "",+ "performance_model_version": fp.performance_model_version if fp else 0,+ "introduced_count": delta.introduced_total,+ "worsened_count": delta.worsened_total,+ "resolved_count": delta.resolved_total,+ "files_analyzed": delta.scope.analyzed,+ "files_skipped": delta.scope.skipped,+ "findings_stored": kept,+ }+++def _ranked(findings: list[ChangeFinding]) -> list[ChangeFinding]:+ """Worst first, so a capped commit keeps the findings worth showing."""+ from .models import SEVERITY_RANK++ return sorted(+ findings,+ key=lambda f: (+ -SEVERITY_RANK.get(f.severity, 0),+ -abs(f.health_impact or 0.0),+ f.path,+ f.change_finding_id,+ ),+ )+++def _finding_rows(sha: str, findings: list[ChangeFinding]) -> list[dict]:+ return [+ {+ "sha": sha,+ "position": position,+ "change_finding_id": f.change_finding_id,+ "change_kind": f.change_kind,+ "dimension": f.dimension,+ "biomarker_type": f.biomarker_type,+ "severity": f.severity,+ "severity_before": f.severity_before,+ "file_path": f.path,+ "symbol": f.symbol,+ "line_start": f.line_start,+ "line_end": f.line_end,+ "attribution_basis": f.attribution_basis,+ "health_impact": float(f.health_impact or 0.0),+ "reason": f.reason,+ }+ for position, f in enumerate(findings)+ ]+++def scan_commits(+ repo_path: str,+ shas: list[str],+ *,+ service: ChangeHealthDeltaService | None = None,+ budget_seconds: float = 0.0,+ max_findings: int = MAX_FINDINGS_PER_COMMIT,+) -> CommitHealthScan:+ """Compare each sha against its first parent and build the storable rows.++ *shas* is scanned in order, so callers put the commits they most want+ covered first. A non-zero *budget_seconds* stops the scan once it is spent,+ leaving the rest unscanned; the caller can tell from+ :attr:`CommitHealthScan.exhausted_budget`.+ """+ scan = CommitHealthScan()+ if not shas:+ return scan++ service = service or ChangeHealthDeltaService(+ repo_path=repo_path, rules_fingerprint=health_rules_fingerprint(repo_path)+ )+ started = time.monotonic()+ for sha in shas:+ if budget_seconds and time.monotonic() - started >= budget_seconds:+ scan.exhausted_budget = True+ break+ try:+ delta = service.compare(DeltaRequest(repo_path, sha))+ except Exception:+ scan.skipped += 1+ continue+ scan.scanned += 1+ if delta.status not in _STORED_STATUSES:+ scan.skipped += 1+ continue+ kept = _ranked(delta.findings)[:max_findings]+ scan.delta_rows.append(_delta_row(sha, delta, len(kept)))+ scan.finding_rows.extend(_finding_rows(sha, kept))+ return scan+++def current_fingerprint(repo_path: str) -> dict[str, Any]:+ """What a freshly computed row would be pinned to, without comparing."""+ from repowise.core.analysis.health.engine import HEALTH_ANALYZER_VERSION+ from repowise.core.analysis.health.perf.causal import PERFORMANCE_MODEL_VERSION++ return {+ "analyzer_version": HEALTH_ANALYZER_VERSION,+ "rules_fingerprint": health_rules_fingerprint(repo_path),+ "performance_model_version": PERFORMANCE_MODEL_VERSION,+ }diff --git a/packages/core/src/repowise/core/persistence/crud/_shared.py b/packages/core/src/repowise/core/persistence/crud/_shared.pyindex f23c88b6a..bab93f981 100644--- a/packages/core/src/repowise/core/persistence/crud/_shared.py+++ b/packages/core/src/repowise/core/persistence/crud/_shared.py@@ -16,6 +16,8 @@ from typing import Anyfrom sqlalchemy import delete, selectfrom sqlalchemy.ext.asyncio import AsyncSession+from repowise.core.persistence.models import _new_uuid, _now_utc+_VALID_JOB_STATUSES = frozenset({"pending", "running", "completed", "failed", "cancelled", "paused"})@@ -256,3 +258,38 @@ async def _batch_delete_in(removed += int(result.rowcount or 0)await session.flush()return removed+++def _row_updater(*natural_key: str) -> Callable[[Any, dict], None]:+ """Build the ``update_fn`` for a table whose rows come in as plain dicts.++ Copies every column the model actually has, never the surrogate id, the+ repository, or *natural_key* — reassigning the key an upsert matched on+ would silently retarget the row.+ """+ held = {"id", "repository_id", *natural_key}++ def update(existing: Any, row: dict) -> None:+ for key, val in row.items():+ if key not in held and hasattr(existing, key):+ setattr(existing, key, val)+ existing.updated_at = _now_utc()++ return update+++def _row_inserter(model: type[Any], repository_id: str) -> Callable[[dict], Any]:+ """Build the matching ``insert_fn``: the same columns, on a fresh row."""++ def insert(row: dict) -> Any:+ return model(+ id=_new_uuid(),+ repository_id=repository_id,+ **{+ k: v+ for k, v in row.items()+ if k not in ("id", "repository_id") and hasattr(model, k)+ },+ )++ return insertdiff --git a/packages/core/src/repowise/core/persistence/crud/git.py b/packages/core/src/repowise/core/persistence/crud/git.pyindex f08d53b4f..8e4c961b5 100644--- a/packages/core/src/repowise/core/persistence/crud/git.py+++ b/packages/core/src/repowise/core/persistence/crud/git.py@@ -16,13 +16,21 @@ from ..models import (FixEvent,GitCommit,GitCommitFile,+ GitCommitHealthDelta,+ GitCommitHealthFinding,GitFunctionBlame,GitMetadata,_new_uuid,_now_utc,)from ..sql import LIKE_ESCAPE, escape_like-from ._shared import _BATCH_SIZE, _batch_delete_in, _batch_upsert_keyed+from ._shared import (+ _BATCH_SIZE,+ _batch_delete_in,+ _batch_upsert_keyed,+ _row_inserter,+ _row_updater,+)# ---------------------------------------------------------------------------# GitMetadata CRUD@@ -351,12 +359,7 @@ WHERE repository_id = :repo_id;# ----------------------------------------------------------------------------def _update_git_commit(existing: GitCommit, row: dict) -> None:- for key, val in row.items():- # ``sha`` is the natural key — never reassign it on update.- if key not in ("id", "repository_id", "sha") and hasattr(existing, key):- setattr(existing, key, val)- existing.updated_at = _now_utc()+_update_git_commit = _row_updater("sha")async def upsert_git_commits_bulk(@@ -373,24 +376,12 @@ async def upsert_git_commits_bulk(item_key_fn=lambda row: row.get("sha", ""),row_key_fn=lambda row: row.sha,update_fn=_update_git_commit,- insert_fn=lambda row: GitCommit(- id=_new_uuid(),- repository_id=repository_id,- **{- k: v- for k, v in row.items()- if k not in ("id", "repository_id") and hasattr(GitCommit, k)- },- ),+ insert_fn=_row_inserter(GitCommit, repository_id),batch_size=_BATCH_SIZE,)-def _update_git_commit_file(existing: GitCommitFile, row: dict) -> None:- for key, val in row.items():- if key not in ("id", "repository_id", "sha", "file_path") and hasattr(existing, key):- setattr(existing, key, val)- existing.updated_at = _now_utc()+_update_git_commit_file = _row_updater("sha", "file_path")async def upsert_git_commit_files_bulk(@@ -407,15 +398,7 @@ async def upsert_git_commit_files_bulk(item_key_fn=lambda row: (row.get("sha", ""), row.get("file_path", "")),row_key_fn=lambda row: (row.sha, row.file_path),update_fn=_update_git_commit_file,- insert_fn=lambda row: GitCommitFile(- id=_new_uuid(),- repository_id=repository_id,- **{- k: v- for k, v in row.items()- if k not in ("id", "repository_id") and hasattr(GitCommitFile, k)- },- ),+ insert_fn=_row_inserter(GitCommitFile, repository_id),batch_size=_BATCH_SIZE,)@@ -456,6 +439,140 @@ async def delete_git_commit_files_by_sha()+# ---------------------------------------------------------------------------+# Per-commit health delta (what a commit introduced, worsened or resolved)+# ---------------------------------------------------------------------------+++_update_git_commit_health_delta = _row_updater("sha")+_update_git_commit_health_finding = _row_updater("sha", "change_finding_id")+++async def upsert_commit_health_bulk(+ session: AsyncSession,+ repository_id: str,+ delta_rows: list[dict],+ finding_rows: list[dict],+) -> None:+ """Store a scan's rows, replacing the findings of every commit it covers.++ The findings are deleted first rather than upserted in place: a rescan can+ return fewer findings than the row it replaces, and a plain upsert would+ leave the surplus behind as findings no commit ever produced.+ """+ shas = [row["sha"] for row in delta_rows if row.get("sha")]+ if shas:+ await delete_commit_health_findings_by_sha(session, repository_id, shas)+ await _batch_upsert_keyed(+ session,+ GitCommitHealthDelta,+ delta_rows,+ prefilter=(GitCommitHealthDelta.repository_id == repository_id,),+ item_key_fn=lambda row: row.get("sha", ""),+ row_key_fn=lambda row: row.sha,+ update_fn=_update_git_commit_health_delta,+ insert_fn=_row_inserter(GitCommitHealthDelta, repository_id),+ batch_size=_BATCH_SIZE,+ )+ await _batch_upsert_keyed(+ session,+ GitCommitHealthFinding,+ finding_rows,+ prefilter=(GitCommitHealthFinding.repository_id == repository_id,),+ item_key_fn=lambda row: (row.get("sha", ""), row.get("change_finding_id", "")),+ row_key_fn=lambda row: (row.sha, row.change_finding_id),+ update_fn=_update_git_commit_health_finding,+ insert_fn=_row_inserter(GitCommitHealthFinding, repository_id),+ batch_size=_BATCH_SIZE,+ )+++async def get_commit_health(+ session: AsyncSession, repository_id: str, sha: str+) -> GitCommitHealthDelta | None:+ """The stored delta for one commit, or None when it was never scanned."""+ result = await session.execute(+ select(GitCommitHealthDelta).where(+ GitCommitHealthDelta.repository_id == repository_id,+ GitCommitHealthDelta.sha == sha,+ )+ )+ return result.scalars().first()+++async def get_commit_health_findings(+ session: AsyncSession, repository_id: str, sha: str+) -> list[GitCommitHealthFinding]:+ """One commit's stored findings, in the worst-first order the scan set."""+ result = await session.execute(+ select(GitCommitHealthFinding)+ .where(+ GitCommitHealthFinding.repository_id == repository_id,+ GitCommitHealthFinding.sha == sha,+ )+ .order_by(GitCommitHealthFinding.position)+ )+ return list(result.scalars().all())+++async def get_scanned_commit_shas(+ session: AsyncSession,+ repository_id: str,+ *,+ analyzer_version: int,+ rules_fingerprint: str,+ performance_model_version: int,+) -> set[str]:+ """Shas already scanned by *this* analyzer, so a scan can skip them.++ A row from an older analyzer is deliberately absent from this set: it will+ be rescanned and overwritten, which is the whole invalidation story.+ """+ rows = await session.execute(+ select(GitCommitHealthDelta.sha).where(+ GitCommitHealthDelta.repository_id == repository_id,+ GitCommitHealthDelta.analyzer_version == analyzer_version,+ GitCommitHealthDelta.rules_fingerprint == rules_fingerprint,+ GitCommitHealthDelta.performance_model_version == performance_model_version,+ )+ )+ return {sha for (sha,) in rows}+++async def delete_commit_health(session: AsyncSession, repository_id: str) -> None:+ """Remove every stored delta and finding (before a clean reindex)."""+ for model in (GitCommitHealthFinding, GitCommitHealthDelta):+ await session.execute(delete(model).where(model.repository_id == repository_id))+ await session.flush()+++async def delete_commit_health_findings_by_sha(+ session: AsyncSession, repository_id: str, shas: Sequence[str]+) -> int:+ """Drop the findings of specific commits, leaving their delta rows alone."""+ return await _batch_delete_in(+ session,+ GitCommitHealthFinding,+ GitCommitHealthFinding.sha,+ shas,+ prefilter=(GitCommitHealthFinding.repository_id == repository_id,),+ )+++async def delete_commit_health_by_sha(+ session: AsyncSession, repository_id: str, shas: Sequence[str]+) -> int:+ """Drop both rows for specific commits, so they leave with their commit."""+ await delete_commit_health_findings_by_sha(session, repository_id, shas)+ return await _batch_delete_in(+ session,+ GitCommitHealthDelta,+ GitCommitHealthDelta.sha,+ shas,+ prefilter=(GitCommitHealthDelta.repository_id == repository_id,),+ )++async def get_commits_missing_offset(session: AsyncSession, repository_id: str, *, limit: int = 20_000) -> list[str]:@@ -671,12 +788,7 @@ async def get_git_commits(# ----------------------------------------------------------------------------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()+_update_git_function_blame = _row_updater("symbol_id")async def upsert_git_function_blame_bulk(@@ -693,15 +805,7 @@ async def upsert_git_function_blame_bulk(item_key_fn=lambda row: row.get("symbol_id", ""),row_key_fn=lambda row: row.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)- },- ),+ insert_fn=_row_inserter(GitFunctionBlame, repository_id),batch_size=_BATCH_SIZE,)@@ -781,12 +885,7 @@ async def get_git_function_blames(# ----------------------------------------------------------------------------def _update_fix_event(existing: FixEvent, row: dict) -> None:- for key, val in row.items():- # ``fix_sha`` + ``file_path`` are the natural key — never reassigned.- if key not in ("id", "repository_id", "fix_sha", "file_path") and hasattr(existing, key):- setattr(existing, key, val)- existing.updated_at = _now_utc()+_update_fix_event = _row_updater("fix_sha", "file_path")async def upsert_fix_events_bulk(@@ -807,15 +906,7 @@ async def upsert_fix_events_bulk(item_key_fn=lambda row: (row.get("fix_sha", ""), row.get("file_path", "")),row_key_fn=lambda row: (row.fix_sha, row.file_path),update_fn=_update_fix_event,- insert_fn=lambda row: FixEvent(- id=_new_uuid(),- repository_id=repository_id,- **{- k: v- for k, v in row.items()- if k not in ("id", "repository_id") and hasattr(FixEvent, k)- },- ),+ insert_fn=_row_inserter(FixEvent, repository_id),batch_size=_BATCH_SIZE,)diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.pyindex fed6fa919..8dfb0143b 100644--- a/packages/core/src/repowise/core/persistence/models.py+++ b/packages/core/src/repowise/core/persistence/models.py@@ -799,6 +799,110 @@ class GitCommitFile(Base):)+class GitCommitHealthDelta(Base):+ """What one commit did to code health, precomputed at index time.++ The comparison behind it needs both sides of every changed file and a+ working tree, so it cannot run on a hosted read path. This row is that+ answer, stored.++ ``status`` distinguishes the three outcomes a reader must not conflate:+ ``available`` (compared cleanly), ``partial`` (some files were skipped),+ and no row at all (never scanned — a scan is bounded, so old commits can+ legitimately have none).++ The three version columns pin the row to the analyzer that produced it.+ A reader compares them against the current versions and treats a mismatch+ as absent rather than stale-but-usable, because findings from two analyzer+ versions cannot be counted together.+ """++ __tablename__ = "git_commit_health_deltas"+ __table_args__ = (+ UniqueConstraint("repository_id", "sha", name="uq_git_commit_health_delta"),+ )++ id: Mapped[str] = mapped_column(String(32), primary_key=True, default=_new_uuid)+ repository_id: Mapped[str] = mapped_column(+ String(32), ForeignKey("repositories.id", ondelete="CASCADE"), nullable=False+ )+ sha: Mapped[str] = mapped_column(String(40), nullable=False)+ status: Mapped[str] = mapped_column(String(16), nullable=False, default="available")++ analyzer_version: Mapped[int] = mapped_column(Integer, nullable=False, default=0)+ rules_fingerprint: Mapped[str] = mapped_column(String(64), nullable=False, default="")+ performance_model_version: Mapped[int] = mapped_column(Integer, nullable=False, default=0)++ # Totals for the whole comparison. `findings_stored` can be lower, because+ # the stored findings are capped; the difference is what the UI is hiding.+ introduced_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0)+ worsened_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0)+ resolved_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0)+ files_analyzed: Mapped[int] = mapped_column(Integer, nullable=False, default=0)+ files_skipped: Mapped[int] = mapped_column(Integer, nullable=False, default=0)+ findings_stored: Mapped[int] = mapped_column(Integer, nullable=False, default=0)++ created_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), nullable=False, default=_now_utc+ )+ updated_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), nullable=False, default=_now_utc, onupdate=_now_utc+ )+++class GitCommitHealthFinding(Base):+ """One thing a commit introduced or worsened, as the delta reported it.++ Only ``introduced`` and ``worsened`` findings are surfaced by the+ comparison, so only those are stored; the ``resolved`` count lives on+ :class:`GitCommitHealthDelta` without per-finding detail.++ ``position`` is the worst-first rank the scan assigned. It is stored rather+ than re-derived so the cap and the display order stay the same answer.+ """++ __tablename__ = "git_commit_health_findings"+ __table_args__ = (+ UniqueConstraint(+ "repository_id", "sha", "change_finding_id", name="uq_git_commit_health_finding"+ ),+ Index("ix_git_commit_health_findings_repo_sha", "repository_id", "sha"),+ )++ id: Mapped[str] = mapped_column(String(32), primary_key=True, default=_new_uuid)+ repository_id: Mapped[str] = mapped_column(+ String(32), ForeignKey("repositories.id", ondelete="CASCADE"), nullable=False+ )+ sha: Mapped[str] = mapped_column(String(40), nullable=False)+ change_finding_id: Mapped[str] = mapped_column(String(64), nullable=False)+ position: Mapped[int] = mapped_column(Integer, nullable=False, default=0)++ change_kind: Mapped[str] = mapped_column(String(16), nullable=False)+ dimension: Mapped[str] = mapped_column(String(32), nullable=False)+ biomarker_type: Mapped[str] = mapped_column(String(64), nullable=False)+ severity: Mapped[str] = mapped_column(String(16), nullable=False)+ # Only set for `worsened`: what the severity was before the commit.+ severity_before: Mapped[str | None] = mapped_column(String(16), nullable=True)++ file_path: Mapped[str] = mapped_column(Text, nullable=False)+ symbol: Mapped[str | None] = mapped_column(Text, nullable=True)+ line_start: Mapped[int | None] = mapped_column(Integer, nullable=True)+ line_end: Mapped[int | None] = mapped_column(Integer, nullable=True)++ # How the finding is tied to the commit, least-to-most direct. Kept so a+ # reader can tell "this change wrote it" from "this change touched it".+ attribution_basis: Mapped[str] = mapped_column(String(24), nullable=False, default="unknown")+ health_impact: Mapped[float] = mapped_column(Float, nullable=False, default=0.0)+ reason: Mapped[str] = mapped_column(Text, nullable=False, default="")++ created_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), nullable=False, default=_now_utc+ )+ updated_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), nullable=False, default=_now_utc, onupdate=_now_utc+ )++class FixEvent(Base):"""One bug-fix commit's effect on one file, with its bug-introducing candidates.diff --git a/packages/core/src/repowise/core/pipeline/commit_health.py b/packages/core/src/repowise/core/pipeline/commit_health.pynew file mode 100644index 000000000..31bba879a--- /dev/null+++ b/packages/core/src/repowise/core/pipeline/commit_health.py@@ -0,0 +1,140 @@+"""Keep the per-commit health delta rows current, for both index paths.++One entry point, :func:`refresh_commit_health`, used by the full index and by+the incremental update. The difference between them is only which shas they+hand over; everything else — what is already scanned, what the budget allows,+how the rows are written — is the same decision and lives here once.++The scan is bounded on purpose — see ``change_health.commit_scan`` for the+per-file cost that forces it. A full index seeds the most recent+:data:`DEFAULT_COMMIT_LIMIT` commits and stops at+:data:`DEFAULT_BUDGET_SECONDS`; this repository's 911 commits would otherwise+take about half an hour. Everything older has no row, which the commit sheet+renders as "not analysed" rather than "nothing found", and updates extend the+covered window one push at a time.+"""++from __future__ import annotations++import asyncio+import os+from typing import Any++import structlog++logger = structlog.get_logger(__name__)++#: Commits a single run will scan, newest first. Sized so a full index of a+#: repository this size pays minutes, not half an hour.+DEFAULT_COMMIT_LIMIT = 150++#: Wall clock one run may spend. The real guard: commit cost varies by an+#: order of magnitude with diff size, so a count alone bounds nothing.+DEFAULT_BUDGET_SECONDS = 300.0+++def _env_number(name: str, default: float) -> float:+ """Read a non-negative numeric override; ignore anything unparseable."""+ raw = os.environ.get(name)+ if raw is None:+ return default+ try:+ value = float(raw)+ except ValueError:+ return default+ return value if value >= 0 else default+++def commit_limit() -> int:+ return int(_env_number("REPOWISE_COMMIT_HEALTH_COMMITS", DEFAULT_COMMIT_LIMIT))+++def budget_seconds() -> float:+ return _env_number("REPOWISE_COMMIT_HEALTH_BUDGET_SECONDS", DEFAULT_BUDGET_SECONDS)+++def recent_shas(commit_rows: list[dict] | None) -> list[str]:+ """Shas from persisted commit rows, newest first.++ Sorted here rather than trusted from the walk: the budget is spent in this+ order, so "newest" has to be a property of the data, not of the caller.+ """+ rows = [row for row in (commit_rows or []) if row.get("sha")]+ rows.sort(key=lambda row: row.get("committed_at") or 0, reverse=True)+ return [row["sha"] for row in rows]+++async def _pending_shas(+ session: Any, repo_id: str, repo_path: str, shas: list[str], limit: int+) -> list[str]:+ """The shas no current-analyzer row covers yet, newest first, capped."""+ from repowise.core.analysis.change_health.commit_scan import current_fingerprint+ from repowise.core.persistence.crud import get_scanned_commit_shas++ done = await get_scanned_commit_shas(+ session, repo_id, **current_fingerprint(repo_path)+ )+ return [sha for sha in shas if sha not in done][:limit]+++async def _scan_and_store(+ session: Any, repo_id: str, repo_path: str, pending: list[str], budget: float+) -> dict[str, int]:+ from repowise.core.analysis.change_health.commit_scan import scan_commits+ from repowise.core.persistence.crud import upsert_commit_health_bulk++ scan = await asyncio.to_thread(scan_commits, repo_path, pending, budget_seconds=budget)+ if scan.delta_rows:+ await upsert_commit_health_bulk(session, repo_id, scan.delta_rows, scan.finding_rows)+ if scan.exhausted_budget:+ logger.info("commit_health_budget_exhausted", scanned=scan.scanned, budget=budget)+ return {+ "candidates": len(pending),+ "scanned": scan.scanned,+ "skipped": scan.skipped,+ "stored": len(scan.delta_rows),+ "findings": len(scan.finding_rows),+ }+++async def refresh_commit_health(+ session: Any,+ repo_id: str,+ repo_path: str,+ shas: list[str],+ *,+ limit: int | None = None,+ budget: float | None = None,+) -> dict[str, int]:+ """Scan the unscanned commits among *shas* and store what they did to health.++ *shas* must be newest first — the budget is spent in that order, so the+ commits a reader is most likely to open get covered first.++ Returns a small stats dict for logging. Never raises: a commit page missing+ one block is a much smaller problem than an index that will not finish.++ The writes run in a savepoint so that staying quiet is actually possible. A+ failed flush marks the whole session for rollback, and the caller keeps+ using it — so without the savepoint, swallowing the error here would hand+ back a poisoned session and take the entire index down several steps later.+ """+ limit = commit_limit() if limit is None else limit+ nothing = dict.fromkeys(("candidates", "scanned", "skipped", "stored", "findings"), 0)+ if not shas or limit <= 0:+ return nothing+ try:+ async with session.begin_nested():+ pending = await _pending_shas(session, repo_id, repo_path, shas, limit)+ if not pending:+ return nothing+ return await _scan_and_store(+ session,+ repo_id,+ repo_path,+ pending,+ budget_seconds() if budget is None else budget,+ )+ except Exception as exc:+ logger.debug("commit_health_refresh_failed", error=str(exc))+ return nothingdiff --git a/packages/core/src/repowise/core/pipeline/incremental.py b/packages/core/src/repowise/core/pipeline/incremental.pyindex 3301b85fd..4d8def532 100644--- a/packages/core/src/repowise/core/pipeline/incremental.py+++ b/packages/core/src/repowise/core/pipeline/incremental.py@@ -1394,6 +1394,15 @@ async def persist_incremental_commits(if file_rows:await upsert_git_commit_files_bulk(session, repo_id, file_rows)+ # What the new commits did to health. An update is a handful of commits, so+ # this is seconds; the same budget still applies if a long gap made it many.+ with timed(timings, "persist.commits.health"):+ from .commit_health import recent_shas, refresh_commit_health++ await refresh_commit_health(+ session, repo_id, str(repo_path), recent_shas(rows)+ )+with timed(timings, "persist.commits.experience"):await reconcile_commit_experience(session, repo_id, indexer)# Fills the commit-offset column on indexes written before it existed, so a@@ -1478,6 +1487,7 @@ async def reconcile_commit_experience(session: Any, repo_id: str, indexer: Any)failure-isolated like the rest of the git-phase refreshes."""from repowise.core.persistence.crud import (+ delete_commit_health_by_sha,delete_git_commit_files_by_sha,delete_git_commits_by_sha,get_commit_experience_inputs,@@ -1494,8 +1504,9 @@ async def reconcile_commit_experience(session: Any, repo_id: str, indexer: Any)orphans = [r["sha"] for r in stored if r["sha"] not in reachable]if orphans:await delete_git_commits_by_sha(session, repo_id, orphans)- # File rows leave with their commit; nothing cascades them.+ # Per-commit rows leave with their commit; nothing cascades them.await delete_git_commit_files_by_sha(session, repo_id, orphans)+ await delete_commit_health_by_sha(session, repo_id, orphans)stored = [r for r in stored if r["sha"] in reachable]logger.info("commit_orphans_pruned", repo_id=repo_id, count=len(orphans))diff --git a/packages/core/src/repowise/core/pipeline/orchestrator.py b/packages/core/src/repowise/core/pipeline/orchestrator.pyindex e23f801bc..dc6b8daf2 100644--- a/packages/core/src/repowise/core/pipeline/orchestrator.py+++ b/packages/core/src/repowise/core/pipeline/orchestrator.py@@ -129,6 +129,10 @@ class PipelineResult:# data module. Populated post-traversal during the graph build phase.tech_stack: list[dict] = field(default_factory=list)+ repo_path: str = ""+ """Working tree this run walked. Empty when the caller did not set it;+ persistence steps that need the tree (the per-commit health scan) skip."""+# External systems parsed from repo manifests (package.json,# pyproject.toml, Cargo.toml, go.mod, .csproj). Powers the C4 L1# System Context view. Plain dicts mirroring ExternalSystemRecord fields@@ -927,6 +931,7 @@ async def run_pipeline(symbol_count = sum(len(pf.symbols) for pf in parsed_files)return PipelineResult(+ repo_path=str(repo_path),parsed_files=parsed_files,file_infos=file_infos,repo_structure=repo_structure,diff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.pyindex 8198b0deb..241f8bff5 100644--- a/packages/core/src/repowise/core/pipeline/persist.py+++ b/packages/core/src/repowise/core/pipeline/persist.py@@ -1718,13 +1718,22 @@ async def replace_git_history(FixEvent,GitCommit,GitCommitFile,+ GitCommitHealthDelta,+ GitCommitHealthFinding,GitMetadata,)# Function blame describes the current source tree and is produced by the# health pass, not by persist_git. Preserve it across a history-window# replacement; scope reconciliation prunes entries for excluded files.- for model in (FixEvent, GitCommit, GitCommitFile, GitMetadata):+ for model in (+ FixEvent,+ GitCommit,+ GitCommitFile,+ GitCommitHealthDelta,+ GitCommitHealthFinding,+ GitMetadata,+ ):await session.execute(delete(model).where(model.repository_id == repo_id))await persist_git(SimpleNamespace(@@ -2246,6 +2255,22 @@ async def persist_kg(kg: Any, session: Any, repo_id: str) -> None:await upsert_kg_node_meta(session, repo_id, file_node_meta)+async def _refresh_commit_health(result: Any, session: Any, repo_id: str) -> None:+ """Seed the per-commit health rows for the commits this run wrote."""+ repo_path = getattr(result, "repo_path", "")+ summary = getattr(result, "git_summary", None)+ if not repo_path or summary is None:+ return+ from .commit_health import recent_shas, refresh_commit_health++ await refresh_commit_health(+ session,+ repo_id,+ repo_path,+ recent_shas(getattr(summary, "commit_rows", None)),+ )++async def persist_pipeline_result(result: Any,session: Any,@@ -2321,6 +2346,11 @@ async def persist_pipeline_result(await persist_analysis(result, session, repo_id)await persist_generation(result, session, repo_id)+ # What each recent commit did to health. Needs the working tree, so it+ # runs here rather than on the read path, and it is bounded: older commits+ # keep no row until a later update reaches them.+ await _refresh_commit_health(result, session, repo_id)+# Sweep structurally-keyed generated pages (module/layer/scc) that this# run did not reproduce — their ids drift between runs, so without the# sweep every re-index strands the previous set as duplicates. Full runsdiff --git a/packages/core/src/repowise/core/repo_config.py b/packages/core/src/repowise/core/repo_config.pyindex 061548192..4b822398f 100644--- a/packages/core/src/repowise/core/repo_config.py+++ b/packages/core/src/repowise/core/repo_config.py@@ -153,6 +153,19 @@ def config_fingerprint(repo_path: Path | str) -> str:return h.hexdigest()+def health_rules_fingerprint(repo_path: Path | str) -> str:+ """:func:`config_fingerprint`, degraded to an empty string when unreadable.++ What a change-health comparison pins its findings to. An empty string is a+ real answer there: it means "rules unknown", which never matches a stored+ fingerprint, so the rows are recomputed rather than trusted.+ """+ try:+ return config_fingerprint(repo_path)+ except Exception:+ return ""++def config_dependency_fingerprints(repo_path: Path | str, *, config: dict[str, Any] | None = None) -> dict[str, str]:diff --git a/packages/server/src/repowise/server/mcp_server/tool_change_risk.py b/packages/server/src/repowise/server/mcp_server/tool_change_risk.pyindex 15e3ffbc1..1e695e039 100644--- a/packages/server/src/repowise/server/mcp_server/tool_change_risk.py+++ b/packages/server/src/repowise/server/mcp_server/tool_change_risk.py@@ -292,8 +292,10 @@ def _delta_service(repo_path: str) -> ChangeHealthDeltaService:_DELTA_SERVICES.move_to_end(repo_path)return service# Built outside the lock: the fingerprint reads config off disk.+ from repowise.core.repo_config import health_rules_fingerprint+service = ChangeHealthDeltaService(- repo_path=repo_path, rules_fingerprint=_rules_fingerprint(repo_path)+ repo_path=repo_path, rules_fingerprint=health_rules_fingerprint(repo_path))with _DELTA_SERVICES_LOCK:existing = _DELTA_SERVICES.get(repo_path)@@ -306,16 +308,6 @@ def _delta_service(repo_path: str) -> ChangeHealthDeltaService:return service-def _rules_fingerprint(repo_path: str) -> str:- """Identity of the effective health rules; empty when they cannot be read."""- try:- from repowise.core.repo_config import config_fingerprint-- return config_fingerprint(repo_path)- except Exception:- return ""--def _compare_health(repo_path: str,revspec: str | None,diff --git a/packages/server/src/repowise/server/routers/git.py b/packages/server/src/repowise/server/routers/git.pyindex 4e1acefa4..ee7f73816 100644--- a/packages/server/src/repowise/server/routers/git.py+++ b/packages/server/src/repowise/server/routers/git.py@@ -50,6 +50,8 @@ from repowise.server.schemas import (CommitEvolutionBucket,CommitEvolutionResponse,CommitFileResponse,+ CommitHealthFindingResponse,+ CommitHealthResponse,CommitResponse,CommitStatsResponse,FixHistoryFileResponse,@@ -220,11 +222,53 @@ async def _commit_files(session: AsyncSession, repo_id: str, sha: str) -> list[C]+async def _commit_health(+ session: AsyncSession, repo_id: str, sha: str+) -> CommitHealthResponse | None:+ """What the commit did to health. None when it was never scanned."""+ try:+ delta = await crud.get_commit_health(session, repo_id, sha)+ rows = await crud.get_commit_health_findings(session, repo_id, sha) if delta else []+ except (OperationalError, ProgrammingError) as exc:+ # An index older than the tables: serve the commit without its health+ # block rather than failing the whole detail view.+ if not is_missing_table(exc):+ raise+ return None+ if delta is None:+ return None+ return CommitHealthResponse(+ status=delta.status,+ introduced_count=delta.introduced_count,+ worsened_count=delta.worsened_count,+ resolved_count=delta.resolved_count,+ files_analyzed=delta.files_analyzed,+ files_skipped=delta.files_skipped,+ findings=[+ CommitHealthFindingResponse(+ change_kind=f.change_kind,+ dimension=f.dimension,+ biomarker_type=f.biomarker_type,+ severity=f.severity,+ severity_before=f.severity_before,+ path=f.file_path,+ symbol=f.symbol,+ line_start=f.line_start,+ line_end=f.line_end,+ attribution_basis=f.attribution_basis,+ reason=f.reason,+ )+ for f in rows+ ],+ )++def _commit_detail_from_row(r: GitCommit,normalizer: RiskNormalizer,author_counts: dict[str, int] | None = None,files: list[CommitFileResponse] | None = None,+ health: CommitHealthResponse | None = None,) -> CommitDetailResponse:"""Map a commit row to its detail view, recomputing the risk-driverbreakdown from the persisted Kamei features + author experience.@@ -248,6 +292,7 @@ def _commit_detail_from_row(drivers=drivers,agent_channel=r.agent_channel,files=files or [],+ health=health,)@@ -511,7 +556,8 @@ async def get_commit(normalizer = RiskNormalizer.from_scores(await crud.get_commit_risk_scores(session, repo_id))author_counts = await _author_commit_counts(session, repo_id)files = await _commit_files(session, repo_id, row.sha)- return _commit_detail_from_row(row, normalizer, author_counts, files)+ health = await _commit_health(session, repo_id, row.sha)+ return _commit_detail_from_row(row, normalizer, author_counts, files, health)@router.get("/{repo_id}/git-metadata", response_model=GitMetadataResponse)diff --git a/packages/server/src/repowise/server/schemas/__init__.py b/packages/server/src/repowise/server/schemas/__init__.pyindex 13ed97eb6..89e9168d3 100644--- a/packages/server/src/repowise/server/schemas/__init__.py+++ b/packages/server/src/repowise/server/schemas/__init__.py@@ -125,6 +125,8 @@ from .git import (CommitEvolutionBucket,CommitEvolutionResponse,CommitFileResponse,+ CommitHealthFindingResponse,+ CommitHealthResponse,CommitResponse,CommitStatsResponse,FixHistoryFileResponse,@@ -342,6 +344,8 @@ __all__ = ["CommitEvolutionBucket","CommitEvolutionResponse","CommitFileResponse",+ "CommitHealthFindingResponse",+ "CommitHealthResponse","CommitResponse","CommitStatsResponse","CommunityDetailResponse",diff --git a/packages/server/src/repowise/server/schemas/git.py b/packages/server/src/repowise/server/schemas/git.pyindex 7185b247a..6f78664c9 100644--- a/packages/server/src/repowise/server/schemas/git.py+++ b/packages/server/src/repowise/server/schemas/git.py@@ -227,6 +227,47 @@ class RiskDriverResponse(BaseModel):label: str+class CommitHealthFindingResponse(BaseModel):+ """One thing a commit introduced or worsened."""++ change_kind: str+ dimension: str+ biomarker_type: str+ severity: str+ #: Only set on ``worsened``: what the severity was before the commit.+ severity_before: str | None = None+ path: str+ symbol: str | None = None+ line_start: int | None = None+ line_end: int | None = None+ #: How directly the commit is responsible, from ``added_lines`` down to+ #: ``unknown``. Lets a reader separate what a change wrote from what it+ #: merely touched.+ attribution_basis: str+ reason: str+++class CommitHealthResponse(BaseModel):+ """What a commit did to code health, as computed at index time.++ Absent on the commit, rather than empty, when the commit was never+ scanned — the scan is bounded, so older commits routinely have no row and+ that is not the same claim as "changed nothing".+ """++ #: ``available`` when every changed file was compared, ``partial`` when+ #: some were skipped (unsupported language, binary, unreadable).+ status: str+ introduced_count: int+ worsened_count: int+ resolved_count: int+ files_analyzed: int+ files_skipped: int+ #: Worst first, capped. ``introduced_count + worsened_count`` is the true+ #: total, so a shorter list means the rest was not stored.+ findings: list[CommitHealthFindingResponse] = []++class CommitDetailResponse(CommitResponse):"""A single commit with its full, attributable risk-driver breakdown."""@@ -235,6 +276,8 @@ class CommitDetailResponse(CommitResponse):#: Files this commit touched, biggest churn first. Empty on an index#: written before per-commit files were captured — re-index to fill it.files: list[CommitFileResponse] = []+ #: What the commit did to health. ``None`` when it was never scanned.+ health: CommitHealthResponse | None = Noneclass AgentTrendBucket(BaseModel):diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.tsindex e22435a17..14d86c02c 100644--- a/packages/types/src/generated/http.ts+++ b/packages/types/src/generated/http.ts@@ -432,6 +432,7 @@ export interface CommitDetailResponse {drivers?: RiskDriverResponse[];agent_channel?: string | null;files?: CommitFileResponse[];+ health?: CommitHealthResponse | null;}/**@@ -473,6 +474,38 @@ export interface CommitFileResponse {prior_fixes?: number | null;}+/** One thing a commit introduced or worsened. */+export interface CommitHealthFindingResponse {+ change_kind: string;+ dimension: string;+ biomarker_type: string;+ severity: string;+ severity_before?: string | null;+ path: string;+ symbol?: string | null;+ line_start?: number | null;+ line_end?: number | null;+ attribution_basis: string;+ reason: string;+}++/**+ * What a commit did to code health, as computed at index time.+ *+ * Absent on the commit, rather than empty, when the commit was never+ * scanned — the scan is bounded, so older commits routinely have no row and+ * that is not the same claim as "changed nothing".+ */+export interface CommitHealthResponse {+ status: string;+ introduced_count: number;+ worsened_count: number;+ resolved_count: number;+ files_analyzed: number;+ files_skipped: number;+ findings?: CommitHealthFindingResponse[];+}+/*** One per-commit row from the ``git_commits`` table.*diff --git a/packages/types/src/git.ts b/packages/types/src/git.tsindex 632e704b6..c3f8bd23b 100644--- a/packages/types/src/git.ts+++ b/packages/types/src/git.ts@@ -179,6 +179,43 @@ export interface CommitFile {prior_fixes?: number | null;}+/** One thing a commit introduced or worsened. */+export interface CommitHealthFinding {+ change_kind: string;+ dimension: string;+ biomarker_type: string;+ severity: string;+ /** Only set on `worsened`: what the severity was before the commit. */+ severity_before?: string | null;+ path: string;+ symbol?: string | null;+ line_start?: number | null;+ line_end?: number | null;+ /** How directly the commit is responsible, from `added_lines` down to+ * `unknown`. Separates what a change wrote from what it merely touched. */+ attribution_basis: string;+ reason: string;+}++/** What a commit did to code health, computed at index time.+ *+ * Absent rather than empty when the commit was never scanned: the scan is+ * bounded, so older commits routinely have none, and that is not the same+ * claim as "changed nothing". */+export interface CommitHealth {+ /** `available` when every changed file was compared, `partial` when some+ * were skipped (unsupported language, binary, unreadable). */+ status: string;+ introduced_count: number;+ worsened_count: number;+ resolved_count: number;+ files_analyzed: number;+ files_skipped: number;+ /** Worst first, capped. `introduced_count + worsened_count` is the true+ * total, so a shorter list means the rest was not stored. */+ findings: CommitHealthFinding[];+}+export interface CommitDetail extends Commit {/** Per-feature breakdown, strongest contribution first. */drivers: RiskDriver[];@@ -187,6 +224,8 @@ export interface CommitDetail extends Commit {/** Files this commit touched, biggest churn first. Empty on an index written* before per-commit files were captured — re-index to fill it. */files?: CommitFile[];+ /** What the commit did to health; null when it was never scanned. */+ health?: CommitHealth | null;}/** One month of agent-vs-human commit volume. */diff --git a/packages/ui/__tests__/commits/commit-detail-card.test.tsx b/packages/ui/__tests__/commits/commit-detail-card.test.tsxindex 7056ec18a..ee7faf7b6 100644--- a/packages/ui/__tests__/commits/commit-detail-card.test.tsx+++ b/packages/ui/__tests__/commits/commit-detail-card.test.tsx@@ -1,6 +1,6 @@import { render, screen } from "@testing-library/react";import { describe, expect, it } from "vitest";-import type { CommitDetail } from "@repowise-dev/types/git";+import type { CommitDetail, CommitHealth } from "@repowise-dev/types/git";import { CommitDetailCard } from "../../src/commits/commit-detail-card";const commit: CommitDetail = {@@ -32,6 +32,40 @@ const files = [{ path: "core/workspace/update.py", lines_added: 3, lines_deleted: 0, prior_fixes: null },];+const health: CommitHealth = {+ status: "available",+ introduced_count: 2,+ worsened_count: 1,+ resolved_count: 4,+ files_analyzed: 4,+ files_skipped: 0,+ findings: [+ {+ change_kind: "worsened",+ dimension: "defect",+ biomarker_type: "complex_method",+ severity: "critical",+ severity_before: "high",+ path: "core/workspace/update.py",+ symbol: "sync_store",+ line_start: 42,+ line_end: 130,+ attribution_basis: "added_lines",+ reason: "sync_store has cyclomatic complexity 26",+ },+ {+ change_kind: "introduced",+ dimension: "maintainability",+ biomarker_type: "low_cohesion",+ severity: "medium",+ path: "cli/commands/update_cmd/command.py",+ line_start: 9,+ attribution_basis: "file_change",+ reason: "Updater has low cohesion (LCOM4=2)",+ },+ ],+};+describe("commit detail card", () => {it("leads with the repo-relative percentile, not a raw score", () => {render(<CommitDetailCard commit={commit} />);@@ -83,4 +117,103 @@ describe("commit detail card", () => {expect(details?.hasAttribute("open")).toBe(false);expect(screen.getByText(/How the diff-shape rank was computed/)).toBeInTheDocument();});+ it("counts what the commit broke and what it fixed", () => {+ render(<CommitDetailCard commit={{ ...commit, health }} />);++ expect(screen.getByText(/Introduced or worsened 3 findings/)).toBeInTheDocument();+ expect(screen.getByText(/2 new, 1 made worse/)).toBeInTheDocument();+ expect(screen.getByText(/Resolved 4 existing findings/)).toBeInTheDocument();+ });++ it("shows where each finding landed, worst first", () => {+ render(<CommitDetailCard commit={{ ...commit, health }} />);++ expect(+ screen.getAllByText(/sync_store has cyclomatic complexity 26/).length,+ ).toBeGreaterThan(0);+ expect(screen.getAllByText(/sync_store — core\/workspace\/update\.py:42/).length).toBeGreaterThan(0);+ expect(screen.getAllByText(/was high/).length).toBeGreaterThan(0);+ });++ it("marks a finding the commit only touched, rather than wrote", () => {+ render(<CommitDetailCard commit={{ ...commit, health }} />);++ expect(+ screen.getAllByText(/in a file this commit touched, not on a line it wrote/).length,+ ).toBeGreaterThan(0);+ });++ it("says a clean comparison is clean, rather than staying silent", () => {+ const clean: CommitHealth = {+ ...health,+ introduced_count: 0,+ worsened_count: 0,+ resolved_count: 0,+ findings: [],+ };+ render(<CommitDetailCard commit={{ ...commit, health: clean }} />);++ expect(screen.getByText(/Compared clean/)).toBeInTheDocument();+ });++ it("says how much of a capped list it is showing", () => {+ const capped: CommitHealth = { ...health, introduced_count: 40, worsened_count: 0 };+ render(<CommitDetailCard commit={{ ...commit, health: capped }} />);++ expect(screen.getByText(/Showing the 2 most severe/)).toBeInTheDocument();+ });++ it("names the files it could not analyse", () => {+ const partial: CommitHealth = { ...health, status: "partial", files_skipped: 3 };+ render(<CommitDetailCard commit={{ ...commit, health: partial }} />);++ expect(screen.getByText(/3 of 7 changed files could not be analysed/)).toBeInTheDocument();+ });++ it("puts health above the file list, which the host already shows", () => {+ const { container } = render(<CommitDetailCard commit={{ ...commit, files, health }} />);++ const headings = Array.from(container.querySelectorAll("h2")).map((h) => h.textContent);+ expect(headings).toEqual([+ "What this commit did to code health",+ "Where this change lands",+ ]);+ });++ it("keeps a long file list collapsed so it cannot bury what is below it", () => {+ const many = Array.from({ length: 12 }, (_, i) => ({+ path: `src/f${i}.py`,+ lines_added: 1,+ lines_deleted: 0,+ prior_fixes: null,+ }));+ const { container } = render(<CommitDetailCard commit={{ ...commit, files: many, health }} />);++ const [healthSection, filesSection] = Array.from(container.querySelectorAll("details"));+ expect(healthSection?.open).toBe(true);+ expect(filesSection?.open).toBe(false);+ // Collapsed, it still says how much is behind it.+ expect(screen.getByText("12 files")).toBeInTheDocument();+ });++ it("leaves a short file list open", () => {+ const { container } = render(<CommitDetailCard commit={{ ...commit, files, health }} />);++ // Only the two content sections; the driver breakdown below stays shut.+ const [healthSection, filesSection] = Array.from(container.querySelectorAll("details"));+ expect([healthSection?.open, filesSection?.open]).toEqual([true, true]);+ });++ it("names the headline count on the collapsed health toggle", () => {+ render(<CommitDetailCard commit={{ ...commit, health }} />);++ expect(screen.getByText("3 introduced or worsened")).toBeInTheDocument();+ });++ it("renders no health section for a commit that was never scanned", () => {+ render(<CommitDetailCard commit={commit} />);++ expect(screen.queryByText(/What this commit did to code health/)).toBeNull();+ expect(screen.queryByText(/Compared clean/)).toBeNull();+ });});diff --git a/packages/ui/src/commits/commit-detail-card.tsx b/packages/ui/src/commits/commit-detail-card.tsxindex 37b1a82ec..9240d2557 100644--- a/packages/ui/src/commits/commit-detail-card.tsx+++ b/packages/ui/src/commits/commit-detail-card.tsx@@ -4,10 +4,14 @@ import { AgentBadge, NewContributorBadge, isNewContributor } from "./agent-badgeimport { PriorityBadge } from "./priority-badge";import { RiskDriverBreakdown, describeDriver } from "./risk-driver-breakdown";import { CommitFilesTable } from "./commit-files-table";+import { CommitHealthTable } from "./commit-health-table";import { PageLede } from "../shared/page-lede";import { OverviewSection } from "../overview/section";import { formatDateTime } from "../lib/format";-import type { CommitDetail } from "@repowise-dev/types/git";+import type { CommitDetail, CommitHealth } from "@repowise-dev/types/git";++/** Above this many files, the list starts collapsed. */+const LONG_FILE_LIST = 10;export interface CommitDetailCardProps {commit: CommitDetail;@@ -31,6 +35,7 @@ export function CommitDetailCard({}: CommitDetailCardProps) {const c = commit;const files = c.files ?? [];+ const health = c.health ?? null;return (<div className={className}>@@ -99,11 +104,28 @@ export function CommitDetailCard({</PageLede></div>+ {health && (+ <OverviewSection+ className="mt-7"+ title="What this commit did to code health"+ description={healthSentence(health)}+ hint={healthHint(health)}+ collapsible+ >+ <CommitHealthTable findings={health.findings} />+ </OverviewSection>+ )}+{files.length > 0 && (<OverviewSectionclassName="mt-7"title="Where this change lands"description="The files this commit touched, and how much bug-fix history each one carries. Unlike the percentile above, this does not grow with the size of the diff."+ hint={`${files.length} file${files.length === 1 ? "" : "s"}`}+ collapsible+ // A long file list is the thing that buries everything below it, and+ // it is the one block a reader can already get from the host.+ defaultOpen={files.length <= LONG_FILE_LIST}><CommitFilesTable files={files} /></OverviewSection>@@ -128,6 +150,50 @@ export function CommitDetailCard({);}+function plural(n: number, word: string): string {+ return `${n} ${word}${n === 1 ? "" : "s"}`;+}++/** The counts, phrased so "2 new, 1 made worse" only appears when it adds+ * something the total does not already say. */+function madePhrase(h: CommitHealth): string | null {+ const made = h.introduced_count + h.worsened_count;+ if (made === 0) return null;+ const split =+ h.introduced_count > 0 && h.worsened_count > 0+ ? ` (${h.introduced_count} new, ${h.worsened_count} made worse)`+ : "";+ return `Introduced or worsened ${plural(made, "finding")}${split}.`;+}++/** What a collapsed health section still says: the count that matters most. */+function healthHint(h: CommitHealth): string {+ const made = h.introduced_count + h.worsened_count;+ if (made > 0) return `${made} introduced or worsened`;+ return h.resolved_count > 0 ? `${h.resolved_count} resolved` : "clean";+}++/**+ * Summarises the comparison, including what it could not see.+ *+ * Counts before the list: the list is capped and the counts are not.+ */+function healthSentence(h: CommitHealth): string {+ const made = h.introduced_count + h.worsened_count;+ const parts = [+ madePhrase(h),+ h.resolved_count > 0 ? `Resolved ${plural(h.resolved_count, "existing finding")}.` : null,+ h.findings.length < made ? `Showing the ${h.findings.length} most severe.` : null,+ h.files_skipped > 0+ ? `${h.files_skipped} of ${h.files_analyzed + h.files_skipped} changed files could not be analysed.`+ : null,+ ].filter((p): p is string => p !== null);++ // Said out loud: silence would read as "not analysed".+ if (parts.length === 0) return "Compared clean: nothing introduced, worsened or resolved.";+ return parts.join(" ");+}+/*** Says so when the two rankings disagree.*diff --git a/packages/ui/src/commits/commit-health-table.tsx b/packages/ui/src/commits/commit-health-table.tsxnew file mode 100644index 000000000..ae7e8fdfb--- /dev/null+++ b/packages/ui/src/commits/commit-health-table.tsx@@ -0,0 +1,82 @@+import { ResponsiveTable, type ResponsiveColumn } from "../shared/responsive-table";+import { SeverityMark } from "../health/severity-mark";+import type { Severity } from "../health/tokens";+import type { CommitHealthFinding } from "@repowise-dev/types/git";++export interface CommitHealthTableProps {+ findings: CommitHealthFinding[];+ className?: string;+}++/** Bases where the change wrote the code the finding sits on. The rest only+ * touched the file, which is a weaker claim and is labelled as one. */+const DIRECT = new Set(["added_lines", "changed_symbol", "new_file"]);++function where(f: CommitHealthFinding): string {+ const at = f.line_start ? `:${f.line_start}` : "";+ return f.symbol ? `${f.symbol} — ${f.path}${at}` : `${f.path}${at}`;+}++const COLUMNS: ResponsiveColumn<CommitHealthFinding>[] = [+ {+ key: "severity",+ header: "Severity",+ headerClassName: "w-24",+ render: (f) => (+ <span className="inline-flex flex-col gap-0.5">+ <SeverityMark severity={f.severity as Severity} />+ {f.change_kind === "worsened" && f.severity_before && (+ <span className="text-[10px] text-[var(--color-text-tertiary)]">+ was {f.severity_before}+ </span>+ )}+ </span>+ ),+ },+ {+ key: "reason",+ header: "What changed",+ cellClassName: "[overflow-wrap:anywhere]",+ render: (f) => (+ <span>+ {f.reason}+ {!DIRECT.has(f.attribution_basis) && (+ <span className="text-[var(--color-text-tertiary)]">+ {" "}+ (in a file this commit touched, not on a line it wrote)+ </span>+ )}+ </span>+ ),+ },+ {+ key: "where",+ header: "Where",+ cellClassName: "font-mono text-[11px] [overflow-wrap:anywhere]",+ headerClassName: "w-64",+ render: where,+ },+];++/**+ * What a commit introduced or worsened, worst first.+ *+ * Only these two kinds are listed. A resolved finding is real good news but has+ * no location worth pointing at any more, so it is counted in the section+ * heading instead of given a row here.+ */+export function CommitHealthTable({ findings, className }: CommitHealthTableProps) {+ if (findings.length === 0) return null;++ return (+ <ResponsiveTable+ className={className}+ columns={COLUMNS}+ rows={findings}+ rowKey={(f) => `${f.path}:${f.line_start ?? 0}:${f.biomarker_type}`}+ caption="Code-health findings this commit introduced or made worse"+ stacked="sm"+ bare+ />+ );+}diff --git a/packages/ui/src/commits/index.ts b/packages/ui/src/commits/index.tsindex 3c7c0141d..1606f4721 100644--- a/packages/ui/src/commits/index.ts+++ b/packages/ui/src/commits/index.ts@@ -2,6 +2,7 @@ export * from "./code-evolution-chart";export * from "./commits-lede";export * from "./commit-table";export * from "./commit-detail-card";+export * from "./commit-health-table";export * from "./risk-driver-breakdown";export * from "./priority-badge";export * from "./credibility-strip";diff --git a/packages/ui/src/overview/section.tsx b/packages/ui/src/overview/section.tsxindex 788d8d35f..a251a6a26 100644--- a/packages/ui/src/overview/section.tsx+++ b/packages/ui/src/overview/section.tsx@@ -13,6 +13,15 @@ export interface OverviewSectionProps {flush?: boolean;/** Anchor target, for deep links that jump to one section of a page. */id?: string;+ /** Turn the heading into a toggle. Native ``<details>``, so the section+ * stays a server component and keyboard handling comes free. */+ collapsible?: boolean;+ /** Only read when *collapsible*. Defaults to open: a section that hides its+ * content by default has to earn it. */+ defaultOpen?: boolean;+ /** Right-aligned on the toggle, e.g. a row count, so a collapsed section+ * still says how much is behind it. */+ hint?: React.ReactNode;className?: string;children: React.ReactNode;}@@ -36,9 +45,57 @@ export function OverviewSection({action,flush = false,id,+ collapsible = false,+ defaultOpen = true,+ hint,className,children,}: OverviewSectionProps) {+ const heading = (+ <h2 className="text-base font-semibold tracking-tight text-[var(--color-text-primary)]">+ {title}+ </h2>+ );+ const body = (+ <>+ {description && (+ <p className="max-w-[62ch] text-xs leading-relaxed text-[var(--color-text-tertiary)] [text-wrap:pretty]">+ {description}+ </p>+ )}+ {children}+ </>+ );++ if (collapsible) {+ return (+ <section+ {...(id ? { id } : {})}+ className={cn(+ id && "scroll-mt-24",+ !flush && "border-t border-[var(--color-border-default)] pt-6 sm:pt-8",+ className,+ )}+ >+ <details open={defaultOpen} className="group flex flex-col gap-3">+ <summary className="flex cursor-pointer list-none flex-wrap items-baseline gap-x-2 gap-y-1 rounded focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]">+ <span+ className="text-[var(--color-text-tertiary)] transition-transform group-open:rotate-90"+ aria-hidden+ >+ ▸+ </span>+ {heading}+ {hint != null && (+ <span className="ml-auto text-xs text-[var(--color-text-tertiary)]">{hint}</span>+ )}+ </summary>+ <div className="mt-3 flex flex-col gap-3">{body}</div>+ </details>+ </section>+ );+ }+return (<section{...(id ? { id } : {})}@@ -51,17 +108,10 @@ export function OverviewSection({)}><div className="flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1">- <h2 className="text-base font-semibold tracking-tight text-[var(--color-text-primary)]">- {title}- </h2>+ {heading}{action}</div>- {description && (- <p className="max-w-[62ch] text-xs leading-relaxed text-[var(--color-text-tertiary)] [text-wrap:pretty]">- {description}- </p>- )}- {children}+ {body}</section>);}diff --git a/tests/unit/analysis/test_commit_health_scan.py b/tests/unit/analysis/test_commit_health_scan.pynew file mode 100644index 000000000..b48764681--- /dev/null+++ b/tests/unit/analysis/test_commit_health_scan.py@@ -0,0 +1,159 @@+"""Row building and budget behaviour of the per-commit health scan."""++from __future__ import annotations++import time++import pytest++from repowise.core.analysis.change_health.commit_scan import scan_commits+from repowise.core.analysis.change_health.models import (+ AnalysisFingerprint,+ ChangeFinding,+ ChangeHealthDelta,+ RevisionId,+ ScopeCounts,+)++FINGERPRINT = AnalysisFingerprint(+ analyzer_version=21, rules_fingerprint="abc", performance_model_version=2+)+++def _finding(fid: str, severity: str = "high", impact: float = 1.0, **over) -> ChangeFinding:+ return ChangeFinding(+ change_finding_id=fid,+ change_kind=over.pop("change_kind", "introduced"),+ dimension="defect",+ biomarker_type="long_method",+ severity=severity,+ path=over.pop("path", "a.py"),+ symbol="f",+ line_start=1,+ line_end=9,+ reason="added 40 lines",+ attribution_basis="added_lines",+ attribution_confidence="high",+ attribution_detail="",+ suggestion="",+ follow_up="",+ health_impact=impact,+ **over,+ )+++def _delta(findings: list[ChangeFinding], status: str = "available", **over) -> ChangeHealthDelta:+ return ChangeHealthDelta(+ status=status,+ explanation="",+ base=RevisionId("a^", "a" * 40, "commit"),+ head=RevisionId("a", "b" * 40, "commit"),+ comparison_basis="",+ fingerprint=FINGERPRINT,+ scope=ScopeCounts(changed=3, eligible=3, analyzed=3),+ findings=findings,+ **over,+ )+++class _StubService:+ """Stands in for the real comparison; records what it was asked for."""++ def __init__(self, by_sha: dict, delay: float = 0.0) -> None:+ self.by_sha = by_sha+ self.delay = delay+ self.seen: list[str] = []++ def compare(self, request):+ self.seen.append(request.revspec)+ if self.delay:+ time.sleep(self.delay)+ result = self.by_sha[request.revspec]+ if isinstance(result, Exception):+ raise result+ return result+++def test_a_delta_row_carries_the_fingerprint_that_produced_it() -> None:+ service = _StubService({"aaa": _delta([_finding("f0")], resolved_total=2)})++ scan = scan_commits("/repo", ["aaa"], service=service)++ (row,) = scan.delta_rows+ assert row["sha"] == "aaa"+ assert row["analyzer_version"] == 21+ assert row["rules_fingerprint"] == "abc"+ assert row["performance_model_version"] == 2+ assert (row["introduced_count"], row["resolved_count"]) == (1, 2)+ assert row["findings_stored"] == 1+++def test_findings_are_stored_worst_first() -> None:+ findings = [+ _finding("low", "low", 0.1),+ _finding("crit", "critical", 0.1),+ _finding("med", "medium", 0.1),+ ]+ service = _StubService({"aaa": _delta(findings)})++ scan = scan_commits("/repo", ["aaa"], service=service)++ assert [r["change_finding_id"] for r in scan.finding_rows] == ["crit", "med", "low"]+ assert [r["position"] for r in scan.finding_rows] == [0, 1, 2]+++def test_the_cap_keeps_the_worst_and_the_row_still_reports_the_true_total() -> None:+ findings = [_finding(f"f{i}", "high", float(i)) for i in range(10)]+ service = _StubService({"aaa": _delta(findings)})++ scan = scan_commits("/repo", ["aaa"], service=service, max_findings=3)++ (row,) = scan.delta_rows+ assert row["introduced_count"] == 10+ assert row["findings_stored"] == 3+ assert [r["change_finding_id"] for r in scan.finding_rows] == ["f9", "f8", "f7"]++[email protected]("status", ["unavailable", "too_large", "unsupported_range"])+def test_a_comparison_that_could_not_run_stores_nothing(status: str) -> None:+ """A stored row would make "no findings" mean two different things."""+ service = _StubService({"aaa": _delta([], status=status)})++ scan = scan_commits("/repo", ["aaa"], service=service)++ assert scan.delta_rows == []+ assert scan.skipped == 1+++def test_a_partial_comparison_is_stored_and_says_so() -> None:+ service = _StubService({"aaa": _delta([_finding("f0")], status="partial")})++ scan = scan_commits("/repo", ["aaa"], service=service)++ assert scan.delta_rows[0]["status"] == "partial"+++def test_one_commit_blowing_up_does_not_abandon_the_rest() -> None:+ service = _StubService({"bad": RuntimeError("boom"), "good": _delta([_finding("f0")])})++ scan = scan_commits("/repo", ["bad", "good"], service=service)++ assert [r["sha"] for r in scan.delta_rows] == ["good"]+ assert scan.skipped == 1+++def test_the_budget_stops_the_scan_and_says_it_ran_out() -> None:+ by_sha = {sha: _delta([]) for sha in ("a", "b", "c", "d")}+ service = _StubService(by_sha, delay=0.05)++ scan = scan_commits("/repo", list(by_sha), service=service, budget_seconds=0.08)++ assert scan.exhausted_budget+ assert len(service.seen) < 4+ assert service.seen == list(by_sha)[: len(service.seen)] # in the order given+++def test_no_shas_is_not_an_error() -> None:+ scan = scan_commits("/repo", [], service=_StubService({}))++ assert (scan.delta_rows, scan.finding_rows, scan.scanned) == ([], [], 0)diff --git a/tests/unit/persistence/test_commit_health_crud.py b/tests/unit/persistence/test_commit_health_crud.pynew file mode 100644index 000000000..baafd652a--- /dev/null+++ b/tests/unit/persistence/test_commit_health_crud.py@@ -0,0 +1,192 @@+"""CRUD round-trip tests for the per-commit health delta tables."""++from __future__ import annotations++import pytest++from repowise.core.persistence.crud import (+ delete_commit_health,+ delete_commit_health_by_sha,+ get_commit_health,+ get_commit_health_findings,+ get_scanned_commit_shas,+ upsert_commit_health_bulk,+)+from tests.unit.persistence.helpers import insert_repo++FINGERPRINT = {+ "analyzer_version": 21,+ "rules_fingerprint": "abc",+ "performance_model_version": 2,+}+++def _delta(sha: str, **over) -> dict:+ return {"sha": sha, "status": "available", **FINGERPRINT, "introduced_count": 1, **over}+++def _finding(sha: str, fid: str, position: int = 0, **over) -> dict:+ return {+ "sha": sha,+ "change_finding_id": fid,+ "position": position,+ "change_kind": "introduced",+ "dimension": "defect",+ "biomarker_type": "long_method",+ "severity": "high",+ "file_path": "a.py",+ "attribution_basis": "added_lines",+ "reason": "added 40 lines to a method",+ **over,+ }+++async def test_findings_come_back_in_the_order_the_scan_set(async_session) -> None:+ repo = await insert_repo(async_session)+ await upsert_commit_health_bulk(+ async_session,+ repo.id,+ [_delta("aaa")],+ [_finding("aaa", "f2", 1), _finding("aaa", "f0", 0), _finding("aaa", "f1", 2)],+ )+ await async_session.commit()++ rows = await get_commit_health_findings(async_session, repo.id, "aaa")++ assert [r.change_finding_id for r in rows] == ["f0", "f2", "f1"]+++async def test_a_rescan_drops_findings_the_new_run_no_longer_reports(async_session) -> None:+ """A plain upsert would leave the surplus behind as phantom findings."""+ repo = await insert_repo(async_session)+ await upsert_commit_health_bulk(+ async_session, repo.id, [_delta("aaa")], [_finding("aaa", "f0"), _finding("aaa", "f1")]+ )+ await async_session.commit()++ await upsert_commit_health_bulk(+ async_session, repo.id, [_delta("aaa", introduced_count=1)], [_finding("aaa", "f0")]+ )+ await async_session.commit()++ rows = await get_commit_health_findings(async_session, repo.id, "aaa")+ assert [r.change_finding_id for r in rows] == ["f0"]+++async def test_a_rescan_can_reinstate_a_finding_it_just_deleted(async_session) -> None:+ """Same id, deleted then written again in one call, with no commit between."""+ repo = await insert_repo(async_session)+ await upsert_commit_health_bulk(+ async_session, repo.id, [_delta("aaa")], [_finding("aaa", "f0", severity="low")]+ )+ await async_session.commit()++ await upsert_commit_health_bulk(+ async_session, repo.id, [_delta("aaa")], [_finding("aaa", "f0", severity="critical")]+ )+ await async_session.commit()++ (row,) = await get_commit_health_findings(async_session, repo.id, "aaa")+ assert row.severity == "critical"+++async def test_a_commit_with_no_findings_still_stores_a_row(async_session) -> None:+ """"Analysed clean" and "never scanned" must not be the same result."""+ repo = await insert_repo(async_session)+ await upsert_commit_health_bulk(+ async_session, repo.id, [_delta("aaa", introduced_count=0)], []+ )+ await async_session.commit()++ delta = await get_commit_health(async_session, repo.id, "aaa")++ assert delta is not None+ assert delta.introduced_count == 0+ assert await get_commit_health(async_session, repo.id, "never-scanned") is None+++async def test_a_row_from_another_analyzer_does_not_count_as_scanned(async_session) -> None:+ repo = await insert_repo(async_session)+ await upsert_commit_health_bulk(+ async_session,+ repo.id,+ [_delta("current"), _delta("older", analyzer_version=20)],+ [],+ )+ await async_session.commit()++ done = await get_scanned_commit_shas(async_session, repo.id, **FINGERPRINT)++ assert done == {"current"}+++async def test_changed_rules_invalidate_a_row_without_a_migration(async_session) -> None:+ repo = await insert_repo(async_session)+ await upsert_commit_health_bulk(async_session, repo.id, [_delta("aaa")], [])+ await async_session.commit()++ done = await get_scanned_commit_shas(+ async_session, repo.id, **{**FINGERPRINT, "rules_fingerprint": "xyz"}+ )++ assert done == set()+++async def test_rows_leave_with_their_commit(async_session) -> None:+ repo = await insert_repo(async_session)+ await upsert_commit_health_bulk(+ async_session,+ repo.id,+ [_delta("aaa"), _delta("bbb")],+ [_finding("aaa", "f0"), _finding("bbb", "f0")],+ )+ await async_session.commit()++ removed = await delete_commit_health_by_sha(async_session, repo.id, ["aaa"])+ await async_session.commit()++ assert removed == 1+ assert await get_commit_health(async_session, repo.id, "aaa") is None+ assert await get_commit_health_findings(async_session, repo.id, "aaa") == []+ assert await get_commit_health(async_session, repo.id, "bbb") is not None+ assert len(await get_commit_health_findings(async_session, repo.id, "bbb")) == 1+++async def test_a_clean_reindex_clears_both_tables(async_session) -> None:+ repo = await insert_repo(async_session)+ await upsert_commit_health_bulk(+ async_session, repo.id, [_delta("aaa")], [_finding("aaa", "f0")]+ )+ await async_session.commit()++ await delete_commit_health(async_session, repo.id)+ await async_session.commit()++ assert await get_commit_health(async_session, repo.id, "aaa") is None+ assert await get_commit_health_findings(async_session, repo.id, "aaa") == []+++async def test_a_full_reindex_wipes_the_health_rows_with_their_commits(async_session) -> None:+ """A rewritten history must not leave rows pointing at vanished shas."""+ from repowise.core.pipeline.persist import replace_git_history++ repo = await insert_repo(async_session)+ await upsert_commit_health_bulk(+ async_session, repo.id, [_delta("gone")], [_finding("gone", "f0")]+ )+ await async_session.commit()++ await replace_git_history(async_session, repo.id, {}, None)+ await async_session.commit()++ assert await get_commit_health(async_session, repo.id, "gone") is None+ assert await get_commit_health_findings(async_session, repo.id, "gone") == []diff --git a/tests/unit/persistence/test_commit_health_refresh.py b/tests/unit/persistence/test_commit_health_refresh.pynew file mode 100644index 000000000..50c55e394--- /dev/null+++ b/tests/unit/persistence/test_commit_health_refresh.py@@ -0,0 +1,71 @@+"""The scan must fail quietly without taking the caller's transaction with it."""++from __future__ import annotations++import pytest+from sqlalchemy import select++from repowise.core.analysis.change_health.commit_scan import CommitHealthScan+from repowise.core.persistence.crud import get_commit_health, upsert_git_commits_bulk+from repowise.core.persistence.models import GitCommit+from repowise.core.pipeline.commit_health import recent_shas, refresh_commit_health+from tests.unit.persistence.helpers import insert_repo+++def _scan_returning_unwritable_rows(*args, **kwargs):+ """A scan whose rows fail on flush, not before it.++ The failure has to land mid-write: an exception raised before any statement+ leaves the session clean, so it would not exercise the savepoint at all.+ ``change_kind`` is NOT NULL with no default, so the finding insert fails.+ """+ return CommitHealthScan(+ delta_rows=[{"sha": "aaa", "status": "available"}],+ finding_rows=[{"sha": "aaa", "change_finding_id": "f0", "dimension": "defect"}],+ scanned=1,+ )+++async def test_a_failed_write_leaves_the_caller_able_to_keep_writing(+ async_session, monkeypatch+) -> None:+ """The regression: a poisoned session would fail the whole index later."""+ import repowise.core.analysis.change_health.commit_scan as scan_mod++ repo = await insert_repo(async_session)+ monkeypatch.setattr(scan_mod, "scan_commits", _scan_returning_unwritable_rows)++ stats = await refresh_commit_health(async_session, repo.id, "/repo", ["aaa"], limit=5)++ assert stats["stored"] == 0+ assert await get_commit_health(async_session, repo.id, "aaa") is None+ # The caller carries on in the same session, which is the real assertion.+ await upsert_git_commits_bulk(async_session, repo.id, [{"sha": "aaa", "subject": "x"}])+ await async_session.commit()+ rows = (await async_session.execute(select(GitCommit.sha))).scalars().all()+ assert list(rows) == ["aaa"]+++async def test_nothing_to_scan_is_not_an_error(async_session) -> None:+ repo = await insert_repo(async_session)++ assert (await refresh_commit_health(async_session, repo.id, "/repo", []))["scanned"] == 0+ assert (+ await refresh_commit_health(async_session, repo.id, "/repo", ["aaa"], limit=0)+ )["scanned"] == 0+ assert await get_commit_health(async_session, repo.id, "aaa") is None+++def test_shas_are_spent_newest_first() -> None:+ """The budget runs out in this order, so it must not come from the walk."""+ rows = [+ {"sha": "old", "committed_at": 1},+ {"sha": "new", "committed_at": 3},+ {"sha": "mid", "committed_at": 2},+ {"sha": "", "committed_at": 9},+ ]++ assert recent_shas(rows) == ["new", "mid", "old"]+ assert recent_shas(None) == []diff --git a/tests/unit/persistence/test_models.py b/tests/unit/persistence/test_models.pyindex 45797810e..4dc155fc7 100644--- a/tests/unit/persistence/test_models.py+++ b/tests/unit/persistence/test_models.py@@ -302,6 +302,8 @@ def test_base_includes_all_models():"wiki_symbols","git_metadata","git_commit_files",+ "git_commit_health_deltas",+ "git_commit_health_findings","git_commits","git_function_blame","fix_events",diff --git a/tests/unit/server/test_git.py b/tests/unit/server/test_git.pyindex 37007f302..ce964e14a 100644--- a/tests/unit/server/test_git.py+++ b/tests/unit/server/test_git.py@@ -422,6 +422,74 @@ async def test_commit_detail_is_empty_of_files_on_an_older_index(assert resp.json()["files"] == []+async def test_commit_detail_reports_what_the_commit_did_to_health(+ client: AsyncClient, app+) -> None:+ repo = await create_test_repo(client)+ await _insert_git_commits(app.state.session_factory, repo["id"])+ async with get_session(app.state.session_factory) as session:+ await crud.upsert_commit_health_bulk(+ session,+ repo["id"],+ [+ {+ "sha": "bbbbbbbb22",+ "status": "partial",+ "introduced_count": 2,+ "worsened_count": 1,+ "resolved_count": 4,+ "files_analyzed": 3,+ "files_skipped": 1,+ "findings_stored": 1,+ }+ ],+ [+ {+ "sha": "bbbbbbbb22",+ "change_finding_id": "f0",+ "position": 0,+ "change_kind": "worsened",+ "dimension": "defect",+ "biomarker_type": "complex_method",+ "severity": "critical",+ "severity_before": "high",+ "file_path": "src/main.py",+ "symbol": "run",+ "line_start": 12,+ "line_end": 60,+ "attribution_basis": "added_lines",+ "reason": "run has cyclomatic complexity 26",+ }+ ],+ )++ resp = await client.get(f"/api/repos/{repo['id']}/commits/bbbbbbbb")++ assert resp.status_code == 200+ health = resp.json()["health"]+ assert health["status"] == "partial"+ assert (health["introduced_count"], health["worsened_count"]) == (2, 1)+ assert health["resolved_count"] == 4+ # One finding stored against three counted: the cap, reported honestly.+ (finding,) = health["findings"]+ assert finding["severity_before"] == "high"+ assert finding["path"] == "src/main.py"+ assert finding["attribution_basis"] == "added_lines"+++async def test_an_unscanned_commit_has_no_health_block(client: AsyncClient, app) -> None:+ """Absent, not empty — "not analysed" is not "changed nothing"."""+ repo = await create_test_repo(client)+ await _insert_git_commits(app.state.session_factory, repo["id"])++ resp = await client.get(f"/api/repos/{repo['id']}/commits/bbbbbbbb")++ assert resp.status_code == 200+ assert resp.json()["health"] is None++@pytest.mark.asyncioasync def test_get_commit_not_found(client: AsyncClient) -> None:repo = await create_test_repo(client)