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(history): lead commits and changes with their health delta, add wins (#4137)
Raghav Chamadiya679f7d3ffefb
diff --git a/docs/layers/CHANGES.md b/docs/layers/CHANGES.mdindex fa08b70c4..37ef6a608 100644--- a/docs/layers/CHANGES.md+++ b/docs/layers/CHANGES.md@@ -79,9 +79,11 @@ with `REPOWISE_SEAM_CHANGE_METADATA`. See| Surface | Use ||---|---|| CLI | `repowise changes list [--category C] [--shape merge\|squash\|commit] [--grep TEXT]`, `repowise changes show REF [--format table\|json\|in-toto]` |-| REST | `GET /api/repos/{id}/changes` (filters `category`, `shape`, `q`, `needs_attention`; `evidence=true` adds each row's kept checklist status counts), `GET /api/repos/{id}/changes/{change_id}` |+| REST | `GET /api/repos/{id}/changes` (filters `category`, `shape`, `q`, `needs_attention`, `author`, `area`, `since`, `until`, `delta`, `touches_hotspot`; `evidence=true` adds each row's kept checklist status counts), `GET /api/repos/{id}/changes/summary`, `GET /api/repos/{id}/changes/{change_id}` || Web | Commits page, "By change" view: each change with its checklist's attention and unknown counts and a "Needs attention" filter; a detail page per change |+Every row leads with `health`: its commits' stored health deltas summed (introduced, worsened, resolved, files worsened) and a `kind` of `improved`, `worsened`, `mixed` or `neutral`; `null` means no commit was scanned. The `delta` filter's `improved` and `worsened` each include `mixed`. `/changes/summary` counts a period's changes by kind, improvements first, and the detail adds the worse findings (file, lines, symbol, biomarker) behind the counts. `GET /api/repos/{id}/commits` carries the same `health_delta` per commit and takes the same filters, and `GET /api/repos/{id}/wins?since=&author=` lists findings resolved, files whose score rose and refactorings that landed.+`show` and the detail route accept a change id or any commit sha the change landed.Full flags: [CLI_REFERENCE.md](../reference/CLI_REFERENCE.md#repowise-changes).diff --git a/packages/api-client/package.json b/packages/api-client/package.jsonindex cb1b5bfe6..ac45fe042 100644--- a/packages/api-client/package.json+++ b/packages/api-client/package.json@@ -32,6 +32,7 @@"./git": "./src/git.ts","./graph": "./src/graph.ts","./health": "./src/health.ts",+ "./history": "./src/history.ts","./jobs": "./src/jobs.ts","./knowledge-map": "./src/knowledge-map.ts","./mcp-tools": "./src/mcp-tools.ts",diff --git a/packages/api-client/src/changes.ts b/packages/api-client/src/changes.tsindex 1d30a3304..8efd14b29 100644--- a/packages/api-client/src/changes.ts+++ b/packages/api-client/src/changes.ts@@ -13,6 +13,10 @@ import type {ChangeRecord,EvidenceItem,} from "@repowise-dev/types/changes";+import type {+ HistoryFilters,+ PeriodHealthSummaryResponse,+} from "@repowise-dev/types/history";export type {ChangeEvidence,@@ -23,10 +27,12 @@ export type {EvidenceItem,};-/** A page of changes, newest merged first, without file or commit lists. */+/** A page of changes, newest merged first, without file or commit lists.+ * Each row leads with `health`, its commits' rolled-up delta. `since` and+ * `until` read `merged_at`. */export async function listChanges(repoId: string,- opts?: {+ opts?: HistoryFilters & {/** One commit category, e.g. `fix`. */category?: string;shape?: "merge" | "squash" | "commit";@@ -40,7 +46,18 @@ export async function listChanges(offset?: number;},): Promise<ChangeListResponse> {- return apiGet<ChangeListResponse>(`/api/repos/${repoId}/changes`, opts);+ return apiGet<ChangeListResponse>(`/api/repos/${repoId}/changes`, { ...opts });+}++/** A period headline over changes: how many made health better, worse, both+ * or neither (improvements first), and the findings behind it. */+export async function getChangesSummary(+ repoId: string,+ filters: HistoryFilters & { category?: string } = {},+): Promise<PeriodHealthSummaryResponse> {+ return apiGet<PeriodHealthSummaryResponse>(`/api/repos/${repoId}/changes/summary`, {+ ...filters,+ });}/**diff --git a/packages/api-client/src/git.ts b/packages/api-client/src/git.tsindex 7bc69e62e..27ce6d62b 100644--- a/packages/api-client/src/git.ts+++ b/packages/api-client/src/git.ts@@ -12,6 +12,10 @@ import type {Paginated,ReviewerSuggestionsResponse,} from "./types";+import type {+ HistoryFilters,+ PeriodHealthSummaryResponse,+} from "@repowise-dev/types/history";export async function getGitMetadata(repoId: string,@@ -112,13 +116,13 @@ export async function getGitSummary(}/**- * 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`.+ * Paginated per-commit feed, each row led by its `health_delta` and+ * `touches_hotspot`. `sort` defaults to `date`; `risk` orders by the+ * supporting diff-shape score. The history filters narrow the repository.*/export async function getCommitsPage(repoId: string,- options: {+ options: HistoryFilters & {sort?: "risk" | "date";authorship?: "all" | "agent" | "human" | "unknown";/** Narrows the whole repository, not the page: the high review-priority@@ -134,6 +138,7 @@ export async function getCommitsPage(kind = "all",limit = 50,offset = 0,+ ...filters} = options;return apiGet<Paginated<CommitResponse>>(`/api/repos/${repoId}/commits`, {sort,@@ -141,9 +146,22 @@ export async function getCommitsPage(kind,limit,offset,+ ...filters,});}+/** How many commits under the filters made health better, worse, both or+ * neither; improvements first. */+export async function getCommitHealthSummary(+ repoId: string,+ filters: HistoryFilters = {},+): Promise<PeriodHealthSummaryResponse> {+ return apiGet<PeriodHealthSummaryResponse>(+ `/api/repos/${repoId}/commits/health-summary`,+ { ...filters },+ );+}+/** Monthly agent-vs-human commit volume across the indexed window. */export async function getAgentTrend(repoId: string): Promise<AgentTrend> {return apiGet<AgentTrend>(`/api/repos/${repoId}/commits/agent-trend`);diff --git a/packages/api-client/src/history.ts b/packages/api-client/src/history.tsnew file mode 100644index 000000000..06dd248d6--- /dev/null+++ b/packages/api-client/src/history.ts@@ -0,0 +1,23 @@+/**+ * What got better in a window: findings resolved, files whose score rose and+ * refactorings that landed. Positive only; with `author`, that person's wins.+ */+import { apiGet } from "./client";+import type { WinsResponse } from "@repowise-dev/types/history";++export type { WinsResponse };++export async function getWins(+ repoId: string,+ opts: {+ /** ISO 8601; the server defaults to 30 days ago. */+ since?: string;+ until?: string;+ /** Author email or exact name. */+ author?: string;+ /** Items per section, 1-50. */+ top?: number;+ } = {},+): Promise<WinsResponse> {+ return apiGet<WinsResponse>(`/api/repos/${repoId}/wins`, opts);+}diff --git a/packages/api-client/src/types/git.ts b/packages/api-client/src/types/git.tsindex 5195a65cc..f005b5604 100644--- a/packages/api-client/src/types/git.ts+++ b/packages/api-client/src/types/git.ts@@ -1,3 +1,5 @@+import type { HealthDeltaSummaryResponse } from "@repowise-dev/types/history";+// ---------------------------------------------------------------------------// Git Intelligence// ---------------------------------------------------------------------------@@ -137,6 +139,10 @@ export interface CommitResponse {agent_confidence?: string | null;/** agent / human_attested / unknown; null when attribution is off. */attribution?: "agent" | "human_attested" | "unknown" | null;+ /** What the commit did to health, the row's lead; null when never scanned. */+ health_delta?: HealthDeltaSummaryResponse | null;+ /** Hotspot files (as flagged now) the commit touched. */+ touches_hotspot?: number;}export interface RiskDriverResponse {@@ -184,6 +190,9 @@ export interface CommitHealthResponse {/** `available` when every changed file was compared, `partial` when some* were skipped (unsupported language, binary, unreadable). */status: string;+ /** An older analyzer wrote it: the direction holds, the counts do not+ * compare with current rows. */+ stale?: boolean;introduced_count: number;worsened_count: number;resolved_count: number;diff --git a/packages/core/src/repowise/core/analysis/history/__init__.py b/packages/core/src/repowise/core/analysis/history/__init__.pynew file mode 100644index 000000000..62d16e7c8--- /dev/null+++ b/packages/core/src/repowise/core/analysis/history/__init__.py@@ -0,0 +1,45 @@+"""The better/worse story of commits and changes, read from stored health data.++Pure functions only: :mod:`.delta` reads one commit's stored delta,+:mod:`.rollup` sums commits into a change and changes into a period, and+:mod:`.wins` names files whose score rose. Nothing here re-runs the health+comparison; it belongs to :mod:`repowise.core.analysis.change_health`.+"""++from .delta import (+ DELTA_FILTERS,+ MIN_SHOWN_ANALYZER_VERSION,+ Currency,+ DeltaKind,+ DeltaStamp,+ FileScoreShift,+ HealthDeltaSummary,+ delta_currency,+ delta_kind,+ matches_delta,+ summarize_delta,+)+from .rollup import HealthRollup, PeriodHealthSummary, rollup_deltas, summarize_period+from .wins import MIN_GAIN, FileGain, parse_score_map, rising_files++__all__ = [+ "DELTA_FILTERS",+ "MIN_GAIN",+ "MIN_SHOWN_ANALYZER_VERSION",+ "Currency",+ "DeltaKind",+ "DeltaStamp",+ "FileGain",+ "FileScoreShift",+ "HealthDeltaSummary",+ "HealthRollup",+ "PeriodHealthSummary",+ "delta_currency",+ "delta_kind",+ "matches_delta",+ "parse_score_map",+ "rising_files",+ "rollup_deltas",+ "summarize_delta",+ "summarize_period",+]diff --git a/packages/core/src/repowise/core/analysis/history/delta.py b/packages/core/src/repowise/core/analysis/history/delta.pynew file mode 100644index 000000000..d9539f4a1--- /dev/null+++ b/packages/core/src/repowise/core/analysis/history/delta.py@@ -0,0 +1,145 @@+"""One commit's stored health delta, read as better or worse.++The comparison itself belongs to :mod:`repowise.core.analysis.change_health`+and is stored per commit at index time (``git_commit_health_deltas``). This+module only reads those rows back into the better/worse vocabulary the history+surfaces lead with; it never re-derives a finding.+"""++from __future__ import annotations++from dataclasses import dataclass+from typing import Any, Literal++DeltaKind = Literal["improved", "worsened", "mixed", "neutral"]+Currency = Literal["current", "stale", "absent"]++#: Oldest analyzer version whose stored delta a row still shows, flagged stale.+#: Rows below it come from the change-health model before its per-commit store+#: was rebuilt (the v21-era rows long-lived indexes still hold); their counts+#: are not readable next to today's, so they read as never scanned. Raise it+#: when a version bump changes what a finding means.+MIN_SHOWN_ANALYZER_VERSION = 40++#: Values the ``delta`` filter accepts. ``improved`` and ``worsened`` each+#: include ``mixed``: a change that fixed three things and broke one did make+#: something better, and did make something worse.+DELTA_FILTERS: tuple[str, ...] = ("improved", "worsened", "mixed", "neutral")+++@dataclass(frozen=True, slots=True)+class DeltaStamp:+ """The analyzer a stored delta was computed by. Counts from two stamps never+ add up: every aggregate reads rows with the current stamp only."""++ analyzer_version: int+ rules_fingerprint: str+ performance_model_version: int++ @classmethod+ def of(cls, row: Any) -> DeltaStamp:+ return cls(+ int(row.analyzer_version or 0),+ row.rules_fingerprint or "",+ int(row.performance_model_version or 0),+ )+++def delta_currency(row: Any, current: DeltaStamp) -> Currency:+ """``current`` when *row* has the current stamp; ``stale`` when an older but+ still readable analyzer wrote it (its sign holds, its magnitude does not+ compare); ``absent`` below :data:`MIN_SHOWN_ANALYZER_VERSION`."""+ if DeltaStamp.of(row) == current:+ return "current"+ if int(row.analyzer_version or 0) >= MIN_SHOWN_ANALYZER_VERSION:+ return "stale"+ return "absent"+++@dataclass(frozen=True, slots=True)+class FileScoreShift:+ """A file's health score before and after a change; ``None`` when unscored."""++ path: str+ before: float | None+ after: float | None++ @property+ def change(self) -> float | None:+ if self.before is None or self.after is None:+ return None+ return round(self.after - self.before, 2)+++@dataclass(frozen=True, slots=True)+class HealthDeltaSummary:+ """The counts behind one commit's delta, and which way it went.++ ``improved`` is the analyzer's count of findings that measure better+ without going away, and ``moved`` the findings carried to another file+ with their code (never counted as introduced). Both are ``None`` on a+ stale row, where the stored 0 means unknown. ``files``+ holds per-file score shifts; the stored rows never carry them (they are+ live-only, in ``get_change_risk``), so it stays empty for stored deltas.+ ``stale`` marks a row an older analyzer wrote: its direction holds, its+ counts do not compare with current rows.+ """++ status: str+ introduced: int+ worsened: int+ resolved: int+ improved: int | None = None+ moved: int | None = None+ files: tuple[FileScoreShift, ...] = ()+ stale: bool = False++ @property+ def better(self) -> int:+ return self.resolved + (self.improved or 0)++ @property+ def worse(self) -> int:+ return self.introduced + self.worsened++ @property+ def kind(self) -> DeltaKind:+ return delta_kind(self.better, self.worse)+++def delta_kind(better: int, worse: int) -> DeltaKind:+ """``improved`` / ``worsened`` / ``mixed`` / ``neutral`` from the two sides."""+ if better and worse:+ return "mixed"+ if better:+ return "improved"+ if worse:+ return "worsened"+ return "neutral"+++def matches_delta(kind: DeltaKind, wanted: str | None) -> bool:+ """Whether a delta of *kind* passes the ``delta`` filter *wanted*."""+ if not wanted:+ return True+ if wanted in ("improved", "worsened"):+ return kind in (wanted, "mixed")+ return kind == wanted+++def summarize_delta(row: Any, *, stale: bool = False) -> HealthDeltaSummary:+ """A stored ``GitCommitHealthDelta`` row as a :class:`HealthDeltaSummary`.++ The one reader of stored rows. ``improved_count`` and ``moved_count`` are+ read only when not *stale*: an older analyzer's row stores 0 there, which+ means unknown, not zero.+ """+ return HealthDeltaSummary(+ status=row.status,+ introduced=int(row.introduced_count or 0),+ worsened=int(row.worsened_count or 0),+ resolved=int(row.resolved_count or 0),+ improved=None if stale else int(row.improved_count or 0),+ moved=None if stale else int(row.moved_count or 0),+ stale=stale,+ )diff --git a/packages/core/src/repowise/core/analysis/history/rollup.py b/packages/core/src/repowise/core/analysis/history/rollup.pynew file mode 100644index 000000000..026856f10--- /dev/null+++ b/packages/core/src/repowise/core/analysis/history/rollup.py@@ -0,0 +1,143 @@+"""Roll stored commit deltas up to a change, and changes up to a period.++Counts only add: a change's introduced count is the sum of its commits'. Two+commits in one change that introduce and then resolve the same finding both+count, which is what happened on the branch. A squash change has one commit,+so its rollup is that commit's delta exactly; merge commits themselves are+never scanned (the commit walk skips merges), so a merge change sums its+branch commits.+"""++from __future__ import annotations++from collections.abc import Iterable, Sequence+from dataclasses import dataclass+from typing import Protocol++from .delta import DeltaKind, HealthDeltaSummary, delta_kind+++class _Counted(Protocol):+ @property+ def kind(self) -> DeltaKind: ...++ introduced: int+ worsened: int+ resolved: int+ improved: int | None+++@dataclass(frozen=True, slots=True)+class HealthRollup:+ """What a group of commits did to health, summed.++ ``files_worsened`` counts distinct paths named by the stored worse+ findings (capped per commit at scan time, so a floor) plus files whose+ stored score fell. ``files_improved`` needs stored per-file scores and is+ ``None`` until delta rows carry them; resolved findings are stored as a+ count without paths, so they cannot name a file.+ """++ status: str+ scanned_commits: int+ unscanned_commits: int+ introduced: int+ worsened: int+ resolved: int+ improved: int | None+ moved: int | None+ files_improved: int | None+ files_worsened: int++ @property+ def kind(self) -> DeltaKind:+ return delta_kind(self.resolved + (self.improved or 0), self.introduced + self.worsened)+++def _net_score_change(deltas: Sequence[HealthDeltaSummary]) -> dict[str, float]:+ """``path -> summed score change`` over the deltas' stored per-file shifts."""+ net: dict[str, float] = {}+ for shift in (s for d in deltas for s in d.files if s.change is not None):+ net[shift.path] = net.get(shift.path, 0.0) + shift.change+ return net+++def rollup_deltas(+ deltas: Sequence[HealthDeltaSummary | None], worse_paths: Iterable[str] = ()+) -> HealthRollup | None:+ """Sum the deltas of one change's commits; ``None`` when none was scanned.++ *deltas* has one entry per commit, ``None`` for a commit never scanned.+ *worse_paths* are the paths the commits' stored worse findings name.+ """+ scanned = [d for d in deltas if d is not None]+ if not scanned:+ return None+ unscanned = len(deltas) - len(scanned)+ improved_known = [d.improved for d in scanned if d.improved is not None]+ moved_known = [d.moved for d in scanned if d.moved is not None]+ net_by_path = _net_score_change(scanned)+ falling = {p for p, net in net_by_path.items() if net < 0}+ complete = unscanned == 0 and all(d.status == "available" for d in scanned)+ return HealthRollup(+ status="available" if complete else "partial",+ scanned_commits=len(scanned),+ unscanned_commits=unscanned,+ introduced=sum(d.introduced for d in scanned),+ worsened=sum(d.worsened for d in scanned),+ resolved=sum(d.resolved for d in scanned),+ improved=sum(improved_known) if improved_known else None,+ moved=sum(moved_known) if moved_known else None,+ files_improved=(sum(1 for net in net_by_path.values() if net > 0) if net_by_path else None),+ files_worsened=len(set(worse_paths) | falling),+ )+++@dataclass(frozen=True, slots=True)+class PeriodHealthSummary:+ """A period's headline: how many items made health better, worse, both or neither.++ Improvements lead the field order on purpose: the headline reads them+ first. ``net_findings`` is findings made better minus findings made worse.+ """++ total: int+ improved: int+ worsened: int+ mixed: int+ neutral: int+ unscanned: int+ findings_resolved: int+ findings_improved: int | None+ findings_introduced: int+ findings_worsened: int+ net_findings: int+++def summarize_period(items: Iterable[_Counted | None]) -> PeriodHealthSummary:+ """Count *items* (commit deltas or change rollups; ``None`` = never scanned)."""+ kinds = {"improved": 0, "worsened": 0, "mixed": 0, "neutral": 0}+ total = unscanned = resolved = introduced = worsened = 0+ improved_known: list[int] = []+ for item in items:+ total += 1+ if item is None:+ unscanned += 1+ continue+ kinds[item.kind] += 1+ resolved += item.resolved+ introduced += item.introduced+ worsened += item.worsened+ if item.improved is not None:+ improved_known.append(item.improved)+ improved = sum(improved_known) if improved_known else None+ return PeriodHealthSummary(+ total=total,+ unscanned=unscanned,+ findings_resolved=resolved,+ findings_improved=improved,+ findings_introduced=introduced,+ findings_worsened=worsened,+ net_findings=resolved + (improved or 0) - introduced - worsened,+ **kinds,+ )diff --git a/packages/core/src/repowise/core/analysis/history/wins.py b/packages/core/src/repowise/core/analysis/history/wins.pynew file mode 100644index 000000000..4f01cbd5a--- /dev/null+++ b/packages/core/src/repowise/core/analysis/history/wins.py@@ -0,0 +1,63 @@+"""Files whose health score rose over a window, from two stored snapshots.++A snapshot holds every scored file's score, so comparing the one taken at the+start of a window with the newest names the files that got better. A score+also moves when the analyzer is re-tuned, which is not anyone's work, so a+caller passes the paths commits actually touched in the window and only those+count.+"""++from __future__ import annotations++import json+from collections.abc import Collection, Mapping+from dataclasses import dataclass++#: Smallest rise worth naming: below it a score moved by rounding, not by work.+MIN_GAIN = 0.1+++@dataclass(frozen=True, slots=True)+class FileGain:+ path: str+ before: float+ after: float++ @property+ def gain(self) -> float:+ return round(self.after - self.before, 2)+++def parse_score_map(raw: str | None) -> dict[str, float]:+ """A snapshot's ``{path: score}`` JSON; empty when absent or not an object."""+ try:+ parsed = json.loads(raw or "{}")+ except (TypeError, ValueError):+ return {}+ if not isinstance(parsed, dict):+ return {}+ out: dict[str, float] = {}+ for path, score in parsed.items():+ try:+ out[path] = float(score)+ except (TypeError, ValueError):+ continue+ return out+++def rising_files(+ before: Mapping[str, float],+ after: Mapping[str, float],+ touched: Collection[str],+ *,+ min_gain: float = MIN_GAIN,+) -> list[FileGain]:+ """Touched files scored in both maps whose score rose by *min_gain* or more,+ biggest gain first (path breaks ties)."""+ gains = [+ FileGain(path, before[path], after[path])+ for path in touched+ if path in before and path in after and after[path] - before[path] >= min_gain+ ]+ gains.sort(key=lambda g: (-g.gain, g.path))+ return gainsdiff --git a/packages/core/src/repowise/core/persistence/crud/__init__.py b/packages/core/src/repowise/core/persistence/crud/__init__.pyindex 5c7ae2c18..660ad3f66 100644--- a/packages/core/src/repowise/core/persistence/crud/__init__.py+++ b/packages/core/src/repowise/core/persistence/crud/__init__.py@@ -12,7 +12,7 @@ Versioning contract for upsert_page:in place (version increments). created_at is preserved.This module is a façade: the implementations live in per-domain submodules-(repository, pages, graph, external_systems, git, analysis, decisions, chat,+(repository, pages, graph, external_systems, git, history, analysis, decisions, chat,knowledge_graph). Import names from here — sub-module layout may change."""@@ -26,6 +26,7 @@ from .decisions import * # noqa: F403from .external_systems import * # noqa: F403from .git import * # noqa: F403from .graph import * # noqa: F403+from .history import * # noqa: F403from .knowledge_graph import * # noqa: F403from .pages import * # noqa: F403from .repository import * # noqa: F403diff --git a/packages/core/src/repowise/core/persistence/crud/changes.py b/packages/core/src/repowise/core/persistence/crud/changes.pyindex d5f93f005..51880fdef 100644--- a/packages/core/src/repowise/core/persistence/crud/changes.py+++ b/packages/core/src/repowise/core/persistence/crud/changes.py@@ -14,6 +14,7 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom ..models import Change, GitCommitfrom ..sql import LIKE_ESCAPE, escape_likefrom ._shared import _BATCH_SIZE, _batch_upsert_keyed, _row_inserter, _row_updater+from .history import author_clause_update_change = _row_updater("change_id")@@ -75,6 +76,9 @@ class ChangeFilter:*since* is inclusive and *until* exclusive, on ``merged_at``. *attention*keeps changes whose kept checklist may flag attention (a prefilter; thecaller confirms on the parsed evidence). *change_ids* keeps only those.+ *author* matches the author email (any case) or exact name; *area* keeps+ changes with a stored file at or under that path (a floor: a record stores+ at most ``MAX_STORED_FILES`` files)."""category: str | None = None@@ -84,6 +88,28 @@ class ChangeFilter:until: datetime | None = Noneattention: bool = Falsechange_ids: Sequence[str] | None = None+ author: str | None = None+ area: str | None = None+++def _files_json_area(area: str) -> Any:+ """``files_json`` names a path at or under *area*, matched in its stored layout."""+ root = area.strip().strip("/")+ key = '"path": ' + json.dumps(root)[:-1]+ return or_(+ Change.files_json.like(f'%{escape_like(key)}"%', escape=LIKE_ESCAPE),+ Change.files_json.like(f"%{escape_like(key)}/%", escape=LIKE_ESCAPE),+ )+++def _who_and_where(where: ChangeFilter) -> list[Any]:+ """The author and area predicates *where* asks for."""+ clauses = []+ if where.author:+ clauses.append(author_clause(Change.author_name, Change.author_email, where.author))+ if where.area and where.area.strip().strip("/"):+ clauses.append(_files_json_area(where.area))+ return clausesdef _filters(repository_id: str, where: ChangeFilter) -> list[Any]:@@ -106,6 +132,7 @@ def _filters(repository_id: str, where: ChangeFilter) -> list[Any]:clauses.append(Change.category == where.category)if where.shape:clauses.append(Change.shape == where.shape)+ clauses.extend(_who_and_where(where))if where.q:like = f"%{escape_like(where.q)}%"clauses.append(@@ -181,6 +208,19 @@ async def list_change_keys(return [(cid, bool(kept)) for cid, kept in rows.tuples()]+async def list_change_health_inputs(+ session: AsyncSession, repository_id: str, where: ChangeFilter | None = None+) -> list[tuple[str, str, str]]:+ """``(change_id, commit_shas_json, files_json)`` of every change matching+ *where*, newest merged first: what a health rollup reads, and nothing else."""+ rows = await session.execute(+ select(Change.change_id, Change.commit_shas_json, Change.files_json)+ .where(*_filters(repository_id, where or ChangeFilter()))+ .order_by(Change.merged_at.desc().nulls_last(), Change.change_id)+ )+ return list(rows.tuples())++async def keep_evidence_if_unchanged(session: AsyncSession,repository_id: str,diff --git a/packages/core/src/repowise/core/persistence/crud/git.py b/packages/core/src/repowise/core/persistence/crud/git.pyindex 9a890814f..ff72b0655 100644--- a/packages/core/src/repowise/core/persistence/crud/git.py+++ b/packages/core/src/repowise/core/persistence/crud/git.py@@ -38,6 +38,7 @@ from ._shared import (_row_inserter,_row_updater,)+from .history import CommitFilter, commit_filter_clauses# ---------------------------------------------------------------------------# GitMetadata CRUD@@ -809,56 +810,15 @@ async def clear_attribution_if_disabled(session: AsyncSession, repository_id: streturn True-def _commit_authorship_clause(authorship: str | None):- """Optional authorship predicate over the three-state label: ``agent``,- ``human`` (human-attested only; a commit without a marker is never human)- or ``unknown``. ``None`` / ``"all"`` means no filtering."""- if authorship == "agent":- return GitCommit.agent_name.is_not(None)- if authorship == "human":- return GitCommit.attribution == "human_attested"- if authorship == "unknown":- return and_(- GitCommit.agent_name.is_(None),- or_(GitCommit.attribution.is_(None), GitCommit.attribution == "unknown"),- )- return None---def _commit_kind_clause(kind: str | None, high_cut: float | None):- """Optional predicate for the review-priority band or bug-fix commits.-- ``high`` compares against the repo's own moderate/high boundary on the- score axis, which is where the tercile actually falls; deriving it per row- would mean ranking every commit before paging any of them.- """- if kind == "fixes":- return GitCommit.is_fix.is_(True)- if kind == "high":- if high_cut is None:- return None- return GitCommit.change_risk_score >= high_cut- return None--async def count_git_commits(session: AsyncSession,repository_id: str,- *,- authorship: str | None = None,- kind: str | None = None,- high_cut: float | None = None,+ where: CommitFilter | None = None,) -> int:"""Count persisted commits for a repository, under the same filters."""- stmt = (- select(func.count()).select_from(GitCommit).where(GitCommit.repository_id == repository_id)+ stmt = select(func.count()).select_from(GitCommit).where(+ GitCommit.repository_id == repository_id, *commit_filter_clauses(where))- for clause in (- _commit_authorship_clause(authorship),- _commit_kind_clause(kind, high_cut),- ):- if clause is not None:- stmt = stmt.where(clause)result = await session.execute(stmt)return int(result.scalar_one() or 0)@@ -910,27 +870,20 @@ async def get_git_commits(limit: int = 50,offset: int = 0,sort: str = "risk",- authorship: str | None = None,- kind: str | None = None,- high_cut: float | None = None,+ where: CommitFilter | None = None,) -> list[GitCommit]:"""Return a page of commits, sorted by change-risk (default) or recency.``sort="risk"`` ranks by ``change_risk_score`` descending (the review-priority order); ``sort="date"`` ranks by ``committed_at`` descending.- ``authorship`` narrows to ``agent`` / ``human`` / ``unknown``; ``kind`` narrows to the- ``high`` review-priority band or to ``fixes``. Both filter the repository- rather than the page, so a filter still answers when the page it would- have filtered is uniform.+ *where* (:class:`~repowise.core.persistence.crud.history.CommitFilter`)+ filters the repository rather than the page, so a filter still answers+ when the page it would have filtered is uniform."""order = GitCommit.committed_at.desc() if sort == "date" else GitCommit.change_risk_score.desc()- stmt = select(GitCommit).where(GitCommit.repository_id == repository_id)- for clause in (- _commit_authorship_clause(authorship),- _commit_kind_clause(kind, high_cut),- ):- if clause is not None:- stmt = stmt.where(clause)+ stmt = select(GitCommit).where(+ GitCommit.repository_id == repository_id, *commit_filter_clauses(where)+ )result = await session.execute(stmt.order_by(order).limit(limit).offset(offset))return list(result.scalars().all())diff --git a/packages/core/src/repowise/core/persistence/crud/history.py b/packages/core/src/repowise/core/persistence/crud/history.pynew file mode 100644index 000000000..bbbfbf824--- /dev/null+++ b/packages/core/src/repowise/core/persistence/crud/history.py@@ -0,0 +1,391 @@+"""Reads behind the better/worse history surfaces: commit filters, stored+health deltas in bulk, hotspot touches, and what landed in a window.++Every bulk read takes a page's shas and answers in one query per 500, so a+listing never issues a query per row.+"""++from __future__ import annotations++from collections.abc import Sequence+from dataclasses import dataclass+from datetime import datetime+from typing import Any++from sqlalchemy import and_, exists, func, or_, select+from sqlalchemy.ext.asyncio import AsyncSession++from ...analysis.history.delta import DeltaStamp+from ..models import (+ GitCommit,+ GitCommitFile,+ GitCommitHealthDelta,+ GitCommitHealthFinding,+ GitMetadata,+ HealthSnapshot,+ RefactoringPayoff,+ RefactoringSuggestion,+)+from ..sql import LIKE_ESCAPE, escape_like++_CHUNK = 500+++@dataclass(frozen=True)+class CommitFilter:+ """Which commits a history read keeps; every field narrows, ``None`` does not.++ *author* matches the author email (any case) or the exact author name.+ *area* is a directory (``packages/core``) or one file path. *since* is+ inclusive and *until* exclusive, on ``committed_at``. *delta* is one of+ :data:`repowise.core.analysis.history.DELTA_FILTERS`; it keeps only scanned+ commits. *touches_hotspot* keeps commits that touched a hotspot file.+ *authorship* and *kind* are the feed's attribution and review-priority+ filters; *high_cut* is the repo's high-band boundary that *kind* ``high``+ compares against. *stamp* is the current analyzer's; *delta* reads only+ rows written under it.+ """++ authorship: str | None = None+ kind: str | None = None+ high_cut: float | None = None+ author: str | None = None+ area: str | None = None+ since: datetime | None = None+ until: datetime | None = None+ delta: str | None = None+ touches_hotspot: bool = False+ stamp: DeltaStamp | None = None+++def _commit_authorship_clause(authorship: str | None):+ """Optional authorship predicate over the three-state label: ``agent``,+ ``human`` (human-attested only; a commit without a marker is never human)+ or ``unknown``. ``None`` / ``"all"`` means no filtering."""+ if authorship == "agent":+ return GitCommit.agent_name.is_not(None)+ if authorship == "human":+ return GitCommit.attribution == "human_attested"+ if authorship == "unknown":+ return and_(+ GitCommit.agent_name.is_(None),+ or_(GitCommit.attribution.is_(None), GitCommit.attribution == "unknown"),+ )+ return None+++def _commit_kind_clause(kind: str | None, high_cut: float | None):+ """Optional predicate for the review-priority band or bug-fix commits.++ ``high`` compares against the repo's own moderate/high boundary on the+ score axis, which is where the tercile actually falls; deriving it per row+ would mean ranking every commit before paging any of them.+ """+ if kind == "fixes":+ return GitCommit.is_fix.is_(True)+ if kind == "high":+ if high_cut is None:+ return None+ return GitCommit.change_risk_score >= high_cut+ return None+++def author_clause(name_column: Any, email_column: Any, author: str) -> Any:+ """The author email (any case) or exact name is *author*."""+ return or_(func.lower(email_column) == author.strip().lower(), name_column == author.strip())+++def area_clause(column: Any, area: str) -> Any:+ """*column* is the path *area* names, or a path under it."""+ root = area.strip().strip("/")+ return or_(column == root, column.like(f"{escape_like(root)}/%", escape=LIKE_ESCAPE))+++def current_delta_clause(stamp: DeltaStamp | None) -> Any:+ """``GitCommitHealthDelta`` rows written under *stamp*, the current analyzer.++ Every aggregate and filter reads only these: counts from two analyzer+ versions never add up. A filter without a stamp is a caller bug.+ """+ if stamp is None:+ raise ValueError("a health delta filter needs the current analyzer stamp")+ return and_(+ GitCommitHealthDelta.analyzer_version == stamp.analyzer_version,+ GitCommitHealthDelta.rules_fingerprint == stamp.rules_fingerprint,+ GitCommitHealthDelta.performance_model_version == stamp.performance_model_version,+ )+++def _delta_clause(wanted: str, stamp: DeltaStamp | None) -> Any:+ """SQL twin of :func:`repowise.core.analysis.history.matches_delta`, over+ current-stamp rows only.++ Better is resolved plus improved, exactly as+ :func:`~repowise.core.analysis.history.summarize_delta` reads a current+ row; ``test_history_routes`` holds the two to the same answer.+ """+ better = (GitCommitHealthDelta.resolved_count + GitCommitHealthDelta.improved_count) > 0+ worse = (GitCommitHealthDelta.introduced_count + GitCommitHealthDelta.worsened_count) > 0+ condition = {+ "improved": better,+ "worsened": worse,+ "mixed": and_(better, worse),+ "neutral": and_(~better, ~worse),+ }[wanted]+ return exists().where(+ GitCommitHealthDelta.repository_id == GitCommit.repository_id,+ GitCommitHealthDelta.sha == GitCommit.sha,+ current_delta_clause(stamp),+ condition,+ )+++def _touches_hotspot_clause() -> Any:+ return exists().where(+ GitCommitFile.repository_id == GitCommit.repository_id,+ GitCommitFile.sha == GitCommit.sha,+ GitMetadata.repository_id == GitCommitFile.repository_id,+ GitMetadata.file_path == GitCommitFile.file_path,+ GitMetadata.is_hotspot.is_(True),+ )+++def _commit_area_clause(area: str | None) -> Any:+ if not area or not area.strip().strip("/"):+ return None+ return exists().where(+ GitCommitFile.repository_id == GitCommit.repository_id,+ GitCommitFile.sha == GitCommit.sha,+ area_clause(GitCommitFile.file_path, area),+ )+++def _window_clauses(since: datetime | None, until: datetime | None) -> list[Any]:+ return [+ *([GitCommit.committed_at >= since] if since is not None else []),+ *([GitCommit.committed_at < until] if until is not None else []),+ ]+++def commit_filter_clauses(where: CommitFilter | None) -> list[Any]:+ """The ``GitCommit`` predicates *where* asks for (repository scoping is the caller's)."""+ if where is None:+ return []+ optional = [+ _commit_authorship_clause(where.authorship),+ _commit_kind_clause(where.kind, where.high_cut),+ author_clause(GitCommit.author_name, GitCommit.author_email, where.author)+ if where.author+ else None,+ _commit_area_clause(where.area),+ _delta_clause(where.delta, where.stamp) if where.delta else None,+ _touches_hotspot_clause() if where.touches_hotspot else None,+ ]+ return [c for c in optional if c is not None] + _window_clauses(where.since, where.until)+++def _chunks(shas: Sequence[str]) -> list[list[str]]:+ wanted = list(dict.fromkeys(shas))+ return [wanted[i : i + _CHUNK] for i in range(0, len(wanted), _CHUNK)]+++async def list_commit_shas(+ session: AsyncSession, repository_id: str, where: CommitFilter | None = None+) -> list[str]:+ """Every commit sha under *where*; the commit table is bounded by ``commit_limit``."""+ rows = await session.execute(+ select(GitCommit.sha).where(+ GitCommit.repository_id == repository_id, *commit_filter_clauses(where)+ )+ )+ return list(rows.scalars())+++async def get_commit_health_bulk(+ session: AsyncSession, repository_id: str, shas: Sequence[str]+) -> dict[str, GitCommitHealthDelta]:+ """``sha -> stored delta`` for the scanned commits among *shas*."""+ out: dict[str, GitCommitHealthDelta] = {}+ for chunk in _chunks(shas):+ rows = await session.execute(+ select(GitCommitHealthDelta).where(+ GitCommitHealthDelta.repository_id == repository_id,+ GitCommitHealthDelta.sha.in_(chunk),+ )+ )+ out.update({row.sha: row for row in rows.scalars()})+ return out+++async def get_worse_paths_bulk(+ session: AsyncSession, repository_id: str, shas: Sequence[str]+) -> dict[str, set[str]]:+ """``sha -> paths its stored worse findings name`` (capped per commit at scan)."""+ out: dict[str, set[str]] = {}+ for chunk in _chunks(shas):+ rows = await session.execute(+ select(GitCommitHealthFinding.sha, GitCommitHealthFinding.file_path)+ .where(+ GitCommitHealthFinding.repository_id == repository_id,+ GitCommitHealthFinding.sha.in_(chunk),+ )+ .distinct()+ )+ for sha, path in rows.tuples():+ out.setdefault(sha, set()).add(path)+ return out+++async def get_commit_findings_bulk(+ session: AsyncSession, repository_id: str, shas: Sequence[str], *, limit: int+) -> list[GitCommitHealthFinding]:+ """The stored worse findings of *shas*, worst-ranked first, at most *limit*.++ Each commit's ``position`` is its own worst-first rank, so ordering by it+ interleaves the commits' worst findings before anyone's minor ones.+ """+ found: list[GitCommitHealthFinding] = []+ for chunk in _chunks(shas):+ rows = await session.execute(+ select(GitCommitHealthFinding)+ .where(+ GitCommitHealthFinding.repository_id == repository_id,+ GitCommitHealthFinding.sha.in_(chunk),+ )+ .order_by(GitCommitHealthFinding.position, GitCommitHealthFinding.sha)+ .limit(limit)+ )+ found.extend(rows.scalars())+ found.sort(key=lambda f: (f.position, f.sha))+ return found[:limit]+++async def count_hotspot_files_bulk(+ session: AsyncSession, repository_id: str, shas: Sequence[str]+) -> dict[str, int]:+ """``sha -> hotspot files it touched``; a sha that touched none is absent."""+ out: dict[str, int] = {}+ for chunk in _chunks(shas):+ rows = await session.execute(+ select(GitCommitFile.sha, func.count())+ .join(+ GitMetadata,+ and_(+ GitMetadata.repository_id == GitCommitFile.repository_id,+ GitMetadata.file_path == GitCommitFile.file_path,+ ),+ )+ .where(+ GitCommitFile.repository_id == repository_id,+ GitCommitFile.sha.in_(chunk),+ GitMetadata.is_hotspot.is_(True),+ )+ .group_by(GitCommitFile.sha)+ )+ out.update({sha: int(n) for sha, n in rows.tuples()})+ return out+++async def get_hotspot_paths(session: AsyncSession, repository_id: str) -> set[str]:+ """Every path currently flagged a hotspot."""+ rows = await session.execute(+ select(GitMetadata.file_path).where(+ GitMetadata.repository_id == repository_id, GitMetadata.is_hotspot.is_(True)+ )+ )+ return set(rows.scalars())+++async def get_resolving_commits(+ session: AsyncSession, repository_id: str, where: CommitFilter+) -> list[tuple[GitCommit, int]]:+ """``(commit, resolved_count)`` for commits under *where* that resolved a+ finding, most resolved first; current-stamp rows only (``where.stamp``)."""+ rows = await session.execute(+ select(GitCommit, GitCommitHealthDelta.resolved_count)+ .join(+ GitCommitHealthDelta,+ and_(+ GitCommitHealthDelta.repository_id == GitCommit.repository_id,+ GitCommitHealthDelta.sha == GitCommit.sha,+ ),+ )+ .where(+ GitCommit.repository_id == repository_id,+ GitCommitHealthDelta.resolved_count > 0,+ current_delta_clause(where.stamp),+ *commit_filter_clauses(where),+ )+ .order_by(GitCommitHealthDelta.resolved_count.desc(), GitCommit.committed_at.desc())+ )+ return [(commit, int(n)) for commit, n in rows.tuples()]+++async def get_touched_paths(+ session: AsyncSession, repository_id: str, where: CommitFilter+) -> set[str]:+ """Every path a commit under *where* touched."""+ rows = await session.execute(+ select(GitCommitFile.file_path)+ .join(+ GitCommit,+ and_(+ GitCommit.repository_id == GitCommitFile.repository_id,+ GitCommit.sha == GitCommitFile.sha,+ ),+ )+ .where(GitCommitFile.repository_id == repository_id, *commit_filter_clauses(where))+ .distinct()+ )+ return set(rows.scalars())+++async def get_snapshot_scores_at(+ session: AsyncSession, repository_id: str, at: datetime | None+) -> tuple[datetime, str] | None:+ """``(taken_at, per_file_scores_json)`` of the newest snapshot at or before+ *at* (the newest overall when *at* is ``None``), else the oldest kept one."""+ base = select(HealthSnapshot.taken_at, HealthSnapshot.per_file_scores_json).where(+ HealthSnapshot.repository_id == repository_id+ )+ newest_first = (HealthSnapshot.taken_at.desc(), HealthSnapshot.id.desc())+ if at is not None:+ row = (+ await session.execute(+ base.where(HealthSnapshot.taken_at <= at).order_by(*newest_first).limit(1)+ )+ ).first()+ if row is not None:+ return row[0], row[1]+ order: tuple[Any, ...] = (HealthSnapshot.taken_at.asc(), HealthSnapshot.id.asc())+ else:+ order = newest_first+ row = (await session.execute(base.order_by(*order).limit(1))).first()+ return (row[0], row[1]) if row is not None else None+++async def get_applied_refactorings(+ session: AsyncSession,+ repository_id: str,+ *,+ since: datetime | None,+ until: datetime | None = None,+) -> list[tuple[RefactoringSuggestion, RefactoringPayoff]]:+ """Plans resolved as ``applied`` in the window, newest first."""+ # Deferred: the refactoring package imports crud.git, which imports this module.+ from ...analysis.health.refactoring.payoff import APPLIED++ stmt = (+ select(RefactoringSuggestion, RefactoringPayoff)+ .join(RefactoringPayoff, RefactoringPayoff.suggestion_id == RefactoringSuggestion.id)+ .where(+ RefactoringPayoff.repository_id == repository_id,+ RefactoringPayoff.outcome == APPLIED,+ )+ .order_by(RefactoringPayoff.resolved_at.desc(), RefactoringSuggestion.file_path)+ )+ if since is not None:+ stmt = stmt.where(RefactoringPayoff.resolved_at >= since)+ if until is not None:+ stmt = stmt.where(RefactoringPayoff.resolved_at < until)+ return list((await session.execute(stmt)).tuples())diff --git a/packages/server/src/repowise/server/app.py b/packages/server/src/repowise/server/app.pyindex 815947363..cc5cd4e90 100644--- a/packages/server/src/repowise/server/app.py+++ b/packages/server/src/repowise/server/app.py@@ -76,6 +76,7 @@ from repowise.server.routers import (stats,symbols,webhooks,+ wins,workspace,)from repowise.server.scheduler import setup_scheduler@@ -330,6 +331,7 @@ _ROUTERS = (webhooks,git,changes,+ wins,events,dead_code,doc_drift,diff --git a/packages/server/src/repowise/server/routers/_history_filters.py b/packages/server/src/repowise/server/routers/_history_filters.pynew file mode 100644index 000000000..ce0d406e1--- /dev/null+++ b/packages/server/src/repowise/server/routers/_history_filters.py@@ -0,0 +1,65 @@+"""Query parameters the commit and change history surfaces share, as dependencies."""++from __future__ import annotations++from dataclasses import dataclass+from datetime import UTC, datetime+from typing import Any++from fastapi import Query++from repowise.core.analysis.history import DELTA_FILTERS+from repowise.core.persistence import crud++_DELTA_PATTERN = f"^({'|'.join(DELTA_FILTERS)})$"+++def utc(moment: datetime | None) -> datetime | None:+ """*moment* in UTC, assumed UTC when it names no zone. Converted rather than+ kept as given: SQLite stores wall-clock UTC and drops a bound value's zone."""+ if moment is None:+ return None+ if moment.tzinfo is None:+ return moment.replace(tzinfo=UTC)+ return moment.astimezone(UTC)+++@dataclass(frozen=True)+class HistoryParams:+ author: str | None+ area: str | None+ since: datetime | None+ until: datetime | None+ delta: str | None+ touches_hotspot: bool++ def commit_filter(self, **feed: Any) -> crud.CommitFilter:+ """The commit filter, plus the caller's own fields (the feed's+ *authorship* / *kind* / *high_cut*, the current analyzer *stamp*)."""+ return crud.CommitFilter(+ **feed,+ author=self.author,+ area=self.area,+ since=self.since,+ until=self.until,+ delta=self.delta,+ touches_hotspot=self.touches_hotspot,+ )+++def history_params(+ author: str | None = Query(None, description="Author email (any case) or exact name"),+ area: str | None = Query(None, description="A directory or file path; keeps work touching it"),+ since: datetime | None = Query(None, description="ISO 8601, inclusive"),+ until: datetime | None = Query(None, description="ISO 8601, exclusive"),+ delta: str | None = Query(+ None,+ pattern=_DELTA_PATTERN,+ description=(+ "What it did to health: improved | worsened (each includes mixed) | mixed | "+ "neutral. Never-scanned work matches none."+ ),+ ),+ touches_hotspot: bool = Query(False, description="Only work that touched a hotspot file"),+) -> HistoryParams:+ return HistoryParams(author, area, utc(since), utc(until), delta, touches_hotspot)diff --git a/packages/server/src/repowise/server/routers/changes.py b/packages/server/src/repowise/server/routers/changes.pyindex d3f1558af..a1e033da6 100644--- a/packages/server/src/repowise/server/routers/changes.py+++ b/packages/server/src/repowise/server/routers/changes.py@@ -30,6 +30,7 @@ from repowise.core.persistence.database import get_sessionfrom repowise.core.suspects import Symptomfrom repowise.core.suspects.index import find_suspectsfrom repowise.server.deps import get_db_session, resolve_request_session_factory, verify_api_key+from repowise.server.routers._history_filters import HistoryParams, history_paramsfrom repowise.server.schemas.changes import (ChangeEvidenceSummary,ChangeListResponse,@@ -39,6 +40,19 @@ from repowise.server.schemas.changes import (SuspectsResponse,summary_from_record,)+from repowise.server.schemas.history import PeriodHealthSummaryResponse+from repowise.server.services.history.changes import (+ ChangeInputs,+ change_detail_health,+ change_health,+ change_period_summary,+ narrow_by_health,+)+from repowise.server.services.history.health import (+ current_stamp,+ period_response,+ rollup_response,+)router = APIRouter(prefix="/api/repos",@@ -79,20 +93,34 @@ async def list_changes(),limit: int = Query(50, ge=1, le=_MAX_PAGE),offset: int = Query(0, ge=0),+ params: HistoryParams = Depends(history_params),session: AsyncSession = Depends(get_db_session),) -> ChangeListResponse:- """A page of changes, newest merged first."""+ """A page of changes, newest merged first, each led by what its commits did+ to health. ``since``/``until`` read ``merged_at``; ``delta`` and+ ``touches_hotspot`` judge the change's rollup."""attribution = await _attribution(session, repo_id)- where = crud.ChangeFilter(category=category, shape=shape, q=q)+ stamp = await current_stamp(session, repo_id)+ where = await narrow_by_health(+ session,+ repo_id,+ _change_filter(params, category=category, shape=shape, q=q),+ stamp,+ delta=params.delta,+ touches_hotspot=params.touches_hotspot,+ )if needs_attention:rows, total = await list_needing_attention(session, repo_id, where, limit=limit, offset=offset)else:rows, total = await crud.list_changes(session, repo_id, where, limit=limit, offset=offset)+ health = await change_health(session, repo_id, [_inputs(r) for r in rows], stamp)items = []for r in rows:item = summary_from_record(change_record(r, attribution=attribution))+ item.health = rollup_response(health[r.change_id].rollup)+ item.touches_hotspot = health[r.change_id].touches_hotspotif evidence:summary = evidence_summary(r)item.evidence_summary = summary and ChangeEvidenceSummary(**summary)@@ -111,6 +139,41 @@ async def list_changes()+def _change_filter(params: HistoryParams, **narrow: str | None) -> crud.ChangeFilter:+ return crud.ChangeFilter(+ **narrow,+ since=params.since,+ until=params.until,+ author=params.author,+ area=params.area,+ )+++def _inputs(row: Any) -> ChangeInputs:+ return ChangeInputs.parse(row.change_id, row.commit_shas_json, row.files_json)++[email protected]("/{repo_id}/changes/summary", response_model=PeriodHealthSummaryResponse)+async def changes_summary(+ repo_id: str,+ category: str | None = Query(None, description="One commit category, e.g. fix"),+ params: HistoryParams = Depends(history_params),+ session: AsyncSession = Depends(get_db_session),+) -> PeriodHealthSummaryResponse:+ """A period headline: how many changes made health better, worse, both or+ neither (improvements first), and the findings behind it."""+ await _attribution(session, repo_id)+ summary = await change_period_summary(+ session,+ repo_id,+ _change_filter(params, category=category),+ await current_stamp(session, repo_id),+ delta=params.delta,+ touches_hotspot=params.touches_hotspot,+ )+ return period_response(summary, params.since, params.until)++@router.get("/{repo_id}/changes/{change_id}", response_model=ChangeRecord)async def get_change(request: Request,@@ -128,6 +191,9 @@ async def get_change(if row is None:raise HTTPException(status_code=404, detail="Change not found")record = change_record(row, attribution=attribution)+ record["health"], record["touches_hotspot"] = await change_detail_health(+ session, repo_id, _inputs(row), await current_stamp(session, repo_id)+ )if evidence:kept = None if refresh else cached_evidence(row)repo = await crud.get_repository(session, repo_id)diff --git a/packages/server/src/repowise/server/routers/git.py b/packages/server/src/repowise/server/routers/git.pyindex edadc72f7..18b7946ff 100644--- a/packages/server/src/repowise/server/routers/git.py+++ b/packages/server/src/repowise/server/routers/git.py@@ -27,6 +27,7 @@ from repowise.core.analysis.change_risk import (score_change,scores_excluding,)+from repowise.core.analysis.history import DeltaStamp, delta_currencyfrom repowise.core.analysis.owners import people_resolverfrom repowise.core.analysis.risk_semantics import change_risk_authorityfrom repowise.core.attribution import (@@ -47,6 +48,7 @@ from repowise.core.persistence.models import GitCommit, GitMetadata, Repositoryfrom repowise.core.persistence.sql import is_missing_tablefrom repowise.server.deps import get_db_session, verify_api_keyfrom repowise.server.mcp_server.tool_risk import _check_test_gap+from repowise.server.routers._history_filters import HistoryParams, history_paramsfrom repowise.server.routers._local_git import (repo_attribution_on,resolve_local_repo,@@ -77,7 +79,17 @@ from repowise.server.schemas import (RiskHistogramBucket,RiskRangeResponse,)-from repowise.server.schemas.git import MovedFromResponse+from repowise.server.schemas.history import PeriodHealthSummaryResponse+from repowise.server.services.history.commits import (+ CommitHistory,+ commit_history,+ commit_period_summary,+)+from repowise.server.services.history.health import (+ current_stamp,+ finding_fields,+ period_response,+)from repowise.server.services.module_health import top_level_modulefrom repowise.server.services.reviewer_suggestions import suggest_reviewers@@ -167,16 +179,27 @@ async def _author_commit_counts(session: AsyncSession, repo_id: str) -> dict[strreturn counts+def _attribution_fields(r: GitCommit) -> dict:+ return {+ "agent_name": r.agent_name,+ "agent_autonomy_tier": r.agent_autonomy_tier,+ "agent_confidence": r.agent_confidence,+ "attribution": commit_label(r.attribution, r.agent_name),+ }++def _commit_fields(r: GitCommit,normalizer: RiskNormalizer,author_counts: dict[str, int] | None = None,*,attribution_on: bool,+ history: CommitHistory | None = None,) -> dict:"""Shared CommitResponse field map (raw row + repo-relative normalization).- Attribution fields stay None when attribution is off for the repository.+ Attribution fields stay None when attribution is off for the repository;+ the health delta and hotspot touches come from *history* when given."""risk = _commit_risk(r)top_driver = risk.top_driver.label if risk and risk.top_driver else None@@ -205,16 +228,8 @@ def _commit_fields(if author_counts is not Noneelse None),- **(- {- "agent_name": r.agent_name,- "agent_autonomy_tier": r.agent_autonomy_tier,- "agent_confidence": r.agent_confidence,- "attribution": commit_label(r.attribution, r.agent_name),- }- if attribution_on- else {}- ),+ **(_attribution_fields(r) if attribution_on else {}),+ **(history.fields(r.sha) if history is not None else {}),}@@ -224,8 +239,11 @@ def _commit_from_row(author_counts: dict[str, int] | None = None,*,attribution_on: bool,+ history: CommitHistory | None = None,) -> CommitResponse:- fields = _commit_fields(r, normalizer, author_counts, attribution_on=attribution_on)+ fields = _commit_fields(+ r, normalizer, author_counts, attribution_on=attribution_on, history=history+ )return CommitResponse(**fields)@@ -254,9 +272,10 @@ async def _commit_files(session: AsyncSession, repo_id: str, sha: str) -> list[Casync def _commit_health(- session: AsyncSession, repo_id: str, sha: str+ session: AsyncSession, repo_id: str, sha: str, stamp: DeltaStamp) -> CommitHealthResponse | None:- """What the commit did to health. None when it was never scanned."""+ """What the commit did to health. None when it was never scanned, or only+ by an analyzer too old to read; ``stale`` when an older one wrote it."""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 []@@ -266,10 +285,12 @@ async def _commit_health(if not is_missing_table(exc):raisereturn None- if delta is None:+ currency = delta_currency(delta, stamp) if delta is not None else "absent"+ if currency == "absent":return Nonereturn CommitHealthResponse(status=delta.status,+ stale=currency == "stale",introduced_count=delta.introduced_count,worsened_count=delta.worsened_count,resolved_count=delta.resolved_count,@@ -277,27 +298,7 @@ async def _commit_health(moved_count=delta.moved_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,- moved_from=(- MovedFromResponse(path=f.moved_from_path, symbol=f.moved_from_symbol)- if f.moved_from_path- else None- ),- )- for f in rows- ],+ findings=[CommitHealthFindingResponse(**finding_fields(f)) for f in rows],)@@ -309,6 +310,7 @@ def _commit_detail_from_row(health: CommitHealthResponse | None = None,*,attribution_on: bool,+ history: CommitHistory | None = None,) -> CommitDetailResponse:"""Map a commit row to its detail view, recomputing the risk-driverbreakdown from the persisted Kamei features + author experience.@@ -328,7 +330,9 @@ def _commit_detail_from_row(for d in (risk.top_drivers if risk else [])]return CommitDetailResponse(- **_commit_fields(r, normalizer, author_counts, attribution_on=attribution_on),+ **_commit_fields(+ r, normalizer, author_counts, attribution_on=attribution_on, history=history+ ),drivers=drivers,agent_channel=r.agent_channel if attribution_on else None,files=files or [],@@ -344,6 +348,7 @@ async def get_commits(kind: str = Query("all", pattern="^(all|high|fixes)$"),limit: int = Query(50, ge=1, le=200),offset: int = Query(0, ge=0),+ params: HistoryParams = Depends(history_params),session: AsyncSession = Depends(get_db_session),) -> Paginated[CommitResponse]:"""Per-commit change-risk feed — the review-priority queue.@@ -354,7 +359,10 @@ async def get_commits(attribution is off), and ``kind`` to the ``high``review-priority band or to ``fixes``. Each commit carries a**repo-relative** ``risk_percentile`` + ``review_priority`` so the ranking- is portable across repos (the absolute calibration band is not).+ is portable across repos (the absolute calibration band is not), and leads+ with ``health_delta`` (what it made better or worse) and ``touches_hotspot``.+ ``author``, ``area``, ``since``/``until``, ``delta`` and ``touches_hotspot``+ narrow the repository, like the other filters."""attribution_on = await repo_attribution_on(session, repo_id)if not attribution_on:@@ -363,22 +371,23 @@ async def get_commits(# The high band is a tercile of the repo's own scores, so the boundary has# to be resolved before the page is cut rather than derived per row.high_cut = normalizer.high_cut- total = await crud.count_git_commits(- session, repo_id, authorship=authorship, kind=kind, high_cut=high_cut- )+ stamp = await current_stamp(session, repo_id)+ where = params.commit_filter(authorship=authorship, kind=kind, high_cut=high_cut, stamp=stamp)+ total = await crud.count_git_commits(session, repo_id, where=where)rows = await crud.get_git_commits(session,repo_id,limit=limit,offset=offset,sort=sort,- authorship=authorship,- kind=kind,- high_cut=high_cut,+ where=where,)author_counts = await _author_commit_counts(session, repo_id)+ history = await commit_history(session, repo_id, [r.sha for r in rows], stamp)items = [- _commit_from_row(r, normalizer, author_counts, attribution_on=attribution_on)+ _commit_from_row(+ r, normalizer, author_counts, attribution_on=attribution_on, history=history+ )for r in rows]next_offset = offset + limit if offset + limit < total else None@@ -515,6 +524,19 @@ async def get_commit_stats()[email protected]("/{repo_id}/commits/health-summary", response_model=PeriodHealthSummaryResponse)+async def get_commit_health_summary(+ repo_id: str,+ params: HistoryParams = Depends(history_params),+ session: AsyncSession = Depends(get_db_session),+) -> PeriodHealthSummaryResponse:+ """How many commits under the filters made health better, worse, both or+ neither, and the findings behind it; improvements first."""+ where = params.commit_filter(stamp=await current_stamp(session, repo_id))+ summary = await commit_period_summary(session, repo_id, where)+ return period_response(summary, params.since, params.until)++_HISTOGRAM_BINS = 20 # 0.5-wide bins across the 0-10 supporting diff-shape score@@ -628,7 +650,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)- health = await _commit_health(session, repo_id, row.sha)+ stamp = await current_stamp(session, repo_id)+ health = await _commit_health(session, repo_id, row.sha, stamp)return _commit_detail_from_row(row,normalizer,@@ -636,6 +659,7 @@ async def get_commit(files,health,attribution_on=await repo_attribution_on(session, repo_id),+ history=await commit_history(session, repo_id, [row.sha], stamp),)diff --git a/packages/server/src/repowise/server/routers/wins.py b/packages/server/src/repowise/server/routers/wins.pynew file mode 100644index 000000000..1c22ceab8--- /dev/null+++ b/packages/server/src/repowise/server/routers/wins.py@@ -0,0 +1,45 @@+"""/api/repos/{repo_id}/wins — what got better in a window."""++from __future__ import annotations++from datetime import UTC, datetime, timedelta++from fastapi import APIRouter, Depends, HTTPException, Query+from sqlalchemy.ext.asyncio import AsyncSession++from repowise.core.persistence import crud+from repowise.server.deps import get_db_session, verify_api_key+from repowise.server.routers._history_filters import utc+from repowise.server.schemas.history import WinsResponse+from repowise.server.services.history.wins import build_wins++router = APIRouter(+ prefix="/api/repos",+ tags=["history"],+ dependencies=[Depends(verify_api_key)],+)++DEFAULT_WINDOW_DAYS = 30++[email protected]("/{repo_id}/wins", response_model=WinsResponse)+async def get_wins(+ repo_id: str,+ since: datetime | None = Query(None, description="ISO 8601; default 30 days ago"),+ until: datetime | None = Query(None, description="ISO 8601, exclusive; default now"),+ author: str | None = Query(+ None, description="Author email (any case) or exact name: that person's wins only"+ ),+ top: int = Query(10, ge=1, le=50, description="Items per section"),+ session: AsyncSession = Depends(get_db_session),+) -> WinsResponse:+ """Findings resolved, files whose score rose and refactorings that landed.++ Positive only: an author gets credit, never a comparison.+ """+ if await crud.get_repository(session, repo_id) is None:+ raise HTTPException(status_code=404, detail="Repository not found")+ since = utc(since) or datetime.now(UTC) - timedelta(days=DEFAULT_WINDOW_DAYS)+ return await build_wins(+ session, repo_id, since=since, until=utc(until), author=author, top=top+ )diff --git a/packages/server/src/repowise/server/schemas/changes.py b/packages/server/src/repowise/server/schemas/changes.pyindex ac31baddd..972060cdc 100644--- a/packages/server/src/repowise/server/schemas/changes.py+++ b/packages/server/src/repowise/server/schemas/changes.py@@ -11,6 +11,9 @@ from typing import Any, Literalfrom pydantic import BaseModel, Field, model_serializer+from repowise.server.schemas.git import CommitHealthFindingResponse+from repowise.server.schemas.history import HealthRollupResponse+class ChangeIdentity(BaseModel):"""``pr`` | ``change_id`` | ``merge`` | ``commit``, first that applies."""@@ -68,6 +71,11 @@ class ChangeSummary(BaseModel):category: str# Null while AI attribution is off, or on rows indexed before it.provenance: ChangeProvenance | None = None+ #: What the change's commits did to health, the row's lead. Null when+ #: none of them was scanned.+ health: HealthRollupResponse | None = None+ #: Files the change touched that are hotspots now.+ touches_hotspot: int = 0class EvidenceLine(BaseModel):@@ -102,7 +110,21 @@ class ChangeEvidence(BaseModel):items: list[EvidenceItem]+class ChangeHealthFindingResponse(CommitHealthFindingResponse):+ """A finding a change's commit introduced or worsened, with that commit."""++ sha: str+++class ChangeHealthResponse(HealthRollupResponse):+ """A change's health rollup plus its worse findings, worst first and+ capped: file, lines, symbol and biomarker, enough for a fix prompt."""++ findings: list[ChangeHealthFindingResponse] = Field(default_factory=list)++class ChangeRecord(ChangeSummary):+ health: ChangeHealthResponse | None = Nonecommits: list[str]files: list[ChangeFile]metadata: ChangeForgeMetadatadiff --git a/packages/server/src/repowise/server/schemas/git.py b/packages/server/src/repowise/server/schemas/git.pyindex 806a72295..722ab5e05 100644--- a/packages/server/src/repowise/server/schemas/git.py+++ b/packages/server/src/repowise/server/schemas/git.py@@ -10,6 +10,7 @@ from pydantic import BaseModelfrom repowise.core.attribution import file_sharefrom repowise.core.co_change import parse_partners+from repowise.server.schemas.history import HealthDeltaSummaryResponsefrom repowise.server.schemas.risk_semantics import RiskAuthority@@ -245,6 +246,11 @@ class CommitResponse(BaseModel):agent_autonomy_tier: int | None = Noneagent_confidence: str | None = Noneattribution: str | None = None+ #: What the commit did to health, the row's lead. ``None`` when it was+ #: never scanned, which is not the same claim as "changed nothing".+ health_delta: HealthDeltaSummaryResponse | None = None+ #: Hotspot files (as flagged now) the commit touched.+ touches_hotspot: int = 0class RiskDriverResponse(BaseModel):@@ -296,6 +302,9 @@ class CommitHealthResponse(BaseModel):#: ``available`` when every changed file was compared, ``partial`` when#: some were skipped (unsupported language, binary, unreadable).status: str+ #: An older analyzer wrote it: the direction holds, the counts do not+ #: compare with current rows.+ stale: bool = Falseintroduced_count: intworsened_count: intresolved_count: intdiff --git a/packages/server/src/repowise/server/schemas/history.py b/packages/server/src/repowise/server/schemas/history.pynew file mode 100644index 000000000..5e6b720ed--- /dev/null+++ b/packages/server/src/repowise/server/schemas/history.py@@ -0,0 +1,159 @@+"""Better/worse history shapes: commit and change health deltas, period+headlines and wins. Twins of :mod:`repowise.core.analysis.history`."""++from __future__ import annotations++from datetime import datetime+from typing import Literal++from pydantic import BaseModel++DeltaKindLiteral = Literal["improved", "worsened", "mixed", "neutral"]+++class FileScoreShiftResponse(BaseModel):+ """A file's health score before and after; ``None`` on a side it was unscored."""++ path: str+ before: float | None = None+ after: float | None = None+ change: float | None = None+++class HealthDeltaSummaryResponse(BaseModel):+ """What one commit did to health, as list rows carry it.++ ``kind`` reads the counts: ``improved`` when it only made things better,+ ``worsened`` when it only made them worse, ``mixed`` for both, ``neutral``+ for neither. ``improved`` (findings that measure better) and ``moved`` are+ null on a stale row, where the stored 0 means unknown; ``files`` stays empty for stored deltas (per-file scores are+ live-only). ``stale`` means an older analyzer wrote it: the direction holds,+ the counts do not compare with current rows, and no aggregate counts it.+ """++ status: str+ kind: DeltaKindLiteral+ introduced: int+ worsened: int+ resolved: int+ improved: int | None = None+ #: Findings carried to another file with their code; never introduced.+ moved: int | None = None+ stale: bool = False+ files: list[FileScoreShiftResponse] = []+++class HealthRollupResponse(BaseModel):+ """What a change's commits did to health, summed.++ ``status`` is ``partial`` when a commit was not scanned or skipped files.+ Only rows from the current analyzer count; the rest are unscanned.+ ``files_worsened`` counts paths the stored worse findings name (a floor:+ findings are capped per commit). ``files_improved`` is null until stored+ deltas carry per-file scores.+ """++ status: str+ kind: DeltaKindLiteral+ scanned_commits: int+ unscanned_commits: int+ introduced: int+ worsened: int+ resolved: int+ improved: int | None = None+ moved: int | None = None+ files_improved: int | None = None+ files_worsened: int+++class PeriodHealthSummaryResponse(BaseModel):+ """A period headline: items that made health better first, then worse.++ Items are changes on ``/changes/summary`` and commits on+ ``/commits/health-summary``. ``unscanned`` items have no delta from the+ current analyzer ("not yet analysed") and are in none of the four kinds;+ recent commits refill as updates rescan them.+ """++ since: datetime | None = None+ until: datetime | None = None+ total: int+ improved: int+ mixed: int+ worsened: int+ neutral: int+ unscanned: int+ findings_resolved: int+ findings_improved: int | None = None+ findings_introduced: int+ findings_worsened: int+ net_findings: int+++class WinsResolvingCommit(BaseModel):+ sha: str+ subject: str+ author_name: str+ committed_at: datetime | None = None+ resolved: int+++class WinsFindingsResolved(BaseModel):+ """Findings commits in the window resolved. Resolved findings are stored as+ per-commit counts, so the top items are the commits that resolved most."""++ count: int+ commits: int+ top_commits: list[WinsResolvingCommit] = []+++class WinsFileGain(BaseModel):+ path: str+ before: float+ after: float+ gain: float+++class WinsFilesImproved(BaseModel):+ """Files commits in the window touched whose score rose between the snapshot+ at ``baseline_at`` and the one at ``current_at``."""++ count: int+ baseline_at: datetime | None = None+ current_at: datetime | None = None+ top: list[WinsFileGain] = []+++class WinsRefactoring(BaseModel):+ """A refactoring plan that landed: its target is gone or shrank as planned."""++ file_path: str+ target_symbol: str+ refactoring_type: str+ resolved_at: datetime | None = None+ before_ccn: int | None = None+ after_ccn: int | None = None+ before_nloc: int | None = None+ after_nloc: int | None = None+++class WinsRefactorings(BaseModel):+ count: int+ top: list[WinsRefactoring] = []+++class WinsResponse(BaseModel):+ """What got better since ``since``. Positive only.++ With ``author`` every section narrows to that person's commits and the+ files they touched. ``unavailable`` names wins the index cannot answer+ from stored data (no history is kept for them).+ """++ since: datetime+ until: datetime | None = None+ author: str | None = None+ findings_resolved: WinsFindingsResolved+ files_improved: WinsFilesImproved+ refactorings_landed: WinsRefactorings+ unavailable: list[str] = []diff --git a/packages/server/src/repowise/server/services/history/__init__.py b/packages/server/src/repowise/server/services/history/__init__.pynew file mode 100644index 000000000..5fca8bfb3--- /dev/null+++ b/packages/server/src/repowise/server/services/history/__init__.py@@ -0,0 +1 @@+"""Better/worse history: commit and change health rollups, period headlines, wins."""diff --git a/packages/server/src/repowise/server/services/history/changes.py b/packages/server/src/repowise/server/services/history/changes.pynew file mode 100644index 000000000..3ab224a77--- /dev/null+++ b/packages/server/src/repowise/server/services/history/changes.py@@ -0,0 +1,170 @@+"""Roll a change's commit deltas up, filter changes by them, and head a period.++A change keeps its commits as ``commit_shas_json`` and its files as+``files_json``; both are read with the change, and every commit delta, worse+finding path and hotspot flag the rollups need comes from one bulk read per+request.+"""++from __future__ import annotations++import json+from collections.abc import Sequence+from dataclasses import dataclass, replace++from sqlalchemy.ext.asyncio import AsyncSession++from repowise.core.analysis.history import (+ DeltaStamp,+ HealthRollup,+ PeriodHealthSummary,+ matches_delta,+ rollup_deltas,+ summarize_period,+)+from repowise.core.persistence import crud+from repowise.server.schemas.changes import ChangeHealthFindingResponse, ChangeHealthResponse++from .health import finding_fields, rollup_fields, stored_deltas++#: Worse findings a change detail carries for a fix prompt; the counts are whole.+DETAIL_FINDINGS = 50+++@dataclass(frozen=True, slots=True)+class ChangeInputs:+ """What a change's rollup reads: its commits and its stored file paths."""++ change_id: str+ shas: tuple[str, ...]+ paths: tuple[str, ...]++ @classmethod+ def parse(cls, change_id: str, commit_shas_json: str, files_json: str) -> ChangeInputs:+ files = _loads_list(files_json)+ return cls(+ change_id,+ tuple(str(s) for s in _loads_list(commit_shas_json)),+ tuple(f["path"] for f in files if isinstance(f, dict) and f.get("path")),+ )+++def _loads_list(raw: str | None) -> list:+ try:+ value = json.loads(raw or "[]")+ except (TypeError, ValueError):+ return []+ return value if isinstance(value, list) else []+++@dataclass(frozen=True, slots=True)+class ChangeHealth:+ rollup: HealthRollup | None+ touches_hotspot: int+ # The commits the rollup counted, so detail findings come from the same rows.+ counted_shas: tuple[str, ...] = ()+++async def change_health(+ session: AsyncSession, repo_id: str, changes: Sequence[ChangeInputs], stamp: DeltaStamp+) -> dict[str, ChangeHealth]:+ """``change_id -> rollup and hotspot touches`` for *changes*, in three reads.++ A rollup is an aggregate: rows under the current *stamp* only, the rest unscanned.+ """+ shas = [sha for c in changes for sha in c.shas]+ deltas = await stored_deltas(session, repo_id, shas, stamp, current_only=True)+ worse_paths = await crud.get_worse_paths_bulk(session, repo_id, list(deltas))+ hotspots = await crud.get_hotspot_paths(session, repo_id)+ out: dict[str, ChangeHealth] = {}+ for c in changes:+ rollup = rollup_deltas(+ [deltas.get(sha) for sha in c.shas],+ (path for sha in c.shas for path in worse_paths.get(sha, ())),+ )+ out[c.change_id] = ChangeHealth(+ rollup,+ sum(1 for p in set(c.paths) if p in hotspots),+ tuple(sha for sha in c.shas if sha in deltas),+ )+ return out+++async def _matching_inputs(+ session: AsyncSession, repo_id: str, where: crud.ChangeFilter+) -> list[ChangeInputs]:+ rows = await crud.list_change_health_inputs(session, repo_id, where)+ return [ChangeInputs.parse(*row) for row in rows]+++async def narrow_by_health(+ session: AsyncSession,+ repo_id: str,+ where: crud.ChangeFilter,+ stamp: DeltaStamp,+ *,+ delta: str | None,+ touches_hotspot: bool,+) -> crud.ChangeFilter:+ """*where* narrowed to the changes whose rollup passes *delta* and *touches_hotspot*.++ Both are judged on the rollup, so the matching ids are fixed here and the+ caller's own listing (plain or needs-attention) still orders and pages.+ A change no commit of which was scanned passes no delta filter.++ Reads every matching change's commits and files, then binds the kept ids+ as one ``IN`` list. Bounded by the change window (``commit_limit``); the+ ceiling is the driver's bind limit (32k on SQLite, 65k on PostgreSQL),+ past which this would move into SQL over a stored per-change rollup.+ """+ if not delta and not touches_hotspot:+ return where+ inputs = await _matching_inputs(session, repo_id, where)+ health = await change_health(session, repo_id, inputs, stamp)+ keep = [+ c.change_id+ for c in inputs+ if _passes(health[c.change_id], delta=delta, touches_hotspot=touches_hotspot)+ ]+ return replace(where, change_ids=keep)+++def _passes(health: ChangeHealth, *, delta: str | None, touches_hotspot: bool) -> bool:+ if touches_hotspot and not health.touches_hotspot:+ return False+ if not delta:+ return True+ return health.rollup is not None and matches_delta(health.rollup.kind, delta)+++async def change_period_summary(+ session: AsyncSession,+ repo_id: str,+ where: crud.ChangeFilter,+ stamp: DeltaStamp,+ *,+ delta: str | None = None,+ touches_hotspot: bool = False,+) -> PeriodHealthSummary:+ """How many changes under the filters made health better, worse, both or neither."""+ inputs = await _matching_inputs(session, repo_id, where)+ health = await change_health(session, repo_id, inputs, stamp)+ return summarize_period(+ health[c.change_id].rollup+ for c in inputs+ if _passes(health[c.change_id], delta=delta, touches_hotspot=touches_hotspot)+ )+++async def change_detail_health(+ session: AsyncSession, repo_id: str, change: ChangeInputs, stamp: DeltaStamp+) -> tuple[ChangeHealthResponse | None, int]:+ """A change detail's health block, with its worse findings, and hotspot touches."""+ got = (await change_health(session, repo_id, [change], stamp))[change.change_id]+ if got.rollup is None:+ return None, got.touches_hotspot+ rows = await crud.get_commit_findings_bulk(+ session, repo_id, got.counted_shas, limit=DETAIL_FINDINGS+ )+ findings = [ChangeHealthFindingResponse(sha=f.sha, **finding_fields(f)) for f in rows]+ return ChangeHealthResponse(**rollup_fields(got.rollup), findings=findings), got.touches_hotspotdiff --git a/packages/server/src/repowise/server/services/history/commits.py b/packages/server/src/repowise/server/services/history/commits.pynew file mode 100644index 000000000..18f9fc166--- /dev/null+++ b/packages/server/src/repowise/server/services/history/commits.py@@ -0,0 +1,56 @@+"""Health delta and hotspot touches for commit rows, and a commit period headline."""++from __future__ import annotations++from collections.abc import Sequence+from dataclasses import dataclass++from sqlalchemy.ext.asyncio import AsyncSession++from repowise.core.analysis.history import (+ DeltaStamp,+ HealthDeltaSummary,+ PeriodHealthSummary,+ summarize_period,+)+from repowise.core.persistence import crud++from .health import delta_response, stored_deltas+++@dataclass(frozen=True, slots=True)+class CommitHistory:+ """What a page of commits did to health and how many hotspots each touched."""++ deltas: dict[str, HealthDeltaSummary]+ hotspots: dict[str, int]++ def fields(self, sha: str) -> dict:+ """The ``CommitResponse`` history fields for *sha*."""+ return {+ "health_delta": delta_response(self.deltas.get(sha)),+ "touches_hotspot": self.hotspots.get(sha, 0),+ }+++async def commit_history(+ session: AsyncSession, repo_id: str, shas: Sequence[str], stamp: DeltaStamp+) -> CommitHistory:+ """Two bulk reads for the whole page, whatever its size. A row from an older+ analyzer shows, flagged stale."""+ return CommitHistory(+ deltas=await stored_deltas(session, repo_id, shas, stamp, current_only=False),+ hotspots=await crud.count_hotspot_files_bulk(session, repo_id, shas),+ )+++async def commit_period_summary(+ session: AsyncSession, repo_id: str, where: crud.CommitFilter+) -> PeriodHealthSummary:+ """How many commits under *where* made health better, worse, both or+ neither; only current-analyzer rows count (``where.stamp``)."""+ if where.stamp is None:+ raise ValueError("a period summary needs the current analyzer stamp")+ shas = await crud.list_commit_shas(session, repo_id, where)+ deltas = await stored_deltas(session, repo_id, shas, where.stamp, current_only=True)+ return summarize_period(deltas.get(sha) for sha in shas)diff --git a/packages/server/src/repowise/server/services/history/health.py b/packages/server/src/repowise/server/services/history/health.pynew file mode 100644index 000000000..6642c88e7--- /dev/null+++ b/packages/server/src/repowise/server/services/history/health.py@@ -0,0 +1,128 @@+"""Stored commit deltas read in bulk, and their wire shapes.++Shared by the commit and change surfaces so both read a delta the same way.+"""++from __future__ import annotations++from collections.abc import Sequence+from dataclasses import asdict+from datetime import datetime+from typing import Any++from fastapi import HTTPException+from sqlalchemy.exc import OperationalError, ProgrammingError+from sqlalchemy.ext.asyncio import AsyncSession++from repowise.core.analysis.history import (+ DeltaStamp,+ HealthDeltaSummary,+ HealthRollup,+ PeriodHealthSummary,+ delta_currency,+ summarize_delta,+)+from repowise.core.persistence import crud+from repowise.core.persistence.sql import is_missing_table+from repowise.server.schemas.git import MovedFromResponse+from repowise.server.schemas.history import (+ FileScoreShiftResponse,+ HealthDeltaSummaryResponse,+ HealthRollupResponse,+ PeriodHealthSummaryResponse,+)+++async def current_stamp(session: AsyncSession, repo_id: str) -> DeltaStamp:+ """The analyzer stamp a delta computed now would carry (a config hash, ~5 ms)."""+ from repowise.core.analysis.change_health.commit_scan import current_fingerprint++ repo = await crud.get_repository(session, repo_id)+ if repo is None:+ raise HTTPException(status_code=404, detail="Repository not found")+ return DeltaStamp(**current_fingerprint(repo.local_path))+++async def stored_deltas(+ session: AsyncSession,+ repo_id: str,+ shas: Sequence[str],+ stamp: DeltaStamp,+ *,+ current_only: bool,+) -> dict[str, HealthDeltaSummary]:+ """``sha -> delta`` for the scanned commits among *shas*; empty on an index+ older than the delta table.++ *current_only* (every aggregate) keeps rows with the current *stamp* and+ treats the rest as never scanned. Otherwise (one row on display) an older+ readable row comes back flagged ``stale``; one below the shown floor is absent.+ """+ try:+ rows = await crud.get_commit_health_bulk(session, repo_id, shas)+ except (OperationalError, ProgrammingError) as exc:+ if not is_missing_table(exc):+ raise+ return {}+ out: dict[str, HealthDeltaSummary] = {}+ for sha, row in rows.items():+ currency = delta_currency(row, stamp)+ if currency == "current" or (currency == "stale" and not current_only):+ out[sha] = summarize_delta(row, stale=currency == "stale")+ return out+++def delta_response(delta: HealthDeltaSummary | None) -> HealthDeltaSummaryResponse | None:+ if delta is None:+ return None+ return HealthDeltaSummaryResponse(+ status=delta.status,+ kind=delta.kind,+ introduced=delta.introduced,+ worsened=delta.worsened,+ resolved=delta.resolved,+ improved=delta.improved,+ moved=delta.moved,+ stale=delta.stale,+ files=[+ FileScoreShiftResponse(path=f.path, before=f.before, after=f.after, change=f.change)+ for f in delta.files+ ],+ )+++def finding_fields(row: Any) -> dict:+ """``CommitHealthFindingResponse`` fields of a stored ``GitCommitHealthFinding``."""+ return {+ "change_kind": row.change_kind,+ "dimension": row.dimension,+ "biomarker_type": row.biomarker_type,+ "severity": row.severity,+ "severity_before": row.severity_before,+ "path": row.file_path,+ "symbol": row.symbol,+ "line_start": row.line_start,+ "line_end": row.line_end,+ "attribution_basis": row.attribution_basis,+ "reason": row.reason,+ "moved_from": (+ MovedFromResponse(path=row.moved_from_path, symbol=row.moved_from_symbol)+ if row.moved_from_path+ else None+ ),+ }+++def rollup_fields(rollup: HealthRollup) -> dict:+ """The :class:`HealthRollupResponse` fields of *rollup*."""+ return {**asdict(rollup), "kind": rollup.kind}+++def rollup_response(rollup: HealthRollup | None) -> HealthRollupResponse | None:+ return None if rollup is None else HealthRollupResponse(**rollup_fields(rollup))+++def period_response(+ summary: PeriodHealthSummary, since: datetime | None, until: datetime | None+) -> PeriodHealthSummaryResponse:+ return PeriodHealthSummaryResponse(since=since, until=until, **asdict(summary))diff --git a/packages/server/src/repowise/server/services/history/wins.py b/packages/server/src/repowise/server/services/history/wins.pynew file mode 100644index 000000000..e07d73715--- /dev/null+++ b/packages/server/src/repowise/server/services/history/wins.py@@ -0,0 +1,142 @@+"""What got better in a window, from stored data only. Positive by design.++Three wins are answerable without new history:++* findings resolved, from the stored per-commit deltas;+* files whose score rose, from the snapshot at the window's start and the+ newest one, counting only files a commit in the window touched;+* refactoring plans that landed, from the stored payoffs.++With an author every section narrows to that person's commits and the files+they touched; nothing is ranked against anyone else.+"""++from __future__ import annotations++from datetime import datetime++from sqlalchemy.ext.asyncio import AsyncSession++from repowise.core.analysis.history import parse_score_map, rising_files+from repowise.core.persistence import crud+from repowise.server.schemas.history import (+ WinsFileGain,+ WinsFilesImproved,+ WinsFindingsResolved,+ WinsRefactoring,+ WinsRefactorings,+ WinsResolvingCommit,+ WinsResponse,+)+from repowise.server.services.history.health import current_stamp++#: Wins the index keeps no history for, so it cannot say they happened.+UNAVAILABLE = (+ "dead_code_removed: dead-code findings are replaced on each index, not kept as history",+ "bus_factor_gains: ownership is stored as current state only",+ "resolved_finding_items: resolved findings are stored as per-commit counts, without the items",+)+++async def _findings_resolved(+ session: AsyncSession, repo_id: str, where: crud.CommitFilter, top: int+) -> WinsFindingsResolved:+ rows = await crud.get_resolving_commits(session, repo_id, where)+ return WinsFindingsResolved(+ count=sum(n for _, n in rows),+ commits=len(rows),+ top_commits=[+ WinsResolvingCommit(+ sha=c.sha,+ subject=c.subject or "",+ author_name=c.author_name or "",+ committed_at=c.committed_at,+ resolved=n,+ )+ for c, n in rows[:top]+ ],+ )+++async def _files_improved(+ session: AsyncSession,+ repo_id: str,+ since: datetime,+ until: datetime | None,+ touched: set[str],+ top: int,+) -> WinsFilesImproved:+ baseline = await crud.get_snapshot_scores_at(session, repo_id, since)+ current = await crud.get_snapshot_scores_at(session, repo_id, until)+ if baseline is None or current is None or baseline[0] == current[0]:+ return WinsFilesImproved(count=0)+ gains = rising_files(parse_score_map(baseline[1]), parse_score_map(current[1]), touched)+ return WinsFilesImproved(+ count=len(gains),+ baseline_at=baseline[0],+ current_at=current[0],+ top=[+ WinsFileGain(path=g.path, before=g.before, after=g.after, gain=g.gain)+ for g in gains[:top]+ ],+ )+++async def _refactorings_landed(+ session: AsyncSession,+ repo_id: str,+ since: datetime,+ until: datetime | None,+ touched: set[str] | None,+ top: int,+) -> WinsRefactorings:+ landed = [+ (plan, payoff)+ for plan, payoff in await crud.get_applied_refactorings(+ session, repo_id, since=since, until=until+ )+ if touched is None or plan.file_path in touched+ ]+ return WinsRefactorings(+ count=len(landed),+ top=[+ WinsRefactoring(+ file_path=plan.file_path,+ target_symbol=plan.target_symbol,+ refactoring_type=plan.refactoring_type,+ resolved_at=payoff.resolved_at,+ before_ccn=payoff.before_ccn,+ after_ccn=payoff.after_ccn,+ before_nloc=payoff.before_nloc,+ after_nloc=payoff.after_nloc,+ )+ for plan, payoff in landed[:top]+ ],+ )+++async def build_wins(+ session: AsyncSession,+ repo_id: str,+ *,+ since: datetime,+ until: datetime | None,+ author: str | None,+ top: int,+) -> WinsResponse:+ stamp = await current_stamp(session, repo_id)+ where = crud.CommitFilter(author=author, since=since, until=until, stamp=stamp)+ touched = await crud.get_touched_paths(session, repo_id, where)+ return WinsResponse(+ since=since,+ until=until,+ author=author,+ findings_resolved=await _findings_resolved(session, repo_id, where, top),+ files_improved=await _files_improved(session, repo_id, since, until, touched, top),+ # A plan's resolving run is whoever indexed next, not who did the work,+ # so an author is credited only with plans in files they touched.+ refactorings_landed=await _refactorings_landed(+ session, repo_id, since, until, touched if author else None, top+ ),+ unavailable=list(UNAVAILABLE),+ )diff --git a/packages/types/package.json b/packages/types/package.jsonindex 24c0dea60..449727f4c 100644--- a/packages/types/package.json+++ b/packages/types/package.json@@ -20,6 +20,7 @@"./chat": "./src/chat.ts","./cards": "./src/cards.ts","./changes": "./src/changes.ts",+ "./history": "./src/history.ts","./events": "./src/events.ts","./views": "./src/views.ts","./workspace": "./src/workspace.ts",diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.tsindex 85d1eeea5..fd12e9650 100644--- a/packages/types/src/generated/http.ts+++ b/packages/types/src/generated/http.ts@@ -564,6 +564,42 @@ export interface ChangeForgeMetadata {linked_issues?: string[] | null;}+/** A finding a change's commit introduced or worsened, with that commit. */+export interface ChangeHealthFindingResponse {+ 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;+ moved_from?: MovedFromResponse | null;+ sha: string;+}++/**+ * A change's health rollup plus its worse findings, worst first and+ * capped: file, lines, symbol and biomarker, enough for a fix prompt.+ */+export interface ChangeHealthResponse {+ status: string;+ kind: "improved" | "worsened" | "mixed" | "neutral";+ scanned_commits: number;+ unscanned_commits: number;+ introduced: number;+ worsened: number;+ resolved: number;+ improved?: number | null;+ moved?: number | null;+ files_improved?: number | null;+ files_worsened: number;+ findings?: ChangeHealthFindingResponse[];+}+/** ``pr`` | ``change_id`` | ``merge`` | ``commit``, first that applies. */export interface ChangeIdentity {kind: string;@@ -587,6 +623,8 @@ export interface ChangeListItem {lines_deleted: number;category: string;provenance?: ChangeProvenance | null;+ health?: HealthRollupResponse | null;+ touches_hotspot?: number;evidence_summary?: ChangeEvidenceSummary | null;}@@ -625,6 +663,8 @@ export interface ChangeRecord {lines_deleted: number;category: string;provenance?: ChangeProvenance | null;+ health?: ChangeHealthResponse | null;+ touches_hotspot?: number;commits: string[];files: ChangeFile[];metadata: ChangeForgeMetadata;@@ -921,6 +961,8 @@ export interface CommitDetailResponse {agent_autonomy_tier?: number | null;agent_confidence?: string | null;attribution?: string | null;+ health_delta?: HealthDeltaSummaryResponse | null;+ touches_hotspot?: number;drivers?: RiskDriverResponse[];agent_channel?: string | null;files?: CommitFileResponse[];@@ -991,6 +1033,7 @@ export interface CommitHealthFindingResponse {*/export interface CommitHealthResponse {status: string;+ stale?: boolean;introduced_count: number;worsened_count: number;resolved_count: number;@@ -1035,6 +1078,8 @@ export interface CommitResponse {agent_autonomy_tier?: number | null;agent_confidence?: string | null;attribution?: string | null;+ health_delta?: HealthDeltaSummaryResponse | null;+ touches_hotspot?: number;}/**@@ -1967,6 +2012,14 @@ export interface FileHealthTrendResponse {snapshot_count?: number;}+/** A file's health score before and after; ``None`` on a side it was unscored. */+export interface FileScoreShiftResponse {+ path: string;+ before?: number | null;+ after?: number | null;+ change?: number | null;+}+export interface FileTrendPointResponse {taken_at?: string | null;score: number;@@ -2319,6 +2372,28 @@ export interface HealthBadgeResponse {band: string;}+/**+ * What one commit did to health, as list rows carry it.+ *+ * ``kind`` reads the counts: ``improved`` when it only made things better,+ * ``worsened`` when it only made them worse, ``mixed`` for both, ``neutral``+ * for neither. ``improved`` (findings that measure better) and ``moved`` are+ * null on a stale row, where the stored 0 means unknown; ``files`` stays empty for stored deltas (per-file scores are+ * live-only). ``stale`` means an older analyzer wrote it: the direction holds,+ * the counts do not compare with current rows, and no aggregate counts it.+ */+export interface HealthDeltaSummaryResponse {+ status: string;+ kind: "improved" | "worsened" | "mixed" | "neutral";+ introduced: number;+ worsened: number;+ resolved: number;+ improved?: number | null;+ moved?: number | null;+ stale?: boolean;+ files?: FileScoreShiftResponse[];+}+/** One file's movement between the last two snapshots. */export interface HealthFileDelta {file_path: string;@@ -2377,6 +2452,29 @@ export interface HealthResponse {version: string;}+/**+ * What a change's commits did to health, summed.+ *+ * ``status`` is ``partial`` when a commit was not scanned or skipped files.+ * Only rows from the current analyzer count; the rest are unscanned.+ * ``files_worsened`` counts paths the stored worse findings name (a floor:+ * findings are capped per commit). ``files_improved`` is null until stored+ * deltas carry per-file scores.+ */+export interface HealthRollupResponse {+ status: string;+ kind: "improved" | "worsened" | "mixed" | "neutral";+ scanned_commits: number;+ unscanned_commits: number;+ introduced: number;+ worsened: number;+ resolved: number;+ improved?: number | null;+ moved?: number | null;+ files_improved?: number | null;+ files_worsened: number;+}+export interface HealthTrendAlert {kind: string;metric: string;@@ -3181,6 +3279,30 @@ export interface PatchCoverageTestHint {total: number;}+/**+ * A period headline: items that made health better first, then worse.+ *+ * Items are changes on ``/changes/summary`` and commits on+ * ``/commits/health-summary``. ``unscanned`` items have no delta from the+ * current analyzer ("not yet analysed") and are in none of the four kinds;+ * recent commits refill as updates rescan them.+ */+export interface PeriodHealthSummaryResponse {+ since?: string | null;+ until?: string | null;+ total: number;+ improved: number;+ mixed: number;+ worsened: number;+ neutral: number;+ unscanned: number;+ findings_resolved: number;+ findings_improved?: number | null;+ findings_introduced: number;+ findings_worsened: number;+ net_findings: number;+}+/** A function's stored size measures; an absent one was not measured. */export interface PlanMeasuresResponse {ccn?: number | null;@@ -4141,6 +4263,76 @@ export interface WebhookResponse {status?: string;}+export interface WinsFileGain {+ path: string;+ before: number;+ after: number;+ gain: number;+}++/**+ * Files commits in the window touched whose score rose between the snapshot+ * at ``baseline_at`` and the one at ``current_at``.+ */+export interface WinsFilesImproved {+ count: number;+ baseline_at?: string | null;+ current_at?: string | null;+ top?: WinsFileGain[];+}++/**+ * Findings commits in the window resolved. Resolved findings are stored as+ * per-commit counts, so the top items are the commits that resolved most.+ */+export interface WinsFindingsResolved {+ count: number;+ commits: number;+ top_commits?: WinsResolvingCommit[];+}++/** A refactoring plan that landed: its target is gone or shrank as planned. */+export interface WinsRefactoring {+ file_path: string;+ target_symbol: string;+ refactoring_type: string;+ resolved_at?: string | null;+ before_ccn?: number | null;+ after_ccn?: number | null;+ before_nloc?: number | null;+ after_nloc?: number | null;+}++export interface WinsRefactorings {+ count: number;+ top?: WinsRefactoring[];+}++export interface WinsResolvingCommit {+ sha: string;+ subject: string;+ author_name: string;+ committed_at?: string | null;+ resolved: number;+}++/**+ * What got better since ``since``. Positive only.+ *+ * With ``author`` every section narrows to that person's commits and the+ * files they touched. ``unavailable`` names wins the index cannot answer+ * from stored data (no history is kept for them).+ */+export interface WinsResponse {+ since: string;+ until?: string | null;+ author?: string | null;+ findings_resolved: WinsFindingsResolved;+ files_improved: WinsFilesImproved;+ refactorings_landed: WinsRefactorings;+ unavailable?: string[];+}+export interface WorkspaceActionsResponse {repos: WorkspaceRepoActions[];cross_repo: WorkspaceCrossRepoAction[];diff --git a/packages/types/src/git.ts b/packages/types/src/git.tsindex 83f040a7d..d21b01b43 100644--- a/packages/types/src/git.ts+++ b/packages/types/src/git.ts@@ -7,6 +7,8 @@* adapter before passing data to components.*/+import type { HealthDeltaSummaryResponse } from "./generated/http.js";+export interface FileAuthor {name: string;email: string;@@ -164,6 +166,10 @@ export interface Commit {agent_confidence?: string | null;/** agent / human_attested / unknown; null when attribution is off. */attribution?: CommitAttribution | null;+ /** What the commit did to health, the row's lead; null when never scanned. */+ health_delta?: HealthDeltaSummaryResponse | null;+ /** Hotspot files (as flagged now) the commit touched. */+ touches_hotspot?: number;}export type CommitAttribution = "agent" | "human_attested" | "unknown";@@ -215,6 +221,9 @@ export interface CommitHealth {/** `available` when every changed file was compared, `partial` when some* were skipped (unsupported language, binary, unreadable). */status: string;+ /** An older analyzer wrote it: the direction holds, the counts do not+ * compare with current rows. */+ stale?: boolean;introduced_count: number;worsened_count: number;resolved_count: number;diff --git a/packages/types/src/history.ts b/packages/types/src/history.tsnew file mode 100644index 000000000..fcbbbcb27--- /dev/null+++ b/packages/types/src/history.ts@@ -0,0 +1,46 @@+/**+ * Better/worse history: what a commit or change did to code health, a period+ * headline that counts improvements first, and the wins in a window.+ *+ * Generated from the server's response models+ * (`packages/server/src/repowise/server/schemas/history.py`), so the wire+ * shape cannot drift. A `kind` reads the counts: `improved` only made things+ * better, `worsened` only worse, `mixed` both, `neutral` neither. A null delta+ * or rollup means not yet analysed, which is not the same claim as `neutral`.+ * A row's `stale` delta came from an older analyzer: show its direction, not+ * its counts. Aggregates count current-analyzer rows only. `improved` is null+ * until stored deltas carry it; `files` stays empty for stored deltas.+ */+export type {+ ChangeHealthFindingResponse,+ ChangeHealthResponse,+ FileScoreShiftResponse,+ HealthDeltaSummaryResponse,+ HealthRollupResponse,+ PeriodHealthSummaryResponse,+ WinsFileGain,+ WinsFilesImproved,+ WinsFindingsResolved,+ WinsRefactoring,+ WinsRefactorings,+ WinsResolvingCommit,+ WinsResponse,+} from "./generated/http.js";++/** Values the `delta` filter takes; `improved` and `worsened` include `mixed`. */+export const DELTA_FILTERS = ["improved", "worsened", "mixed", "neutral"] as const;+export type DeltaFilter = (typeof DELTA_FILTERS)[number];++/** History filters shared by the commit and change lists and their summaries. */+export interface HistoryFilters {+ /** Author email (any case) or exact name. */+ author?: string;+ /** A directory or file path; keeps work touching it. */+ area?: string;+ /** ISO 8601, inclusive. */+ since?: string;+ /** ISO 8601, exclusive. */+ until?: string;+ delta?: DeltaFilter;+ touches_hotspot?: boolean;+}diff --git a/packages/types/src/index.ts b/packages/types/src/index.tsindex b0322f42c..878b3e0a1 100644--- a/packages/types/src/index.ts+++ b/packages/types/src/index.ts@@ -20,6 +20,7 @@ export * from "./symbols.js";export * from "./chat.js";export * from "./cards.js";export * from "./changes.js";+export * from "./history.js";export * from "./events.js";export * from "./views.js";export * from "./workspace.js";diff --git a/packages/ui/vitest.config.ts b/packages/ui/vitest.config.tsindex 3641cf671..5afa8d5c7 100644--- a/packages/ui/vitest.config.ts+++ b/packages/ui/vitest.config.ts@@ -33,6 +33,7 @@ export default defineConfig({"@repowise-dev/types/chat": path.resolve(__dirname, "../types/src/chat.ts"),"@repowise-dev/types/cards": path.resolve(__dirname, "../types/src/cards.ts"),"@repowise-dev/types/changes": path.resolve(__dirname, "../types/src/changes.ts"),+ "@repowise-dev/types/history": path.resolve(__dirname, "../types/src/history.ts"),"@repowise-dev/types/events": path.resolve(__dirname, "../types/src/events.ts"),"@repowise-dev/types/views": path.resolve(__dirname, "../types/src/views.ts"),"@repowise-dev/types/workspace": path.resolve(__dirname, "../types/src/workspace.ts"),diff --git a/tests/unit/analysis/test_history_rollups.py b/tests/unit/analysis/test_history_rollups.pynew file mode 100644index 000000000..d3f141aa9--- /dev/null+++ b/tests/unit/analysis/test_history_rollups.py@@ -0,0 +1,171 @@+"""Pure better/worse readings: one delta, a change's rollup, a period, rising files."""++from __future__ import annotations++from types import SimpleNamespace++import pytest++from repowise.core.analysis.history import (+ MIN_SHOWN_ANALYZER_VERSION,+ DeltaStamp,+ FileScoreShift,+ HealthDeltaSummary,+ delta_currency,+ delta_kind,+ matches_delta,+ parse_score_map,+ rising_files,+ rollup_deltas,+ summarize_delta,+ summarize_period,+)+++def _row(**over) -> SimpleNamespace:+ """A stored delta row; every count 0 unless given."""+ base = {+ "status": "available",+ "introduced_count": 0,+ "worsened_count": 0,+ "resolved_count": 0,+ "improved_count": 0,+ "moved_count": 0,+ }+ return SimpleNamespace(**{**base, **over})+++def _d(introduced=0, worsened=0, resolved=0, status="available", **over) -> HealthDeltaSummary:+ return HealthDeltaSummary(status, introduced, worsened, resolved, **over)+++ ("better", "worse", "kind"),+ [(0, 0, "neutral"), (2, 0, "improved"), (0, 1, "worsened"), (3, 1, "mixed")],+)+def test_delta_kind_reads_both_sides(better: int, worse: int, kind: str) -> None:+ assert delta_kind(better, worse) == kind+++ ("kind", "wanted", "passes"),+ [+ ("mixed", "improved", True),+ ("mixed", "worsened", True),+ ("mixed", "mixed", True),+ ("improved", "worsened", False),+ ("neutral", "neutral", True),+ ("mixed", "neutral", False),+ ("worsened", None, True),+ ],+)+def test_improved_and_worsened_filters_include_mixed(kind, wanted, passes) -> None:+ assert matches_delta(kind, wanted) is passes+++def test_a_stored_row_reads_as_counts_and_kind() -> None:+ row = _row(status="partial", introduced_count=1, worsened_count=None, resolved_count=4)+ got = summarize_delta(row)+ assert (got.introduced, got.worsened, got.resolved, got.improved, got.moved) == (1, 0, 4, 0, 0)+ assert got.kind == "mixed" and got.files == ()+++def test_a_current_row_counts_improved_and_moved_findings() -> None:+ got = summarize_delta(_row(improved_count=3, moved_count=2))+ assert (got.improved, got.moved, got.kind) == (3, 2, "improved")+++def test_a_stale_row_reads_improved_and_moved_as_unknown() -> None:+ got = summarize_delta(_row(improved_count=0, moved_count=0, introduced_count=1), stale=True)+ assert (got.improved, got.moved, got.kind) == (None, None, "worsened")+++def test_the_improved_count_makes_a_commit_better_once_stored() -> None:+ assert _d(improved=2).kind == "improved"+ assert _d(introduced=1, improved=0).kind == "worsened"+++def test_rollup_sums_scanned_commits_and_marks_gaps_partial() -> None:+ rollup = rollup_deltas([_d(introduced=2), None, _d(resolved=3)], ["a.py", "a.py", "b.py"])+ assert rollup is not None and rollup.moved is None+ assert (rollup.introduced, rollup.resolved) == (2, 3)+ assert (rollup.scanned_commits, rollup.unscanned_commits) == (2, 1)+ assert rollup.status == "partial" and rollup.kind == "mixed"+ assert rollup.files_worsened == 2+ assert rollup.files_improved is None and rollup.improved is None+++def test_rollup_is_available_only_when_every_commit_compared_cleanly() -> None:+ assert rollup_deltas([_d(), _d()]).status == "available"+ assert rollup_deltas([_d(), _d(status="partial")]).status == "partial"+++def test_a_change_with_no_scanned_commit_has_no_rollup() -> None:+ assert rollup_deltas([None, None]) is None+ assert rollup_deltas([]) is None+++def test_rollup_reads_per_file_scores_when_stored() -> None:+ first = _d(files=(FileScoreShift("a.py", 5.0, 6.0), FileScoreShift("b.py", 8.0, 7.5)))+ second = _d(files=(FileScoreShift("a.py", 6.0, 5.5), FileScoreShift("c.py", None, 9.0)))+ rollup = rollup_deltas([first, second], ["d.py"])+ # a.py nets +0.5, b.py falls; c.py has no before side and counts for neither.+ assert rollup.files_improved == 1+ assert rollup.files_worsened == 2+++def test_period_counts_improvements_and_nets_findings() -> None:+ summary = summarize_period(+ [_d(resolved=2), _d(introduced=1, resolved=1), _d(worsened=3), _d(), None]+ )+ assert (summary.improved, summary.mixed, summary.worsened, summary.neutral) == (1, 1, 1, 1)+ assert (summary.total, summary.unscanned) == (5, 1)+ assert summary.findings_resolved == 3 and summary.findings_introduced == 1+ assert summary.net_findings == 3 - 1 - 3+ assert summary.findings_improved is None+++def test_period_of_rollups_reads_the_same_way() -> None:+ summary = summarize_period([rollup_deltas([_d(resolved=1)]), None])+ assert (summary.improved, summary.unscanned, summary.net_findings) == (1, 1, 1)+++def test_rising_files_counts_only_touched_files_that_rose() -> None:+ before = {"a.py": 5.0, "b.py": 7.0, "c.py": 4.0, "d.py": 6.0}+ after = {"a.py": 8.0, "b.py": 6.0, "c.py": 4.05, "d.py": 9.0, "e.py": 9.0}+ gains = rising_files(before, after, {"a.py", "b.py", "c.py", "e.py"})+ assert [(g.path, g.gain) for g in gains] == [("a.py", 3.0)]+++def test_rising_files_orders_by_gain_then_path() -> None:+ gains = rising_files({"b": 1.0, "a": 1.0, "c": 2.0}, {"b": 3.0, "a": 3.0, "c": 9.0}, "abc")+ assert [g.path for g in gains] == ["c", "a", "b"]++[email protected]("raw", [None, "", "not json", "[1, 2]", '"x"'])+def test_an_unreadable_score_map_is_empty(raw) -> None:+ assert parse_score_map(raw) == {}+++def test_a_score_map_skips_values_that_are_not_numbers() -> None:+ assert parse_score_map('{"a.py": 7.5, "b.py": "x", "c.py": 3}') == {"a.py": 7.5, "c.py": 3.0}+++def test_a_delta_is_current_only_under_the_current_stamp() -> None:+ current = DeltaStamp(MIN_SHOWN_ANALYZER_VERSION + 1, "rules", 3)++ def row(version: int, rules: str = "rules", perf: int = 3) -> SimpleNamespace:+ return SimpleNamespace(+ analyzer_version=version, rules_fingerprint=rules, performance_model_version=perf+ )++ assert delta_currency(row(current.analyzer_version), current) == "current"+ assert delta_currency(row(current.analyzer_version, rules="edited"), current) == "stale"+ assert delta_currency(row(current.analyzer_version, perf=2), current) == "stale"+ assert delta_currency(row(MIN_SHOWN_ANALYZER_VERSION), current) == "stale"+ assert delta_currency(row(MIN_SHOWN_ANALYZER_VERSION - 1), current) == "absent"+++def test_a_stale_reading_keeps_its_direction() -> None:+ got = summarize_delta(_row(introduced_count=2), stale=True)+ assert got.stale and got.kind == "worsened"diff --git a/tests/unit/server/conftest.py b/tests/unit/server/conftest.pyindex d0e6bc8d0..54bad97dc 100644--- a/tests/unit/server/conftest.py+++ b/tests/unit/server/conftest.py@@ -60,6 +60,7 @@ def _create_test_app():security,symbols,webhooks,+ wins,)@asynccontextmanager@@ -96,6 +97,7 @@ def _create_test_app():app.include_router(webhooks.router)app.include_router(git.router)app.include_router(changes.router)+ app.include_router(wins.router)app.include_router(events.router)app.include_router(files.router)app.include_router(dead_code.router)diff --git a/tests/unit/server/test_git.py b/tests/unit/server/test_git.pyindex e2868e204..706d6fcbb 100644--- a/tests/unit/server/test_git.py+++ b/tests/unit/server/test_git.py@@ -8,6 +8,7 @@ from datetime import UTC, datetimeimport pytestfrom httpx import AsyncClient+from repowise.core.analysis.change_health.commit_scan import current_fingerprintfrom repowise.core.persistence import crudfrom repowise.core.persistence.database import get_sessionfrom tests.unit.server.conftest import create_test_repo@@ -434,11 +435,13 @@ async def test_commit_detail_reports_what_the_commit_did_to_health(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:+ stored = await crud.get_repository(session, repo["id"])await crud.upsert_commit_health_bulk(session,repo["id"],[{+ **current_fingerprint(stored.local_path),"sha": "bbbbbbbb22","status": "partial","introduced_count": 2,@@ -492,11 +495,13 @@ async def test_commit_detail_names_where_a_moved_finding_came_from(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:+ stored = await crud.get_repository(session, repo["id"])await crud.upsert_commit_health_bulk(session,repo["id"],[{+ **current_fingerprint(stored.local_path),"sha": "bbbbbbbb22","status": "available","worsened_count": 1,diff --git a/tests/unit/server/test_history_routes.py b/tests/unit/server/test_history_routes.pynew file mode 100644index 000000000..a75787c27--- /dev/null+++ b/tests/unit/server/test_history_routes.py@@ -0,0 +1,560 @@+"""Better/worse history: commit and change rows led by their health delta, the+history filters, period headlines and /wins."""++from __future__ import annotations++import json+from datetime import UTC, datetime+from pathlib import Path++import pytest+from httpx import AsyncClient+from sqlalchemy import select++from repowise.core import attribution+from repowise.core.analysis.change_health.commit_scan import current_fingerprint+from repowise.core.analysis.history import (+ DELTA_FILTERS,+ MIN_SHOWN_ANALYZER_VERSION,+ DeltaStamp,+ matches_delta,+ summarize_delta,+)+from repowise.core.persistence import crud+from repowise.core.persistence.database import get_session+from repowise.core.persistence.models import (+ GitCommitHealthDelta,+ HealthSnapshot,+ RefactoringPayoff,+ RefactoringSuggestion,+)+from tests.unit.server.conftest import create_test_repo++SHAS = {name: name * 40 for name in "abcde"}+++def _when(day: int) -> datetime:+ return datetime(2026, 10, day, 12, tzinfo=UTC)++[email protected](autouse=True)+def _private_user_config(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ user_file = tmp_path / "home" / ".repowise" / "config.yaml"+ monkeypatch.setattr(attribution, "user_config_path", lambda: user_file)+++def _commit(key: str, day: int, author: str) -> dict:+ return {+ "sha": SHAS[key],+ "author_name": author,+ "author_email": f"{author.lower()}@example.com",+ "committed_at": _when(day),+ "subject": f"commit {key}",+ "lines_added": 10,+ "lines_deleted": 2,+ "files_changed": 1,+ "dirs_changed": 1,+ "subsystems_changed": 1,+ "entropy": 0.5,+ "is_fix": False,+ "author_experience": 3,+ "change_risk_score": 3.0,+ "change_risk_level": "low",+ }+++def _delta(key: str, introduced=0, worsened=0, resolved=0, status="available") -> dict:+ return {+ "sha": SHAS[key],+ "status": status,+ "introduced_count": introduced,+ "worsened_count": worsened,+ "resolved_count": resolved,+ "files_analyzed": 1,+ "files_skipped": 0,+ "findings_stored": introduced + worsened,+ }+++def _finding(key: str, path: str, position: int = 0) -> dict:+ return {+ "sha": SHAS[key],+ "change_finding_id": f"{key}{position}",+ "position": position,+ "change_kind": "introduced",+ "dimension": "defect",+ "biomarker_type": "complex_method",+ "severity": "high",+ "file_path": path,+ "symbol": "run",+ "line_start": 10,+ "line_end": 40,+ "attribution_basis": "added_lines",+ "reason": "run has cyclomatic complexity 22",+ }+++def _change(change_id: str, day: int, keys: str, paths: list[str], author="Ann") -> dict:+ return {+ "change_id": change_id,+ "identity_kind": "pr",+ "identity_value": change_id.removeprefix("pr-"),+ "shape": "merge" if len(keys) > 1 else "squash",+ "forge": "github",+ "forge_ref": "#" + change_id.removeprefix("pr-"),+ "title": f"change {change_id}",+ "merged_at": _when(day),+ "head_sha": SHAS[keys[-1]],+ "author_name": author,+ "author_email": f"{author.lower()}@example.com",+ "commit_shas_json": json.dumps([SHAS[k] for k in keys]),+ "files_json": json.dumps([{"path": p, "added": 1, "deleted": 0} for p in paths]),+ "files_changed": len(paths),+ "lines_added": len(paths),+ "lines_deleted": 0,+ "category": "feature",+ }+++async def _current(session, repo_id: str) -> dict:+ """The stamp a delta computed now carries for this repository."""+ repo = await crud.get_repository(session, repo_id)+ return current_fingerprint(repo.local_path)+++async def _seed(app, repo_id: str) -> None:+ """a: resolves in src/core (Ann); b: introduces in src/core/hot.py, a hotspot+ (Bob); c: neutral in docs (Ann); d: never scanned (Ann)."""+ async with get_session(app.state.session_factory) as session:+ await crud.upsert_git_commits_bulk(+ session,+ repo_id,+ [_commit("a", 1, "Ann"), _commit("b", 2, "Bob"), _commit("c", 3, "Ann"),+ _commit("d", 4, "Ann")],+ )+ await crud.upsert_git_commit_files_bulk(+ session,+ repo_id,+ [+ {"sha": SHAS["a"], "file_path": "src/core/a.py", "lines_added": 1, "lines_deleted": 0},+ {"sha": SHAS["b"], "file_path": "src/core/hot.py", "lines_added": 1, "lines_deleted": 0},+ {"sha": SHAS["c"], "file_path": "docs/x.md", "lines_added": 1, "lines_deleted": 0},+ {"sha": SHAS["d"], "file_path": "src/corex/d.py", "lines_added": 1, "lines_deleted": 0},+ ],+ )+ await crud.upsert_git_metadata(+ session, repository_id=repo_id, file_path="src/core/hot.py", is_hotspot=True+ )+ stamp = await _current(session, repo_id)+ await crud.upsert_commit_health_bulk(+ session,+ repo_id,+ [+ {**_delta("a", resolved=3), **stamp},+ {**_delta("b", introduced=2, worsened=1), **stamp},+ {**_delta("c"), **stamp},+ ],+ [_finding("b", "src/core/hot.py"), _finding("b", "src/core/hot.py", 1)],+ )+ await crud.upsert_changes(+ session,+ repo_id,+ [+ _change("pr-1", 2, "ab", ["src/core/a.py", "src/core/hot.py"]),+ _change("pr-2", 3, "c", ["docs/x.md"]),+ _change("pr-3", 4, "d", ["src/corex/d.py"]),+ ],+ )+++def _shorts(page: dict) -> list[str]:+ return [item["sha"][0] for item in page["items"]]+++async def test_commit_rows_lead_with_their_health_delta(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ await _seed(app, repo["id"])+ page = (await client.get(f"/api/repos/{repo['id']}/commits")).json()+ rows = {item["sha"][0]: item for item in page["items"]}++ assert rows["a"]["health_delta"]["kind"] == "improved"+ assert rows["b"]["health_delta"] == {+ "status": "available",+ "kind": "worsened",+ "introduced": 2,+ "worsened": 1,+ "resolved": 0,+ "improved": 0,+ "moved": 0,+ "stale": False,+ "files": [],+ }+ assert rows["c"]["health_delta"]["kind"] == "neutral"+ # Never scanned is absent, not neutral.+ assert rows["d"]["health_delta"] is None+ assert (rows["b"]["touches_hotspot"], rows["a"]["touches_hotspot"]) == (1, 0)+++ ("params", "expected"),+ [+ ({"delta": "improved"}, ["a"]),+ ({"delta": "worsened"}, ["b"]),+ ({"delta": "neutral"}, ["c"]),+ ({"touches_hotspot": "true"}, ["b"]),+ ({"author": "[email protected]"}, ["d", "c", "a"]),+ ({"author": "Bob"}, ["b"]),+ ({"area": "src/core"}, ["b", "a"]),+ ({"area": "src/core/a.py"}, ["a"]),+ ({"since": "2026-10-02T00:00:00Z", "until": "2026-10-04T00:00:00Z"}, ["c", "b"]),+ # 13:00 at +05:30 is 07:30 UTC on the 2nd, before b's noon: b stays in.+ ({"since": "2026-10-02T13:00:00+05:30"}, ["d", "c", "b"]),+ ],+)+async def test_commit_history_filters_narrow_the_repository(+ client: AsyncClient, app, params: dict, expected: list[str]+) -> None:+ repo = await create_test_repo(client)+ await _seed(app, repo["id"])+ page = (await client.get(f"/api/repos/{repo['id']}/commits", params=params)).json()+ assert _shorts(page) == expected+ assert page["total"] == len(expected)+++async def test_an_unknown_delta_filter_is_rejected(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ resp = await client.get(f"/api/repos/{repo['id']}/commits", params={"delta": "better"})+ assert resp.status_code == 422+++async def test_the_sql_delta_filter_agrees_with_the_python_reading(+ client: AsyncClient, app+) -> None:+ """The commit filter runs in SQL and the change filter in Python; both must+ read a stored row the same way."""+ repo = await create_test_repo(client)+ await _seed(app, repo["id"])+ async with get_session(app.state.session_factory) as session:+ rows = (await session.execute(select(GitCommitHealthDelta))).scalars().all()+ stamp = DeltaStamp(**await _current(session, repo["id"]))+ for wanted in DELTA_FILTERS:+ where = crud.CommitFilter(delta=wanted, stamp=stamp)+ by_sql = set(await crud.list_commit_shas(session, repo["id"], where))+ by_python = {r.sha for r in rows if matches_delta(summarize_delta(r).kind, wanted)}+ assert by_sql == by_python, wanted+++async def test_commit_detail_carries_the_delta_and_the_findings_a_prompt_needs(+ client: AsyncClient, app+) -> None:+ repo = await create_test_repo(client)+ await _seed(app, repo["id"])+ detail = (await client.get(f"/api/repos/{repo['id']}/commits/{SHAS['b'][:8]}")).json()+ assert detail["health_delta"]["kind"] == "worsened"+ finding = detail["health"]["findings"][0]+ assert (finding["path"], finding["symbol"], finding["biomarker_type"]) == (+ "src/core/hot.py",+ "run",+ "complex_method",+ )+ assert (finding["line_start"], finding["line_end"]) == (10, 40)+++async def test_commit_health_summary_counts_improvements_first(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ await _seed(app, repo["id"])+ summary = (await client.get(f"/api/repos/{repo['id']}/commits/health-summary")).json()+ assert list(summary)[:4] == ["since", "until", "total", "improved"]+ assert (summary["improved"], summary["worsened"], summary["neutral"]) == (1, 1, 1)+ assert (summary["total"], summary["unscanned"]) == (4, 1)+ assert summary["net_findings"] == 3 - 3+++async def test_change_rows_roll_up_their_commits(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ await _seed(app, repo["id"])+ page = (await client.get(f"/api/repos/{repo['id']}/changes")).json()+ rows = {item["id"]: item for item in page["items"]}++ merged = rows["pr-1"]["health"]+ assert merged["kind"] == "mixed"+ assert (merged["introduced"], merged["worsened"], merged["resolved"]) == (2, 1, 3)+ assert (merged["scanned_commits"], merged["files_worsened"]) == (2, 1)+ assert merged["files_improved"] is None+ assert rows["pr-1"]["touches_hotspot"] == 1+ assert rows["pr-2"]["health"]["kind"] == "neutral"+ assert rows["pr-3"]["health"] is None+++ ("params", "expected"),+ [+ ({"delta": "improved"}, ["pr-1"]),+ ({"delta": "mixed"}, ["pr-1"]),+ ({"delta": "neutral"}, ["pr-2"]),+ ({"touches_hotspot": "true"}, ["pr-1"]),+ ({"area": "src/core"}, ["pr-1"]),+ ({"area": "src/corex/"}, ["pr-3"]),+ ({"since": "2026-10-03T00:00:00Z"}, ["pr-3", "pr-2"]),+ ({"author": "nobody"}, []),+ ],+)+async def test_change_history_filters(+ client: AsyncClient, app, params: dict, expected: list[str]+) -> None:+ repo = await create_test_repo(client)+ await _seed(app, repo["id"])+ page = (await client.get(f"/api/repos/{repo['id']}/changes", params=params)).json()+ assert [c["id"] for c in page["items"]] == expected+ assert page["total"] == len(expected)+++async def test_change_summary_is_the_period_headline(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ await _seed(app, repo["id"])+ url = f"/api/repos/{repo['id']}/changes/summary"+ summary = (await client.get(url)).json()+ assert (summary["mixed"], summary["neutral"], summary["unscanned"]) == (1, 1, 1)+ assert summary["findings_resolved"] == 3 and summary["net_findings"] == 0+ narrowed = (await client.get(url, params={"delta": "neutral"})).json()+ assert (narrowed["total"], narrowed["neutral"]) == (1, 1)+++async def test_change_detail_carries_its_worse_findings_with_their_commit(+ client: AsyncClient, app+) -> None:+ repo = await create_test_repo(client)+ await _seed(app, repo["id"])+ detail = (await client.get(f"/api/repos/{repo['id']}/changes/pr-1")).json()+ health = detail["health"]+ assert health["kind"] == "mixed" and len(health["findings"]) == 2+ assert {f["sha"] for f in health["findings"]} == {SHAS["b"]}+ assert detail["title"] == "change pr-1" and detail["head_sha"] == SHAS["b"]+++async def _seed_wins(app, repo_id: str) -> None:+ async with get_session(app.state.session_factory) as session:+ session.add_all(+ [+ HealthSnapshot(+ repository_id=repo_id,+ taken_at=datetime(2026, 9, 30, tzinfo=UTC),+ per_file_scores_json=json.dumps(+ {"src/core/a.py": 5.0, "src/core/hot.py": 6.0, "docs/x.md": 4.0}+ ),+ ),+ HealthSnapshot(+ repository_id=repo_id,+ taken_at=datetime(2026, 10, 5, tzinfo=UTC),+ per_file_scores_json=json.dumps(+ {"src/core/a.py": 8.0, "src/core/hot.py": 7.0, "docs/x.md": 9.0}+ ),+ ),+ ]+ )+ plan = RefactoringSuggestion(+ repository_id=repo_id,+ refactoring_type="extract_method",+ file_path="src/core/a.py",+ target_symbol="run",+ status="resolved",+ )+ session.add(plan)+ await session.flush()+ session.add(+ RefactoringPayoff(+ suggestion_id=plan.id,+ repository_id=repo_id,+ outcome="applied",+ resolved_at=_when(2),+ before_ccn=30,+ after_ccn=6,+ )+ )+++async def test_wins_name_what_got_better(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ await _seed(app, repo["id"])+ await _seed_wins(app, repo["id"])+ wins = (+ await client.get(f"/api/repos/{repo['id']}/wins", params={"since": "2026-10-01T00:00:00Z"})+ ).json()++ assert wins["findings_resolved"]["count"] == 3+ assert wins["findings_resolved"]["top_commits"][0]["sha"] == SHAS["a"]+ # Every file here was touched in the window; biggest gain first.+ assert [f["path"] for f in wins["files_improved"]["top"]] == [+ "docs/x.md",+ "src/core/a.py",+ "src/core/hot.py",+ ]+ assert wins["refactorings_landed"]["top"][0]["after_ccn"] == 6+ assert wins["unavailable"]+++async def test_wins_for_an_author_credit_only_their_work(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ await _seed(app, repo["id"])+ await _seed_wins(app, repo["id"])+ url = f"/api/repos/{repo['id']}/wins"+ params = {"since": "2026-10-01T00:00:00Z"}++ bob = (await client.get(url, params={**params, "author": "Bob"})).json()+ assert bob["findings_resolved"]["count"] == 0+ assert [f["path"] for f in bob["files_improved"]["top"]] == ["src/core/hot.py"]+ assert bob["refactorings_landed"]["count"] == 0++ ann = (await client.get(url, params={**params, "author": "[email protected]"})).json()+ assert ann["findings_resolved"]["count"] == 3+ assert ann["refactorings_landed"]["count"] == 1+++async def test_wins_without_snapshots_or_history_are_empty_not_errors(+ client: AsyncClient, app+) -> None:+ repo = await create_test_repo(client)+ wins = (await client.get(f"/api/repos/{repo['id']}/wins")).json()+ assert wins["findings_resolved"]["count"] == 0+ assert wins["files_improved"] == {+ "count": 0,+ "baseline_at": None,+ "current_at": None,+ "top": [],+ }+++async def test_wins_for_an_unknown_repo_is_404(client: AsyncClient) -> None:+ assert (await client.get("/api/repos/nope/wins")).status_code == 404+++async def _add_old_deltas(app, repo_id: str) -> None:+ """d gets a row from an older readable analyzer (stale); a v21-era row for+ a fifth commit e stays below the shown floor."""+ async with get_session(app.state.session_factory) as session:+ stamp = await _current(session, repo_id)+ await crud.upsert_git_commits_bulk(session, repo_id, [_commit("e", 5, "Ann")])+ older = {**stamp, "analyzer_version": MIN_SHOWN_ANALYZER_VERSION, "rules_fingerprint": "old"}+ ancient = {**stamp, "analyzer_version": MIN_SHOWN_ANALYZER_VERSION - 1}+ await crud.upsert_commit_health_bulk(+ session,+ repo_id,+ [{**_delta("d", introduced=5), **older}, {**_delta("e", resolved=9), **ancient}],+ [],+ )+++async def test_an_older_analyzers_row_shows_stale_and_an_ancient_one_not_at_all(+ client: AsyncClient, app+) -> None:+ repo = await create_test_repo(client)+ await _seed(app, repo["id"])+ await _add_old_deltas(app, repo["id"])+ base = f"/api/repos/{repo['id']}"++ rows = {i["sha"][0]: i for i in (await client.get(f"{base}/commits")).json()["items"]}+ assert rows["d"]["health_delta"]["stale"] is True+ assert rows["d"]["health_delta"]["kind"] == "worsened"+ assert rows["a"]["health_delta"]["stale"] is False+ assert rows["e"]["health_delta"] is None+ detail = (await client.get(f"{base}/commits/{SHAS['d'][:8]}")).json()+ assert detail["health"]["stale"] is True+ assert (await client.get(f"{base}/commits/{SHAS['e'][:8]}")).json()["health"] is None+++async def test_aggregates_count_current_analyzer_rows_only(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ await _seed(app, repo["id"])+ await _add_old_deltas(app, repo["id"])+ base = f"/api/repos/{repo['id']}"++ summary = (await client.get(f"{base}/commits/health-summary")).json()+ assert (summary["worsened"], summary["unscanned"]) == (1, 2)+ assert summary["findings_introduced"] == 2+ worse = (await client.get(f"{base}/commits", params={"delta": "worsened"})).json()+ assert _shorts(worse) == ["b"]+ changes = {c["id"]: c for c in (await client.get(f"{base}/changes")).json()["items"]}+ assert changes["pr-3"]["health"] is None+ wins = (await client.get(f"{base}/wins", params={"since": "2026-10-01T00:00:00Z"})).json()+ assert wins["findings_resolved"]["count"] == 3+++async def test_change_detail_findings_come_from_the_commits_its_counts_read(+ client: AsyncClient, app+) -> None:+ repo = await create_test_repo(client)+ await _seed(app, repo["id"])+ async with get_session(app.state.session_factory) as session:+ stamp = await _current(session, repo["id"])+ older = {**stamp, "analyzer_version": MIN_SHOWN_ANALYZER_VERSION, "rules_fingerprint": "old"}+ await crud.upsert_commit_health_bulk(+ session,+ repo["id"],+ [{**_delta("d", introduced=1), **older}],+ [_finding("d", "src/corex/d.py")],+ )+ await crud.upsert_changes(+ session, repo["id"], [_change("pr-4", 5, "bd", ["src/core/hot.py", "src/corex/d.py"])]+ )+ health = (await client.get(f"/api/repos/{repo['id']}/changes/pr-4")).json()["health"]+ assert (health["introduced"], health["scanned_commits"]) == (2, 1)+ assert {f["sha"] for f in health["findings"]} == {SHAS["b"]}+++async def test_improved_findings_make_a_commit_better_and_moved_ones_name_their_origin(+ client: AsyncClient, app+) -> None:+ """e only shrank a function (improved) and carried another to a new file,+ where it measures worse: worsened with its origin, never introduced."""+ repo = await create_test_repo(client)+ await _seed(app, repo["id"])+ async with get_session(app.state.session_factory) as session:+ stamp = await _current(session, repo["id"])+ await crud.upsert_git_commits_bulk(session, repo["id"], [_commit("e", 5, "Ann")])+ await crud.upsert_changes(session, repo["id"], [_change("pr-5", 5, "e", ["src/pkg/b.py"])])+ moved = {+ **_finding("e", "src/pkg/b.py"),+ "change_kind": "worsened",+ "attribution_basis": "moved",+ "moved_from_path": "src/pkg/a.py",+ "moved_from_symbol": "run",+ }+ await crud.upsert_commit_health_bulk(+ session,+ repo["id"],+ [{**_delta("e", worsened=1), "improved_count": 2, "moved_count": 3, **stamp}],+ [moved],+ )+ base = f"/api/repos/{repo['id']}"++ row = next(+ i for i in (await client.get(f"{base}/commits")).json()["items"] if i["sha"] == SHAS["e"]+ )+ assert row["health_delta"]["improved"] == 2 and row["health_delta"]["moved"] == 3+ assert row["health_delta"]["introduced"] == 0+ assert row["health_delta"]["kind"] == "mixed"+ better = (await client.get(f"{base}/commits", params={"delta": "improved"})).json()+ assert "e" in _shorts(better)++ detail = (await client.get(f"{base}/changes/pr-5")).json()["health"]+ assert (detail["improved"], detail["moved"], detail["introduced"]) == (2, 3, 0)+ (finding,) = detail["findings"]+ assert finding["moved_from"] == {"path": "src/pkg/a.py", "symbol": "run"}