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(changes): evidence checklist on Change Records (#3791)
Raghav Chamadiya12dc71f60821
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.mdindex 080b4c064..06aa46b6d 100644--- a/docs/agent/MCP_TOOLS.md+++ b/docs/agent/MCP_TOOLS.md@@ -267,7 +267,7 @@ Reviews one commit, a `base..head` range, or uncommitted work by comparing the t| `exclude_patterns` | list[string] | none | Gitignore-style paths to omit; combined with a root `.riskignore` || `include_paths` | list[string] or string | all | Gitignore-style paths to keep, as a list or one comma-separated string. Like `exclude_patterns`, it scopes the score, the health delta and every per-file block; `impacted_tests` still selects over the whole change, less only repowise's own output || `baseline` | int | `200` | Recent commits sampled for percentile ranking; `0` disables percentiles |-| `include` | list[string] | none | `findings` (every finding), `diagnostics` (raw score mechanics, plus the delta's analyzer, revisions and limits), `scales` (units) |+| `include` | list[string] | none | `findings` (every finding), `diagnostics` (raw score mechanics, plus the delta's analyzer, revisions and limits), `scales` (units), `evidence` (the change's evidence checklist, the same record `repowise changes show` prints) || `finding_id` | string | none | Expand one `health_delta` finding || `repo` | string | default repo | Workspace repo alias. `"all"` is not supported |diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.mdindex b3702eee9..b05fb874a 100644--- a/docs/reference/CLI_REFERENCE.md+++ b/docs/reference/CLI_REFERENCE.md@@ -1598,9 +1598,12 @@ 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.+```bashrepowise changes list [--path PATH] [--category C] [--shape merge|squash|commit] [--grep TEXT] [--limit N] [--offset N] [--format table|json]-repowise changes show REF [--path PATH] [--format table|json|in-toto]+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/packages/api-client/src/changes.ts b/packages/api-client/src/changes.tsindex 5d0369ab9..d40d903ae 100644--- a/packages/api-client/src/changes.ts+++ b/packages/api-client/src/changes.ts@@ -6,12 +6,14 @@*/import { apiGet } from "./client";import type {+ ChangeEvidence,ChangeListResponse,ChangeRecord,ChangeSummary,+ EvidenceItem,} from "@repowise-dev/types/changes";-export type { ChangeListResponse, ChangeRecord, ChangeSummary };+export type { ChangeEvidence, ChangeListResponse, ChangeRecord, ChangeSummary, EvidenceItem };/** A page of changes, newest merged first, without file or commit lists. */export async function listChanges(@@ -29,12 +31,17 @@ export async function listChanges(return apiGet<ChangeListResponse>(`/api/repos/${repoId}/changes`, opts);}-/** One change by id (`pr-123`), or the change that landed a commit sha. */+/**+ * One change by id (`pr-123`), or the change that landed a commit sha.+ * `evidence` adds its checklist, built on first read (seconds) and then kept.+ */export async function getChange(repoId: string,changeId: string,+ opts?: { evidence?: boolean },): Promise<ChangeRecord> {return apiGet<ChangeRecord>(`/api/repos/${repoId}/changes/${encodeURIComponent(changeId)}`,+ opts,);}diff --git a/packages/cli/src/repowise/cli/commands/changes_cmd.py b/packages/cli/src/repowise/cli/commands/changes_cmd.pyindex 465326033..598899d77 100644--- a/packages/cli/src/repowise/cli/commands/changes_cmd.py+++ b/packages/cli/src/repowise/cli/commands/changes_cmd.py@@ -1,18 +1,29 @@"""``repowise changes`` - the merged changes reconstructed from git.-``list`` pages the indexed changes newest first; ``show`` prints one as the-native versioned JSON record or, with ``--format in-toto``, as an in-toto-Statement v1. Both read the index; ``repowise init`` or ``update`` fills it.+``list`` pages the indexed changes newest first; ``show`` prints one with its+evidence checklist, as the native versioned JSON record or, with+``--format in-toto``, as an in-toto Statement v1; ``export`` writes every+change merged in a window with its checklist, as JSON Lines or CSV. All read the+index; ``repowise init`` or ``update`` fills it. A checklist is built on first+read (seconds per change) and kept on the change until ``--refresh``."""from __future__ import annotations+from collections.abc import Callable+from datetime import datetimefrom pathlib import Pathfrom typing import Anyimport click-from repowise.cli.helpers import console, repo_index_session, resolve_command_target, run_async+from repowise.cli.helpers import (+ console,+ repo_index_session,+ resolve_command_target,+ run_async,+ silence_logs_for_machine_output_until_close,+)from repowise.cli.output import emit_json, format_option@@ -41,8 +52,9 @@ async def _list(root: Path, **filters: Any) -> tuple[list[dict], int] | None:return [change_record(r, attribution=on) for r in rows], total-async def _show(root: Path, ref: str) -> dict | None | bool:+async def _show(root: Path, ref: str, *, evidence: bool, refresh: bool) -> dict | None | bool:from repowise.core.attribution import attribution_enabled+ from repowise.core.changes.collect import change_evidencefrom repowise.core.changes.record import change_recordfrom repowise.core.persistence.crud import get_change@@ -51,12 +63,132 @@ async def _show(root: Path, ref: str) -> dict | None | bool:return Falsesession, repo_id = openedrow = await get_change(session, repo_id, ref)- return None if row is None else change_record(row, attribution=attribution_enabled(root))+ if row is None:+ return None+ record = change_record(row, attribution=attribution_enabled(root))+ if evidence:+ got = await change_evidence(session, repo_id, root, row, refresh=refresh)+ record["evidence"] = got.to_dict()+ return record+++#: Changes read from the index per page during an export.+_EXPORT_PAGE = 50+++async def _export(+ root: Path,+ since: datetime | None,+ until: datetime | None,+ refresh: bool,+ emit: Callable[[dict], None],+) -> int | None:+ """Emit each change in the window with its checklist, a page at a time; the count."""+ from repowise.core.attribution import attribution_enabled+ from repowise.core.changes.collect import change_evidence+ from repowise.core.changes.record import change_record+ from repowise.core.persistence.crud import list_changes++ async with repo_index_session(root) as opened:+ if opened is None:+ return None+ session, repo_id = opened+ on = attribution_enabled(root)+ done = 0+ while True:+ rows, total = await list_changes(+ session, repo_id, since=since, until=until, limit=_EXPORT_PAGE, offset=done+ )+ for row in rows:+ done += 1+ if refresh or not row.evidence_json:+ click.echo(f"evidence {done}/{total}: {row.change_id}", err=True)+ record = change_record(row, attribution=on)+ record["evidence"] = (+ await change_evidence(session, repo_id, root, row, refresh=refresh)+ ).to_dict()+ # Kept as it goes, so an interrupted export resumes where it stopped.+ await session.commit()+ emit(record)+ session.expunge_all()+ if len(rows) < _EXPORT_PAGE:+ return done+++_STATUS_STYLE = {"ok": "green", "attention": "yellow", "unknown": "dim"}+++def _print_checklist(evidence: dict) -> None:+ from rich.markup import escape+ from rich.table import Table++ table = Table("Evidence", "Status", "Basis", "Value", title="Evidence checklist")+ for item in evidence["items"]:+ style = _STATUS_STYLE.get(item["status"], "")+ table.add_row(+ escape(item["label"]),+ f"[{style}]{item['status']}[/{style}]",+ item["basis"],+ escape(_value_text(item)),+ )+ console.print(table)+ console.print(f"[dim]generated {evidence['generated_at']}; `--refresh` rebuilds it.[/dim]")+++def _value_text(item: dict) -> str:+ value = item["value"]+ if value is None:+ reasons = [d.get("reason") for d in item["details"] if d.get("reason")]+ return reasons[0] if reasons else ""+ if isinstance(value, list):+ more = f" (+{len(value) - 6})" if len(value) > 6 else ""+ return ", ".join(map(str, value[:6])) + more+ if isinstance(value, dict):+ return ", ".join(f"{k} {v}" for k, v in value.items() if v is not None and v != [])+ return str(value)+++_CSV_COLUMNS = (+ "change_id",+ "merged_at",+ "title",+ "kind",+ "label",+ "status",+ "basis",+ "value",+ "source",+)+++def _csv_rows(record: dict) -> str:+ """One CSV row per evidence item of *record*; ``value`` is its JSON."""+ import csv+ import io+ import json++ buf = io.StringIO()+ writer = csv.writer(buf, lineterminator="\n")+ for item in record["evidence"]["items"]:+ writer.writerow(+ [+ record["id"],+ record["merged_at"] or "",+ record["title"],+ item["kind"],+ item["label"],+ item["status"],+ item["basis"],+ json.dumps(item["value"], sort_keys=True),+ item["source"],+ ]+ )+ return buf.getvalue()@click.group("changes")def changes_group() -> None:- """List and show merged changes (PRs, MRs, commits) reconstructed from git."""+ """List, show and export merged changes (PRs, MRs, commits) reconstructed from git."""@changes_group.command("list")@@ -115,10 +247,20 @@ def changes_list(choices=("table", "json", "in-toto"),help="table, the native JSON record, or an in-toto Statement v1.",)-def changes_show(ref: str, repo: str | None, fmt: str) -> None:+ "--evidence/--no-evidence",+ default=True,+ show_default=True,+ help="Include the evidence checklist (built on first read, then kept).",+)[email protected]("--refresh", is_flag=True, help="Rebuild the evidence checklist.")+def changes_show(ref: str, repo: str | None, fmt: str, evidence: bool, refresh: bool) -> None:"""Show one change by id (pr-123, change-I..., commit-<sha>) or by a commit sha."""root = _repo_root(repo)- record = run_async(_show(root, ref))+ if evidence:+ # Building a checklist parses code, which logs; keep the table clean.+ silence_logs_for_machine_output_until_close()+ record = run_async(_show(root, ref, evidence=evidence, refresh=refresh))if record is False:_no_index()if record is None:@@ -158,3 +300,46 @@ def changes_show(ref: str, repo: str | None, fmt: str) -> None:console.print(f" {escape(f['path'])} +{f['added']}/-{f['deleted']}")if record["files_changed"] > 50:console.print(f"[dim] ... {record['files_changed'] - 50} more[/dim]")+ if "evidence" in record:+ _print_checklist(record["evidence"])+++@changes_group.command("export")[email protected]("--path", "repo", default=None, help="Repo path (defaults to cwd).")+ "--since", type=click.DateTime(), default=None, help="Merged on or after this date (UTC)."+)[email protected]("--until", type=click.DateTime(), default=None, help="Merged before this date (UTC).")+@format_option(+ choices=("json", "csv"),+ default="json",+ help="json: one record per line (JSON Lines); csv: one row per change and item.",+)[email protected]("--refresh", is_flag=True, help="Rebuild every evidence checklist.")+def changes_export(+ repo: str | None, since: datetime | None, until: datetime | None, fmt: str, refresh: bool+) -> None:+ """Export the changes merged in a window, each with its evidence checklist.++ A change without a kept checklist has one built and kept first, which+ costs a few seconds per change (about 7 to 9s measured on a mid-size+ repository); kept checklists are read back at no cost. Records stream as+ they are ready, and progress goes to stderr.+ """+ import json+ from datetime import UTC++ root = _repo_root(repo)+ since, until = (d.replace(tzinfo=UTC) if d else None for d in (since, until))+ if fmt == "csv":+ click.echo(",".join(_CSV_COLUMNS))++ def emit(record: dict) -> None:+ click.echo(_csv_rows(record), nl=False)+ else:++ def emit(record: dict) -> None:+ click.echo(json.dumps(record, default=str))++ if run_async(_export(root, since, until, refresh, emit)) is None:+ _no_index()diff --git a/packages/core/alembic/versions/0112_change_evidence.py b/packages/core/alembic/versions/0112_change_evidence.pynew file mode 100644index 000000000..a502a1b04--- /dev/null+++ b/packages/core/alembic/versions/0112_change_evidence.py@@ -0,0 +1,33 @@+"""Cached evidence checklist on ``changes``.++``changes.evidence_json`` holds a change's evidence checklist and the index+commit it read; it is built on first read and rebuilt on request.++Local SQLite stores never run Alembic; ``init_db`` adds the column there from+the model.++Revision ID: 0112+Revises: 0111+Create Date: 2026-10-14+"""++from __future__ import annotations++from collections.abc import Sequence++import sqlalchemy as sa+from alembic import op++# revision identifiers+revision: str = "0112"+down_revision: str | None = "0111"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None+++def upgrade() -> None:+ op.add_column("changes", sa.Column("evidence_json", sa.Text, nullable=True))+++def downgrade() -> None:+ op.drop_column("changes", "evidence_json")diff --git a/packages/core/src/repowise/core/changes/__init__.py b/packages/core/src/repowise/core/changes/__init__.pyindex cd4c51fb7..3b3f48267 100644--- a/packages/core/src/repowise/core/changes/__init__.py+++ b/packages/core/src/repowise/core/changes/__init__.py@@ -3,11 +3,19 @@:mod:`.reconstruct` reads changes off the main line, :mod:`.source` is theseam forge metadata comes through (git only by default), :mod:`.record` is theversioned JSON shape and its in-toto export, and :mod:`.store` keeps the-``changes`` table in step with each index and update.+``changes`` table in step with each index and update. :mod:`.evidence` is the+checklist attached to a record, and :mod:`.collect` gathers and caches it."""from __future__ import annotations+from repowise.core.changes.evidence import (+ EVIDENCE_SCHEMA_VERSION,+ ChangeEvidence,+ EvidenceInputs,+ EvidenceItem,+ build_change_evidence,+)from repowise.core.changes.reconstruct import ReconstructedChange, reconstruct_changesfrom repowise.core.changes.record import (PREDICATE_TYPE,@@ -22,11 +30,16 @@ from repowise.core.changes.source import ()__all__ = [+ "EVIDENCE_SCHEMA_VERSION","PREDICATE_TYPE","SCHEMA_VERSION",+ "ChangeEvidence","ChangeMetadata","ChangeMetadataSource",+ "EvidenceInputs",+ "EvidenceItem","ReconstructedChange",+ "build_change_evidence","change_metadata_sources","change_record","in_toto_statement",diff --git a/packages/core/src/repowise/core/changes/collect.py b/packages/core/src/repowise/core/changes/collect.pynew file mode 100644index 000000000..c28e316a8--- /dev/null+++ b/packages/core/src/repowise/core/changes/collect.py@@ -0,0 +1,614 @@+"""Gather a change's evidence from git and the index, and keep it on its row.++:func:`evidence_for_revspec` reviews any commit, range or the working tree;+:func:`build_stored_evidence` does it for a stored Change Record without+writing, :func:`save_evidence` keeps the result on ``changes.evidence_json``,+and :func:`change_evidence` does both. All end in+:func:`~repowise.core.changes.evidence.build_change_evidence`.++A review costs seconds per change (the health comparison parses both sides),+so it is computed on first read, never during an index or update, and kept:+a merged change's checklist is a snapshot stamped with ``generated_at`` and+the ``index_commit`` it read, rebuilt only on request (``refresh``).+"""++from __future__ import annotations++import asyncio+import json+import re+from collections.abc import Sequence+from pathlib import Path+from typing import Any++import structlog++from repowise.core.changes.evidence import (+ EVIDENCE_SCHEMA_VERSION,+ ChangeEvidence,+ EvidenceInputs,+ Unavailable,+ build_change_evidence,+)+from repowise.core.ownership.codeowners import (+ CodeownersMatcher,+ parse_codeowners,+ read_codeowners,+)++logger = structlog.get_logger(__name__)++#: Reviewers listed per change; more is no better than none.+REVIEWER_LIMIT = 5++NO_INDEX = "the repository has no index"++#: Decision statuses that no longer bind anything.+_RETIRED = frozenset({"dismissed", "superseded", "deprecated"})++#: The basis kind behind a reviewer, never a weight or a count.+_REVIEWER_REASONS = {"touched": "owns path", "co-change history": "co-change"}++_CO_AUTHOR = re.compile(r"^\s*(.*?)\s*<([^>]*)>\s*$")+++# -- review -------------------------------------------------------------------+++def _review(+ repo_root: str,+ revspec: str | None,+ *,+ tests: dict[str, Any] | None,+ risk: Any = None,+ health: Any = None,+ extensions: tuple[str, ...] = (),+ exclude_patterns: tuple[str, ...] = (),+) -> Any:+ from repowise.core.analysis.change_health.sources import GitRevisionSource+ from repowise.core.analysis.change_review import (+ ChangeReviewEvidence,+ ChangeReviewRequest,+ ChangeReviewService,+ )++ service = ChangeReviewService(GitRevisionSource(repo_root), repo_path=repo_root)+ return service.review(+ ChangeReviewRequest(+ revspec=revspec, extensions=extensions, exclude_patterns=exclude_patterns+ ),+ evidence=ChangeReviewEvidence(risk=risk, health=health, tests=tests),+ )+++def _manifest(+ repo_root: str,+ revspec: str | None,+ extensions: tuple[str, ...],+ exclude_patterns: tuple[str, ...],+) -> dict[str, str]:+ """``{path: status}`` the review will count, read before it runs."""+ from repowise.core.analysis.change_health.sources import GitRevisionSource, filter_changes++ pair = GitRevisionSource(repo_root, hunks=False).resolve(revspec)+ changes = filter_changes(+ pair.changes, extensions=extensions, exclude_patterns=exclude_patterns+ )+ return {c.path: c.status for c in changes}+++async def evidence_for_revspec(+ session: Any | None,+ repo_id: str,+ repo_root: Path | str,+ revspec: str | None,+ *,+ change_id: str | None = None,+ row: Any = None,+ risk: Any = None,+ health: Any = None,+ extensions: Sequence[str] = (),+ exclude_patterns: Sequence[str] = (),+ no_index: str = NO_INDEX,+) -> ChangeEvidence:+ """The checklist for *revspec* (``None`` is the working tree).++ *row* is the stored change *revspec* names, when there is one: its id,+ commits and stored provenance are used. *risk* and *health* are results+ the caller already computed; omitted, the review computes them. Without a+ *session* only the git-derived items are filled, and *no_index* says why.+ """+ from repowise.core.analysis.test_impact import analyze_test_impact+ from repowise.core.persistence.crud import get_repository++ root = str(repo_root)+ ext, excl = tuple(extensions), tuple(exclude_patterns)+ try:+ statuses = await asyncio.to_thread(_manifest, root, revspec, ext, excl)+ except (ValueError, OSError) as exc:+ statuses, missing = {}, str(exc)+ else:+ missing = None if session is not None else no_index+ tests = None+ if statuses and session is not None:+ try:+ tests = await analyze_test_impact(+ session, repo_id, sorted(statuses), change_status=statuses+ )+ except Exception as exc:+ logger.debug("evidence_tests_failed", error=str(exc))+ bundle = await asyncio.to_thread(+ _review,+ root,+ revspec,+ tests=tests,+ risk=risk,+ health=health,+ extensions=ext,+ exclude_patterns=excl,+ )+ if row is not None:+ change_id = row.change_id+ if missing:+ gone = Unavailable(missing)+ inputs = EvidenceInputs(+ components=gone,+ owners=gone,+ reviewers=gone,+ contracts=gone,+ consumers=gone,+ decisions=gone,+ provenance=gone,+ )+ index_commit = None+ else:+ shas = await asyncio.to_thread(_change_commits, root, revspec, row)+ inputs = await gather_inputs(+ session,+ repo_id,+ Path(root),+ [e.path for e in bundle.manifest],+ shas=shas,+ row=row,+ )+ index_commit = getattr(await get_repository(session, repo_id), "head_commit", None)+ return build_change_evidence(+ bundle, inputs, change_id=change_id, revspec=revspec, index_commit=index_commit+ )+++# -- stored changes -------------------------------------------------------------+++async def build_stored_evidence(+ session: Any,+ repo_id: str,+ repo_root: Path | str,+ row: Any,+ *,+ risk: Any = None,+ health: Any = None,+) -> ChangeEvidence:+ """The stored change's checklist, built now and not written.++ The change is its head commit against that commit's first parent.+ """+ return await evidence_for_revspec(+ session, repo_id, repo_root, row.head_sha, row=row, risk=risk, health=health+ )+++async def save_evidence(+ session: Any, repo_id: str, change_id: str, evidence: ChangeEvidence+) -> None:+ """Keep *evidence* on its change row."""+ from sqlalchemy import update++ from repowise.core.persistence.models import Change++ await session.execute(+ update(Change)+ .where(Change.repository_id == repo_id, Change.change_id == change_id)+ .values(evidence_json=json.dumps(evidence.to_dict()))+ )+++async def change_evidence(+ session: Any,+ repo_id: str,+ repo_root: Path | str,+ row: Any,+ *,+ refresh: bool = False,+ risk: Any = None,+ health: Any = None,+) -> ChangeEvidence:+ """The stored change's checklist: the kept one, or built and kept now."""+ if not refresh and (cached := cached_evidence(row)) is not None:+ return cached+ evidence = await build_stored_evidence(+ session, repo_id, repo_root, row, risk=risk, health=health+ )+ row.evidence_json = json.dumps(evidence.to_dict())+ await session.flush()+ return evidence+++async def stored_change_at(+ session: Any, repo_id: str, repo_root: Path | str, revspec: str | None+) -> Any:+ """The stored change whose head commit *revspec* names, or ``None``."""+ from repowise.core.git_refs import resolve, split_revspec+ from repowise.core.persistence.crud import get_change++ if not revspec or split_revspec(revspec) is not None:+ return None+ sha = await asyncio.to_thread(resolve, str(repo_root), revspec)+ if not sha:+ return None+ row = await get_change(session, repo_id, sha)+ return row if row is not None and row.head_sha == sha else None+++def cached_evidence(row: Any) -> ChangeEvidence | None:+ """The kept checklist, or ``None`` when there is none in this schema."""+ raw = getattr(row, "evidence_json", None)+ if not raw:+ return None+ try:+ evidence = ChangeEvidence.from_dict(json.loads(raw))+ except (TypeError, ValueError, KeyError):+ return None+ return evidence if evidence.schema_version == EVIDENCE_SCHEMA_VERSION else None+++# -- inputs -------------------------------------------------------------------+++async def gather_inputs(+ session: Any,+ repo_id: str,+ repo_root: Path,+ paths: list[str],+ *,+ shas: list[str],+ row: Any = None,+) -> EvidenceInputs:+ """Index facts for *paths* and the change's commits *shas*.++ A source that fails reads as ``Unavailable``, with the reason.+ """+ components = await _guard(_components(session, repo_id, repo_root, paths))+ owners, owner_sources = await _guard_pair(_owners(repo_root, paths, components))+ contracts, consumers = await _guard_pair(asyncio.to_thread(_workspace, repo_root, paths))+ return EvidenceInputs(+ code_paths=_code_paths(paths),+ components=components,+ owners=owners,+ owner_sources=owner_sources,+ reviewers=await _guard(_reviewers(session, repo_id, repo_root, paths, shas)),+ contracts=contracts,+ consumers=consumers,+ decisions=await _guard(_decisions(session, repo_id, paths)),+ provenance=await _guard(_provenance(session, repo_id, repo_root, shas, row)),+ )+++async def _guard(coro: Any) -> Any:+ try:+ return await coro+ except Exception as exc:+ logger.debug("evidence_input_failed", error=str(exc))+ return Unavailable(f"could not be read: {type(exc).__name__}: {exc}")+++async def _guard_pair(coro: Any) -> tuple[Any, Any]:+ got = await _guard(coro)+ return (got, got) if isinstance(got, Unavailable) else got+++def _code_paths(paths: list[str]) -> list[str]:+ from repowise.core.ingestion.languages.registry import REGISTRY+ from repowise.core.test_paths import is_test_related_path++ suffixes = REGISTRY.non_infra_code_extensions()+ return [p for p in paths if Path(p).suffix in suffixes and not is_test_related_path(p)]+++async def _components(+ session: Any, repo_id: str, repo_root: Path, paths: list[str]+) -> list[dict[str, Any]]:+ from repowise.core.components import resolve_components+ from repowise.core.components.catalog import owner_group_name+ from repowise.core.components.store import component_rollups, load_repo_components++ loaded = await load_repo_components(session, repo_id, repo_root)+ known = loaded.resolved.components+ # Resolved again over the change's own paths, which the index may no+ # longer hold (a later change deleted them).+ mine = resolve_components(+ [c for c in known if c.declared], [c for c in known if not c.declared], paths+ )+ touched = [c for c in mine.components if mine.files.get(c.name)]+ # The bus factor is the whole component's, not just the changed files'.+ rollups = await component_rollups(+ session,+ repo_id,+ {c.name: loaded.resolved.files.get(c.name) or mine.files[c.name] for c in touched},+ loaded.test_files,+ )+ rows = []+ for c in touched:+ bus = (rollups.get(c.name) or {}).get("bus_factor") or {}+ rows.append(+ {+ "name": c.name,+ "source": c.source,+ "owner": owner_group_name(c.owner),+ "criticality": c.criticality,+ "tags": list(c.tags),+ "files": mine.files[c.name],+ "bus_factor": int(bus["value"]) if bus.get("basis") == "measured" else None,+ }+ )+ return rows+++async def _owners(+ repo_root: Path, paths: list[str], components: Any+) -> tuple[dict[str, list[str]], list[str]]:+ """``{path: owners}`` from CODEOWNERS (per section, last match wins), else the component owner."""+ sources: list[str] = []+ matcher: CodeownersMatcher | None = None+ if found := read_codeowners(repo_root):+ rel, text = found+ matcher = CodeownersMatcher(parse_codeowners(text))+ sources.append(rel)+ by_component: dict[str, str] = {}+ if not isinstance(components, Unavailable):+ for comp in components:+ if comp.get("owner"):+ for path in comp["files"]:+ by_component[path] = comp["owner"]+ if by_component:+ sources.append("component catalog")+ owners: dict[str, list[str]] = {}+ for path in paths:+ named = matcher.owners(path) if matcher else ()+ if named:+ owners[path] = list(named)+ elif path in by_component:+ owners[path] = [by_component[path]]+ return owners, sources+++async def _reviewers(+ session: Any, repo_id: str, repo_root: Path, paths: list[str], shas: list[str]+) -> list[dict[str, Any]] | Unavailable:+ """People with history in these files, by name, leaving out the change's own."""+ from sqlalchemy import select++ from repowise.core.analysis.reviewers import cochange_paths, suggest_reviewers+ from repowise.core.git_refs import is_shallow+ from repowise.core.persistence.models import GitMetadata++ if await asyncio.to_thread(is_shallow, str(repo_root)):+ return Unavailable("a shallow clone cuts off the history ownership is read from")++ async def rows(wanted: set[str] | list[str]) -> list[Any]:+ if not wanted:+ return []+ q = select(GitMetadata).where(+ GitMetadata.repository_id == repo_id, GitMetadata.file_path.in_(list(wanted))+ )+ return list((await session.execute(q)).scalars().all())++ direct = await rows(paths)+ own = await asyncio.to_thread(_change_people, str(repo_root), shas)+ candidates = suggest_reviewers(direct, await rows(cochange_paths(direct)), limit=50)+ kept = [+ s+ for s in candidates+ if (s["email"] or "").strip().lower() not in own+ and (s["name"] or "").strip().lower() not in own+ ][:REVIEWER_LIMIT]+ # Listed by name: the order says nothing about who matters more.+ return sorted(+ (+ {+ "name": s["name"],+ "paths": s["owned_paths"],+ "reasons": sorted({_REVIEWER_REASONS.get(r, r) for r in s["reasons"]}),+ }+ for s in kept+ ),+ key=lambda r: r["name"].casefold(),+ )+++def _change_people(repo_root: str, shas: list[str]) -> set[str]:+ """Lower-cased names and emails of the change's authors and co-authors."""+ from repowise.core.git_refs import _read++ if not shas:+ return set()+ raw = _read(+ repo_root,+ [+ "log",+ "--no-walk=unsorted",+ "--format=%an%x1f%ae%x1f%(trailers:key=Co-authored-by,valueonly,separator=%x1e)%x1d",+ *shas,+ ],+ )+ people: set[str] = set()+ for record in raw.split("\x1d"):+ parts = record.strip().split("\x1f")+ if len(parts) < 2:+ continue+ people.update({parts[0], parts[1]})+ for trailer in (parts[2] if len(parts) > 2 else "").split("\x1e"):+ if m := _CO_AUTHOR.match(trailer):+ people.update(m.groups())+ return {p.strip().lower() for p in people if p and p.strip()}+++def _workspace(+ repo_root: Path, paths: list[str]+) -> tuple[list[dict[str, Any]], list[dict[str, Any]]] | tuple[Unavailable, Unavailable]:+ """Workspace contracts in *paths*, and the other repos consuming them."""+ from repowise.core.workspace.config import WorkspaceConfig, find_workspace_root+ from repowise.core.workspace.contracts import load_contract_store++ none = Unavailable("the repository is not in a workspace with a contract map")+ ws_root = find_workspace_root(repo_root)+ if ws_root is None:+ return none, none+ root = repo_root.resolve()+ config = WorkspaceConfig.load(ws_root)+ alias = next((r.alias for r in config.repos if (ws_root / r.path).resolve() == root), None)+ store = load_contract_store(ws_root)+ if alias is None or store is None:+ return none, none+ touched = set(paths)+ contracts = [+ {+ "path": c.file_path,+ "contract_id": c.contract_id,+ "type": c.contract_type,+ "role": c.role,+ }+ for c in store.contracts+ if c.repo == alias and c.file_path in touched+ ]+ consumers = [+ {+ "repo": lk.consumer_repo,+ "file": lk.consumer_file,+ "contract_id": lk.contract_id,+ "provider_file": lk.provider_file,+ }+ for lk in store.contract_links+ if lk.provider_repo == alias+ and lk.provider_file in touched+ and lk.consumer_repo != alias+ ]+ return contracts, consumers+++async def _decisions(session: Any, repo_id: str, paths: list[str]) -> list[dict[str, Any]]:+ """Decisions linked to a changed file itself; a module link is not a file's."""+ from sqlalchemy import select++ from repowise.core.persistence.crud.authority import accepted_decision_ids+ from repowise.core.persistence.models import DecisionNodeLink, DecisionRecord++ if not paths:+ return []+ rows = (+ await session.execute(+ select(+ DecisionRecord.id,+ DecisionRecord.title,+ DecisionRecord.status,+ DecisionNodeLink.node_id,+ )+ .join(DecisionNodeLink, DecisionNodeLink.decision_id == DecisionRecord.id)+ .where(+ DecisionNodeLink.repository_id == repo_id,+ DecisionNodeLink.link_type == "file",+ DecisionNodeLink.node_id.in_(paths),+ )+ )+ ).all()+ accepted = await accepted_decision_ids(session, repo_id, governing_only=True)+ out: dict[str, dict[str, Any]] = {}+ for did, title, status, node in rows:+ if status in _RETIRED:+ continue+ slot = out.setdefault(+ did,+ {+ "id": did,+ "title": title,+ "authority": "accepted" if did in accepted else "candidate",+ "status": status,+ "paths": [],+ },+ )+ slot["paths"].append(node)+ return sorted(out.values(), key=lambda r: (r["authority"] != "accepted", r["title"]))+++async def _provenance(+ session: Any, repo_id: str, repo_root: Path, shas: list[str], row: Any+) -> dict[str, Any] | Unavailable:+ """Three-state provenance over the change's commits, with one row per commit."""+ from sqlalchemy import select++ from repowise.core.attribution import UNKNOWN, attribution_enabled, commit_label+ from repowise.core.changes.record import provenance_block+ from repowise.core.changes.store import change_provenance+ from repowise.core.persistence.models import GitCommit++ if not attribution_enabled(repo_root):+ return Unavailable("AI attribution is off for this repository")+ if not shas:+ return Unavailable("uncommitted work carries no commit markers")+ stored: dict[str, tuple[str | None, str | None, int | None]] = {}+ for i in range(0, len(shas), 500):+ found = await session.execute(+ select(+ GitCommit.sha,+ GitCommit.attribution,+ GitCommit.agent_name,+ GitCommit.agent_autonomy_tier,+ ).where(GitCommit.repository_id == repo_id, GitCommit.sha.in_(shas[i : i + 500]))+ )+ for sha, attribution, agent, tier in found.tuples():+ stored[sha] = (attribution, agent, tier)+ commits = []+ for sha in shas:+ attribution, agent, tier = stored.get(sha, (None, None, None))+ label = commit_label(attribution, agent) if sha in stored else UNKNOWN+ commits.append({"sha": sha, "label": label, "tier": tier if label == "agent" else None})+ block = None+ if row is not None and row.provenance is not None:+ block = provenance_block(+ row.provenance, row.provenance_agent, row.provenance_known, len(shas)+ )+ if block is None:+ labels = {sha: stored[sha][:2] for sha in stored}+ block = provenance_block(*change_provenance(shas, labels), len(shas))+ if block is None:+ return Unavailable("no attribution was stored for these commits")+ return {**block, "commits": commits}+++def _change_commits(repo_root: str, revspec: str | None, row: Any) -> list[str]:+ """The change's commits: the stored list, else those *revspec* names."""+ from repowise.core.git_refs import _read, split_revspec++ if row is not None:+ try:+ return list(json.loads(row.commit_shas_json or "[]"))+ except (TypeError, ValueError):+ return [row.head_sha]+ if not revspec:+ return []+ parts = split_revspec(revspec)+ span = f"{parts[0]}..{parts[2]}" if parts else f"{revspec}^!"+ return _read(repo_root, ["rev-list", span]).split()+++__all__ = [+ "NO_INDEX",+ "REVIEWER_LIMIT",+ "build_stored_evidence",+ "cached_evidence",+ "change_evidence",+ "evidence_for_revspec",+ "gather_inputs",+ "save_evidence",+ "stored_change_at",+]diff --git a/packages/core/src/repowise/core/changes/evidence.py b/packages/core/src/repowise/core/changes/evidence.pynew file mode 100644index 000000000..be87d77d5--- /dev/null+++ b/packages/core/src/repowise/core/changes/evidence.py@@ -0,0 +1,474 @@+"""The evidence checklist on a Change Record, as versioned JSON.++One :class:`ChangeEvidence` per change: a fixed list of checkable items, each+saying what was found (``value``), whether it needs a reviewer's eye+(``status``) and how it is known (``basis``). The risk score is one item+among them, never the headline.++:func:`build_change_evidence` is the one builder every surface calls. It reads+a :class:`~repowise.core.analysis.change_review.ChangeReviewBundle` (health+delta, tests, contracts, risk) plus the index facts in :class:`EvidenceInputs`+and decides each item's status here, so the CLI, REST, MCP and a PR comment+cannot reach different verdicts from the same facts. Gathering those facts is+:mod:`.collect`'s job; nothing here does IO.++Detail rows a policy reads have fixed keys (the local change policy in+``repowise.core.policy`` evaluates them):++* ``components_touched``: ``{name, source, owner, criticality, tags, files,+ bus_factor}``; ``owner`` is a team name or ``None``, ``bus_factor`` an int+ when measured, else ``None``;+* ``reaching_tests``: one row per changed source file, ``{path, tests, ...}``;+ ``tests`` lists test ids, ``[]`` only for a measured absence, ``None`` when+ nothing knows;+* ``contracts``: ``{path, breaking, ...}``;+* ``provenance``: one row per commit, ``{sha, label, tier}``;+* ``decisions_crossed``: ``{id, title, authority, status, paths}``.+"""++from __future__ import annotations++from collections.abc import Mapping, Sequence+from dataclasses import dataclass, field+from datetime import UTC, datetime+from typing import TYPE_CHECKING, Any, Literal++if TYPE_CHECKING:+ from repowise.core.analysis.change_review import ChangeReviewBundle++#: Bumped when a field is renamed or removed or changes meaning; adding one does not.+EVIDENCE_SCHEMA_VERSION = 1++Status = Literal["ok", "attention", "unknown"]+Basis = Literal["measured", "inferred", "declared", "unresolved"]++#: Every item a record carries, in this order.+KINDS: tuple[str, ...] = (+ "components_touched",+ "owners",+ "suggested_reviewers",+ "reaching_tests",+ "contracts",+ "cross_repo_consumers",+ "decisions_crossed",+ "health_delta",+ "provenance",+ "risk_score",+)+++@dataclass(frozen=True, slots=True)+class EvidenceItem:+ kind: str+ label: str+ status: Status+ basis: Basis+ value: Any = None+ details: list[dict[str, Any]] = field(default_factory=list)+ source: str = ""++ def to_dict(self) -> dict[str, Any]:+ return {+ "kind": self.kind,+ "label": self.label,+ "status": self.status,+ "basis": self.basis,+ "value": self.value,+ "details": list(self.details),+ "source": self.source,+ }++ @classmethod+ def from_dict(cls, data: Mapping[str, Any]) -> EvidenceItem:+ return cls(+ kind=data["kind"],+ label=data["label"],+ status=data["status"],+ basis=data["basis"],+ value=data.get("value"),+ details=list(data.get("details") or []),+ source=data.get("source", ""),+ )+++@dataclass(frozen=True, slots=True)+class ChangeEvidence:+ change_id: str | None+ revspec: str | None+ generated_at: str+ items: list[EvidenceItem]+ schema_version: int = EVIDENCE_SCHEMA_VERSION+ #: The indexed commit the index facts were read at; ``None`` when unknown.+ index_commit: str | None = None++ def item(self, kind: str) -> EvidenceItem | None:+ return next((i for i in self.items if i.kind == kind), None)++ def to_dict(self) -> dict[str, Any]:+ return {+ "schema_version": self.schema_version,+ "change_id": self.change_id,+ "revspec": self.revspec,+ "generated_at": self.generated_at,+ "index_commit": self.index_commit,+ "items": [i.to_dict() for i in self.items],+ }++ @classmethod+ def from_dict(cls, data: Mapping[str, Any]) -> ChangeEvidence:+ return cls(+ schema_version=int(data.get("schema_version", EVIDENCE_SCHEMA_VERSION)),+ change_id=data.get("change_id"),+ revspec=data.get("revspec"),+ generated_at=data["generated_at"],+ index_commit=data.get("index_commit"),+ items=[EvidenceItem.from_dict(i) for i in data.get("items") or []],+ )+++@dataclass(frozen=True, slots=True)+class Unavailable:+ """An input that could not be read, and why. Its item reads ``unknown``."""++ reason: str+++@dataclass(frozen=True, slots=True)+class EvidenceInputs:+ """Index facts the bundle does not carry. ``None`` means nobody gathered it.++ Rows are plain dicts so a surface with its own stores can fill them.+ """++ #: Touched production paths (no tests), used to judge owner and test gaps.+ #: ``None`` takes every manifest path.+ code_paths: Sequence[str] | None = None+ #: ``{name, source, owner, criticality, tags, files, bus_factor}`` per+ #: touched component.+ components: Sequence[Mapping[str, Any]] | Unavailable | None = None+ #: ``{path: [owner, ...]}`` from CODEOWNERS and component owners; a path+ #: with no declared owner is absent. ``owner_sources`` names what was read.+ owners: Mapping[str, Sequence[str]] | Unavailable | None = None+ owner_sources: Sequence[str] = ()+ #: ``{name, paths, reasons}``, by name; no score, count or rank.+ reviewers: Sequence[Mapping[str, Any]] | Unavailable | None = None+ #: ``{path, contract_id, type, role}`` for workspace contracts in touched files.+ contracts: Sequence[Mapping[str, Any]] | Unavailable | None = None+ #: ``{repo, file, contract_id, provider_file}`` for other repos' consumers.+ consumers: Sequence[Mapping[str, Any]] | Unavailable | None = None+ #: ``{id, title, authority, status, path}`` per governing decision crossed.+ decisions: Sequence[Mapping[str, Any]] | Unavailable | None = None+ #: The provenance summary (``label``, counts, ``coverage``) plus+ #: ``commits``: ``[{sha, label, tier}]``.+ provenance: Mapping[str, Any] | Unavailable | None = None+++def _now() -> str:+ return datetime.now(UTC).isoformat(timespec="seconds")+++def _unknown(kind: str, label: str, reason: str, source: str) -> EvidenceItem:+ return EvidenceItem(kind, label, "unknown", "unresolved", None, [{"reason": reason}], source)+++def _missing(value: Any) -> str | None:+ """Why an input reads unknown, or ``None`` when it was gathered."""+ if value is None:+ return "not gathered for this change"+ if isinstance(value, Unavailable):+ return value.reason+ return None+++def build_change_evidence(+ bundle: ChangeReviewBundle,+ inputs: EvidenceInputs | None = None,+ *,+ change_id: str | None,+ revspec: str | None,+ generated_at: str | None = None,+ index_commit: str | None = None,+) -> ChangeEvidence:+ """The checklist for one change, every kind in :data:`KINDS` present."""+ inputs = inputs or EvidenceInputs()+ paths = [e.path for e in bundle.manifest]+ code = list(inputs.code_paths) if inputs.code_paths is not None else paths+ items = [+ _components(inputs),+ _owners(inputs, code),+ _reviewers(inputs),+ _tests(bundle, code),+ _contracts(bundle, inputs),+ _consumers(inputs),+ _decisions(inputs),+ _health(bundle),+ _provenance(inputs),+ _risk(bundle),+ ]+ return ChangeEvidence(+ change_id=change_id,+ revspec=revspec,+ generated_at=generated_at or _now(),+ items=items,+ index_commit=index_commit,+ )+++# -- items -------------------------------------------------------------------+++def _components(inputs: EvidenceInputs) -> EvidenceItem:+ kind, label, source = "components_touched", "Components touched", "components"+ if reason := _missing(inputs.components):+ return _unknown(kind, label, reason, source)+ rows = [dict(r) for r in inputs.components] # type: ignore[union-attr]+ if not rows:+ return _unknown(kind, label, "no component holds the changed files", source)+ declared = any(r.get("source") == "declared" for r in rows)+ return EvidenceItem(+ kind,+ label,+ "ok",+ "declared" if declared else "inferred",+ [r["name"] for r in rows],+ rows,+ source,+ )+++def _owners(inputs: EvidenceInputs, code: list[str]) -> EvidenceItem:+ kind, label = "owners", "Declared owners"+ source = ", ".join(inputs.owner_sources) or "CODEOWNERS, component catalog"+ if reason := _missing(inputs.owners):+ return _unknown(kind, label, reason, source)+ owners: Mapping[str, Sequence[str]] = inputs.owners # type: ignore[assignment]+ if not inputs.owner_sources:+ return _unknown(kind, label, "the repository declares no owners", source)+ by_owner: dict[str, list[str]] = {}+ for path, names in owners.items():+ for name in names:+ by_owner.setdefault(name, []).append(path)+ unowned = sorted(p for p in code if not owners.get(p))+ details = [{"owner": o, "paths": sorted(ps)} for o, ps in sorted(by_owner.items())]+ if unowned:+ details.append({"owner": None, "paths": unowned})+ return EvidenceItem(+ kind,+ label,+ "attention" if unowned else "ok",+ "declared",+ sorted(by_owner),+ details,+ source,+ )+++def _reviewers(inputs: EvidenceInputs) -> EvidenceItem:+ kind, label, source = "suggested_reviewers", "Suggested reviewers", "git history"+ if reason := _missing(inputs.reviewers):+ return _unknown(kind, label, reason, source)+ rows = [dict(r) for r in inputs.reviewers] # type: ignore[union-attr]+ if not rows:+ return _unknown(kind, label, "no one else has history in these files", source)+ return EvidenceItem(kind, label, "ok", "inferred", [r["name"] for r in rows], rows, source)+++def _tests(bundle: ChangeReviewBundle, code: list[str]) -> EvidenceItem:+ kind, label, source = "reaching_tests", "Tests reaching the change", "test impact"+ tests = bundle.tests+ if tests is None:+ return _unknown(kind, label, bundle.lane("tests").reason or "not gathered", source)+ by_basis = tests.get("recommendations_by_primary_basis") or {}+ files = {row["source_file"]: row for row in tests.get("files") or []}+ coverage = tests.get("coverage") or {}+ # An empty answer is a known absence only against a current measured map.+ map_current = bool(coverage.get("map_present")) and (+ (coverage.get("freshness") or {}).get("status") == "current"+ )+ rows: list[dict[str, Any]] = []+ for path in sorted(set(code)):+ row = files.get(path)+ measured = list(row.get("measured_tests") or []) if row else []+ found = sorted(set(measured) | set(row.get("inferred_tests") or [])) if row else []+ if found:+ reach: list[str] | None = found+ elif row is not None and map_current:+ reach = []+ else:+ reach = None+ rows.append(+ {+ "path": path,+ "tests": reach,+ "measured": bool(measured) or reach == [],+ "measured_tests": len(measured),+ "inferred_tests": (row or {}).get("inferred_tests_total", 0),+ }+ )+ absent = sum(r["tests"] == [] for r in rows)+ unknown = sum(r["tests"] is None for r in rows)+ value = {+ "measured": int(by_basis.get("measured", 0)),+ "inferred": int(by_basis.get("inferred", 0)),+ "files_without_tests": absent,+ "files_unknown": unknown,+ }+ if rows and unknown == len(rows):+ return EvidenceItem(kind, label, "unknown", "unresolved", value, rows, source)+ return EvidenceItem(+ kind,+ label,+ "attention" if absent or unknown else "ok",+ "measured" if rows and all(r["measured"] for r in rows) else "inferred",+ value,+ rows,+ source,+ )+++def _contracts(bundle: ChangeReviewBundle, inputs: EvidenceInputs) -> EvidenceItem:+ kind, label, source = "contracts", "Contracts touched", "workspace contracts"+ symbol = bundle.contracts if bundle.lane("contracts").state != "unsupported" else None+ breaking = symbol.breaking if symbol is not None else []+ reason = _missing(inputs.contracts)+ if reason and symbol is None:+ return _unknown(kind, label, reason, source)+ rows = [] if reason else [dict(r) for r in inputs.contracts] # type: ignore[union-attr]+ details = [{**r, "breaking": False} for r in rows] + [+ {"path": c.file, "symbol_id": c.symbol_id, "change": c.change, "breaking": True}+ for c in breaking+ ]+ return EvidenceItem(+ kind,+ label,+ "attention" if rows or breaking else "ok",+ "measured" if symbol is not None and not rows else "inferred",+ {"touched": len(rows), "breaking_symbols": len(breaking) if symbol is not None else None},+ details,+ source if symbol is None else f"{source}, signature diff",+ )+++def _consumers(inputs: EvidenceInputs) -> EvidenceItem:+ kind, label, source = "cross_repo_consumers", "Consumers in other repos", "workspace contracts"+ if reason := _missing(inputs.consumers):+ return _unknown(kind, label, reason, source)+ rows = [dict(r) for r in inputs.consumers] # type: ignore[union-attr]+ repos = sorted({r["repo"] for r in rows if r.get("repo")})+ return EvidenceItem(+ kind,+ label,+ "attention" if rows else "ok",+ "inferred",+ {"repos": repos, "links": len(rows)},+ rows,+ source,+ )+++def _decisions(inputs: EvidenceInputs) -> EvidenceItem:+ kind, label, source = "decisions_crossed", "Decisions crossed", "decision records"+ if reason := _missing(inputs.decisions):+ return _unknown(kind, label, reason, source)+ rows = [dict(r) for r in inputs.decisions] # type: ignore[union-attr]+ accepted = sum(r.get("authority") == "accepted" for r in rows)+ return EvidenceItem(+ kind,+ label,+ "attention" if accepted else "ok",+ "declared" if accepted else ("inferred" if rows else "declared"),+ {"accepted": accepted, "candidate": len(rows) - accepted},+ rows,+ source,+ )+++def _health(bundle: ChangeReviewBundle) -> EvidenceItem:+ kind, label, source = "health_delta", "Health delta", "change health"+ delta = bundle.health+ if delta is None or delta.status not in ("available", "partial"):+ reason = delta.explanation if delta is not None else bundle.lane("health").reason+ return _unknown(kind, label, reason or "not compared", source)+ worse = delta.introduced_total + delta.worsened_total+ details = [+ {+ "change": f.change_kind,+ "dimension": f.dimension,+ "severity": f.severity,+ "path": f.path,+ "symbol": f.symbol,+ "reason": f.reason,+ }+ for f in delta.findings+ ]+ if delta.status == "partial":+ details.append({"note": delta.explanation})+ return EvidenceItem(+ kind,+ label,+ "attention" if worse else "ok",+ "measured",+ {+ "introduced": delta.introduced_total,+ "worsened": delta.worsened_total,+ "resolved": delta.resolved_total,+ "complete": delta.status == "available",+ },+ details,+ source,+ )+++def _provenance(inputs: EvidenceInputs) -> EvidenceItem:+ kind, label, source = "provenance", "AI provenance", "attribution"+ if reason := _missing(inputs.provenance):+ return _unknown(kind, label, reason, source)+ block = dict(inputs.provenance) # type: ignore[arg-type]+ commits = [dict(c) for c in block.pop("commits", None) or []]+ # Unknown is never human: a change with any unattributed commit stays+ # unknown, and an unknown label answers nothing.+ unknown = block["label"] == "unknown"+ return EvidenceItem(+ kind,+ label,+ "unknown" if unknown else "ok",+ "unresolved" if unknown else "measured",+ block,+ commits,+ source,+ )+++def _risk(bundle: ChangeReviewBundle) -> EvidenceItem:+ kind, label, source = "risk_score", "Diff size rank", "change risk"+ risk = bundle.risk+ if risk is None or risk.percentile is None:+ reason = bundle.lane("risk").reason or "not scored"+ return _unknown(kind, label, reason, source)+ # One row, and never "attention": the rank is not calibrated as a defect+ # probability, so it informs a reviewer and decides nothing.+ return EvidenceItem(+ kind,+ label,+ "ok",+ "measured",+ {"percentile": round(risk.percentile, 1)},+ [+ {+ "baseline_sample_size": risk.baseline_sample_size,+ "note": "ranks diff size against recent commits; not a defect probability",+ }+ ],+ source,+ )+++__all__ = [+ "EVIDENCE_SCHEMA_VERSION",+ "KINDS",+ "ChangeEvidence",+ "EvidenceInputs",+ "EvidenceItem",+ "Unavailable",+ "build_change_evidence",+]diff --git a/packages/core/src/repowise/core/persistence/crud/changes.py b/packages/core/src/repowise/core/persistence/crud/changes.pyindex 10049be2a..5a190df9e 100644--- a/packages/core/src/repowise/core/persistence/crud/changes.py+++ b/packages/core/src/repowise/core/persistence/crud/changes.py@@ -3,6 +3,7 @@from __future__ import annotationsfrom collections.abc import Sequence+from datetime import datetimefrom sqlalchemy import delete, func, or_, selectfrom sqlalchemy.ext.asyncio import AsyncSession@@ -54,8 +55,19 @@ 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):+def _filters(+ repository_id: str,+ category: str | None,+ shape: str | None,+ q: str | None,+ since: datetime | None = None,+ until: datetime | None = None,+):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:@@ -79,11 +91,17 @@ async def list_changes(category: str | None = None,shape: str | None = None,q: str | None = None,- limit: int = 50,+ 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."""- clauses = _filters(repository_id, category, shape, q)+ """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)total = (await session.execute(select(func.count()).select_from(Change).where(*clauses))).scalar_one()rows = await session.execute(select(Change)diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.pyindex c1f0d9750..4503c5153 100644--- a/packages/core/src/repowise/core/persistence/models.py+++ b/packages/core/src/repowise/core/persistence/models.py@@ -866,6 +866,8 @@ class Change(Base):approvals: Mapped[int | None] = mapped_column(Integer, nullable=True)labels_json: Mapped[str | None] = mapped_column(Text, nullable=True)linked_issues_json: Mapped[str | None] = mapped_column(Text, nullable=True)+ # Evidence checklist JSON, built on first read and kept until a refresh.+ evidence_json: Mapped[str | None] = mapped_column(Text, nullable=True)created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=_now_utcdiff --git a/packages/server/src/repowise/server/mcp_server/_budget/contracts.py b/packages/server/src/repowise/server/mcp_server/_budget/contracts.pyindex 8db4b1581..0a4342589 100644--- a/packages/server/src/repowise/server/mcp_server/_budget/contracts.py+++ b/packages/server/src/repowise/server/mcp_server/_budget/contracts.py@@ -151,6 +151,7 @@ _CONTRACTS: dict[str, ResponseBudgetContract] = {"impacted_tests","health_delta.skipped","health_delta.top_findings[]",+ "evidence",),protected=("directive",@@ -158,6 +159,8 @@ _CONTRACTS: dict[str, ResponseBudgetContract] = {"classification","risk_percentile",),+ # Present only when asked for, and then it is the answer.+ requested_projections=(("evidence", ("evidence",)),),),"get_answer": ResponseBudgetContract("blocks",diff --git a/packages/server/src/repowise/server/mcp_server/tool_change_risk.py b/packages/server/src/repowise/server/mcp_server/tool_change_risk.pyindex 2a35b7ba5..ce1487111 100644--- a/packages/server/src/repowise/server/mcp_server/tool_change_risk.py+++ b/packages/server/src/repowise/server/mcp_server/tool_change_risk.py@@ -119,7 +119,9 @@ _SHED_ORDER = response_budget_shed_order("get_change_risk")#: Per-field units and calibration. Identical on every call, so it is opt-in.#: ``diagnostics`` carries the raw model mechanics; ``findings`` lifts the#: top-findings cap. Both are projections, recoverable by an exact call.-_INCLUDE_BLOCKS = frozenset({"scales", "diagnostics", "findings"})+#: ``evidence`` adds the change's evidence checklist, the record ``repowise+#: changes show`` and the REST change detail serve.+_INCLUDE_BLOCKS = frozenset({"scales", "diagnostics", "findings", "evidence"})#: Score mechanics that are identical or near-identical on every call. Moved#: behind ``include=["diagnostics"]`` so the action-first blocks lead.@@ -351,8 +353,8 @@ async def get_change_risk(include_paths: Gitignore-style paths to keep, as a list or onecomma-separated string, e.g. ``"src/api/,src/db/"``. Omit for all.baseline: Recent commits sampled for percentile ranking; 0 disables it.- include: ``"findings"``, ``"diagnostics"`` (raw mechanics) or- ``"scales"`` (units, size tercile).+ include: ``"findings"``, ``"diagnostics"`` (raw mechanics),+ ``"scales"`` (units, tercile) or ``"evidence"`` (checklist).finding_id: Expand one ``health_delta`` finding by its id."""if repo == "all":@@ -425,6 +427,16 @@ async def get_change_risk(expand="findings" in include_set,diagnostics="diagnostics" in include_set,)+ if "evidence" in include_set:+ payload["evidence"] = await _evidence_block(+ ctx,+ revspec,+ result,+ delta,+ tuple(extensions or ()),+ tuple(result.riskignore_excludes + result.request_excludes),+ scoped=bool(extensions or exclude_patterns or includes or baseline != 200),+ )# source: live_git marks that the *score* is computed from the working# checkout's git. The two blocks above are index-backed, so the freshness# fields do apply to them, scoped to the change's files. None (not []) when@@ -441,6 +453,58 @@ async def get_change_risk(return payload+async def _evidence_block(+ ctx: Any,+ revspec: str | None,+ result: Any,+ delta: Any,+ extensions: tuple[str, ...],+ exclude_patterns: tuple[str, ...],+ *,+ scoped: bool,+) -> dict[str, Any]:+ """The change's evidence checklist, reusing the score and delta already computed.++ A revspec naming a stored change, asked with no filters of the caller's+ own, returns that change's kept record (building and keeping it when+ there is none), so this and ``repowise changes show`` serve the same one.+ """+ from repowise.core.changes.collect import (+ NO_INDEX,+ change_evidence,+ evidence_for_revspec,+ stored_change_at,+ )+ from repowise.core.persistence.database import get_session++ kwargs: dict[str, Any] = {+ "risk": result,+ "health": delta,+ "extensions": extensions,+ "exclude_patterns": exclude_patterns,+ }+ no_index = NO_INDEX+ session_factory = getattr(ctx, "session_factory", None)+ if session_factory is not None:+ try:+ async with get_session(session_factory) as session:+ repo = await _get_repo(session)+ row = await stored_change_at(session, repo.id, ctx.path, revspec)+ if row is not None and not scoped and not result.riskignore_excludes:+ evidence = await change_evidence(+ session, repo.id, ctx.path, row, risk=result, health=delta+ )+ else:+ evidence = await evidence_for_revspec(+ session, repo.id, ctx.path, revspec, row=row, **kwargs+ )+ return evidence.to_dict()+ except (LookupError, SQLAlchemyError) as exc:+ no_index = f"the index could not be read: {type(exc).__name__}: {exc}"+ evidence = await evidence_for_revspec(None, "", ctx.path, revspec, no_index=no_index, **kwargs)+ return evidence.to_dict()++#: One service per repository, so its comparison cache and stampede guard#: outlive a single call. LRU-bounded: a long-lived server can see many#: worktrees and workspace members over its lifetime.diff --git a/packages/server/src/repowise/server/routers/changes.py b/packages/server/src/repowise/server/routers/changes.pyindex 6cc2420ab..6acb07c08 100644--- a/packages/server/src/repowise/server/routers/changes.py+++ b/packages/server/src/repowise/server/routers/changes.py@@ -2,13 +2,19 @@from __future__ import annotations-from fastapi import APIRouter, Depends, HTTPException, Query+import asyncio+from typing import Any++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.evidence import ChangeEvidencefrom repowise.core.changes.record import change_recordfrom repowise.core.persistence import crud-from repowise.server.deps import get_db_session, verify_api_key+from repowise.core.persistence.database import get_session+from repowise.server.deps import get_db_session, resolve_request_session_factory, verify_api_keyfrom repowise.server.schemas.changes import (ChangeListResponse,ChangeRecord,@@ -23,6 +29,13 @@ router = APIRouter(_MAX_PAGE = 200+#: How long a request waits on a checklist build before answering without it+#: (``evidence_building``); the build carries on and keeps its result.+EVIDENCE_WAIT_SECONDS = 15.0++#: One build per change at a time, shared by every request that asks.+_BUILDS: dict[tuple[str, str], asyncio.Task[ChangeEvidence]] = {}+async def _attribution(session: AsyncSession, repo_id: str) -> bool:repo = await crud.get_repository(session, repo_id)@@ -57,8 +70,13 @@ async def list_changes(@router.get("/{repo_id}/changes/{change_id}", response_model=ChangeRecord)async def get_change(+ request: Request,repo_id: str,change_id: str,+ evidence: bool = Query(+ False, description="Include the evidence checklist (built on first read, then kept)"+ ),+ refresh: bool = Query(False, description="Rebuild the evidence checklist"),session: AsyncSession = Depends(get_db_session),) -> ChangeRecord:"""One change by id (``pr-123``), or the change that landed a commit sha."""@@ -67,4 +85,37 @@ async def get_change(if row is None:raise HTTPException(status_code=404, detail="Change not found")record = change_record(row, attribution=attribution)+ if evidence:+ kept = None if refresh else cached_evidence(row)+ if kept is None:+ repo = await crud.get_repository(session, repo_id)+ factory = resolve_request_session_factory(request)+ task = _build(factory, repo_id, row.change_id, repo.local_path)+ try:+ kept = await asyncio.wait_for(asyncio.shield(task), EVIDENCE_WAIT_SECONDS)+ except TimeoutError:+ record["evidence_building"] = True+ if kept is not None:+ record["evidence"] = kept.to_dict()return ChangeRecord(**record, commit_count=len(record["commits"]))+++def _build(factory: Any, repo_id: str, change_id: str, root: str) -> asyncio.Task[ChangeEvidence]:+ """The running build for this change, or a new one; a finished build leaves the map."""+ key = (repo_id, change_id)+ task = _BUILDS.get(key)+ if task is None:+ task = asyncio.create_task(_build_and_keep(factory, repo_id, change_id, root))+ _BUILDS[key] = task+ task.add_done_callback(lambda _t: _BUILDS.pop(key, None))+ return task+++async def _build_and_keep(factory: Any, repo_id: str, change_id: str, root: str) -> ChangeEvidence:+ """Build outside any write, then keep the result in a short transaction of its own."""+ async with get_session(factory) as session:+ row = await crud.get_change(session, repo_id, change_id)+ evidence = await build_stored_evidence(session, repo_id, root, row)+ async with get_session(factory) as session:+ await save_evidence(session, repo_id, change_id, evidence)+ return evidencediff --git a/packages/server/src/repowise/server/schemas/changes.py b/packages/server/src/repowise/server/schemas/changes.pyindex 6d968589a..14e987f9d 100644--- a/packages/server/src/repowise/server/schemas/changes.py+++ b/packages/server/src/repowise/server/schemas/changes.py@@ -7,6 +7,8 @@ commit lists and carries their counts.from __future__ import annotations+from typing import Any, Literal+from pydantic import BaseModel@@ -68,10 +70,37 @@ class ChangeSummary(BaseModel):provenance: ChangeProvenance | None = None+class EvidenceItem(BaseModel):+ """One checklist row: what was found, whether it needs a look, how it is known."""++ kind: str+ label: str+ status: Literal["ok", "attention", "unknown"]+ basis: Literal["measured", "inferred", "declared", "unresolved"]+ value: Any = None+ details: list[dict[str, Any]]+ source: str+++class ChangeEvidence(BaseModel):+ """The evidence checklist (``repowise.core.changes.evidence``), versioned."""++ schema_version: int+ change_id: str | None = None+ revspec: str | None = None+ generated_at: str+ index_commit: str | None = None+ items: list[EvidenceItem]++class ChangeRecord(ChangeSummary):commits: list[str]files: list[ChangeFile]metadata: ChangeForgeMetadata+ # Present only when the request asked for it (``?evidence=true``).+ evidence: ChangeEvidence | None = None+ # True when the checklist is still being built; ask again shortly.+ evidence_building: bool = Falseclass ChangeListResponse(BaseModel):diff --git a/packages/types/src/changes.ts b/packages/types/src/changes.tsindex 2cccc9063..b13bb0a3d 100644--- a/packages/types/src/changes.ts+++ b/packages/types/src/changes.ts@@ -6,9 +6,15 @@* (`packages/server/src/repowise/server/schemas/changes.py`), so the wire* shape cannot drift. `provenance` is null while AI attribution is off for* the repository; forge metadata fields are null when unknown, never empty.+ *+ * `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+ * risk score is one item, never the headline.*/export type {ChangeAuthor,+ ChangeEvidence,ChangeFile,ChangeForgeMetadata,ChangeIdentity,@@ -16,4 +22,23 @@ export type {ChangeProvenance,ChangeRecord,ChangeSummary,+ EvidenceItem,} from "./generated/http.js";++/** Bumped when an evidence field is renamed or removed or changes meaning. */+export const EVIDENCE_SCHEMA_VERSION = 1;++/** Every item a checklist carries, in order. */+export const EVIDENCE_KINDS = [+ "components_touched",+ "owners",+ "suggested_reviewers",+ "reaching_tests",+ "contracts",+ "cross_repo_consumers",+ "decisions_crossed",+ "health_delta",+ "provenance",+ "risk_score",+] as const;+export type EvidenceKind = (typeof EVIDENCE_KINDS)[number];diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.tsindex f277ece58..f76900619 100644--- a/packages/types/src/generated/http.ts+++ b/packages/types/src/generated/http.ts@@ -380,6 +380,16 @@ export interface ChangeAuthor {email: string;}+/** The evidence checklist (``repowise.core.changes.evidence``), versioned. */+export interface ChangeEvidence {+ schema_version: number;+ change_id?: string | null;+ revspec?: string | null;+ generated_at: string;+ index_commit?: string | null;+ items: EvidenceItem[];+}+/** The Kamei change-shape features the risk model scores. */export interface ChangeFeaturesResponse {la: number;@@ -449,6 +459,8 @@ export interface ChangeRecord {commits: string[];files: ChangeFile[];metadata: ChangeForgeMetadata;+ evidence?: ChangeEvidence | null;+ evidence_building?: boolean;}export interface ChangeSummary {@@ -1557,6 +1569,17 @@ export interface EpisodeSummary {still_true?: string | null;}+/** One checklist row: what was found, whether it needs a look, how it is known. */+export interface EvidenceItem {+ kind: string;+ label: string;+ status: "ok" | "attention" | "unknown";+ basis: "measured" | "inferred" | "declared" | "unresolved";+ value?: unknown;+ details: Record<string, unknown>[];+ source: string;+}+/** The top-ranked evidence row, slimmed for list rows. */export interface EvidencePreview {source: string;diff --git a/packages/web/messages/en.json b/packages/web/messages/en.jsonindex c790a9a9d..37f63e0c3 100644--- a/packages/web/messages/en.json+++ b/packages/web/messages/en.json@@ -273,7 +273,15 @@"coverage": "coverage {pct}%","back": "All changes","shape": "Shape",- "head": "Head"+ "head": "Head",+ "detailEvidence": "Evidence checklist",+ "evidenceLoading": "Building the evidence checklist. The first view of a change takes a few seconds.",+ "evidenceUnavailable": "The evidence checklist could not be built for this change.",+ "evidenceBuilding": "The evidence checklist is still being built. Reload the page in a moment.",+ "evidenceGenerated": "Generated {date}",+ "statusOk": "ok",+ "statusAttention": "attention",+ "statusUnknown": "unknown"},"architecture": {"tabs": {diff --git a/packages/web/messages/zh-CN.json b/packages/web/messages/zh-CN.jsonindex 49635e10c..fccb3e73b 100644--- a/packages/web/messages/zh-CN.json+++ b/packages/web/messages/zh-CN.json@@ -273,7 +273,15 @@"coverage": "覆盖率 {pct}%","back": "全部变更","shape": "形式",- "head": "头部提交"+ "head": "头部提交",+ "detailEvidence": "证据清单",+ "evidenceLoading": "正在生成证据清单。首次查看一个变更需要几秒钟。",+ "evidenceUnavailable": "无法为此变更生成证据清单。",+ "evidenceBuilding": "证据清单仍在生成中,请稍后重新加载页面。",+ "evidenceGenerated": "生成于 {date}",+ "statusOk": "正常",+ "statusAttention": "需关注",+ "statusUnknown": "未知"},"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 127ae2515..b6b7e54fa 100644--- a/packages/web/src/app/repos/[id]/changes/[changeId]/page.tsx+++ b/packages/web/src/app/repos/[id]/changes/[changeId]/page.tsx@@ -1,4 +1,5 @@import type { Metadata } from "next";+import { Suspense } from "react";import Link from "next/link";import { notFound } from "next/navigation";import { GitPullRequest } from "lucide-react";@@ -6,6 +7,8 @@ import { getTranslations } from "next-intl/server";import { PageShell } from "@repowise-dev/ui/shared/page-shell";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 { getChange } from "@/lib/api/changes";@@ -23,6 +26,68 @@ export async function generateMetadata({ params }: Props): Promise<Metadata> {}}+const STATUS_VARIANT = { ok: "fresh", attention: "stale", unknown: "outline" } as const;+const STATUS_KEY = { ok: "statusOk", attention: "statusAttention", unknown: "statusUnknown" } as const;++/** An item's value in one line; an unknown one shows why. */+function valueText(item: EvidenceItem): string {+ const value = item.value;+ if (value == null) {+ const reason = item.details.find((d) => typeof d.reason === "string")?.reason;+ return typeof reason === "string" ? reason : "";+ }+ if (Array.isArray(value)) return value.join(", ");+ if (typeof value === "object") {+ return Object.entries(value as Record<string, unknown>)+ .filter(([, v]) => v != null && !(Array.isArray(v) && v.length === 0))+ .map(([k, v]) => `${k.replaceAll("_", " ")} ${Array.isArray(v) ? v.join(", ") : String(v)}`)+ .join(" · ");+ }+ return String(value);+}++/** The evidence checklist, streamed in: the first read of a change builds it. */+async function EvidenceChecklist({ repoId, changeId }: { repoId: string; changeId: string }) {+ const t = await getTranslations("views.changes");+ let evidence;+ let building = false;+ try {+ const change = await getChange(repoId, changeId, { evidence: true });+ evidence = change.evidence;+ building = change.evidence_building ?? false;+ } catch {+ evidence = null;+ }+ if (!evidence) {+ return (+ <p className="text-xs text-[var(--color-text-tertiary)]">+ {t(building ? "evidenceBuilding" : "evidenceUnavailable")}+ </p>+ );+ }+ return (+ <>+ <ul className="divide-y divide-[var(--color-border-default)] text-xs">+ {evidence.items.map((item) => (+ <li key={item.kind} className="flex flex-wrap items-baseline gap-x-3 gap-y-1 py-2">+ <span className="w-48 shrink-0 font-medium text-[var(--color-text-primary)]">+ {item.label}+ </span>+ <Badge variant={STATUS_VARIANT[item.status]}>{t(STATUS_KEY[item.status])}</Badge>+ <span className="text-[var(--color-text-tertiary)]">{item.basis}</span>+ <span className="min-w-0 flex-1 break-words text-[var(--color-text-secondary)]">+ {valueText(item)}+ </span>+ </li>+ ))}+ </ul>+ <p className="mt-2 text-xs text-[var(--color-text-tertiary)]">+ {t("evidenceGenerated", { date: formatDate(evidence.generated_at) })}+ </p>+ </>+ );+}+/** One Change Record: what landed, from which commits, with what provenance. */export default async function ChangeDetailPage({ params }: Props) {const { id, changeId } = await params;@@ -71,6 +136,16 @@ export default async function ChangeDetailPage({ params }: Props) {))}</dl>+ <OverviewSection title={t("detailEvidence")}>+ <Suspense+ fallback={+ <p className="text-xs text-[var(--color-text-tertiary)]">{t("evidenceLoading")}</p>+ }+ >+ <EvidenceChecklist repoId={id} changeId={decodeURIComponent(changeId)} />+ </Suspense>+ </OverviewSection>+<OverviewSection title={`${t("detailFiles")} (${change.files_changed})`}><ul className="space-y-1 font-mono text-xs">{change.files.map((f) => (diff --git a/tests/unit/cli/test_changes_cmd.py b/tests/unit/cli/test_changes_cmd.pyindex 97151a942..6ab702cd6 100644--- a/tests/unit/cli/test_changes_cmd.py+++ b/tests/unit/cli/test_changes_cmd.py@@ -101,3 +101,73 @@ def test_no_index_exits_non_zero(tmp_path):(root / ".git").mkdir(parents=True)result = CliRunner().invoke(changes_group, ["list", "--path", str(root)])assert result.exit_code == 1 and "No index" in result.output+++def _fake_evidence(monkeypatch):+ """Stand in for the review: these tests are about the command, not the evidence."""+ from repowise.core.changes import collect+ from repowise.core.changes.evidence import ChangeEvidence, EvidenceItem++ calls: list[str] = []++ async def _evidence(session, repo_id, root, row, *, refresh=False):+ calls.append(row.change_id)+ return ChangeEvidence(+ change_id=row.change_id,+ revspec=row.head_sha,+ generated_at="2026-10-14T00:00:00+00:00",+ items=[+ EvidenceItem("owners", "Declared owners", "attention", "declared", ["@core"], [], "CODEOWNERS"),+ EvidenceItem("risk_score", "Diff size rank", "ok", "measured", {"percentile": 40.0}, [], "change risk"),+ ],+ )++ monkeypatch.setattr(collect, "change_evidence", _evidence)+ return calls+++def test_show_carries_the_checklist_unless_asked_not_to(tmp_path, monkeypatch):+ root = _repo(tmp_path)+ calls = _fake_evidence(monkeypatch)+ runner = CliRunner()++ shown = json.loads(+ runner.invoke(changes_group, ["show", "pr-5", "--path", str(root), "--format", "json"]).output+ )+ assert shown["evidence"]["schema_version"] == 1+ assert [i["kind"] for i in shown["evidence"]["items"]] == ["owners", "risk_score"]++ table = runner.invoke(changes_group, ["show", "pr-5", "--path", str(root)])+ assert table.exit_code == 0 and "Evidence checklist" in table.output and "attention" in table.output++ bare = json.loads(+ runner.invoke(+ changes_group, ["show", "pr-5", "--path", str(root), "--format", "json", "--no-evidence"]+ ).output+ )+ assert "evidence" not in bare and calls == ["pr-5", "pr-5"]+++def test_export_windows_and_formats(tmp_path, monkeypatch):+ root = _repo(tmp_path)+ _fake_evidence(monkeypatch)+ runner = CliRunner(mix_stderr=False)++ inside = runner.invoke(+ changes_group,+ ["export", "--path", str(root), "--since", "2026-02-01", "--until", "2026-04-01"],+ )+ assert inside.exit_code == 0, inside.output+ records = [json.loads(line) for line in inside.stdout.splitlines()]+ assert "evidence 1/1: pr-5" in inside.stderr+ assert [c["id"] for c in records] == ["pr-5"]+ assert records[0]["evidence"]["items"][0]["kind"] == "owners"++ outside = runner.invoke(changes_group, ["export", "--path", str(root), "--since", "2026-03-02"])+ assert outside.exit_code == 0 and outside.stdout == ""++ csv_out = runner.invoke(changes_group, ["export", "--path", str(root), "--format", "csv"])+ lines = csv_out.stdout.strip().splitlines()+ 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) == 3diff --git a/tests/unit/core/test_change_evidence.py b/tests/unit/core/test_change_evidence.pynew file mode 100644index 000000000..aea704d74--- /dev/null+++ b/tests/unit/core/test_change_evidence.py@@ -0,0 +1,546 @@+"""The evidence checklist on a Change Record: the builder, the gather and the cache."""++from __future__ import annotations++import json+import os+import subprocess+from datetime import UTC, datetime+from pathlib import Path+from types import SimpleNamespace++import pytest++from repowise.core import attribution+from repowise.core.analysis.change_health.models import ChangeFinding, ChangeHealthDelta+from repowise.core.analysis.change_review import (+ LANES,+ ChangeManifestEntry,+ ChangeReviewBundle,+ ChangeReviewRequest,+ LaneState,+)+from repowise.core.analysis.review_directive import ReviewDirective+from repowise.core.changes.evidence import (+ EVIDENCE_SCHEMA_VERSION,+ KINDS,+ ChangeEvidence,+ EvidenceInputs,+ Unavailable,+ build_change_evidence,+)+++def _entry(path: str) -> ChangeManifestEntry:+ return ChangeManifestEntry(+ path=path, base_path=path, head_path=path, status="modified", diff_reliability="parsed"+ )+++def _finding(kind: str = "introduced") -> ChangeFinding:+ return ChangeFinding(+ change_finding_id="cf1",+ change_kind=kind,+ dimension="maintainability",+ biomarker_type="long_function",+ severity="medium",+ path="src/a.py",+ symbol="run",+ line_start=1,+ line_end=40,+ reason="run grew to 40 lines",+ attribution_basis="changed_lines",+ attribution_confidence="high",+ attribution_detail="",+ suggestion="",+ follow_up="",+ )+++def _tests(files: dict[str, str], *, map_current: bool = False) -> dict:+ """A test-impact result: per file ``inferred``, ``measured`` or ``unknown`` (none found)."""+ rows = []+ for p, s in files.items():+ stem = p.rsplit("/", 1)[-1]+ rows.append(+ {+ "source_file": p,+ "status": s,+ "measured_tests": [f"tests/test_{stem}::t"] if s == "measured" else [],+ "inferred_tests": [f"tests/test_{stem}"] if s == "inferred" else [],+ "inferred_tests_total": 1 if s == "inferred" else 0,+ }+ )+ return {+ "recommendations_by_primary_basis": {+ "measured": sum(s == "measured" for s in files.values()),+ "inferred": sum(s == "inferred" for s in files.values()),+ },+ "files": rows,+ "coverage": {+ "map_present": map_current,+ "freshness": {"status": "current" if map_current else "unknown"},+ },+ }+++def _bundle(paths: list[str], *, health=None, tests=None, risk=None) -> ChangeReviewBundle:+ lanes = {name: LaneState("unsupported", "not gathered") for name in LANES}+ return ChangeReviewBundle(+ request=ChangeReviewRequest(revspec="abc"),+ base=None,+ head=None,+ manifest=tuple(_entry(p) for p in paths),+ directive=ReviewDirective(status="unknown", headline="x", evidence_state="unavailable"),+ lanes=lanes,+ risk=risk,+ health=health,+ tests=tests,+ )+++def _delta(findings: list[ChangeFinding]) -> ChangeHealthDelta:+ return ChangeHealthDelta(+ status="available",+ explanation="",+ base=None,+ head=None,+ comparison_basis="commit",+ fingerprint=None,+ findings=findings,+ )+++def test_every_kind_is_present_in_order_and_round_trips():+ evidence = build_change_evidence(_bundle(["src/a.py"]), change_id="pr-1", revspec="abc")+ assert [i.kind for i in evidence.items] == list(KINDS)+ data = evidence.to_dict()+ assert data["schema_version"] == EVIDENCE_SCHEMA_VERSION == 1+ assert set(data) >= {"schema_version", "change_id", "revspec", "generated_at", "items"}+ assert set(data["items"][0]) == {+ "kind",+ "label",+ "status",+ "basis",+ "value",+ "details",+ "source",+ }+ assert ChangeEvidence.from_dict(json.loads(json.dumps(data))).to_dict() == data+ # Nothing gathered: every item says so rather than reading as clear.+ assert all(i.status == "unknown" and i.basis == "unresolved" for i in evidence.items)+++def test_statuses_follow_the_facts():+ paths = ["src/a.py", "src/b.py", "tests/test_a.py"]+ bundle = _bundle(+ paths,+ health=_delta([_finding()]),+ tests=_tests({"src/a.py": "inferred", "src/b.py": "unknown", "tests/test_a.py": "unknown"}),+ risk=SimpleNamespace(percentile=97.5, baseline_sample_size=200),+ )+ inputs = EvidenceInputs(+ code_paths=["src/a.py", "src/b.py"],+ components=[+ {+ "name": "core",+ "source": "declared",+ "owner": "team-core",+ "criticality": "high",+ "tags": ["pci"],+ "files": ["src/a.py"],+ "bus_factor": 1,+ }+ ],+ owners={"src/a.py": ["@team-core"]},+ owner_sources=["CODEOWNERS"],+ reviewers=[{"name": "Bob", "paths": ["src/a.py"], "reasons": ["owns path"]}],+ contracts=[],+ consumers=[{"repo": "web", "file": "x.ts", "contract_id": "http::GET::/a", "provider_file": "src/a.py"}],+ decisions=[{"id": "d1", "title": "Keep a pure", "authority": "accepted", "paths": ["src/a.py"]}],+ provenance={+ "label": "agent",+ "coverage": 1.0,+ "agent_commits": 1,+ "commits": [{"sha": "abc", "label": "agent", "tier": 2}],+ },+ )+ evidence = build_change_evidence(bundle, inputs, change_id="pr-1", revspec="abc")+ by = {i.kind: i for i in evidence.items}++ assert by["components_touched"].basis == "declared" and by["components_touched"].value == ["core"]+ # src/b.py is code with no declared owner; the test file does not count.+ assert by["owners"].status == "attention"+ assert by["owners"].details[-1] == {"owner": None, "paths": ["src/b.py"]}+ assert by["suggested_reviewers"].value == ["Bob"] and "score" not in by["suggested_reviewers"].details[0]+ tests = by["reaching_tests"]+ assert tests.status == "attention" and tests.basis == "inferred"+ assert tests.value == {+ "measured": 0,+ "inferred": 1,+ "files_without_tests": 0,+ "files_unknown": 1,+ }+ # No current measured map: an empty answer is "nobody knows", not absence.+ assert [(r["path"], r["tests"]) for r in tests.details] == [+ ("src/a.py", ["tests/test_a.py"]),+ ("src/b.py", None),+ ]+ assert by["cross_repo_consumers"].status == "attention"+ assert by["cross_repo_consumers"].value == {"repos": ["web"], "links": 1}+ assert by["decisions_crossed"].status == "attention"+ assert by["health_delta"].status == "attention" and by["health_delta"].value["introduced"] == 1+ assert by["provenance"].status == "ok" and by["provenance"].value["label"] == "agent"+ assert by["provenance"].details == [{"sha": "abc", "label": "agent", "tier": 2}]+ # A high diff-size rank is one row and never a verdict.+ assert by["risk_score"].status == "ok" and by["risk_score"].value == {"percentile": 97.5}+++def test_unknown_provenance_stays_unknown_and_unavailable_inputs_name_why():+ inputs = EvidenceInputs(+ owners=Unavailable("could not be read: OSError"),+ provenance={"label": "unknown", "coverage": 0.0},+ decisions=[{"id": "d", "title": "t", "authority": "candidate", "paths": ["a.py"]}],+ )+ evidence = build_change_evidence(_bundle(["a.py"]), inputs, change_id=None, revspec=None)+ by = {i.kind: i for i in evidence.items}+ assert by["provenance"].status == "unknown" and by["provenance"].basis == "unresolved"+ assert by["owners"].details == [{"reason": "could not be read: OSError"}]+ # Only a candidate: listed, but nothing anyone has signed.+ assert by["decisions_crossed"].status == "ok" and by["decisions_crossed"].basis == "inferred"+++def test_reaching_tests_absence_is_known_only_against_a_current_map():+ bundle = _bundle(+ ["src/a.py", "src/b.py", "src/c.py"],+ tests=_tests({"src/a.py": "measured", "src/b.py": "unknown"}, map_current=True),+ )+ evidence = build_change_evidence(bundle, change_id=None, revspec=None)+ tests = {i.kind: i for i in evidence.items}["reaching_tests"]+ by_path = {r["path"]: r["tests"] for r in tests.details}+ assert by_path == {"src/a.py": ["tests/test_a.py::t"], "src/b.py": [], "src/c.py": None}+ # c.py is missing from the result: unknown, so the item is neither measured nor ok.+ assert tests.status == "attention" and tests.basis == "inferred"+++def _full_inputs() -> EvidenceInputs:+ return EvidenceInputs(+ code_paths=["src/a.py"],+ components=[+ {+ "name": "core",+ "source": "declared",+ "owner": "team-core",+ "criticality": "high",+ "tags": ["pci"],+ "files": ["src/a.py"],+ "bus_factor": None,+ }+ ],+ owners={"src/a.py": ["@team-core"]},+ owner_sources=["CODEOWNERS"],+ reviewers=[{"name": "Bob", "paths": ["src/a.py"], "reasons": ["co-change", "owns path"]}],+ contracts=[+ {"path": "src/a.py", "contract_id": "http::GET::/a", "type": "http", "role": "provider"}+ ],+ consumers=[],+ decisions=[+ {"id": "d1", "title": "t", "authority": "accepted", "status": "active", "paths": ["src/a.py"]}+ ],+ provenance={+ "label": "agent",+ "coverage": 1.0,+ "commits": [{"sha": "s1", "label": "agent", "tier": None}],+ },+ )+++def test_detail_rows_keep_the_policy_contract():+ """The row keys and types the local change policy reads, kind by kind."""+ from repowise.core.analysis.change_contracts import ContractImpact, SymbolContractChange++ impact = ContractImpact(+ changes=[+ SymbolContractChange(+ file="src/a.py",+ name="run",+ symbol_id="src/a.py::run",+ kind="function",+ change="signature",+ start_line=1,+ end_line=3,+ outside_production_callers=["src/b.py::use"],+ )+ ]+ )+ base = _bundle(["src/a.py"], tests=_tests({"src/a.py": "inferred"}))+ bundle = ChangeReviewBundle(+ request=base.request,+ base=None,+ head=None,+ manifest=base.manifest,+ directive=base.directive,+ lanes={**base.lanes, "contracts": LaneState("available")},+ tests=base.tests,+ contracts=impact,+ )+ items = build_change_evidence(bundle, _full_inputs(), change_id="c", revspec="r").items+ by = {i.kind: i for i in items}++ for row in by["components_touched"].details:+ assert {"name", "criticality", "tags", "owner", "files", "bus_factor"} <= set(row)+ assert row["owner"] is None or isinstance(row["owner"], str)+ assert row["bus_factor"] is None or isinstance(row["bus_factor"], int)+ assert isinstance(row["tags"], list) and isinstance(row["files"], list)+ for row in by["reaching_tests"].details:+ assert isinstance(row["path"], str)+ assert row["tests"] is None or all(isinstance(t, str) for t in row["tests"])+ contracts = by["contracts"].details+ assert contracts and all(+ isinstance(r["path"], str) and isinstance(r["breaking"], bool) for r in contracts+ )+ assert [r["breaking"] for r in contracts] == [False, True]+ for row in by["provenance"].details:+ assert set(row) == {"sha", "label", "tier"}+ assert row["label"] in ("agent", "human_attested", "unknown")+ assert row["tier"] is None or row["tier"] in (1, 2, 3)+ assert isinstance(by["provenance"].value, dict) and by["provenance"].value["label"] == "agent"+ for row in by["decisions_crossed"].details:+ assert {"id", "title", "paths"} <= set(row) and isinstance(row["paths"], list)+ for row in by["suggested_reviewers"].details:+ assert set(row) == {"name", "paths", "reasons"}+ assert set(row["reasons"]) <= {"owns path", "recent change", "co-change"}+++def test_the_policy_evaluator_reads_the_built_record():+ """A record from the builder drives ``repowise check`` rules end to end."""+ from repowise.core.policy import evaluate, parse_policy++ policy = parse_policy(+ """\+rules:+ - name: agent-pci-needs-owner+ match:+ components: {tags: [pci]}+ when:+ attribution: agent+ reaching_tests: missing+ action: require_owner_review+ - name: no-contract-break+ when:+ contract_break: true+ action: warn+ - name: decision+ when:+ decision_crossed: true+ action: warn+"""+ )+ inputs = _full_inputs()+ bundle = _bundle(+ ["src/a.py"], tests=_tests({"src/a.py": "unknown"}, map_current=True)+ )+ record = build_change_evidence(bundle, inputs, change_id="c", revspec="r").to_dict()+ results = {r.rule.name: r for r in evaluate(policy, json.loads(json.dumps(record)))}+ owner = results["agent-pci-needs-owner"]+ assert owner.outcome == "triggered" and owner.owners == ["team-core"]+ # The contract row is a touched contract, not a break.+ assert results["no-contract-break"].outcome == "passed"+ assert results["decision"].outcome == "triggered"+++async def test_an_older_store_gains_evidence_json_on_init_db(tmp_path):+ """A local SQLite index from before the column gets it from the startup reconcile."""+ import sqlite3++ from repowise.core.persistence import create_engine, init_db++ db = tmp_path / "wiki.db"+ engine = create_engine(f"sqlite+aiosqlite:///{db.as_posix()}")+ try:+ await init_db(engine)+ finally:+ await engine.dispose()+ with sqlite3.connect(db) as conn:+ conn.execute("ALTER TABLE changes DROP COLUMN evidence_json")+ assert "evidence_json" not in {r[1] for r in conn.execute("PRAGMA table_info(changes)")}+ engine = create_engine(f"sqlite+aiosqlite:///{db.as_posix()}")+ try:+ await init_db(engine)+ finally:+ await engine.dispose()+ with sqlite3.connect(db) as conn:+ assert "evidence_json" in {r[1] for r in conn.execute("PRAGMA table_info(changes)")}+++# ---------------------------------------------------------------------------+# Gather and cache over a real repository and index+# ---------------------------------------------------------------------------+++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 _git(root: Path, *args: str) -> str:+ env = {+ **os.environ,+ "GIT_AUTHOR_NAME": "Ann",+ "GIT_AUTHOR_EMAIL": "[email protected]",+ "GIT_COMMITTER_NAME": "Ann",+ "GIT_COMMITTER_EMAIL": "[email protected]",+ }+ return subprocess.run(+ ["git", *args], cwd=root, env=env, check=True, capture_output=True, text=True+ ).stdout.strip()+++def repo(tmp_path: Path) -> tuple[Path, str]:+ root = tmp_path / "repo"+ root.mkdir()+ _git(root, "init", "-q", "-b", "main")+ _git(root, "config", "commit.gpgsign", "false")+ (root / "CODEOWNERS").write_text("src/core/ @team-core\n", encoding="utf-8")+ (root / "src" / "core").mkdir(parents=True)+ (root / "src" / "core" / "a.py").write_text("def a():\n return 1\n", encoding="utf-8")+ _git(root, "add", ".")+ _git(root, "commit", "-q", "-m", "chore: seed")+ (root / "src" / "core" / "a.py").write_text("def a():\n return 2\n", encoding="utf-8")+ (root / "src" / "web.py").write_text("def w():\n return 3\n", encoding="utf-8")+ _git(root, "add", ".")+ _git(+ root,+ "commit",+ "-q",+ "-m",+ "feat: a and web (#7)\n\nCo-authored-by: Carol <[email protected]>",+ )+ return root, _git(root, "rev-parse", "HEAD")+++async def _index(tmp_path: Path, root: Path, head: str):+ from repowise.core.persistence import (+ create_engine,+ create_session_factory,+ init_db,+ upsert_repository,+ )+ from repowise.core.persistence.crud import upsert_changes, upsert_decision+ from repowise.core.persistence.database import get_session++ engine = create_engine(f"sqlite+aiosqlite:///{(tmp_path / 'wiki.db').as_posix()}")+ await init_db(engine)+ factory = create_session_factory(engine)+ async with get_session(factory) as session:+ repo = await upsert_repository(session, name="repo", local_path=str(root))+ await upsert_changes(+ session,+ repo.id,+ [+ {+ "change_id": "pr-7",+ "identity_kind": "pr",+ "identity_value": "7",+ "shape": "squash",+ "forge": "github",+ "forge_ref": "#7",+ "title": "feat: a and web (#7)",+ "merged_at": datetime(2026, 3, 1, tzinfo=UTC),+ "head_sha": head,+ "author_name": "Ann",+ "author_email": "[email protected]",+ "commit_shas_json": json.dumps([head]),+ "files_json": "[]",+ "category": "feature",+ "provenance": "unknown",+ "provenance_agent": 0,+ "provenance_known": 0,+ "metadata_source": "git",+ }+ ],+ )+ from repowise.core.persistence.crud import upsert_git_metadata++ authors = [+ {"name": n, "email": f"{n.lower()}@example.com", "commit_count": c}+ for n, c in (("Zed", 1), ("Ann", 9), ("Carol", 5), ("Bob", 3))+ ]+ await upsert_git_metadata(+ session,+ repository_id=repo.id,+ file_path="src/core/a.py",+ top_authors_json=json.dumps(authors),+ commit_count_90d=4,+ )+ await upsert_decision(+ session,+ repository_id=repo.id,+ title="Keep a pure",+ decision="a has no side effects",+ affected_files=["src/core/a.py"],+ )+ repo_id = repo.id+ return engine, factory, repo_id++[email protected]("_private_user_config")+async def test_stored_change_evidence_is_gathered_then_kept(tmp_path, repo):+ from repowise.core.changes.collect import change_evidence+ from repowise.core.persistence.crud import get_change+ from repowise.core.persistence.database import get_session++ root, head = repo+ engine, factory, repo_id = await _index(tmp_path, root, head)+ try:+ async with get_session(factory) as session:+ row = await get_change(session, repo_id, "pr-7")+ first = await change_evidence(session, repo_id, root, row)+ by = {i.kind: i for i in first.items}+ assert first.change_id == "pr-7" and first.revspec == head+ owners = by["owners"]+ assert owners.basis == "declared" and owners.value == ["@team-core"]+ assert owners.status == "attention" # src/web.py has no declared owner+ assert {"owner": None, "paths": ["src/web.py"]} in owners.details+ decisions = by["decisions_crossed"]+ assert decisions.value == {"accepted": 0, "candidate": 1}+ assert decisions.details[0]["paths"] == ["src/core/a.py"]+ provenance = by["provenance"]+ assert provenance.value["label"] == "unknown" and provenance.basis == "unresolved"+ assert provenance.details == [{"sha": head, "label": "unknown", "tier": None}]+ assert by["health_delta"].basis == "measured"+ # Ann wrote the change and Carol co-wrote it; the rest are listed by name.+ reviewers = by["suggested_reviewers"]+ assert reviewers.value == ["Bob", "Zed"]+ assert reviewers.details[0] == {+ "name": "Bob",+ "paths": ["src/core/a.py"],+ "reasons": ["owns path"],+ }+ assert by["cross_repo_consumers"].basis == "unresolved"++ async with get_session(factory) as session:+ row = await get_change(session, repo_id, "pr-7")+ assert json.loads(row.evidence_json)["generated_at"] == first.generated_at+ again = await change_evidence(session, repo_id, root, row)+ assert again.to_dict() == first.to_dict()+ rebuilt = await change_evidence(session, repo_id, root, row, refresh=True)+ assert [i.kind for i in rebuilt.items] == list(KINDS)+ finally:+ await engine.dispose()+++async def test_without_an_index_only_git_items_are_filled(repo):+ from repowise.core.changes.collect import evidence_for_revspec++ root, head = repo+ evidence = await evidence_for_revspec(None, "", root, head)+ by = {i.kind: i for i in evidence.items}+ assert by["owners"].details == [{"reason": "the repository has no index"}]+ assert by["health_delta"].status in {"ok", "attention"}+ assert evidence.index_commit is Nonediff --git a/tests/unit/server/mcp/test_change_risk.py b/tests/unit/server/mcp/test_change_risk.pyindex d3b25b7fc..83cf3f97f 100644--- a/tests/unit/server/mcp/test_change_risk.py+++ b/tests/unit/server/mcp/test_change_risk.py@@ -724,3 +724,107 @@ async def test_get_change_risk_keeps_is_fix_when_true(tmp_path, monkeypatch) ->result = await module.get_change_risk("HEAD", baseline=0)assert result["is_fix"] is True+++async def test_evidence_include_adds_the_checklist_and_nothing_else(tmp_path, monkeypatch) -> None:+ from repowise.core.changes.evidence import KINDS++ repo = tmp_path / "repo"+ repo.mkdir()+ _git(["init", "-q"], repo)+ _commit(repo, {"README.md": "# seed\n"}, "chore: seed")+ _commit(repo, {"src/app.py": "def value():\n return 1\n"}, "feat: app")++ module = importlib.import_module("repowise.server.mcp_server.tool_change_risk")++ async def _context(_: str | None) -> SimpleNamespace:+ return SimpleNamespace(path=str(repo))++ monkeypatch.setattr(module, "_resolve_repo_context", _context)+ default = await module.get_change_risk("HEAD", baseline=0)+ assert "evidence" not in default+ asked = await module.get_change_risk("HEAD", baseline=0, include=["evidence"])+ assert set(asked) - set(default) == {"evidence"}++ evidence = asked["evidence"]+ assert evidence["schema_version"] == 1 and evidence["revspec"] == "HEAD"+ by = {i["kind"]: i for i in evidence["items"]}+ assert list(by) == list(KINDS)+ # No index here: the index-backed items say so instead of reading as clear.+ assert by["owners"]["details"] == [{"reason": "the repository has no index"}]+ assert by["health_delta"]["basis"] == "measured"+ # baseline=0 ranks nothing, so the one risk row is unknown, never a verdict.+ assert by["risk_score"]["status"] == "unknown"+++async def test_evidence_for_a_stored_change_is_its_kept_record(tmp_path, monkeypatch, factory) -> None:+ import json+ from datetime import UTC, datetime++ from sqlalchemy.exc import OperationalError++ from repowise.core.persistence import upsert_repository+ from repowise.core.persistence.crud import upsert_changes++ repo = tmp_path / "repo"+ repo.mkdir()+ _git(["init", "-q"], repo)+ _commit(repo, {"README.md": "# seed\n"}, "chore: seed")+ _commit(repo, {"src/app.py": "def value():\n return 1\n"}, "feat: app (#3)")+ head = subprocess.run(+ ["git", "rev-parse", "HEAD"], cwd=repo, check=True, capture_output=True, text=True+ ).stdout.strip()+ kept = {+ "schema_version": 1,+ "change_id": "pr-3",+ "revspec": head,+ "generated_at": "2026-10-14T00:00:00+00:00",+ "index_commit": None,+ "items": [],+ }+ async with factory() as session:+ row = await upsert_repository(session, name="repo", local_path=str(repo))+ await upsert_changes(+ session,+ row.id,+ [+ {+ "change_id": "pr-3",+ "identity_kind": "pr",+ "identity_value": "3",+ "shape": "squash",+ "title": "feat: app (#3)",+ "merged_at": datetime(2026, 3, 1, tzinfo=UTC),+ "head_sha": head,+ "commit_shas_json": json.dumps([head]),+ "evidence_json": json.dumps(kept),+ }+ ],+ )+ await session.commit()++ module = importlib.import_module("repowise.server.mcp_server.tool_change_risk")++ async def _context(_: str | None) -> SimpleNamespace:+ return SimpleNamespace(path=str(repo), session_factory=factory)++ async def _repo(session):+ from repowise.core.persistence.crud import get_repository_by_path++ return await get_repository_by_path(session, str(repo))++ monkeypatch.setattr(module, "_resolve_repo_context", _context)+ monkeypatch.setattr(module, "_get_repo", _repo)+ # No filters of the caller's own: the same record `changes show` serves.+ same = await module.get_change_risk("HEAD", include=["evidence"])+ assert same["evidence"] == kept++ async def _broken(_session):+ raise OperationalError("SELECT 1", {}, Exception("database is locked"))++ monkeypatch.setattr(module, "_get_repo", _broken)+ degraded = await module.get_change_risk("HEAD", baseline=0, include=["evidence"])+ owners = {i["kind"]: i for i in degraded["evidence"]["items"]}["owners"]+ assert "database is locked" in owners["details"][0]["reason"]diff --git a/tests/unit/server/test_changes_routes.py b/tests/unit/server/test_changes_routes.pyindex b90f7008b..62bb6dc2e 100644--- a/tests/unit/server/test_changes_routes.py+++ b/tests/unit/server/test_changes_routes.py@@ -110,3 +110,88 @@ async def test_attribution_off_hides_provenance(client: AsyncClient, app) -> Nonassert page["attribution"] is Falseassert all(c["provenance"] is None for c in page["items"])assert (await client.get(f"/api/repos/{repo['id']}/changes/pr-1")).json()["provenance"] is None+++def _fake_build(monkeypatch, seen: list[str], gate=None):+ import asyncio++ from repowise.core.changes.evidence import ChangeEvidence, EvidenceItem+ from repowise.server.routers import changes as route++ async def _build(session, repo_id, root, row):+ seen.append(row.change_id)+ if gate is not None:+ await gate.wait()+ await asyncio.sleep(0)+ return ChangeEvidence(+ change_id=row.change_id,+ revspec=row.head_sha,+ generated_at="2026-10-14T00:00:00+00:00",+ items=[+ EvidenceItem(+ "health_delta", "Health delta", "ok", "measured", {"introduced": 0}, [], "change health"+ )+ ],+ )++ monkeypatch.setattr(route, "build_stored_evidence", _build)+ return route+++async def test_detail_carries_evidence_only_when_asked_and_keeps_it(+ client: AsyncClient, app, monkeypatch+) -> None:+ seen: list[str] = []+ _fake_build(monkeypatch, seen)+ repo = await create_test_repo(client)+ await _seed(app, repo["id"])+ base = f"/api/repos/{repo['id']}/changes/pr-1"++ plain = (await client.get(base)).json()+ assert plain["evidence"] is None and plain["evidence_building"] is False and seen == []+ record = (await client.get(base, params={"evidence": "true"})).json()+ evidence = record["evidence"]+ assert evidence["schema_version"] == 1 and evidence["change_id"] == "pr-1"+ assert evidence["items"][0] == {+ "kind": "health_delta",+ "label": "Health delta",+ "status": "ok",+ "basis": "measured",+ "value": {"introduced": 0},+ "details": [],+ "source": "change health",+ }+ # Kept: the next read builds nothing; refresh builds again.+ again = (await client.get(base, params={"evidence": "true"})).json()+ assert again["evidence"] == evidence and seen == ["pr-1"]+ await client.get(base, params={"evidence": "true", "refresh": "true"})+ assert seen == ["pr-1", "pr-1"]+++async def test_a_slow_build_answers_building_and_runs_once(client: AsyncClient, app, monkeypatch) -> None:+ import asyncio++ seen: list[str] = []+ gate = asyncio.Event()+ route = _fake_build(monkeypatch, seen, gate)+ monkeypatch.setattr(route, "EVIDENCE_WAIT_SECONDS", 0.05)+ repo = await create_test_repo(client)+ await _seed(app, repo["id"])+ base = f"/api/repos/{repo['id']}/changes/pr-1"++ first, second = await asyncio.gather(+ client.get(base, params={"evidence": "true"}),+ client.get(base, params={"evidence": "true"}),+ )+ for reply in (first.json(), second.json()):+ assert reply["evidence"] is None and reply["evidence_building"] is True+ assert seen == ["pr-1"]+ gate.set()+ for _ in range(100):+ if not route._BUILDS:+ break+ 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"]