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: group the Commits page by change, with each change's evidence checklist (#3803)
Raghav Chamadiyaa7b30925a4fd
diff --git a/docs/layers/CHANGES.md b/docs/layers/CHANGES.mdindex a43667d45..5228060bb 100644--- a/docs/layers/CHANGES.md+++ b/docs/layers/CHANGES.md@@ -79,8 +79,8 @@ 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`), `GET /api/repos/{id}/changes/{change_id}` |-| Web | Changes page with category filters, and a detail page per change |+| 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}` |+| 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 |`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/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.mdindex 7f9cf0d1b..2a2e31fda 100644--- a/docs/reference/CLI_REFERENCE.md+++ b/docs/reference/CLI_REFERENCE.md@@ -1599,10 +1599,10 @@ repowise components ownership [--path PATH] [--format table|json]Merged changes read back from git at each index and update: one per first-parent commit, identified by the PR or MR number its message names, then a Gerrit `Change-Id`, then the merge or commit sha. A merge lands the commits its branch brought in, and rebase merges read as one change per commit. `show` takes an id (`pr-123`) or any commit sha the change landed, and prints the versioned JSON record or, with `--format in-toto`, an in-toto Statement v1 whose subjects are the commits.-`show` also prints the change's evidence checklist: components touched, declared owners, suggested reviewers, reaching tests, contracts, consumers in other repos, decisions crossed, health delta, AI provenance and the diff size rank, each with a status (`ok`, `attention`, `unknown`) and the basis it rests on. The checklist is built on first read and kept on the change; `--refresh` rebuilds it. `export` writes every change merged in a `--since`/`--until` window (UTC, `--until` exclusive) with its checklist, streamed as JSON Lines (one record per line) or CSV rows (one row per change and item); building a missing checklist costs a few seconds per change.+`show` also prints the change's evidence checklist: components touched, declared owners, suggested reviewers, reaching tests, contracts, consumers in other repos, decisions crossed, health delta, AI provenance and the diff size rank, each with a status (`ok`, `attention`, `unknown`) and the basis it rests on. The checklist is built on first read and kept on the change; `--refresh` rebuilds it. `export` writes every change merged in a `--since`/`--until` window (UTC, `--until` exclusive) with its checklist, streamed as JSON Lines (one record per line) or CSV rows (one row per change and item); building a missing checklist costs a few seconds per change. `list --needs-attention` keeps only changes whose kept checklist flags an item for attention; it reads checklists already built and builds none, so a change nobody has opened or exported is not listed.```bash-repowise changes list [--path PATH] [--category C] [--shape merge|squash|commit] [--grep TEXT] [--limit N] [--offset N] [--format table|json]+repowise changes list [--path PATH] [--category C] [--shape merge|squash|commit] [--grep TEXT] [--needs-attention] [--limit N] [--offset N] [--format table|json]repowise changes show REF [--path PATH] [--format table|json|in-toto] [--no-evidence] [--refresh]repowise changes export [--path PATH] [--since DATE] [--until DATE] [--format json|csv] [--refresh]```diff --git a/docs/start/DASHBOARD.md b/docs/start/DASHBOARD.mdindex aa90ba09b..1715dc63c 100644--- a/docs/start/DASHBOARD.md+++ b/docs/start/DASHBOARD.md@@ -267,13 +267,17 @@ risk model is documented in## Changes-`/repos/<id>/changes`, `/repos/<id>/changes/<changeId>`+`/repos/<id>/commits?view=changes`, `/repos/<id>/changes/<changeId>`-**Answers:** what landed, from which commits, touching which files?+**Answers:** what landed, from which commits, touching which files, and what+its evidence checklist flags?-Merged pull requests, merge requests and commits, newest first, filtered by-category. Each detail page lists the commits, files, provenance and metadata of-one Change Record. See [CHANGES.md](../layers/CHANGES.md).+The Commits page's "By change" view lists merged pull requests, merge requests+and commits, newest first, filtered by category or by "Needs attention". Each+row counts the attention and unknown items of the change's evidence checklist+once it is built; the detail page builds it on first view and lists the+commits, files, provenance and metadata of one Change Record. See+[CHANGES.md](../layers/CHANGES.md).## Contributorsdiff --git a/packages/api-client/src/changes.ts b/packages/api-client/src/changes.tsindex d40d903ae..1d30a3304 100644--- a/packages/api-client/src/changes.ts+++ b/packages/api-client/src/changes.ts@@ -7,13 +7,21 @@import { apiGet } from "./client";import type {ChangeEvidence,+ ChangeEvidenceSummary,+ ChangeListItem,ChangeListResponse,ChangeRecord,- ChangeSummary,EvidenceItem,} from "@repowise-dev/types/changes";-export type { ChangeEvidence, ChangeListResponse, ChangeRecord, ChangeSummary, EvidenceItem };+export type {+ ChangeEvidence,+ ChangeEvidenceSummary,+ ChangeListItem,+ ChangeListResponse,+ ChangeRecord,+ EvidenceItem,+};/** A page of changes, newest merged first, without file or commit lists. */export async function listChanges(@@ -24,6 +32,10 @@ export async function listChanges(shape?: "merge" | "squash" | "commit";/** Substring of the title, id or a file path. */q?: string;+ /** Add each row's kept checklist status counts; never builds a checklist. */+ evidence?: boolean;+ /** Only changes whose kept checklist has an attention item. */+ needs_attention?: boolean;limit?: number;offset?: number;},diff --git a/packages/cli/src/repowise/cli/commands/changes_cmd.py b/packages/cli/src/repowise/cli/commands/changes_cmd.pyindex 598899d77..69d5580d6 100644--- a/packages/cli/src/repowise/cli/commands/changes_cmd.py+++ b/packages/cli/src/repowise/cli/commands/changes_cmd.py@@ -13,7 +13,7 @@ from __future__ import annotationsfrom collections.abc import Callablefrom datetime import datetimefrom pathlib import Path-from typing import Any+from typing import TYPE_CHECKINGimport click@@ -26,6 +26,9 @@ from repowise.cli.helpers import ()from repowise.cli.output import emit_json, format_option+if TYPE_CHECKING:+ from repowise.core.persistence.crud import ChangeFilter+def _repo_root(path: str | None) -> Path:target = resolve_command_target(path=path, no_workspace_flag=True)@@ -38,8 +41,11 @@ def _no_index() -> None:raise SystemExit(1)-async def _list(root: Path, **filters: Any) -> tuple[list[dict], int] | None:+async def _list(+ root: Path, where: ChangeFilter, *, limit: int, offset: int, needs_attention: bool = False+) -> tuple[list[dict], int] | None:from repowise.core.attribution import attribution_enabled+ from repowise.core.changes.collect import list_needing_attentionfrom repowise.core.changes.record import change_recordfrom repowise.core.persistence.crud import list_changes@@ -47,7 +53,8 @@ async def _list(root: Path, **filters: Any) -> tuple[list[dict], int] | None:if opened is None:return Nonesession, repo_id = opened- rows, total = await list_changes(session, repo_id, **filters)+ read = list_needing_attention if needs_attention else list_changes+ rows, total = await read(session, repo_id, where, limit=limit, offset=offset)on = attribution_enabled(root)return [change_record(r, attribution=on) for r in rows], total@@ -87,7 +94,7 @@ async def _export(from repowise.core.attribution import attribution_enabledfrom repowise.core.changes.collect import change_evidencefrom repowise.core.changes.record import change_record- from repowise.core.persistence.crud import list_changes+ from repowise.core.persistence.crud import ChangeFilter, list_changesasync with repo_index_session(root) as opened:if opened is None:@@ -97,7 +104,11 @@ async def _export(done = 0while True:rows, total = await list_changes(- session, repo_id, since=since, until=until, limit=_EXPORT_PAGE, offset=done+ session,+ repo_id,+ ChangeFilter(since=since, until=until),+ limit=_EXPORT_PAGE,+ offset=done,)for row in rows:done += 1@@ -198,6 +209,11 @@ def changes_group() -> None:"--shape", type=click.Choice(["merge", "squash", "commit"]), default=None, help="Only this shape.")@click.option("--grep", "q", default=None, help="Substring of the title, id or a file path.")+ "--needs-attention",+ is_flag=True,+ help="Only changes whose kept checklist flags attention (never builds one).",+)@click.option("--limit", default=30, show_default=True, type=click.IntRange(1, 1000))@click.option("--offset", default=0, type=click.IntRange(0))@format_option()@@ -206,14 +222,18 @@ def changes_list(category: str | None,shape: str | None,q: str | None,+ needs_attention: bool,limit: int,offset: int,fmt: str,) -> None:"""List indexed changes, newest merged first."""+ from repowise.core.persistence.crud import ChangeFilter+root = _repo_root(repo)+ where = ChangeFilter(category=category, shape=shape, q=q)got = run_async(- _list(root, category=category, shape=shape, q=q, limit=limit, offset=offset)+ _list(root, where, limit=limit, offset=offset, needs_attention=needs_attention))if got is None:_no_index()diff --git a/packages/core/src/repowise/core/changes/collect.py b/packages/core/src/repowise/core/changes/collect.pyindex c28e316a8..49d6f57ec 100644--- a/packages/core/src/repowise/core/changes/collect.py+++ b/packages/core/src/repowise/core/changes/collect.py@@ -19,7 +19,7 @@ import jsonimport refrom collections.abc import Sequencefrom pathlib import Path-from typing import Any+from typing import TYPE_CHECKING, Anyimport structlog@@ -36,6 +36,9 @@ from repowise.core.ownership.codeowners import (read_codeowners,)+if TYPE_CHECKING:+ from repowise.core.persistence.crud import ChangeFilter+logger = structlog.get_logger(__name__)#: Reviewers listed per change; more is no better than none.@@ -204,12 +207,13 @@ async def save_evidence("""Keep *evidence* on its change row."""from sqlalchemy import update+ from repowise.core.persistence.crud.changes import dump_evidencefrom repowise.core.persistence.models import Changeawait session.execute(update(Change).where(Change.repository_id == repo_id, Change.change_id == change_id)- .values(evidence_json=json.dumps(evidence.to_dict()))+ .values(evidence_json=dump_evidence(evidence.to_dict())))@@ -229,7 +233,9 @@ async def change_evidence(evidence = await build_stored_evidence(session, repo_id, repo_root, row, risk=risk, health=health)- row.evidence_json = json.dumps(evidence.to_dict())+ from repowise.core.persistence.crud.changes import dump_evidence++ row.evidence_json = dump_evidence(evidence.to_dict())await session.flush()return evidence@@ -262,6 +268,45 @@ def cached_evidence(row: Any) -> ChangeEvidence | None:return evidence if evidence.schema_version == EVIDENCE_SCHEMA_VERSION else None+def evidence_summary(row: Any) -> dict[str, Any] | None:+ """Status counts of the kept checklist, or ``None`` when none is kept."""+ evidence = cached_evidence(row)+ if evidence is None:+ return None+ counts = {"generated_at": evidence.generated_at, "ok": 0, "attention": 0, "unknown": 0}+ for item in evidence.items:+ # A status this reader does not know is not a pass.+ counts[item.status if item.status in ("ok", "attention") else "unknown"] += 1+ return counts+++async def list_needing_attention(+ session: Any,+ repo_id: str,+ where: ChangeFilter | None = None,+ *,+ limit: int | None,+ offset: int = 0,+) -> tuple[list[Any], int]:+ """Changes matching *where* whose kept checklist flags attention, newest+ merged first, and their total. Reads kept checklists only, never builds one.+ """+ from repowise.core.persistence.crud import (+ ChangeFilter,+ list_attention_candidates,+ list_changes,+ )++ # Checklists are built on first view, so the prefiltered set stays small;+ # confirm on the parsed evidence, then page here. Ceiling: if checklists+ # are ever built in bulk, move this filter into SQL.+ candidates = await list_attention_candidates(session, repo_id, where)+ ids = [r.change_id for r in candidates if (evidence_summary(r) or {}).get("attention")]+ page = ids[offset:] if limit is None else ids[offset : offset + limit]+ rows, _ = await list_changes(session, repo_id, ChangeFilter(change_ids=page), limit=None)+ return rows, len(ids)++# -- inputs -------------------------------------------------------------------diff --git a/packages/core/src/repowise/core/persistence/crud/changes.py b/packages/core/src/repowise/core/persistence/crud/changes.pyindex 5a190df9e..1518c5241 100644--- a/packages/core/src/repowise/core/persistence/crud/changes.py+++ b/packages/core/src/repowise/core/persistence/crud/changes.py@@ -2,8 +2,11 @@from __future__ import annotations+import jsonfrom collections.abc import Sequence+from dataclasses import dataclass, replacefrom datetime import datetime+from typing import Anyfrom sqlalchemy import delete, func, or_, selectfrom sqlalchemy.ext.asyncio import AsyncSession@@ -14,6 +17,16 @@ from ._shared import _BATCH_SIZE, _batch_upsert_keyed, _row_inserter, _row_updat_update_change = _row_updater("change_id")+#: The one JSON layout ``changes.evidence_json`` is written in. The attention+#: filter below matches text in this layout, so both read it from here.+_EVIDENCE_SEPARATORS = (", ", ": ")+_ATTENTION_LIKE = f"%{json.dumps({'status': 'attention'}, separators=_EVIDENCE_SEPARATORS)[1:-1]}%"+++def dump_evidence(evidence: dict[str, Any]) -> str:+ """A change's checklist as stored in ``evidence_json``."""+ return json.dumps(evidence, separators=_EVIDENCE_SEPARATORS)+async def upsert_changes(session: AsyncSession, repository_id: str, rows: list[dict]) -> None:"""Bulk upsert change rows keyed on ``(repository_id, change_id)``."""@@ -55,25 +68,42 @@ async def get_newest_change_head(session: AsyncSession, repository_id: str) -> s).scalar_one_or_none()-def _filters(- repository_id: str,- category: str | None,- shape: str | None,- q: str | None,- since: datetime | None = None,- until: datetime | None = None,-):+@dataclass(frozen=True)+class ChangeFilter:+ """Which stored changes a list reads; every field narrows, ``None`` does not.++ *since* is inclusive and *until* exclusive, on ``merged_at``. *attention*+ keeps changes whose kept checklist may flag attention (a prefilter; the+ caller confirms on the parsed evidence). *change_ids* keeps only those.+ """++ category: str | None = None+ shape: str | None = None+ q: str | None = None+ since: datetime | None = None+ until: datetime | None = None+ attention: bool = False+ change_ids: Sequence[str] | None = None+++def _filters(repository_id: str, where: ChangeFilter) -> list[Any]:clauses = [Change.repository_id == repository_id]- if since is not None:- clauses.append(Change.merged_at >= since)- if until is not None:- clauses.append(Change.merged_at < until)- if category:- clauses.append(Change.category == category)- if shape:- clauses.append(Change.shape == shape)- if q:- like = f"%{escape_like(q)}%"+ if where.attention:+ # A kept checklist with an attention item, in dump_evidence's layout; a+ # prefilter only, since the text could sit inside an item's details.+ clauses.append(Change.evidence_json.like(_ATTENTION_LIKE))+ if where.change_ids is not None:+ clauses.append(Change.change_id.in_(where.change_ids))+ if where.since is not None:+ clauses.append(Change.merged_at >= where.since)+ if where.until is not None:+ clauses.append(Change.merged_at < where.until)+ if where.category:+ clauses.append(Change.category == where.category)+ if where.shape:+ clauses.append(Change.shape == where.shape)+ if where.q:+ like = f"%{escape_like(where.q)}%"clauses.append(or_(Change.title.ilike(like, escape=LIKE_ESCAPE),@@ -87,21 +117,14 @@ def _filters(async def list_changes(session: AsyncSession,repository_id: str,+ where: ChangeFilter | None = None,*,- category: str | None = None,- shape: str | None = None,- q: str | None = None,- since: datetime | None = None,- until: datetime | None = None,limit: int | None = 50,offset: int = 0,) -> tuple[list[Change], int]:- """A page of changes, newest merged first, and the total that matched.-- *since* is inclusive and *until* exclusive, on ``merged_at``; ``limit=None``- returns every match.- """- clauses = _filters(repository_id, category, shape, q, since, until)+ """A page of changes matching *where*, newest merged first, and the total+ that matched; ``limit=None`` returns every match."""+ clauses = _filters(repository_id, where or ChangeFilter())total = (await session.execute(select(func.count()).select_from(Change).where(*clauses))).scalar_one()rows = await session.execute(select(Change)@@ -113,6 +136,34 @@ async def list_changes(return list(rows.scalars().all()), int(total)+async def list_attention_candidates(+ session: AsyncSession, repository_id: str, where: ChangeFilter | None = None+) -> list[Any]:+ """``(change_id, evidence_json)`` rows of every change matching *where*+ whose kept checklist may flag attention, newest merged first. A+ prefilter: the caller confirms on the parsed evidence."""+ rows = await session.execute(+ select(Change.change_id, Change.evidence_json)+ .where(*_filters(repository_id, replace(where or ChangeFilter(), attention=True)))+ .order_by(Change.merged_at.desc().nulls_last(), Change.change_id)+ )+ return list(rows.all())+++async def count_checklists_built(+ session: AsyncSession, repository_id: str, where: ChangeFilter | None = None+) -> tuple[int, int]:+ """``(built, changes)``: how many changes matching *where* keep a checklist."""+ built, changes = (+ await session.execute(+ select(func.count(Change.evidence_json), func.count()).where(+ *_filters(repository_id, where or ChangeFilter())+ )+ )+ ).one()+ return int(built), int(changes)++async def get_change(session: AsyncSession, repository_id: str, ref: str) -> Change | None:"""A change by its id, or the newest change that landed a commit (a sha of 7+ hex)."""found = await find_changes(session, repository_id, ref, limit=1)diff --git a/packages/server/src/repowise/server/routers/changes.py b/packages/server/src/repowise/server/routers/changes.pyindex 6acb07c08..1fe09e0df 100644--- a/packages/server/src/repowise/server/routers/changes.py+++ b/packages/server/src/repowise/server/routers/changes.py@@ -9,15 +9,23 @@ from fastapi import APIRouter, Depends, HTTPException, Query, Requestfrom sqlalchemy.ext.asyncio import AsyncSessionfrom repowise.core.attribution import attribution_enabled-from repowise.core.changes.collect import build_stored_evidence, cached_evidence, save_evidence+from repowise.core.changes.collect import (+ build_stored_evidence,+ cached_evidence,+ evidence_summary,+ list_needing_attention,+ save_evidence,+)from repowise.core.changes.evidence import ChangeEvidencefrom repowise.core.changes.record import change_recordfrom repowise.core.persistence import crudfrom repowise.core.persistence.database import get_sessionfrom repowise.server.deps import get_db_session, resolve_request_session_factory, verify_api_keyfrom repowise.server.schemas.changes import (+ ChangeEvidenceSummary,ChangeListResponse,ChangeRecord,+ ChecklistsBuilt,summary_from_record,)@@ -50,21 +58,43 @@ async def list_changes(category: str | None = Query(None, description="One commit category, e.g. fix"),shape: str | None = Query(None, description="merge | squash | commit"),q: str | None = Query(None, description="Substring of the title, id or a file path"),+ evidence: bool = Query(+ False, description="Add each row's kept checklist status counts; never builds one"+ ),+ needs_attention: bool = Query(+ False, description="Only changes whose kept checklist has an attention item"+ ),limit: int = Query(50, ge=1, le=_MAX_PAGE),offset: int = Query(0, ge=0),session: AsyncSession = Depends(get_db_session),) -> ChangeListResponse:"""A page of changes, newest merged first."""attribution = await _attribution(session, repo_id)- rows, total = await crud.list_changes(- session, repo_id, category=category, shape=shape, q=q, limit=limit, offset=offset- )+ where = crud.ChangeFilter(category=category, shape=shape, q=q)+ 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)+ items = []+ for r in rows:+ item = summary_from_record(change_record(r, attribution=attribution))+ if evidence:+ summary = evidence_summary(r)+ item.evidence_summary = summary and ChangeEvidenceSummary(**summary)+ items.append(item)+ checklists = None+ if evidence:+ built, changes = await crud.count_checklists_built(session, repo_id, where)+ checklists = ChecklistsBuilt(built=built, changes=changes)return ChangeListResponse(- items=[summary_from_record(change_record(r, attribution=attribution)) for r in rows],+ items=items,total=total,limit=limit,offset=offset,attribution=attribution,+ checklists_built=checklists,)diff --git a/packages/server/src/repowise/server/schemas/changes.py b/packages/server/src/repowise/server/schemas/changes.pyindex 14e987f9d..f10d3965b 100644--- a/packages/server/src/repowise/server/schemas/changes.py+++ b/packages/server/src/repowise/server/schemas/changes.py@@ -9,7 +9,7 @@ from __future__ import annotationsfrom typing import Any, Literal-from pydantic import BaseModel+from pydantic import BaseModel, model_serializerclass ChangeIdentity(BaseModel):@@ -103,17 +103,55 @@ class ChangeRecord(ChangeSummary):evidence_building: bool = False+class ChangeEvidenceSummary(BaseModel):+ """Status counts of a change's kept checklist; never builds one."""++ generated_at: str+ ok: int+ attention: int+ unknown: int+++class ChangeListItem(ChangeSummary):+ # Sent only when the list asked for it (``?evidence=true``) and the change+ # has a kept checklist; absent otherwise, so the default row is unchanged.+ evidence_summary: ChangeEvidenceSummary | None = None++ @model_serializer(mode="wrap")+ def _omit_absent_summary(self, handler): # no return annotation: keeps the schema+ data = handler(self)+ if self.evidence_summary is None:+ data.pop("evidence_summary", None)+ return data+++class ChecklistsBuilt(BaseModel):+ """How many of the changes a list's filters match keep an evidence checklist."""++ built: int+ changes: int++class ChangeListResponse(BaseModel):- items: list[ChangeSummary]+ items: list[ChangeListItem]total: intlimit: intoffset: int#: False when ``attribution.enabled`` is off for the repository.attribution: bool+ # Sent only with ``?evidence=true``; absent otherwise.+ checklists_built: ChecklistsBuilt | None = None++ @model_serializer(mode="wrap")+ def _omit_absent_count(self, handler): # no return annotation: keeps the schema+ data = handler(self)+ if self.checklists_built is None:+ data.pop("checklists_built", None)+ return data-def summary_from_record(record: dict) -> ChangeSummary:- return ChangeSummary(+def summary_from_record(record: dict) -> ChangeListItem:+ return ChangeListItem(**{k: v for k, v in record.items() if k in ChangeSummary.model_fields},commit_count=len(record["commits"]),)diff --git a/packages/types/src/changes.ts b/packages/types/src/changes.tsindex b13bb0a3d..b78e55c2e 100644--- a/packages/types/src/changes.ts+++ b/packages/types/src/changes.ts@@ -7,6 +7,10 @@* shape cannot drift. `provenance` is null while AI attribution is off for* the repository; forge metadata fields are null when unknown, never empty.*+ * `ChangeListItem` is a list row: the record without its file and commit+ * lists, plus `evidence_summary` (kept checklist status counts) when the list+ * asked for it.+ ** `ChangeEvidence` is the record's evidence checklist (twin of* `repowise.core.changes.evidence`): one `EvidenceItem` per kind in* `EVIDENCE_KINDS`, each with a `status` and the `basis` it rests on. The@@ -15,13 +19,14 @@export type {ChangeAuthor,ChangeEvidence,+ ChangeEvidenceSummary,ChangeFile,ChangeForgeMetadata,ChangeIdentity,+ ChangeListItem,ChangeListResponse,ChangeProvenance,ChangeRecord,- ChangeSummary,EvidenceItem,} from "./generated/http.js";diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.tsindex 49dba64be..a7345a4ff 100644--- a/packages/types/src/generated/http.ts+++ b/packages/types/src/generated/http.ts@@ -390,6 +390,14 @@ export interface ChangeEvidence {items: EvidenceItem[];}+/** Status counts of a change's kept checklist; never builds one. */+export interface ChangeEvidenceSummary {+ generated_at: string;+ ok: number;+ attention: number;+ unknown: number;+}+/** The Kamei change-shape features the risk model scores. */export interface ChangeFeaturesResponse {la: number;@@ -422,12 +430,33 @@ export interface ChangeIdentity {value: string;}+export interface ChangeListItem {+ schema_version: number;+ id: string;+ identity: ChangeIdentity;+ shape: string;+ forge: string;+ forge_ref?: string | null;+ title: string;+ merged_at?: string | null;+ head_sha: string;+ author: ChangeAuthor;+ commit_count: number;+ files_changed: number;+ lines_added: number;+ lines_deleted: number;+ category: string;+ provenance?: ChangeProvenance | null;+ evidence_summary?: ChangeEvidenceSummary | null;+}+export interface ChangeListResponse {- items: ChangeSummary[];+ items: ChangeListItem[];total: number;limit: number;offset: number;attribution: boolean;+ checklists_built?: ChecklistsBuilt | null;}/** Three-state AI provenance over the change's commits, with its coverage. */@@ -463,25 +492,6 @@ export interface ChangeRecord {evidence_building?: boolean;}-export interface ChangeSummary {- schema_version: number;- id: string;- identity: ChangeIdentity;- shape: string;- forge: string;- forge_ref?: string | null;- title: string;- merged_at?: string | null;- head_sha: string;- author: ChangeAuthor;- commit_count: number;- files_changed: number;- lines_added: number;- lines_deleted: number;- category: string;- provenance?: ChangeProvenance | null;-}-export interface ChangelogEntryModel {version: string;label?: string | null;@@ -663,6 +673,12 @@ export interface ChatTurnUsage {model_calls?: number;}+/** How many of the changes a list's filters match keep an evidence checklist. */+export interface ChecklistsBuilt {+ built: number;+ changes: number;+}+/*** One file on the churn-vs-complexity scatter.*diff --git a/packages/web/messages/en.json b/packages/web/messages/en.jsonindex 37f63e0c3..755c2a533 100644--- a/packages/web/messages/en.json+++ b/packages/web/messages/en.json@@ -107,7 +107,6 @@"refactoring": "Refactoring","files": "Files","commits": "Commits",- "changes": "Changes","contributors": "Contributors","decisions": "Decisions","stats": "Stats",@@ -244,10 +243,12 @@"scoreBehaviourDescription": "Two views of the same model: where the cuts fall, and what commit shape lands you above them.","changeRisk": "Change risk","evolutionTitle": "How the work changed shape",- "evolutionDescription": "Commit categories over time, read off the subject line. Fixes carry the accent because that is the series this chart exists to show."+ "evolutionDescription": "Commit categories over time, read off the subject line. Fixes carry the accent because that is the series this chart exists to show.",+ "viewLabel": "Group the history",+ "viewByChange": "By change",+ "viewByCommit": "By commit"},"changes": {- "title": "Changes","description": "Every merged change on the main line, read back from git: pull and merge requests, Gerrit changes and lone commits, with the files each one landed.","emptyTitle": "No changes indexed yet","emptyHint": "Changes are read from git history on the next index or update.",@@ -281,7 +282,34 @@"evidenceGenerated": "Generated {date}","statusOk": "ok","statusAttention": "attention",- "statusUnknown": "unknown"+ "statusUnknown": "unknown",+ "byChangeTitle": "Merged changes",+ "byChangeDescription": "One row per merged change. Open a change for its evidence checklist: owners, reaching tests, contracts, decisions crossed and health delta. The Evidence column counts what that checklist flagged.",+ "commits": "Commits",+ "evidence": "Evidence",+ "evidenceNotBuilt": "Not built",+ "evidenceNotBuiltHint": "The checklist is built the first time the change is opened.",+ "evidenceClear": "Nothing flagged",+ "evidenceAttention": "{count, plural, one {# needs attention} other {# need attention}}",+ "evidenceUnknown": "{count} unknown",+ "needsAttention": "Needs attention",+ "attentionScope": "Only changes with a built checklist are listed.",+ "attentionEmpty": "No built checklist flags anything for attention.",+ "filterEmpty": "No change matches this filter.",+ "checklistsBuilt": "Checklists built for {built} of {changes} changes.",+ "checklistsBuildHint": "A change's checklist is built when its page is opened, or by `repowise changes show REF` or `repowise changes export`.",+ "loadErrorTitle": "Could not load changes",+ "loadErrorBody": "The change list could not be read from the server. Reload the page to try again.",+ "categories": {+ "feature": "feature",+ "fix": "fix",+ "refactor": "refactor",+ "docs": "docs",+ "test": "test",+ "deps": "deps",+ "chore": "chore",+ "other": "other"+ }},"architecture": {"tabs": {diff --git a/packages/web/messages/zh-CN.json b/packages/web/messages/zh-CN.jsonindex fccb3e73b..6ae7e094d 100644--- a/packages/web/messages/zh-CN.json+++ b/packages/web/messages/zh-CN.json@@ -107,7 +107,6 @@"refactoring": "重构","files": "文件","commits": "提交",- "changes": "变更","contributors": "贡献者","decisions": "决策","stats": "统计",@@ -244,10 +243,12 @@"scoreBehaviourDescription": "同一个模型的两种视角:分档线落在哪里,以及什么样的提交形态能让你高于这些线。","changeRisk": "变更风险","evolutionTitle": "工作形态如何变化",- "evolutionDescription": "按提交标题归类出的各类提交随时间的变化。修复类高亮显示,因为这张图存在的意义就是展示这一条序列。"+ "evolutionDescription": "按提交标题归类出的各类提交随时间的变化。修复类高亮显示,因为这张图存在的意义就是展示这一条序列。",+ "viewLabel": "历史分组方式",+ "viewByChange": "按变更",+ "viewByCommit": "按提交"},"changes": {- "title": "变更","description": "主线上每个已合并的变更,均从 git 历史读取:拉取请求、合并请求、Gerrit 变更和单独提交,以及每个变更带入的文件。","emptyTitle": "尚未索引任何变更","emptyHint": "变更会在下一次索引或更新时从 git 历史读取。",@@ -281,7 +282,34 @@"evidenceGenerated": "生成于 {date}","statusOk": "正常","statusAttention": "需关注",- "statusUnknown": "未知"+ "statusUnknown": "未知",+ "byChangeTitle": "已合并的变更",+ "byChangeDescription": "每个已合并的变更一行。打开一个变更即可查看其证据清单:负责人、可达测试、契约、涉及的决策和健康度变化。“证据”列统计该清单标记的项目。",+ "commits": "提交",+ "evidence": "证据",+ "evidenceNotBuilt": "尚未生成",+ "evidenceNotBuiltHint": "首次打开该变更时会生成证据清单。",+ "evidenceClear": "无标记项",+ "evidenceAttention": "{count} 项需关注",+ "evidenceUnknown": "{count} 项未知",+ "needsAttention": "需关注",+ "attentionScope": "仅列出已生成证据清单的变更。",+ "attentionEmpty": "已生成的证据清单中没有需关注的项目。",+ "filterEmpty": "没有符合此筛选条件的变更。",+ "checklistsBuilt": "{changes} 个变更中已有 {built} 个生成证据清单。",+ "checklistsBuildHint": "打开变更页面,或运行 `repowise changes show REF` 或 `repowise changes export` 时,会生成该变更的证据清单。",+ "loadErrorTitle": "无法加载变更",+ "loadErrorBody": "无法从服务器读取变更列表。请重新加载页面重试。",+ "categories": {+ "feature": "功能",+ "fix": "修复",+ "refactor": "重构",+ "docs": "文档",+ "test": "测试",+ "deps": "依赖",+ "chore": "杂务",+ "other": "其他"+ }},"architecture": {"tabs": {diff --git a/packages/web/src/app/repos/[id]/changes/[changeId]/page.tsx b/packages/web/src/app/repos/[id]/changes/[changeId]/page.tsxindex b6b7e54fa..616b06867 100644--- a/packages/web/src/app/repos/[id]/changes/[changeId]/page.tsx+++ b/packages/web/src/app/repos/[id]/changes/[changeId]/page.tsx@@ -9,7 +9,7 @@ import { OverviewSection } from "@repowise-dev/ui/overview";import { formatDate } from "@repowise-dev/ui/lib/format";import { Badge } from "@repowise-dev/ui/ui/badge";import type { EvidenceItem } from "@repowise-dev/types/changes";-import { changeLabel } from "@/components/changes/changes-table";+import { changeLabel, commitsViewHref } from "@/lib/changes";import { getChange } from "@/lib/api/changes";interface Props {@@ -122,7 +122,7 @@ export default async function ChangeDetailPage({ params }: Props) {icon={<GitPullRequest />}title={`${changeLabel(change)} ${change.title}`}actions={- <Link href={`/repos/${id}/changes`} className="text-xs hover:underline">+ <Link href={commitsViewHref(id, "changes")} className="text-xs hover:underline">{t("back")}</Link>}diff --git a/packages/web/src/app/repos/[id]/changes/page.test.ts b/packages/web/src/app/repos/[id]/changes/page.test.tsnew file mode 100644index 000000000..d54b2961e--- /dev/null+++ b/packages/web/src/app/repos/[id]/changes/page.test.ts@@ -0,0 +1,35 @@+import { describe, expect, it, vi } from "vitest";++const redirect = vi.fn();+vi.mock("next/navigation", () => ({ redirect: (to: string) => redirect(to) }));++import ChangesPage from "./page";+import { repoNavItems } from "@/components/layout/nav-items";+import { parseCommitsView } from "@/lib/changes";++describe("/repos/[id]/changes", () => {+ it("redirects to the Commits page grouped by change", async () => {+ await ChangesPage({ params: Promise.resolve({ id: "r1" }), searchParams: Promise.resolve({}) });+ expect(redirect).toHaveBeenLastCalledWith("/repos/r1/commits?view=changes");+ });++ it("keeps an old link's category, page and attention filter", async () => {+ await ChangesPage({+ params: Promise.resolve({ id: "r1" }),+ searchParams: Promise.resolve({ category: "fix", offset: "50", needs_attention: "true" }),+ });+ expect(redirect).toHaveBeenLastCalledWith(+ "/repos/r1/commits?view=changes&category=fix&attention=1&offset=50",+ );+ });++ it("is no longer a navigation entry", () => {+ expect(repoNavItems("r1").map((i) => i.href)).not.toContain("/repos/r1/changes");+ });++ it("reads only view=changes as the by-change view", () => {+ expect(parseCommitsView("changes")).toBe("changes");+ expect(parseCommitsView(undefined)).toBe("commits");+ expect(parseCommitsView("anything")).toBe("commits");+ });+});diff --git a/packages/web/src/app/repos/[id]/changes/page.tsx b/packages/web/src/app/repos/[id]/changes/page.tsxindex 4b6d7e4f9..b4fc85f77 100644--- a/packages/web/src/app/repos/[id]/changes/page.tsx+++ b/packages/web/src/app/repos/[id]/changes/page.tsx@@ -1,108 +1,21 @@-import type { Metadata } from "next";-import Link from "next/link";-import { GitPullRequest } from "lucide-react";-import { getTranslations } from "next-intl/server";-import { PageShell } from "@repowise-dev/ui/shared/page-shell";-import { EmptyState } from "@repowise-dev/ui/shared/empty-state";-import { ChangesTable } from "@/components/changes/changes-table";-import { listChanges } from "@/lib/api/changes";--export const metadata: Metadata = { title: "Changes" };--const PAGE_SIZE = 50;-const CATEGORIES = ["feature", "fix", "refactor", "docs", "test", "deps", "chore", "other"];+import { redirect } from "next/navigation";+import { byChangeHref } from "@/lib/changes";/**- * Merged changes, newest first. A server component: filters and paging are- * query parameters, so every view is a link.+ * The change list lives on the Commits page, grouped by change. Old links keep+ * their category, page and attention filter (`?attention=1` or the API's+ * `?needs_attention=true`).*/export default async function ChangesPage({params,searchParams,}: {params: Promise<{ id: string }>;- searchParams: Promise<{ offset?: string; category?: string }>;+ searchParams: Promise<{ category?: string; offset?: string; attention?: string; needs_attention?: string }>;}) {const { id } = await params;const sp = await searchParams;const offset = Math.max(0, Number.parseInt(sp.offset ?? "0", 10) || 0);- const category = CATEGORIES.includes(sp.category ?? "") ? sp.category : undefined;- const base = `/repos/${id}/changes`;- const t = await getTranslations("views.changes");-- let page;- try {- page = await listChanges(id, { limit: PAGE_SIZE, offset, category });- } catch {- page = null;- }-- if (!page || (page.total === 0 && !category)) {- return (- <PageShell icon={<GitPullRequest />} title={t("title")} description={t("description")}>- <EmptyState- title={t("emptyTitle")}- description={t("emptyHint")}- action={{ label: t("emptyAction"), href: `/repos/${id}/overview` }}- />- </PageShell>- );- }-- const href = (next: { offset?: number; category?: string | undefined }) => {- const q = new URLSearchParams();- if (next.category) q.set("category", next.category);- if (next.offset) q.set("offset", String(next.offset));- const s = q.toString();- return s ? `${base}?${s}` : base;- };- const chip =- "rounded-full border px-2.5 py-0.5 text-xs transition-colors border-[var(--color-border-default)] hover:bg-[var(--color-bg-elevated)]";- const active = "bg-[var(--color-bg-elevated)] text-[var(--color-text-primary)] font-medium";-- return (- <PageShell icon={<GitPullRequest />} title={t("title")} description={t("description")}>- <nav className="mb-4 flex flex-wrap gap-2" aria-label={t("category")}>- <Link href={href({})} className={`${chip} ${category ? "" : active}`}>- {t("allCategories")}- </Link>- {CATEGORIES.map((c) => (- <Link- key={c}- href={href({ category: c })}- className={`${chip} ${category === c ? active : ""}`}- >- {c}- </Link>- ))}- </nav>- <ChangesTable- repoId={id}- rows={page.items}- showProvenance={page.attribution}- labels={{- change: t("change"),- merged: t("merged"),- category: t("category"),- files: t("files"),- lines: t("lines"),- title: t("title_col"),- provenance: t("provenance"),- }}- />- <div className="mt-4 flex items-center justify-between text-xs text-[var(--color-text-secondary)]">- <span>{t("showing", { shown: page.items.length, total: page.total })}</span>- <span className="flex gap-3">- {offset > 0 && (- <Link href={href({ category, offset: Math.max(0, offset - PAGE_SIZE) })}>- {t("newer")}- </Link>- )}- {offset + PAGE_SIZE < page.total && (- <Link href={href({ category, offset: offset + PAGE_SIZE })}>{t("older")}</Link>- )}- </span>- </div>- </PageShell>- );+ const attention = sp.attention === "1" || sp.needs_attention === "true" || sp.needs_attention === "1";+ redirect(byChangeHref(id, { category: sp.category, attention, offset }));}diff --git a/packages/web/src/app/repos/[id]/commits/page.tsx b/packages/web/src/app/repos/[id]/commits/page.tsxindex 10d800911..d388dabf2 100644--- a/packages/web/src/app/repos/[id]/commits/page.tsx+++ b/packages/web/src/app/repos/[id]/commits/page.tsx@@ -11,6 +11,9 @@ import { CredibilityInfoButton } from "@repowise-dev/ui/commits/credibility-striimport { CommitQueue } from "@/components/commits/commit-queue";import { CommitDetailSheet } from "@/components/commits/commit-detail-sheet";import { CommitDistribution } from "@/components/commits/commit-distribution";+import { CommitsViewToggle } from "@/components/commits/commits-view-toggle";+import { ByChangeView, type ByChangeParams } from "@/components/commits/by-change-view";+import { parseCommitsView } from "@/lib/changes";import {getAgentTrend,getCommitEvolution,@@ -46,15 +49,37 @@ async function safeFetch<T>(fn: () => Promise<T>): Promise<T | null> {* above the analysis charts rather than below them; the evolution chart keeps* the top slot because it is the only one about the repo rather than about the* scoring model.+ *+ * `?view=changes` swaps all of that for the history grouped by merged change+ * (`ByChangeView`); the commit view stays the default.*/export default async function CommitsPage({params,+ searchParams,}: {params: Promise<{ id: string }>;+ searchParams: Promise<ByChangeParams & { view?: string }>;}) {const { id } = await params;+ const sp = await searchParams;+ const view = parseCommitsView(sp.view);const base = `/repos/${id}`;const t = await getTranslations("views.commits");+ const toggle = <CommitsViewToggle repoId={id} view={view} />;++ if (view === "changes") {+ const tc = await getTranslations("views.changes");+ return (+ <PageShell+ icon={<GitCommitHorizontal />}+ title={t("title")}+ description={tc("description")}+ actions={toggle}+ >+ <ByChangeView repoId={id} params={sp} />+ </PageShell>+ );+ }// One wave. The scatter plots its own recency sample rather than reusing the// queue's first page: the feed is risk-sorted, so reusing it would draw only@@ -77,6 +102,7 @@ export default async function CommitsPage({icon={<GitCommitHorizontal />}title={t("title")}description={t("emptyDescription")}+ actions={toggle}><EmptyStatetitle={t("emptyTitle")}@@ -92,6 +118,7 @@ export default async function CommitsPage({icon={<GitCommitHorizontal />}title={t("title")}description={t("description")}+ actions={toggle}>{stats && <CommitsLede stats={stats} base={base} LinkComponent={Link} />}diff --git a/packages/web/src/components/changes/changes-table.tsx b/packages/web/src/components/changes/changes-table.tsxindex ee45cfeda..b42a155da 100644--- a/packages/web/src/components/changes/changes-table.tsx+++ b/packages/web/src/components/changes/changes-table.tsx@@ -1,44 +1,70 @@"use client";import Link from "next/link";+import { useTranslations } from "next-intl";import { ResponsiveTable, type ResponsiveColumn } from "@repowise-dev/ui/shared/responsive-table";import { formatDate } from "@repowise-dev/ui/lib/format";-import type { ChangeSummary } from "@/lib/api/changes";+import type { ChangeEvidenceSummary, ChangeListItem } from "@/lib/api/changes";+import { categoryLabel, changeLabel } from "@/lib/changes";-export interface ChangesTableLabels {- change: string;- merged: string;- category: string;- files: string;- lines: string;- title: string;- provenance: string;-}--/** The change's short name: the forge ref when it has one, else a trimmed id. */-export function changeLabel(c: Pick<ChangeSummary, "forge_ref" | "id">): string {- return c.forge_ref ?? (c.id.length > 19 ? c.id.slice(0, 19) : c.id);+/**+ * The kept checklist in one cell: attention first, then unknown, quiet when+ * every item checked out. A checklist with no items reads as unknown, never+ * as clean. The list never builds a checklist; the change page does.+ */+function EvidenceCell({ summary }: { summary: ChangeEvidenceSummary | null | undefined }) {+ const t = useTranslations("views.changes");+ if (!summary) {+ return (+ <span className="text-xs text-[var(--color-text-tertiary)]" title={t("evidenceNotBuiltHint")}>+ {t("evidenceNotBuilt")}+ </span>+ );+ }+ if (summary.ok + summary.attention + summary.unknown === 0) {+ return <span className="text-xs text-[var(--color-text-tertiary)]">{t("unknown")}</span>;+ }+ if (summary.attention === 0 && summary.unknown === 0) {+ return <span className="text-xs text-[var(--color-text-tertiary)]">{t("evidenceClear")}</span>;+ }+ return (+ <span className="inline-flex flex-wrap items-center gap-x-2 text-xs">+ {summary.attention > 0 && (+ <span className="inline-flex items-center gap-1.5 text-[var(--color-text-primary)]">+ <span aria-hidden className="h-1.5 w-1.5 rounded-full bg-[var(--color-warning)]" />+ {t("evidenceAttention", { count: summary.attention })}+ </span>+ )}+ {summary.unknown > 0 && (+ <span className="text-[var(--color-text-tertiary)]">+ {t("evidenceUnknown", { count: summary.unknown })}+ </span>+ )}+ </span>+ );}+/** Merged changes, one row each, linking to the change's page and checklist. */export function ChangesTable({repoId,rows,- labels,showProvenance,}: {repoId: string;- rows: ChangeSummary[];- labels: ChangesTableLabels;+ rows: ChangeListItem[];showProvenance: boolean;}) {- const columns: ResponsiveColumn<ChangeSummary>[] = [+ const t = useTranslations("views.changes");+ const columns: ResponsiveColumn<ChangeListItem>[] = [{key: "id",- header: labels.change,+ header: t("change"),+ cellClassName: "whitespace-nowrap",render: (c) => (<Linkhref={`/repos/${repoId}/changes/${encodeURIComponent(c.id)}`}- className="font-mono text-xs text-[var(--color-accent-primary)] hover:underline"+ title={c.id}+ className="inline-block max-w-[12rem] truncate whitespace-nowrap align-bottom font-mono text-xs text-[var(--color-accent-primary)] hover:underline">{changeLabel(c)}</Link>@@ -46,13 +72,18 @@ export function ChangesTable({},{key: "title",- header: labels.title,- cellClassName: "min-w-[220px] max-w-[520px] truncate",+ header: t("title_col"),+ cellClassName: "min-w-[220px] max-w-[440px] truncate",render: (c) => <span title={c.title}>{c.title}</span>,},+ {+ key: "evidence",+ header: t("evidence"),+ render: (c) => <EvidenceCell summary={c.evidence_summary} />,+ },{key: "merged_at",- header: labels.merged,+ header: t("merged"),priority: 2,render: (c) => (<span className="text-xs text-[var(--color-text-secondary)]">@@ -62,20 +93,27 @@ export function ChangesTable({},{key: "category",- header: labels.category,+ header: t("category"),priority: 2,- render: (c) => <span className="text-xs">{c.category}</span>,+ render: (c) => <span className="text-xs">{categoryLabel(t, c.category)}</span>,+ },+ {+ key: "commits",+ header: t("commits"),+ align: "right",+ priority: 3,+ render: (c) => <span className="font-mono text-xs tabular-nums">{c.commit_count}</span>,},{key: "files",- header: labels.files,+ header: t("files"),align: "right",priority: 3,- render: (c) => <span className="tabular-nums">{c.files_changed}</span>,+ render: (c) => <span className="font-mono text-xs tabular-nums">{c.files_changed}</span>,},{key: "lines",- header: labels.lines,+ header: t("lines"),align: "right",priority: 3,render: (c) => (@@ -89,9 +127,21 @@ export function ChangesTable({if (showProvenance) {columns.push({key: "provenance",- header: labels.provenance,+ header: t("provenance"),priority: 3,- render: (c) => <span className="text-xs">{c.provenance?.label.replace("_", " ") ?? ""}</span>,+ render: (c) => {+ const prov = c.provenance;+ if (!prov) return null;+ const pct = prov.coverage == null ? null : Math.round(prov.coverage * 100);+ return (+ <span className="text-xs">+ {prov.label.replace("_", " ")}+ {pct != null && (+ <span className="text-[var(--color-text-tertiary)]"> · {t("coverage", { pct })}</span>+ )}+ </span>+ );+ },});}return <ResponsiveTable columns={columns} rows={rows} rowKey={(c) => c.id} stacked="sm" />;diff --git a/packages/web/src/components/commits/by-change-view.test.tsx b/packages/web/src/components/commits/by-change-view.test.tsxnew file mode 100644index 000000000..3547d6e64--- /dev/null+++ b/packages/web/src/components/commits/by-change-view.test.tsx@@ -0,0 +1,160 @@+// @vitest-environment jsdom++import React from "react";+import { cleanup, render, screen } from "@testing-library/react";+import { createTranslator } from "next-intl";+import { afterEach, describe, expect, it, vi } from "vitest";+import messages from "../../../messages/en.json";+import zhMessages from "../../../messages/zh-CN.json";+import type { ChangeListItem, ChangeListResponse } from "@/lib/api/changes";+import { CHANGE_CATEGORIES, categoryLabel } from "@/lib/changes";++const listChanges = vi.fn();+vi.mock("@/lib/api/changes", () => ({ listChanges: (...a: unknown[]) => listChanges(...a) }));+vi.mock("next-intl/server", () => ({+ getTranslations: async (namespace: string) =>+ createTranslator({ locale: "en", messages, namespace: namespace as never }),+}));+vi.mock("next/link", () => ({+ default: ({ href, children, ...rest }: { href: string; children?: React.ReactNode }) => (+ <a href={href} {...rest}>+ {children}+ </a>+ ),+}));++import { ByChangeView } from "./by-change-view";++function row(id: string, over: Partial<ChangeListItem> = {}): ChangeListItem {+ return {+ schema_version: 1,+ id,+ identity: { kind: "pr", value: id.slice(3) },+ shape: "squash",+ forge: "github",+ forge_ref: `#${id.slice(3)}`,+ title: `change ${id}`,+ merged_at: "2026-10-01T00:00:00+00:00",+ head_sha: "a".repeat(40),+ author: { name: "Ann", email: "[email protected]" },+ commit_count: 3,+ files_changed: 2,+ lines_added: 10,+ lines_deleted: 1,+ category: "feature",+ provenance: null,+ ...over,+ };+}++function page(items: ChangeListItem[]): ChangeListResponse {+ return { items, total: items.length, limit: 50, offset: 0, attribution: false };+}++async function show(params: Record<string, string> = {}) {+ render(await ByChangeView({ repoId: "r1", params }));+}++afterEach(() => {+ cleanup();+ listChanges.mockReset();+});++describe("ByChangeView", () => {+ it("summarises each change's kept checklist and never asks for a build", async () => {+ const at = "2026-10-14T00:00:00+00:00";+ listChanges.mockResolvedValue(+ page([+ row("pr-1", { evidence_summary: { generated_at: at, ok: 5, attention: 2, unknown: 1 } }),+ row("pr-2", { evidence_summary: { generated_at: at, ok: 9, attention: 0, unknown: 0 } }),+ row("pr-3"),+ ]),+ );+ await show();++ expect(listChanges).toHaveBeenCalledWith("r1", {+ limit: 50,+ offset: 0,+ category: undefined,+ evidence: true,+ needs_attention: undefined,+ });+ expect(screen.getAllByText("2 need attention").length).toBeGreaterThan(0);+ expect(screen.getAllByText("1 unknown").length).toBeGreaterThan(0);+ expect(screen.getAllByText("Nothing flagged").length).toBeGreaterThan(0);+ expect(screen.getAllByText("Not built").length).toBeGreaterThan(0);+ expect(screen.getAllByRole("link", { name: "#1" })[0]!.getAttribute("href")).toBe("/repos/r1/changes/pr-1");+ expect(screen.queryByText(/Only changes with a built checklist/)).toBeNull();+ });++ it("filters to changes needing attention and says what the filter covers", async () => {+ listChanges.mockResolvedValue(page([]));+ await show({ attention: "1", category: "fix" });++ expect(listChanges.mock.calls[0]![1]).toMatchObject({ needs_attention: true, category: "fix" });+ expect(screen.getByText(/Only changes with a built checklist are listed/)).toBeTruthy();+ expect(screen.getByText("No built checklist flags anything for attention.")).toBeTruthy();++ const chip = screen.getByRole("link", { name: "Needs attention" });+ expect(chip.getAttribute("aria-pressed")).toBe("true");+ // Pressing it again clears the filter and keeps the category.+ expect(chip.getAttribute("href")).toBe("/repos/r1/commits?view=changes&category=fix");+ // A category chip keeps the attention filter.+ expect(screen.getByRole("link", { name: "docs" }).getAttribute("href")).toBe(+ "/repos/r1/commits?view=changes&category=docs&attention=1",+ );+ });++ it("never reads a checklist with no items as clean", async () => {+ const empty = { generated_at: "2026-10-14T00:00:00+00:00", ok: 0, attention: 0, unknown: 0 };+ listChanges.mockResolvedValue(page([row("pr-1", { evidence_summary: empty })]));+ await show();+ expect(screen.getAllByText("Unknown").length).toBeGreaterThan(0);+ expect(screen.queryByText("Nothing flagged")).toBeNull();+ });++ it("pages within the combined attention and category filter", async () => {+ listChanges.mockResolvedValue({ ...page([row("pr-1")]), total: 120, offset: 50 });+ await show({ attention: "1", category: "fix", offset: "50" });+ expect(listChanges.mock.calls[0]![1]).toMatchObject({ offset: 50, category: "fix", needs_attention: true });+ expect(screen.getByRole("link", { name: "Newer" }).getAttribute("href")).toBe(+ "/repos/r1/commits?view=changes&category=fix&attention=1",+ );+ expect(screen.getByRole("link", { name: "Older" }).getAttribute("href")).toBe(+ "/repos/r1/commits?view=changes&category=fix&attention=1&offset=100",+ );+ });++ it("shows the empty state when no change is indexed", async () => {+ listChanges.mockResolvedValue(page([]));+ await show();+ expect(screen.getByText("No changes indexed yet")).toBeTruthy();+ });++ it("shows an error, never the empty state, when the list cannot be read", async () => {+ listChanges.mockRejectedValue(new Error("502"));+ await show({ attention: "1" });+ expect(screen.getByRole("alert").textContent).toContain("Could not load changes");+ expect(screen.queryByText("No changes indexed yet")).toBeNull();+ expect(screen.queryByText("No built checklist flags anything for attention.")).toBeNull();+ });++ it("says how many checklists are built and how one gets built", async () => {+ listChanges.mockResolvedValue({ ...page([]), checklists_built: { built: 1, changes: 505 } });+ await show({ attention: "1" });+ expect(screen.getByText(/Checklists built for 1 of 505 changes\./)).toBeTruthy();+ expect(screen.getByText(/repowise changes show REF/)).toBeTruthy();+ });++ it("names every category chip in both locales", () => {+ for (const locale of [messages, zhMessages]) {+ const t = createTranslator({ locale: "en", messages: locale, namespace: "views.changes" as never });+ for (const c of CHANGE_CATEGORIES) {+ expect(categoryLabel(t as (k: string) => string, c)).not.toContain("categories.");+ }+ }+ const zh = createTranslator({ locale: "zh-CN", messages: zhMessages, namespace: "views.changes" as never });+ expect(categoryLabel(zh as (k: string) => string, "fix")).toBe("修复");+ expect(categoryLabel(zh as (k: string) => string, "custom")).toBe("custom");+ });+});diff --git a/packages/web/src/components/commits/by-change-view.tsx b/packages/web/src/components/commits/by-change-view.tsxnew file mode 100644index 000000000..a560c3bca--- /dev/null+++ b/packages/web/src/components/commits/by-change-view.tsx@@ -0,0 +1,164 @@+import Link from "next/link";+import { getTranslations } from "next-intl/server";+import { ApiError } from "@repowise-dev/ui/shared/api-error";+import { EmptyState } from "@repowise-dev/ui/shared/empty-state";+import { OverviewSection } from "@repowise-dev/ui/overview";+import { ChangesTable } from "@/components/changes/changes-table";+import { listChanges } from "@/lib/api/changes";+import {+ CHANGE_CATEGORIES,+ byChangeHref,+ categoryLabel,+ type ByChangeQuery,+} from "@/lib/changes";++const PAGE_SIZE = 50;++export interface ByChangeParams {+ category?: string | undefined;+ attention?: string | undefined;+ offset?: string | undefined;+}++const CHIP =+ "rounded-full border px-2.5 py-0.5 text-xs transition-colors border-[var(--color-border-default)] hover:bg-[var(--color-bg-elevated)]";+const ACTIVE = "bg-[var(--color-bg-elevated)] text-[var(--color-text-primary)] font-medium";++type Href = (next: ByChangeQuery) => string;++/** The Needs attention toggle and the category chips; each chip keeps the other filter. */+function FilterChips({+ href,+ category,+ attention,+ categories,+ labels,+}: {+ href: Href;+ category: string | undefined;+ attention: boolean;+ categories: { value: string; label: string }[];+ labels: { needsAttention: string; category: string; allCategories: string };+}) {+ return (+ <div className="mb-4 flex flex-wrap items-center gap-2">+ <Link+ href={href({ category, attention: !attention })}+ aria-pressed={attention}+ className={`${CHIP} ${attention ? ACTIVE : ""}`}+ >+ {labels.needsAttention}+ </Link>+ <span aria-hidden className="mx-1 h-4 w-px bg-[var(--color-border-default)]" />+ <nav className="flex flex-wrap gap-2" aria-label={labels.category}>+ <Link href={href({ attention })} className={`${CHIP} ${category ? "" : ACTIVE}`}>+ {labels.allCategories}+ </Link>+ {categories.map((c) => (+ <Link+ key={c.value}+ href={href({ category: c.value, attention })}+ className={`${CHIP} ${category === c.value ? ACTIVE : ""}`}+ >+ {c.label}+ </Link>+ ))}+ </nav>+ </div>+ );+}++interface PagerLink {+ href: string;+ label: string;+}++/** "Showing n of total" and the newer / older links. */+function Pager({ showing, newer, older }: { showing: string; newer: PagerLink | null; older: PagerLink | null }) {+ return (+ <div className="mt-4 flex items-center justify-between text-xs text-[var(--color-text-secondary)]">+ <span>{showing}</span>+ <span className="flex gap-3">+ {newer && <Link href={newer.href}>{newer.label}</Link>}+ {older && <Link href={older.href}>{older.label}</Link>}+ </span>+ </div>+ );+}++/**+ * The Commits page grouped by merged change, with each change's kept+ * evidence checklist summarised. Server-rendered: filters and paging are+ * query parameters, so every view is a link. The list reads checklists the+ * change pages already built and never builds one itself, so it says how+ * many are built: a short Needs attention list is otherwise unreadable.+ */+export async function ByChangeView({ repoId, params }: { repoId: string; params: ByChangeParams }) {+ const t = await getTranslations("views.changes");+ const offset = Math.max(0, Number.parseInt(params.offset ?? "0", 10) || 0);+ const category = CHANGE_CATEGORIES.includes(params.category ?? "") ? params.category : undefined;+ const attention = params.attention === "1";++ const page = await listChanges(repoId, {+ limit: PAGE_SIZE,+ offset,+ category,+ evidence: true,+ needs_attention: attention || undefined,+ }).catch(() => null);++ // A failed read is an error, never an empty (clean-looking) list.+ if (page === null) {+ return <ApiError title={t("loadErrorTitle")} message={t("loadErrorBody")} />;+ }+ const isEmpty = page.total === 0 && !category && !attention;+ if (isEmpty) {+ return (+ <EmptyState+ title={t("emptyTitle")}+ description={t("emptyHint")}+ action={{ label: t("emptyAction"), href: `/repos/${repoId}/overview` }}+ />+ );+ }++ const href: Href = (next) => byChangeHref(repoId, next);+ const pageLink = (to: number, label: string): PagerLink => ({+ href: href({ category, attention, offset: to }),+ label,+ });+ const built = page.checklists_built;++ return (+ <OverviewSection title={t("byChangeTitle")} description={t("byChangeDescription")}>+ <FilterChips+ href={href}+ category={category}+ attention={attention}+ categories={CHANGE_CATEGORIES.map((c) => ({ value: c, label: categoryLabel(t, c) }))}+ labels={{+ needsAttention: t("needsAttention"),+ category: t("category"),+ allCategories: t("allCategories"),+ }}+ />+ <p className="mb-3 text-xs text-[var(--color-text-tertiary)]">+ {attention && `${t("attentionScope")} `}+ {built && `${t("checklistsBuilt", { built: built.built, changes: built.changes })} `}+ {t("checklistsBuildHint")}+ </p>+ {page.items.length === 0 ? (+ <p className="py-6 text-sm text-[var(--color-text-secondary)]">+ {t(attention ? "attentionEmpty" : "filterEmpty")}+ </p>+ ) : (+ <ChangesTable repoId={repoId} rows={page.items} showProvenance={page.attribution} />+ )}+ <Pager+ showing={t("showing", { shown: page.items.length, total: page.total })}+ newer={offset > 0 ? pageLink(Math.max(0, offset - PAGE_SIZE), t("newer")) : null}+ older={offset + PAGE_SIZE < page.total ? pageLink(offset + PAGE_SIZE, t("older")) : null}+ />+ </OverviewSection>+ );+}diff --git a/packages/web/src/components/commits/commits-view-toggle.test.tsx b/packages/web/src/components/commits/commits-view-toggle.test.tsxnew file mode 100644index 000000000..a0f762473--- /dev/null+++ b/packages/web/src/components/commits/commits-view-toggle.test.tsx@@ -0,0 +1,32 @@+// @vitest-environment jsdom++import { cleanup, fireEvent, render, screen } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";++const push = vi.fn();+vi.mock("next/navigation", () => ({ useRouter: () => ({ push }) }));++import { CommitsViewToggle } from "./commits-view-toggle";++afterEach(() => {+ cleanup();+ push.mockReset();+});++describe("CommitsViewToggle", () => {+ it("marks the current view and switches through the URL", () => {+ render(<CommitsViewToggle repoId="r1" view="commits" />);+ expect(screen.getByRole("radiogroup", { name: "Group the history" })).toBeTruthy();+ expect(screen.getByRole("radio", { name: "By commit" }).getAttribute("aria-checked")).toBe("true");+ expect(screen.getByRole("radio", { name: "By change" }).getAttribute("aria-checked")).toBe("false");++ fireEvent.click(screen.getByRole("radio", { name: "By change" }));+ expect(push).toHaveBeenLastCalledWith("/repos/r1/commits?view=changes");+ });++ it("goes back to the default commit view without a view param", () => {+ render(<CommitsViewToggle repoId="r1" view="changes" />);+ fireEvent.click(screen.getByRole("radio", { name: "By commit" }));+ expect(push).toHaveBeenLastCalledWith("/repos/r1/commits");+ });+});diff --git a/packages/web/src/components/commits/commits-view-toggle.tsx b/packages/web/src/components/commits/commits-view-toggle.tsxnew file mode 100644index 000000000..cb7d286c4--- /dev/null+++ b/packages/web/src/components/commits/commits-view-toggle.tsx@@ -0,0 +1,23 @@+"use client";++import { useRouter } from "next/navigation";+import { useTranslations } from "next-intl";+import { Segmented } from "@repowise-dev/ui/shared/segmented";+import { commitsViewHref, type CommitsView } from "@/lib/changes";++/** The lens over the same history. Switching drops the other view's filters. */+export function CommitsViewToggle({ repoId, view }: { repoId: string; view: CommitsView }) {+ const t = useTranslations("views.commits");+ const router = useRouter();+ return (+ <Segmented<CommitsView>+ label={t("viewLabel")}+ value={view}+ options={[+ { value: "changes", label: t("viewByChange") },+ { value: "commits", label: t("viewByCommit") },+ ]}+ onChange={(next) => router.push(commitsViewHref(repoId, next))}+ />+ );+}diff --git a/packages/web/src/components/layout/nav-items.ts b/packages/web/src/components/layout/nav-items.tsindex b45088a99..da956b439 100644--- a/packages/web/src/components/layout/nav-items.ts+++ b/packages/web/src/components/layout/nav-items.ts@@ -18,7 +18,6 @@ import {FolderTree,GitCommitHorizontal,GitMerge,- GitPullRequest,HeartPulse,LayoutDashboard,Layers,@@ -88,7 +87,6 @@ export function repoNavGroups(repoId: string): NavGroup[] {labelKey: "groupPeopleAndHistory",items: [{ label: "Commits", labelKey: "commits", href: `${base}/commits`, icon: GitCommitHorizontal },- { label: "Changes", labelKey: "changes", href: `${base}/changes`, icon: GitPullRequest },{ label: "Contributors", labelKey: "contributors", href: `${base}/owners`, icon: Users },{ label: "Decisions", labelKey: "decisions", href: `${base}/decisions`, icon: Lightbulb },],diff --git a/packages/web/src/lib/changes.ts b/packages/web/src/lib/changes.tsnew file mode 100644index 000000000..85d2e7288--- /dev/null+++ b/packages/web/src/lib/changes.ts@@ -0,0 +1,48 @@+/**+ * Pure Change Record helpers, safe to call from server and client components+ * alike. Kept out of the client table module: a server component cannot call+ * a function exported from a "use client" file.+ */+import type { ChangeListItem } from "@repowise-dev/types/changes";++/** The change's short name: the forge ref when it has one, else a trimmed id. */+export function changeLabel(c: Pick<ChangeListItem, "forge_ref" | "id">): string {+ return c.forge_ref ?? (c.id.length > 19 ? c.id.slice(0, 19) : c.id);+}++export type CommitsView = "changes" | "commits";++/** The Commits page in one view: `?view=changes` groups by merged change. */+export function commitsViewHref(repoId: string, view: CommitsView): string {+ const base = `/repos/${repoId}/commits`;+ return view === "changes" ? `${base}?view=changes` : base;+}++/** The view a `?view=` value asks for; anything else is the commit view. */+export function parseCommitsView(raw: string | string[] | undefined): CommitsView {+ return raw === "changes" ? "changes" : "commits";+}++/** Filters and paging of the by-change view, as its query parameters keep them. */+export interface ByChangeQuery {+ category?: string | undefined;+ attention?: boolean;+ offset?: number;+}++/** The by-change view with these filters; empty filters stay out of the URL. */+export function byChangeHref(repoId: string, next: ByChangeQuery = {}): string {+ const q = new URLSearchParams({ view: "changes" });+ if (next.category) q.set("category", next.category);+ if (next.attention) q.set("attention", "1");+ if (next.offset) q.set("offset", String(next.offset));+ return `${commitsViewHref(repoId, "commits")}?${q.toString()}`;+}++/** The commit categories a change can carry, in chip order. */+export const CHANGE_CATEGORIES = ["feature", "fix", "refactor", "docs", "test", "deps", "chore", "other"];++/** A category's name under `views.changes`; one this list does not know shows as stored. */+export function categoryLabel(t: (key: string) => string, category: string): string {+ return CHANGE_CATEGORIES.includes(category) ? t(`categories.${category}`) : category;+}diff --git a/packages/web/src/lib/route-links.test.ts b/packages/web/src/lib/route-links.test.tsindex fb0f26fc8..e8a67447d 100644--- a/packages/web/src/lib/route-links.test.ts+++ b/packages/web/src/lib/route-links.test.ts@@ -25,9 +25,10 @@ const ROUTES = join(WEB_SRC, "app/repos/[id]");/*** Deep links we keep pointing at a redirect on purpose. `/wiki/{pageId}` is a* documented permanent entry point, and the repo root is where a repo card is- * supposed to land.+ * supposed to land. `/changes/{changeId}` is a change's own page; only the+ * bare `/changes` list redirects to Commits.*/-const DELIBERATE = new Set(["wiki"]);+const DELIBERATE = new Set(["wiki", "changes"]);function walk(dir: string, out: string[] = []): string[] {for (const entry of readdirSync(dir)) {@@ -137,8 +138,8 @@ describe("route links", () => {});it("still recognises the deep links we keep on purpose", () => {- // If `/wiki` stops being a redirect this allowance is dead weight, and the+ // If one stops being a redirect its allowance is dead weight, and the// set should shrink rather than quietly cover a real page.- expect(redirectOnlySegments().has("wiki")).toBe(true);+ for (const seg of ["wiki", "changes"]) expect(redirectOnlySegments().has(seg)).toBe(true);});});diff --git a/packages/web/src/lib/server-client-boundary.test.ts b/packages/web/src/lib/server-client-boundary.test.tsnew file mode 100644index 000000000..5c3281cd9--- /dev/null+++ b/packages/web/src/lib/server-client-boundary.test.ts@@ -0,0 +1,58 @@+import { readFileSync, readdirSync, existsSync, statSync } from "node:fs";+import path from "node:path";+import { describe, expect, it } from "vitest";+import { changeLabel } from "./changes";++const SRC = path.resolve(__dirname, "..");++function walk(dir: string): string[] {+ return readdirSync(dir).flatMap((name) => {+ const full = path.join(dir, name);+ if (statSync(full).isDirectory()) return walk(full);+ return /\.tsx?$/.test(name) && !/\.test\.tsx?$/.test(name) ? [full] : [];+ });+}++const isClient = (source: string) => /^\s*(\/\/[^\n]*\n|\/\*[\s\S]*?\*\/\s*)*["']use client["']/.test(source);++function resolveAlias(spec: string): string | null {+ const base = path.join(SRC, spec.slice(2));+ for (const candidate of [`${base}.ts`, `${base}.tsx`, path.join(base, "index.ts"), path.join(base, "index.tsx")]) {+ if (existsSync(candidate)) return candidate;+ }+ return null;+}++/**+ * A server component may render a client component, but calling a plain+ * function exported from a "use client" module throws at request time+ * ("Attempted to call X() from the server"). Every value a server file under+ * `app/` imports from a client module must therefore be a component.+ */+describe("server/client module boundary", () => {+ it("server files under app/ import only components from client modules", () => {+ const offenders: string[] = [];+ for (const file of walk(path.join(SRC, "app"))) {+ const source = readFileSync(file, "utf8");+ if (isClient(source)) continue;+ for (const m of source.matchAll(/import\s+(type\s+)?\{([^}]*)\}\s+from\s+["'](@\/[^"']+)["']/g)) {+ if (m[1]) continue;+ const target = resolveAlias(m[3]!);+ if (!target || !isClient(readFileSync(target, "utf8"))) continue;+ for (const raw of m[2]!.split(",")) {+ const name = raw.trim();+ if (!name || name.startsWith("type ")) continue;+ const local = name.split(/\s+as\s+/)[0]!;+ if (!/^[A-Z]/.test(local)) offenders.push(`${path.relative(SRC, file)}: ${local} from ${m[3]}`);+ }+ }+ }+ expect(offenders).toEqual([]);+ });++ it("keeps the change helpers in a module a server component can call", () => {+ expect(isClient(readFileSync(path.join(SRC, "lib/changes.ts"), "utf8"))).toBe(false);+ expect(changeLabel({ forge_ref: "#42", id: "pr-42" })).toBe("#42");+ expect(changeLabel({ forge_ref: null, id: "commit-0123456789abcdef0123" })).toBe("commit-0123456789ab");+ });+});diff --git a/tests/unit/cli/test_changes_cmd.py b/tests/unit/cli/test_changes_cmd.pyindex 6ab702cd6..dd47f6a7e 100644--- a/tests/unit/cli/test_changes_cmd.py+++ b/tests/unit/cli/test_changes_cmd.py@@ -171,3 +171,40 @@ def test_export_windows_and_formats(tmp_path, monkeypatch):assert lines[0] == "change_id,merged_at,title,kind,label,status,basis,value,source"assert lines[1].startswith("pr-5,2026-03-01") and ",owners,Declared owners,attention,declared," in lines[1]assert len(lines) == 3+++async def _keep_checklist(repo_path: Path, status: str) -> None:+ from repowise.core.changes.collect import save_evidence+ from repowise.core.changes.evidence import ChangeEvidence, EvidenceItem+ from repowise.core.persistence import create_engine, create_session_factory, get_session+ from repowise.core.persistence.crud import get_repository_by_path++ engine = create_engine(f"sqlite+aiosqlite:///{(repo_path / '.repowise' / 'wiki.db').as_posix()}")+ try:+ async with get_session(create_session_factory(engine)) as session:+ repo = await get_repository_by_path(session, str(repo_path))+ evidence = ChangeEvidence(+ change_id="pr-5",+ revspec=HEAD,+ generated_at="2026-10-14T00:00:00+00:00",+ items=[EvidenceItem("owners", "Declared owners", status, "declared", None, [], "test")],+ )+ await save_evidence(session, repo.id, "pr-5", evidence)+ finally:+ await engine.dispose()+++def test_list_needs_attention_reads_kept_checklists_only(tmp_path):+ root = _repo(tmp_path)+ runner = CliRunner()+ args = ["list", "--path", str(root), "--format", "json", "--needs-attention"]++ # No checklist kept yet: nothing is listed, and nothing is built.+ assert json.loads(runner.invoke(changes_group, args).output)["total"] == 0+ run_async(_keep_checklist(root, "ok"))+ assert json.loads(runner.invoke(changes_group, args).output)["total"] == 0+ run_async(_keep_checklist(root, "attention"))+ flagged = json.loads(runner.invoke(changes_group, args).output)+ assert flagged["total"] == 1 and flagged["changes"][0]["id"] == "pr-5"+ features = json.loads(runner.invoke(changes_group, [*args, "--category", "feature"]).output)+ assert features["total"] == 0diff --git a/tests/unit/core/test_changes.py b/tests/unit/core/test_changes.pyindex 38d1abcab..b59179322 100644--- a/tests/unit/core/test_changes.py+++ b/tests/unit/core/test_changes.py@@ -366,6 +366,7 @@ async def _db(tmp_path: Path, repo_root: Path):@pytest.mark.usefixtures("_private_user_config")async def test_refresh_rebuilds_then_extends(tmp_path, history):from repowise.core.persistence.crud import (+ ChangeFilter,get_change,list_changes,upsert_git_commits_bulk,@@ -396,7 +397,7 @@ async def test_refresh_rebuilds_then_extends(tmp_path, history):assert await refresh_changes(session, repo_id, r.root, rebuild=False) == 1rows, total = await list_changes(session, repo_id, limit=3)assert total == 10 and rows[0].head_sha == newer- _, fixes = await list_changes(session, repo_id, category="fix")+ _, fixes = await list_changes(session, repo_id, ChangeFilter(category="fix"))assert fixes == 1finally:await engine.dispose()diff --git a/tests/unit/server/test_changes_routes.py b/tests/unit/server/test_changes_routes.pyindex 62bb6dc2e..4106ae2f8 100644--- a/tests/unit/server/test_changes_routes.py+++ b/tests/unit/server/test_changes_routes.py@@ -195,3 +195,107 @@ async def test_a_slow_build_answers_building_and_runs_once(client: AsyncClient,await asyncio.sleep(0.01)done = (await client.get(base, params={"evidence": "true"})).json()assert done["evidence"]["change_id"] == "pr-1" and seen == ["pr-1"]+++def _evidence(change_id: str, *statuses: str, details: list | None = None):+ from repowise.core.changes.evidence import ChangeEvidence, EvidenceItem++ return ChangeEvidence(+ change_id=change_id,+ revspec=None,+ generated_at="2026-10-14T00:00:00+00:00",+ items=[+ EvidenceItem(f"kind{i}", "Item", s, "measured", None, details or [], "test")+ for i, s in enumerate(statuses)+ ],+ )+++def _checklist(change_id: str, *statuses: str, details: list | None = None) -> str:+ return crud.dump_evidence(_evidence(change_id, *statuses, details=details).to_dict())+++async def test_list_evidence_summary_is_opt_in_and_never_builds(+ client: AsyncClient, app, monkeypatch+) -> None:+ seen: list[str] = []+ _fake_build(monkeypatch, seen)+ repo = await create_test_repo(client)+ async with get_session(app.state.session_factory) as session:+ await crud.upsert_changes(+ session,+ repo["id"],+ [+ _row("pr-1", 1, evidence_json=_checklist("pr-1", "ok", "attention", "attention", "unknown")),+ _row("pr-2", 2, evidence_json=_checklist("pr-2", "ok", "unknown")),+ # The phrase sits in a detail, not in a status: not an attention change.+ _row("pr-3", 3, evidence_json=_checklist("pr-3", "ok", details=[{"status": "attention"}])),+ _row("pr-4", 4),+ ],+ )+ url = f"/api/repos/{repo['id']}/changes"++ plain = (await client.get(url)).json()+ assert all("evidence_summary" not in c for c in plain["items"])+ assert "checklists_built" not in plain++ with_evidence = (await client.get(url, params={"evidence": "true"})).json()+ assert with_evidence["checklists_built"] == {"built": 3, "changes": 4}+ rows = {c["id"]: c for c in with_evidence["items"]}+ assert rows["pr-1"]["evidence_summary"] == {+ "generated_at": "2026-10-14T00:00:00+00:00",+ "ok": 1,+ "attention": 2,+ "unknown": 1,+ }+ assert rows["pr-2"]["evidence_summary"]["attention"] == 0+ assert "evidence_summary" not in rows["pr-4"]+ assert seen == []++ flagged = (await client.get(url, params={"needs_attention": "true"})).json()+ assert flagged["total"] == 1 and [c["id"] for c in flagged["items"]] == ["pr-1"]+ paged = (await client.get(url, params={"needs_attention": "true", "offset": 1})).json()+ assert paged["total"] == 1 and paged["items"] == []+++async def test_needs_attention_finds_what_save_evidence_wrote(client: AsyncClient, app) -> None:+ from repowise.core.changes.collect import save_evidence++ repo = await create_test_repo(client)+ await _seed(app, repo["id"]) # pr-1 feature, pr-2 fix, pr-3 feature+ async with get_session(app.state.session_factory) as session:+ await save_evidence(session, repo["id"], "pr-1", _evidence("pr-1", "attention"))+ await save_evidence(session, repo["id"], "pr-2", _evidence("pr-2", "ok", "attention"))+ await save_evidence(session, repo["id"], "pr-3", _evidence("pr-3", "ok"))+ url = f"/api/repos/{repo['id']}/changes"++ flagged = (await client.get(url, params={"needs_attention": "true", "evidence": "true"})).json()+ assert [c["id"] for c in flagged["items"]] == ["pr-2", "pr-1"] and flagged["total"] == 2+ assert flagged["items"][0]["evidence_summary"]["attention"] == 1+ fixes = (+ await client.get(url, params={"needs_attention": "true", "category": "fix", "evidence": "true"})+ ).json()+ assert fixes["total"] == 1 and [c["id"] for c in fixes["items"]] == ["pr-2"]+ # The built count follows the category, not the attention filter.+ assert fixes["checklists_built"] == {"built": 1, "changes": 1}+ # Paging runs after the confirm, over the confirmed set.+ second = (await client.get(url, params={"needs_attention": "true", "limit": 1, "offset": 1})).json()+ assert second["total"] == 2 and [c["id"] for c in second["items"]] == ["pr-1"]+++def test_evidence_summary_never_reads_missing_or_unknown_status_as_clean() -> None:+ from types import SimpleNamespace++ from repowise.core.changes.collect import evidence_summary++ odd = SimpleNamespace(evidence_json=_checklist("pr-1", "ok", "skipped"))+ assert evidence_summary(odd) == {+ "generated_at": "2026-10-14T00:00:00+00:00",+ "ok": 1,+ "attention": 0,+ "unknown": 1,+ }+ empty = evidence_summary(SimpleNamespace(evidence_json=_checklist("pr-1")))+ assert empty is not None and (empty["ok"], empty["attention"], empty["unknown"]) == (0, 0, 0)