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): Change Records reconstructed from git, with CLI, REST and a web page (#3745)
Raghav Chamadiya48803a7cbac8
diff --git a/docs/reference/API_REFERENCE.md b/docs/reference/API_REFERENCE.mdindex 22be2028e..cf27bdb1d 100644--- a/docs/reference/API_REFERENCE.md+++ b/docs/reference/API_REFERENCE.md@@ -504,6 +504,7 @@ one per router area; this table maps an area to the tag to open there.| Refactoring plans, opportunities, settings, code generation | `refactoring` | `routers/refactoring.py` || Dead-code findings | `dead-code` | `routers/dead_code.py` || Change risk, hotspots, ownership, commits, co-changes | `git` | `routers/git.py` |+| Merged changes (Change Records) reconstructed from git | `changes` | `routers/changes.py` || Structural coupling report | `coupling` | `routers/coupling.py` || Blast radius for a change | `blast-radius` | `routers/blast_radius.py` || Architectural decisions, lanes, lineage, policy settings | `decisions` | `routers/decisions.py` |diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.mdindex 0b6068cc4..dc3ab12db 100644--- a/docs/reference/CLI_REFERENCE.md+++ b/docs/reference/CLI_REFERENCE.md@@ -38,7 +38,8 @@ Grouped by what you're trying to do, not alphabetically. `PATH` and flag details[`security`](#repowise-security) ·[`impacted-tests`](#repowise-impacted-tests-revspec) ·[`coverage`](#repowise-coverage) ·-[`components`](#repowise-components)+[`components`](#repowise-components) ·+[`changes`](#repowise-changes)**Decisions**[`decision`](#repowise-decision)@@ -1591,6 +1592,17 @@ repowise components list [--path PATH] [--format table|json]---+### `repowise changes`++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.++```bash+repowise 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 distill <command>`Run a command and print a compact, reversible rendering of its output. Noisediff --git a/packages/api-client/package.json b/packages/api-client/package.jsonindex 41a278de7..c2955b68b 100644--- a/packages/api-client/package.json+++ b/packages/api-client/package.json@@ -16,6 +16,7 @@"./c4": "./src/c4.ts","./cache": "./src/cache.ts","./cards": "./src/cards.ts",+ "./changes": "./src/changes.ts","./chat": "./src/chat.ts","./code-health": "./src/code-health.ts","./costs": "./src/costs.ts",diff --git a/packages/api-client/src/changes.ts b/packages/api-client/src/changes.tsnew file mode 100644index 000000000..5d0369ab9--- /dev/null+++ b/packages/api-client/src/changes.ts@@ -0,0 +1,40 @@+/**+ * Change endpoints: merged changes reconstructed from git.+ *+ * Types come from `@repowise-dev/types/changes`, re-exported here so a+ * consumer needs one import.+ */+import { apiGet } from "./client";+import type {+ ChangeListResponse,+ ChangeRecord,+ ChangeSummary,+} from "@repowise-dev/types/changes";++export type { ChangeListResponse, ChangeRecord, ChangeSummary };++/** A page of changes, newest merged first, without file or commit lists. */+export async function listChanges(+ repoId: string,+ opts?: {+ /** One commit category, e.g. `fix`. */+ category?: string;+ shape?: "merge" | "squash" | "commit";+ /** Substring of the title, id or a file path. */+ q?: string;+ limit?: number;+ offset?: number;+ },+): Promise<ChangeListResponse> {+ return apiGet<ChangeListResponse>(`/api/repos/${repoId}/changes`, opts);+}++/** One change by id (`pr-123`), or the change that landed a commit sha. */+export async function getChange(+ repoId: string,+ changeId: string,+): Promise<ChangeRecord> {+ return apiGet<ChangeRecord>(+ `/api/repos/${repoId}/changes/${encodeURIComponent(changeId)}`,+ );+}diff --git a/packages/cli/src/repowise/cli/commands/changes_cmd.py b/packages/cli/src/repowise/cli/commands/changes_cmd.pynew file mode 100644index 000000000..465326033--- /dev/null+++ b/packages/cli/src/repowise/cli/commands/changes_cmd.py@@ -0,0 +1,160 @@+"""``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.+"""++from __future__ import annotations++from pathlib import Path+from typing import Any++import click++from repowise.cli.helpers import console, repo_index_session, resolve_command_target, run_async+from repowise.cli.output import emit_json, format_option+++def _repo_root(path: str | None) -> Path:+ target = resolve_command_target(path=path, no_workspace_flag=True)+ assert target.repo_path is not None+ return Path(target.repo_path).resolve()+++def _no_index() -> None:+ console.print("No index found. Run `repowise init` first.")+ raise SystemExit(1)+++async def _list(root: Path, **filters: Any) -> tuple[list[dict], int] | None:+ from repowise.core.attribution import attribution_enabled+ 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+ rows, total = await list_changes(session, repo_id, **filters)+ on = attribution_enabled(root)+ return [change_record(r, attribution=on) for r in rows], total+++async def _show(root: Path, ref: str) -> dict | None | bool:+ from repowise.core.attribution import attribution_enabled+ from repowise.core.changes.record import change_record+ from repowise.core.persistence.crud import get_change++ async with repo_index_session(root) as opened:+ if opened is None:+ return False+ session, repo_id = opened+ row = await get_change(session, repo_id, ref)+ return None if row is None else change_record(row, attribution=attribution_enabled(root))++[email protected]("changes")+def changes_group() -> None:+ """List and show merged changes (PRs, MRs, commits) reconstructed from git."""+++@changes_group.command("list")[email protected]("--path", "repo", default=None, help="Repo path (defaults to cwd).")[email protected]("--category", default=None, help="Only this category (feature, fix, ...).")+ "--shape", type=click.Choice(["merge", "squash", "commit"]), default=None, help="Only this shape."+)[email protected]("--grep", "q", default=None, help="Substring of the title, id or a file path.")[email protected]("--limit", default=30, show_default=True, type=click.IntRange(1, 1000))[email protected]("--offset", default=0, type=click.IntRange(0))+@format_option()+def changes_list(+ repo: str | None,+ category: str | None,+ shape: str | None,+ q: str | None,+ limit: int,+ offset: int,+ fmt: str,+) -> None:+ """List indexed changes, newest merged first."""+ root = _repo_root(repo)+ got = run_async(+ _list(root, category=category, shape=shape, q=q, limit=limit, offset=offset)+ )+ if got is None:+ _no_index()+ records, total = got+ if fmt == "json":+ for r in records:+ r.pop("files")+ emit_json({"total": total, "limit": limit, "offset": offset, "changes": records})+ return+ from rich.markup import escape+ from rich.table import Table++ table = Table("Change", "Merged", "Category", "Files", "+/-", "Title")+ for r in records:+ table.add_row(+ escape(r["forge_ref"] or r["id"][:19]),+ (r["merged_at"] or "")[:10],+ r["category"],+ str(r["files_changed"]),+ f"+{r['lines_added']}/-{r['lines_deleted']}",+ escape(r["title"][:80]),+ )+ console.print(table)+ console.print(f"[dim]{len(records)} of {total} change(s).[/dim]")+++@changes_group.command("show")[email protected]("ref")[email protected]("--path", "repo", default=None, help="Repo path (defaults to cwd).")+@format_option(+ 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:+ """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 record is False:+ _no_index()+ if record is None:+ console.print(f"No change {ref!r} in the index.")+ raise SystemExit(1)+ if fmt == "json":+ emit_json(record)+ return+ if fmt == "in-toto":+ from repowise.core.changes.record import in_toto_statement++ emit_json(in_toto_statement(record))+ return+ from rich.markup import escape++ ref_text = record["forge_ref"] or record["id"]+ console.print(f"[bold]{escape(ref_text)}[/bold] {escape(record['title'])}")+ console.print(+ f"{record['shape']} · {record['category']} · merged {record['merged_at'] or 'unknown'}"+ f" · head {record['head_sha'][:12]}"+ )+ console.print(+ f"{len(record['commits'])} commit(s), {record['files_changed']} file(s),"+ f" +{record['lines_added']}/-{record['lines_deleted']}"+ )+ prov = record["provenance"]+ if prov is not None:+ cov = prov["coverage"]+ cov_text = f"{round(cov * 100)}%" if cov is not None else "n/a"+ console.print(f"provenance: {prov['label']} (coverage {cov_text})")+ meta = record["metadata"]+ if meta["linked_issues"]:+ console.print(f"linked issues: {', '.join(meta['linked_issues'])}")+ if meta["approvals"] is not None:+ console.print(f"approvals: {meta['approvals']}")+ for f in record["files"][:50]:+ 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]")diff --git a/packages/cli/src/repowise/cli/main.py b/packages/cli/src/repowise/cli/main.pyindex 8ca3fdde3..fd5302452 100644--- a/packages/cli/src/repowise/cli/main.py+++ b/packages/cli/src/repowise/cli/main.py@@ -72,6 +72,7 @@ _OSS_COMMANDS: tuple[tuple[str, str], ...] = (("decision", "decision_cmd:decision_group"),("coverage", "coverage_cmd:coverage_group"),("components", "components_cmd:components_group"),+ ("changes", "changes_cmd:changes_group"),("impacted-tests", "impacted_tests_cmd:impacted_tests_command"),("search", "search_cmd:search_command"),("ask", "ask_cmd:ask_command"),diff --git a/packages/core/alembic/versions/0110_change_records.py b/packages/core/alembic/versions/0110_change_records.pynew file mode 100644index 000000000..3861d0ba5--- /dev/null+++ b/packages/core/alembic/versions/0110_change_records.py@@ -0,0 +1,76 @@+"""Change Records: the ``changes`` table and a stored commit category.++One row per merged change reconstructed from git (see+``repowise.core.changes``). ``git_commits.category`` keeps the single-label+category the evolution timeline computed on read; existing rows stay NULL+until the next index, which the git-history stamp forces.++Local SQLite stores never run Alembic; ``init_db`` creates the table and adds+the column there.++Revision ID: 0110+Revises: 0109+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 = "0110"+down_revision: str | None = "0109"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None+++def upgrade() -> None:+ op.add_column("git_commits", sa.Column("category", sa.String(16), nullable=True))+ op.create_table(+ "changes",+ sa.Column("id", sa.String(32), primary_key=True),+ sa.Column(+ "repository_id",+ sa.String(32),+ sa.ForeignKey("repositories.id", ondelete="CASCADE"),+ nullable=False,+ ),+ sa.Column("change_id", sa.String(96), nullable=False),+ sa.Column("identity_kind", sa.String(16), nullable=False),+ sa.Column("identity_value", sa.String(64), nullable=False),+ sa.Column("shape", sa.String(16), nullable=False),+ sa.Column("forge", sa.String(16), nullable=False),+ sa.Column("forge_ref", sa.String(32), nullable=True),+ sa.Column("title", sa.Text, nullable=False),+ sa.Column("merged_at", sa.DateTime(timezone=True), nullable=True),+ sa.Column("head_sha", sa.String(40), nullable=False),+ sa.Column("author_name", sa.String(255), nullable=False),+ sa.Column("author_email", sa.String(255), nullable=False),+ sa.Column("commit_shas_json", sa.Text, nullable=False),+ sa.Column("files_json", sa.Text, nullable=False),+ sa.Column("files_changed", sa.Integer, nullable=False),+ sa.Column("lines_added", sa.Integer, nullable=False),+ sa.Column("lines_deleted", sa.Integer, nullable=False),+ sa.Column("category", sa.String(16), nullable=False),+ sa.Column("provenance", sa.String(16), nullable=True),+ sa.Column("provenance_agent", sa.Integer, nullable=True),+ sa.Column("provenance_known", sa.Integer, nullable=True),+ sa.Column("metadata_source", sa.String(32), nullable=True),+ sa.Column("reviewers_json", sa.Text, nullable=True),+ sa.Column("approvals", sa.Integer, nullable=True),+ sa.Column("labels_json", sa.Text, nullable=True),+ sa.Column("linked_issues_json", sa.Text, nullable=True),+ sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),+ sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),+ sa.UniqueConstraint("repository_id", "change_id", name="uq_change"),+ )+ op.create_index("ix_changes_repo_merged", "changes", ["repository_id", "merged_at"])+++def downgrade() -> None:+ op.drop_index("ix_changes_repo_merged", table_name="changes")+ op.drop_table("changes")+ op.drop_column("git_commits", "category")diff --git a/packages/core/src/repowise/core/changes/__init__.py b/packages/core/src/repowise/core/changes/__init__.pynew file mode 100644index 000000000..cd4c51fb7--- /dev/null+++ b/packages/core/src/repowise/core/changes/__init__.py@@ -0,0 +1,34 @@+"""Change Records: merged changes reconstructed from git, stored and exported.++:mod:`.reconstruct` reads changes off the main line, :mod:`.source` is the+seam forge metadata comes through (git only by default), :mod:`.record` is the+versioned JSON shape and its in-toto export, and :mod:`.store` keeps the+``changes`` table in step with each index and update.+"""++from __future__ import annotations++from repowise.core.changes.reconstruct import ReconstructedChange, reconstruct_changes+from repowise.core.changes.record import (+ PREDICATE_TYPE,+ SCHEMA_VERSION,+ change_record,+ in_toto_statement,+)+from repowise.core.changes.source import (+ ChangeMetadata,+ ChangeMetadataSource,+ change_metadata_sources,+)++__all__ = [+ "PREDICATE_TYPE",+ "SCHEMA_VERSION",+ "ChangeMetadata",+ "ChangeMetadataSource",+ "ReconstructedChange",+ "change_metadata_sources",+ "change_record",+ "in_toto_statement",+ "reconstruct_changes",+]diff --git a/packages/core/src/repowise/core/changes/reconstruct.py b/packages/core/src/repowise/core/changes/reconstruct.pynew file mode 100644index 000000000..055fe40f1--- /dev/null+++ b/packages/core/src/repowise/core/changes/reconstruct.py@@ -0,0 +1,424 @@+"""Merged changes read back from git: one per first-parent commit of HEAD.++The main line's first-parent chain is the sequence of things that landed. A+merge commit lands the commits its other parents bring in (``M^1..M^2``), with+the files it changed against its first parent; a squash or lone commit lands+itself. Rebase merges leave no grouping in git, so each rebased commit reads+as its own change.++A merge that names no change of its own (``Merge branch 'main' of …``, a+release branch brought back) often carries changes that do: squash commits+and PR merges made on the other side. Those come out as their own changes, and+the merge keeps only the commits nothing else claims; a merge left with none+is bookkeeping and is dropped.++Identity, first that applies: the PR or MR number the message names+(:func:`~repowise.core.forges.changes.change_number`), a Gerrit ``Change-Id``+trailer, the merge commit, the commit.++Git calls per run: the first-parent walk with ``--numstat``; when it met a+merge, one metadata walk over the commits merges brought in; and when a merge+was split, one ``--numstat`` read of the commits split out of it.+"""++from __future__ import annotations++import re+from collections.abc import Mapping+from dataclasses import dataclass, field+from datetime import UTC, datetime+from typing import Any++from repowise.core.forges import ForgeKind, change_number, get_forge+from repowise.core.ingestion.git_indexer._constants import classify_commit_category++SHAPE_MERGE = "merge"+SHAPE_SQUASH = "squash"+SHAPE_COMMIT = "commit"++KIND_PR = "pr"+KIND_CHANGE_ID = "change_id"+KIND_MERGE = "merge"+KIND_COMMIT = "commit"++_ID_PREFIX = {KIND_PR: "pr", KIND_CHANGE_ID: "change", KIND_MERGE: "merge", KIND_COMMIT: "commit"}+_NAMED = (KIND_PR, KIND_CHANGE_ID)++_CHANGE_ID_RE = re.compile(r"^Change-Id:\s*(I[0-9a-f]{40})\s*$", re.MULTILINE)+#: Merge subjects that are boilerplate; the change's title is the body's first line.+_BOILERPLATE_MERGE = (+ "Merge pull request ",+ "Merge branch ",+ "Merge remote-tracking branch ",+ "Merged in ",+)+_AZURE_MERGED = re.compile(r"^Merged PR \d+:\s*(.+)$")+_TRAILER_LINE = re.compile(r"^[A-Za-z][\w-]*:\s|^See merge request ")+#: Shas per ``git log --no-walk`` call, well under Windows' command-line limit.+_SHA_BATCH = 200+++@dataclass+class ReconstructedChange:+ change_id: str+ identity_kind: str+ identity_value: str+ shape: str+ forge: str+ forge_ref: str | None+ title: str+ merged_at: datetime | None+ head_sha: str+ author_name: str+ author_email: str+ #: Non-merge commits the change landed, newest first.+ commit_shas: list[str]+ #: ``(path, added, deleted)``, renames at their new path.+ files: list[tuple[str, int, int]]+ category: str+ #: The head commit's message body. Read by metadata sources, never stored.+ body: str = field(default="", repr=False)++ @property+ def lines_added(self) -> int:+ return sum(added for _, added, _ in self.files)++ @property+ def lines_deleted(self) -> int:+ return sum(deleted for _, _, deleted in self.files)+++@dataclass(frozen=True)+class _Commit:+ sha: str+ parents: tuple[str, ...]+ author_name: str+ author_email: str+ ts: int+ subject: str+ body: str++ @property+ def is_merge(self) -> bool:+ return len(self.parents) > 1+++def change_title(subject: str, body: str, is_merge: bool) -> str:+ """The change's title: a merge's own boilerplate subject gives way to its body."""+ if not is_merge:+ return subject+ if m := _AZURE_MERGED.match(subject):+ return m.group(1).strip()+ if subject.startswith(_BOILERPLATE_MERGE):+ for line in body.splitlines():+ line = line.strip()+ if line and not _TRAILER_LINE.match(line):+ return line+ return subject+++def change_identity(+ subject: str, body: str, sha: str, is_merge: bool, forge: ForgeKind | str+) -> tuple[str, str, str | None]:+ """``(kind, value, forge_ref)`` in the order PR number, Change-Id, merge, commit."""+ number = change_number(subject, body, forge)+ if number is not None:+ return KIND_PR, str(number), get_forge(forge).format_change_ref(number)+ ids = _CHANGE_ID_RE.findall(body)+ if ids:+ return KIND_CHANGE_ID, ids[-1], None+ return (KIND_MERGE if is_merge else KIND_COMMIT), sha, None+++def _folded_files(numstat_lines: list[str]) -> list[tuple[str, int, int]]:+ from repowise.core.ingestion.git_commit_index import _parse_numstat++ changes, _moved = _parse_numstat(numstat_lines)+ folded: dict[str, tuple[int, int]] = {}+ for path, added, deleted in changes:+ if path:+ a, d = folded.get(path, (0, 0))+ folded[path] = (a + added, d + deleted)+ return [(path, a, d) for path, (a, d) in folded.items()]+++def _merged_files(*file_lists: list[tuple[str, int, int]]) -> list[tuple[str, int, int]]:+ return _folded_files([f"{a}\t{d}\t{p}" for files in file_lists for p, a, d in files])+++def _first_parent_records(repo: Any, rev: str, limit: int) -> list[tuple[dict, list[str]]]:+ from repowise.core.ingestion.git_indexer.records import (+ _LOG_FORMAT,+ _RECORD_SEP,+ _parse_commit_record,+ )++ # ``-m`` with ``--first-parent`` diffs a merge against its first parent+ # only, on old and new git alike.+ raw = repo.git.log(+ f"-{limit}", "--first-parent", "-m", "-M", "--numstat", f"--format={_LOG_FORMAT}", rev+ )+ out = []+ for record in raw.split(_RECORD_SEP):+ if record.strip() and (parsed := _parse_commit_record(record)) is not None:+ out.append(parsed)+ return out+++def _graph(repo: Any, head: str, exclude: list[str]) -> dict[str, _Commit]:+ """Every commit reachable from *head* and from none of *exclude*."""+ raw = repo.git.log(+ "--format=%x00%H%x1f%P%x1f%aN%x1f%aE%x1f%ct%x1f%s%x1f%b",+ head,+ *(f"^{sha}" for sha in exclude),+ )+ graph: dict[str, _Commit] = {}+ for record in raw.split("\x00"):+ parts = record.split("\x1f")+ if len(parts) < 7:+ continue+ sha, parents, name, email, ts, subject = parts[:6]+ try:+ stamp = int(ts)+ except ValueError:+ stamp = 0+ sha = sha.strip()+ graph[sha] = _Commit(+ sha, tuple(parents.split()), name, email, stamp, subject, "\x1f".join(parts[6:]).strip()+ )+ return graph+++def _numstats(repo: Any, shas: list[str]) -> dict[str, list[tuple[str, int, int]]]:+ """Each commit's files against its first parent."""+ out: dict[str, list[tuple[str, int, int]]] = {}+ for i in range(0, len(shas), _SHA_BATCH):+ raw = repo.git.log(+ "--no-walk=unsorted",+ "-m",+ "--first-parent",+ "-M",+ "--numstat",+ "--format=%x00%H",+ *shas[i : i + _SHA_BATCH],+ )+ for record in raw.split("\x00"):+ lines = record.strip().splitlines()+ if lines:+ out[lines[0].strip()] = _folded_files([ln for ln in lines[1:] if ln.strip()])+ return out+++def _is_ancestor(repo: Any, sha: str, head: str) -> bool:+ try:+ repo.git.merge_base("--is-ancestor", sha, head)+ except Exception:+ return False+ return True+++def reconstruct_changes(+ repo: Any,+ forge: ForgeKind | str,+ *,+ limit: int,+ since_sha: str | None = None,+ taken: Mapping[str, str] | None = None,+) -> list[ReconstructedChange] | None:+ """Changes landed on HEAD's first-parent line, newest first.++ *limit* bounds the first-parent commits read. With *since_sha* only+ changes after it are read; ``None`` is returned when it is no longer an+ ancestor of HEAD (a rebase or branch switch), and the caller rebuilds.+ *taken* maps stored change ids to their head sha, so a repeated identity+ (a PR number cherry-picked twice) gets a distinct id while the change that+ holds it keeps its own across runs.+ """+ try:+ head = repo.head.commit.hexsha+ except Exception:+ return []+ if since_sha:+ if since_sha == head:+ return []+ if not _is_ancestor(repo, since_sha, head):+ return None+ rev = f"{since_sha}..{head}" if since_sha else head+ records = _first_parent_records(repo, rev, limit)+ if not records:+ return []++ graph: dict[str, _Commit] = {}+ if any(header["is_merge"] for header, _ in records):+ oldest_parents = records[-1][0]["parents"]+ graph = _graph(repo, head, [*oldest_parents[:1], *([since_sha] if since_sha else [])])++ builder = _Builder(repo, forge, graph, taken)+ builder.claimed.update(header["sha"] for header, _ in records)+ # Oldest first: a branch merged twice belongs to the first merge, and the+ # first holder of a repeated identity keeps the plain id.+ for header, numstat_lines in reversed(records):+ builder.landed(header, _folded_files(numstat_lines))+ builder.out.sort(key=lambda c: (c.merged_at or datetime.min.replace(tzinfo=UTC)), reverse=True)+ return builder.out+++class _Builder:+ def __init__(+ self,+ repo: Any,+ forge: ForgeKind | str,+ graph: Mapping[str, _Commit],+ taken: Mapping[str, str] | None,+ ) -> None:+ self.repo = repo+ self.forge = forge+ self.graph = graph+ self.ids = dict(taken or {})+ self.claimed: set[str] = set()+ self.out: list[ReconstructedChange] = []++ def _members(self, starts: tuple[str, ...], within: set[str] | None = None) -> list[str]:+ """Commits reachable from *starts* that nothing has landed yet."""+ found: list[str] = []+ stack = list(starts)+ while stack:+ sha = stack.pop()+ if sha in self.claimed or sha not in self.graph:+ continue+ if within is not None and sha not in within:+ continue+ self.claimed.add(sha)+ found.append(sha)+ stack.extend(self.graph[sha].parents)+ return found++ def _own(self, shas: list[str]) -> list[str]:+ own = [s for s in shas if not self.graph[s].is_merge]+ own.sort(key=lambda s: self.graph[s].ts, reverse=True)+ return own++ def landed(self, header: dict, files: list[tuple[str, int, int]]) -> None:+ """Record the change one first-parent commit landed."""+ commit = _Commit(+ header["sha"],+ tuple(header["parents"]),+ header["author_name"],+ header["author_email"],+ header["ts"],+ header["subject"],+ header["body"],+ )+ kind, value, ref = change_identity(+ commit.subject, commit.body, commit.sha, commit.is_merge, self.forge+ )+ if not commit.is_merge:+ self._emit(commit, kind, value, ref, [commit.sha], files)+ return+ members = self._members(commit.parents[1:])+ if kind in _NAMED:+ self._emit(commit, kind, value, ref, self._own(members), files)+ return+ self._split(commit, kind, value, ref, members, files)++ def _split(+ self,+ merge: _Commit,+ kind: str,+ value: str,+ ref: str | None,+ members: list[str],+ files: list[tuple[str, int, int]],+ ) -> None:+ """An unnamed merge: changes it carried come out on their own."""+ pool = set(members)+ named = sorted(+ (s for s in members if self._identity(self.graph[s])[0] in _NAMED),+ # Merges first, so a commit inside a named branch stays with it.+ key=lambda s: (not self.graph[s].is_merge, self.graph[s].ts),+ )+ if not named:+ self._emit(merge, kind, value, ref, self._own(members), files)+ return+ self.claimed.difference_update(pool)+ groups: list[tuple[_Commit, list[str]]] = []+ for sha in named:+ if sha in self.claimed:+ continue+ self.claimed.add(sha)+ node = self.graph[sha]+ inner = self._members(node.parents[1:], pool) if node.is_merge else []+ groups.append((node, inner))+ rest = self._own([s for s in members if s not in self.claimed])+ self.claimed.update(pool)+ stats = _numstats(self.repo, [node.sha for node, _ in groups] + rest)+ for node, inner in groups:+ k, v, r = self._identity(node)+ commits = self._own(inner) if node.is_merge else [node.sha]+ self._emit(node, k, v, r, commits, stats.get(node.sha, []))+ if rest:+ self._emit(merge, kind, value, ref, rest, _merged_files(*(stats.get(s, []) for s in rest)))++ def _identity(self, commit: _Commit) -> tuple[str, str, str | None]:+ return change_identity(commit.subject, commit.body, commit.sha, commit.is_merge, self.forge)++ def _emit(+ self,+ head: _Commit,+ kind: str,+ value: str,+ ref: str | None,+ commits: list[str],+ files: list[tuple[str, int, int]],+ ) -> None:+ change_id = f"{_ID_PREFIX[kind]}-{value}"+ if self.ids.get(change_id, head.sha) != head.sha:+ change_id = f"{change_id}-{head.sha[:12]}"+ self.ids[change_id] = head.sha+ author_name, author_email = head.author_name, head.author_email+ if head.is_merge and commits:+ # The oldest commit's author opened the branch; the merge's author+ # only pressed the button.+ oldest = self.graph[commits[-1]]+ author_name, author_email = oldest.author_name, oldest.author_email+ if head.is_merge:+ shape = SHAPE_MERGE+ elif kind == KIND_PR:+ shape = SHAPE_SQUASH+ else:+ shape = SHAPE_COMMIT+ title = change_title(head.subject, head.body, head.is_merge)+ self.out.append(+ ReconstructedChange(+ change_id=change_id,+ identity_kind=kind,+ identity_value=value,+ shape=shape,+ forge=str(ForgeKind(self.forge)),+ forge_ref=ref,+ title=title,+ merged_at=datetime.fromtimestamp(head.ts, tz=UTC) if head.ts > 0 else None,+ head_sha=head.sha,+ author_name=author_name,+ author_email=author_email,+ commit_shas=commits,+ files=files,+ category=classify_commit_category(title),+ body=head.body,+ )+ )+++__all__ = [+ "KIND_CHANGE_ID",+ "KIND_COMMIT",+ "KIND_MERGE",+ "KIND_PR",+ "SHAPE_COMMIT",+ "SHAPE_MERGE",+ "SHAPE_SQUASH",+ "ReconstructedChange",+ "change_identity",+ "change_title",+ "reconstruct_changes",+]diff --git a/packages/core/src/repowise/core/changes/record.py b/packages/core/src/repowise/core/changes/record.pynew file mode 100644index 000000000..14ae939f1--- /dev/null+++ b/packages/core/src/repowise/core/changes/record.py@@ -0,0 +1,114 @@+"""The Change Record as versioned JSON, and its in-toto Statement export.++The native record is primary: every surface (CLI, REST, web) serves this one+shape, and ``schema_version`` moves when a field changes meaning. The in-toto+export wraps the same record as the predicate of a Statement v1 whose+subjects are the change's commits, keyed by the ``gitCommit`` digest. It+claims no SLSA level.+"""++from __future__ import annotations++import json+from datetime import UTC, datetime+from typing import Any++from repowise.core.attribution import AGENT, HUMAN_ATTESTED, UNKNOWN++SCHEMA_VERSION = 1+IN_TOTO_STATEMENT_TYPE = "https://in-toto.io/Statement/v1"+PREDICATE_TYPE = "https://repowise.dev/ChangeRecord/v1"+++def _iso(value: datetime | None) -> str | None:+ if value is None:+ return None+ if value.tzinfo is None: # SQLite drops tzinfo; the column is UTC+ value = value.replace(tzinfo=UTC)+ return value.isoformat()+++def _loads(raw: str | None) -> Any:+ if raw is None:+ return None+ try:+ return json.loads(raw)+ except (TypeError, ValueError):+ return None+++def provenance_block(+ label: str | None, agent: int | None, known: int | None, commits: int+) -> dict[str, Any] | None:+ """Three-state provenance with the counts and coverage behind it."""+ if label not in (AGENT, HUMAN_ATTESTED, UNKNOWN) or known is None or agent is None:+ return None+ return {+ "label": label,+ "agent_commits": agent,+ "human_attested_commits": known - agent,+ "unknown_commits": max(commits - known, 0),+ "coverage": round(known / commits, 4) if commits else None,+ }+++def change_record(row: Any, *, attribution: bool = True) -> dict[str, Any]:+ """The native record for one stored ``changes`` row.++ *attribution* false (``attribution.enabled: false``) leaves provenance+ out even if an older index stored it.+ """+ commits = _loads(row.commit_shas_json) or []+ return {+ "schema_version": SCHEMA_VERSION,+ "id": row.change_id,+ "identity": {"kind": row.identity_kind, "value": row.identity_value},+ "shape": row.shape,+ "forge": row.forge,+ "forge_ref": row.forge_ref,+ "title": row.title,+ "merged_at": _iso(row.merged_at),+ "head_sha": row.head_sha,+ "author": {"name": row.author_name, "email": row.author_email},+ "commits": commits,+ "files": _loads(row.files_json) or [],+ "files_changed": row.files_changed,+ "lines_added": row.lines_added,+ "lines_deleted": row.lines_deleted,+ "category": row.category,+ "provenance": (+ provenance_block(+ row.provenance, row.provenance_agent, row.provenance_known, len(commits)+ )+ if attribution+ else None+ ),+ "metadata": {+ "source": row.metadata_source,+ "reviewers": _loads(row.reviewers_json),+ "approvals": row.approvals,+ "labels": _loads(row.labels_json),+ "linked_issues": _loads(row.linked_issues_json),+ },+ }+++def in_toto_statement(record: dict[str, Any]) -> dict[str, Any]:+ """*record* as an in-toto Statement v1: one subject per commit, head first."""+ shas = list(dict.fromkeys([record["head_sha"], *record.get("commits", [])]))+ return {+ "_type": IN_TOTO_STATEMENT_TYPE,+ "subject": [{"name": sha, "digest": {"gitCommit": sha}} for sha in shas],+ "predicateType": PREDICATE_TYPE,+ "predicate": record,+ }+++__all__ = [+ "IN_TOTO_STATEMENT_TYPE",+ "PREDICATE_TYPE",+ "SCHEMA_VERSION",+ "change_record",+ "in_toto_statement",+ "provenance_block",+]diff --git a/packages/core/src/repowise/core/changes/source.py b/packages/core/src/repowise/core/changes/source.pynew file mode 100644index 000000000..18ed9af28--- /dev/null+++ b/packages/core/src/repowise/core/changes/source.py@@ -0,0 +1,80 @@+"""The seam forge metadata reaches a Change Record through.++A :class:`ChangeMetadataSource` fills what git cannot say for certain:+reviewers, approvals, labels, linked issues. The local default, ``git``,+reads only what the history already holds and never touches the network: the+``Approved-by`` trailers GitLab writes on merge commits, and the issues a+message closes (``Fixes #12``). A field it cannot read stays ``None``, which+means unknown, never none. A plugin registers another source under+``SeamRegistry("change-metadata")`` and is selected with+``REPOWISE_SEAM_CHANGE_METADATA``.+"""++from __future__ import annotations++import re+from collections.abc import Mapping, Sequence+from dataclasses import dataclass+from pathlib import Path+from typing import Protocol++from repowise.core.registry.plugins import SeamRegistry++from .reconstruct import ReconstructedChange++_APPROVED_BY = re.compile(r"^Approved-by:\s*\S", re.MULTILINE)+++@dataclass(frozen=True)+class ChangeMetadata:+ """Forge facts about one change; ``None`` is unknown."""++ reviewers: tuple[str, ...] | None = None+ approvals: int | None = None+ labels: tuple[str, ...] | None = None+ linked_issues: tuple[str, ...] | None = None+++class ChangeMetadataSource(Protocol):+ def metadata(+ self, repo_path: Path, changes: Sequence[ReconstructedChange]+ ) -> Mapping[str, ChangeMetadata]:+ """Metadata by ``change_id``; a change left out gets none."""+ ...+++class GitChangeMetadata:+ """What the commit messages say, and nothing else."""++ def metadata(+ self, repo_path: Path, changes: Sequence[ReconstructedChange]+ ) -> Mapping[str, ChangeMetadata]:+ from repowise.core.analysis.decisions.reverts import _CLOSES_RE++ out: dict[str, ChangeMetadata] = {}+ for change in changes:+ text = f"{change.title}\n{change.body}"+ approvals = len(_APPROVED_BY.findall(change.body)) or None+ issues = tuple(dict.fromkeys(f"#{n}" for n in _CLOSES_RE.findall(text))) or None+ if approvals is not None or issues is not None:+ out[change.change_id] = ChangeMetadata(approvals=approvals, linked_issues=issues)+ return out+++change_metadata_sources: SeamRegistry[ChangeMetadataSource] = SeamRegistry("change-metadata")+change_metadata_sources.register("git", GitChangeMetadata(), default=True)+++def resolve_source() -> tuple[str, ChangeMetadataSource]:+ """The selected source and the name its rows are marked with."""+ source = change_metadata_sources.get()+ return change_metadata_sources.default or "git", source+++__all__ = [+ "ChangeMetadata",+ "ChangeMetadataSource",+ "GitChangeMetadata",+ "change_metadata_sources",+ "resolve_source",+]diff --git a/packages/core/src/repowise/core/changes/store.py b/packages/core/src/repowise/core/changes/store.pynew file mode 100644index 000000000..5399a664f--- /dev/null+++ b/packages/core/src/repowise/core/changes/store.py@@ -0,0 +1,210 @@+"""Keeps the ``changes`` table in step with each index and update."""++from __future__ import annotations++import asyncio+import contextlib+import json+from collections.abc import Mapping+from pathlib import Path+from typing import Any++import structlog++from .reconstruct import ReconstructedChange, reconstruct_changes+from .source import ChangeMetadata, resolve_source++logger = structlog.get_logger(__name__)++#: Files kept on a row; ``files_changed`` carries the full count past it.+MAX_STORED_FILES = 1000+++def change_provenance(+ commits: list[str], labels: Mapping[str, tuple[str | None, str | None]]+) -> tuple[str, int, int]:+ """``(label, agent commits, known commits)`` over a change's commits.++ Agent when any commit is an agent's, human-attested only when every commit+ is, unknown otherwise. A commit missing from ``git_commits`` is unknown.+ """+ from repowise.core.attribution import AGENT, HUMAN_ATTESTED, UNKNOWN, commit_label++ states = [commit_label(*labels[s]) if s in labels else UNKNOWN for s in commits]+ agent = states.count(AGENT)+ known = agent + states.count(HUMAN_ATTESTED)+ if agent:+ label = AGENT+ elif commits and known == len(commits):+ label = HUMAN_ATTESTED+ else:+ label = UNKNOWN+ return label, agent, known+++def change_row(+ change: ReconstructedChange,+ *,+ provenance: tuple[str, int, int] | None,+ source: str,+ metadata: ChangeMetadata | None,+) -> dict[str, Any]:+ meta = metadata or ChangeMetadata()++ def _json(value: tuple[str, ...] | None) -> str | None:+ return None if value is None else json.dumps(list(value))++ return {+ "change_id": change.change_id,+ "identity_kind": change.identity_kind,+ "identity_value": change.identity_value,+ "shape": change.shape,+ "forge": change.forge,+ "forge_ref": change.forge_ref,+ "title": change.title,+ "merged_at": change.merged_at,+ "head_sha": change.head_sha,+ "author_name": change.author_name,+ "author_email": change.author_email,+ "commit_shas_json": json.dumps(change.commit_shas),+ "files_json": json.dumps(+ [{"path": p, "added": a, "deleted": d} for p, a, d in change.files[:MAX_STORED_FILES]]+ ),+ "files_changed": len(change.files),+ "lines_added": change.lines_added,+ "lines_deleted": change.lines_deleted,+ "category": change.category,+ "provenance": provenance[0] if provenance else None,+ "provenance_agent": provenance[1] if provenance else None,+ "provenance_known": provenance[2] if provenance else None,+ "metadata_source": source,+ "reviewers_json": _json(meta.reviewers),+ "approvals": meta.approvals,+ "labels_json": _json(meta.labels),+ "linked_issues_json": _json(meta.linked_issues),+ }+++def _read_changes(+ repo_path: Path, limit: int, since: str | None, taken: dict[str, str]+) -> list[ReconstructedChange] | None:+ import git as gitpython++ from repowise.core.forges import detect_forge+ from repowise.core.ingestion.git_indexer.indexer import GitIndexer++ repo = gitpython.Repo(repo_path, search_parent_directories=True)+ try:+ # A partial clone would fetch blobs for --numstat: never from here.+ if GitIndexer._partial_clone_filter(repo) is not None:+ return []+ return reconstruct_changes(+ repo, detect_forge(repo_path), limit=limit, since_sha=since, taken=taken+ )+ finally:+ with contextlib.suppress(Exception):+ repo.close()+++async def refresh_changes(+ session: Any, repo_id: str, repo_path: Path | str, *, rebuild: bool+) -> int:+ """Rebuild (full index) or extend (update) the repository's changes.++ The window is the repo's ``commit_limit`` first-parent commits, like the+ commit table. An update reads only changes after the newest stored one and+ rebuilds when that one is no longer on HEAD's history. Provenance is read+ from the stored commit labels, so it runs after those are written, and is+ left out while attribution is off. Returns how many rows were written;+ failures are logged and leave the table as it was.+ """+ from repowise.core.attribution import attribution_enabled+ from repowise.core.ingestion.git_indexer._constants import _DEFAULT_COMMIT_LIMIT+ from repowise.core.persistence.crud import (+ delete_changes,+ get_change_heads,+ get_commit_labels,+ get_newest_change_head,+ upsert_changes,+ )+ from repowise.core.repo_config import load_repo_config++ repo_path = Path(repo_path)+ try:+ limit = int(load_repo_config(repo_path).get("commit_limit") or _DEFAULT_COMMIT_LIMIT)+ since = None if rebuild else await get_newest_change_head(session, repo_id)+ taken = {} if since is None else await get_change_heads(session, repo_id)+ changes = await asyncio.to_thread(_read_changes, repo_path, limit, since, taken)+ if changes is None:+ rebuild, since = True, None+ changes = await asyncio.to_thread(_read_changes, repo_path, limit, None, {})+ if since is None:+ rebuild = True+ changes = changes or []++ labels: dict[str, tuple[str | None, str | None]] | None = None+ if attribution_enabled(repo_path):+ labels = await get_commit_labels(+ session, repo_id, [s for c in changes for s in c.commit_shas]+ )+ source_name, source = resolve_source()+ metadata = await asyncio.to_thread(source.metadata, repo_path, changes) if changes else {}+ rows = [+ change_row(+ c,+ provenance=change_provenance(c.commit_shas, labels) if labels is not None else None,+ source=source_name,+ metadata=metadata.get(c.change_id),+ )+ for c in changes+ ]+ if rebuild:+ await delete_changes(session, repo_id)+ if rows:+ await upsert_changes(session, repo_id, rows)+ return len(rows)+ except Exception as exc:+ logger.warning("changes_refresh_failed", repo_id=repo_id, error=str(exc))+ return 0+++async def reconcile_categories(session: Any, repo_id: str) -> int:+ """Re-label commits and changes the current classifier reads differently.++ Pure regex over stored subjects and titles, so an update keeps both+ columns in step with the classifier without a re-index.+ """+ from sqlalchemy import update++ from repowise.core.ingestion.git_indexer._constants import classify_commit_category+ from repowise.core.persistence.crud import get_category_inputs, upsert_git_commits_bulk+ from repowise.core.persistence.models import Change++ commits, changes = await get_category_inputs(session, repo_id)+ commit_rows = [+ {"sha": sha, "category": label}+ for sha, subject, category in commits+ if (label := classify_commit_category(subject or "")) != category+ ]+ if commit_rows:+ await upsert_git_commits_bulk(session, repo_id, commit_rows)+ moved = 0+ for change_id, title, category in changes:+ label = classify_commit_category(title or "")+ if label != category:+ moved += 1+ await session.execute(+ update(Change)+ .where(Change.repository_id == repo_id, Change.change_id == change_id)+ .values(category=label)+ )+ return len(commit_rows) + moved+++__all__ = [+ "MAX_STORED_FILES",+ "change_provenance",+ "change_row",+ "reconcile_categories",+ "refresh_changes",+]diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/_constants.py b/packages/core/src/repowise/core/ingestion/git_indexer/_constants.pyindex 3590d30d1..97773f08e 100644--- a/packages/core/src/repowise/core/ingestion/git_indexer/_constants.py+++ b/packages/core/src/repowise/core/ingestion/git_indexer/_constants.py@@ -321,7 +321,8 @@ HOTSPOT_HALFLIFE_DAYS: float = 180.0#: forge bot accounts).#: v2: co-change records carry focused_frequency, the shared commits no wider#: than the change-entropy sweep cap.-GIT_HISTORY_VERSION: int = 2+#: v3: commits carry their category, and changes are rebuilt from history.+GIT_HISTORY_VERSION: int = 3GIT_HISTORY_VERSION_KEY = "git_history_version"diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/commit_rows.py b/packages/core/src/repowise/core/ingestion/git_indexer/commit_rows.pyindex 2ce737c9b..225a1d398 100644--- a/packages/core/src/repowise/core/ingestion/git_indexer/commit_rows.py+++ b/packages/core/src/repowise/core/ingestion/git_indexer/commit_rows.py@@ -25,7 +25,7 @@ from collections.abc import Iterable, Mappingfrom datetime import UTC, datetimefrom typing import Any-from ._constants import is_fix_commit+from ._constants import classify_commit_category, is_fix_commitfrom .identity import author_identity_key# Commit subjects are a headline (`%s`); cap defensively against a pathological@@ -132,6 +132,7 @@ def build_commit_rows(parsed_commits: list[dict]) -> list[dict]:"agent_confidence": c.get("agent_confidence"),"agent_model_id": c.get("agent_model_id"),"attribution": c.get("attribution"),+ "category": classify_commit_category(subject),})return rowsdiff --git a/packages/core/src/repowise/core/persistence/crud/__init__.py b/packages/core/src/repowise/core/persistence/crud/__init__.pyindex a68e0fbe4..5c7ae2c18 100644--- a/packages/core/src/repowise/core/persistence/crud/__init__.py+++ b/packages/core/src/repowise/core/persistence/crud/__init__.py@@ -20,6 +20,7 @@ from __future__ import annotationsfrom .analysis import * # noqa: F403from .authority import * # noqa: F403+from .changes import * # noqa: F403from .chat import * # noqa: F403from .decisions import * # noqa: F403from .external_systems import * # noqa: F403diff --git a/packages/core/src/repowise/core/persistence/crud/changes.py b/packages/core/src/repowise/core/persistence/crud/changes.pynew file mode 100644index 000000000..33c2fe56d--- /dev/null+++ b/packages/core/src/repowise/core/persistence/crud/changes.py@@ -0,0 +1,160 @@+"""CRUD for the ``changes`` table (Change Records)."""++from __future__ import annotations++from collections.abc import Sequence++from sqlalchemy import delete, func, or_, select+from sqlalchemy.ext.asyncio import AsyncSession++from ..models import Change, GitCommit+from ..sql import LIKE_ESCAPE, escape_like+from ._shared import _BATCH_SIZE, _batch_upsert_keyed, _row_inserter, _row_updater++_update_change = _row_updater("change_id")+++async def upsert_changes(session: AsyncSession, repository_id: str, rows: list[dict]) -> None:+ """Bulk upsert change rows keyed on ``(repository_id, change_id)``."""+ await _batch_upsert_keyed(+ session,+ Change,+ rows,+ prefilter=(Change.repository_id == repository_id,),+ item_key_fn=lambda row: row.get("change_id", ""),+ row_key_fn=lambda row: row.change_id,+ update_fn=_update_change,+ insert_fn=_row_inserter(Change, repository_id),+ batch_size=_BATCH_SIZE,+ )+++async def delete_changes(session: AsyncSession, repository_id: str) -> None:+ await session.execute(delete(Change).where(Change.repository_id == repository_id))+ await session.flush()+++async def get_change_heads(session: AsyncSession, repository_id: str) -> dict[str, str]:+ """``change_id -> head_sha`` for every stored change."""+ rows = await session.execute(+ select(Change.change_id, Change.head_sha).where(Change.repository_id == repository_id)+ )+ return dict(rows.tuples().all())+++async def get_newest_change_head(session: AsyncSession, repository_id: str) -> str | None:+ """Head sha of the most recently merged stored change."""+ return (+ await session.execute(+ select(Change.head_sha)+ .where(Change.repository_id == repository_id)+ .order_by(Change.merged_at.desc().nulls_last())+ .limit(1)+ )+ ).scalar_one_or_none()+++def _filters(repository_id: str, category: str | None, shape: str | None, q: str | None):+ clauses = [Change.repository_id == repository_id]+ if category:+ clauses.append(Change.category == category)+ if shape:+ clauses.append(Change.shape == shape)+ if q:+ like = f"%{escape_like(q)}%"+ clauses.append(+ or_(+ Change.title.ilike(like, escape=LIKE_ESCAPE),+ Change.change_id.ilike(like, escape=LIKE_ESCAPE),+ Change.files_json.ilike(like, escape=LIKE_ESCAPE),+ )+ )+ return clauses+++async def list_changes(+ session: AsyncSession,+ repository_id: str,+ *,+ category: str | None = None,+ shape: str | None = None,+ q: str | None = None,+ limit: int = 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)+ total = (await session.execute(select(func.count()).select_from(Change).where(*clauses))).scalar_one()+ rows = await session.execute(+ select(Change)+ .where(*clauses)+ .order_by(Change.merged_at.desc().nulls_last(), Change.change_id)+ .limit(limit)+ .offset(offset)+ )+ return list(rows.scalars().all()), int(total)+++async def get_change(session: AsyncSession, repository_id: str, ref: str) -> Change | None:+ """A change by its id, or the change that landed a commit (a sha of 7+ hex)."""+ row = (+ await session.execute(+ select(Change).where(Change.repository_id == repository_id, Change.change_id == ref)+ )+ ).scalar_one_or_none()+ if row is not None or len(ref) < 7 or any(c not in "0123456789abcdef" for c in ref.lower()):+ return row+ sha = escape_like(ref.lower())+ return (+ await session.execute(+ select(Change)+ .where(+ Change.repository_id == repository_id,+ or_(+ Change.head_sha.like(f"{sha}%", escape=LIKE_ESCAPE),+ Change.commit_shas_json.like(f'%"{sha}%', escape=LIKE_ESCAPE),+ ),+ )+ .order_by(Change.merged_at.desc().nulls_last())+ .limit(1)+ )+ ).scalar_one_or_none()+++async def get_commit_labels(+ session: AsyncSession, repository_id: str, shas: Sequence[str]+) -> dict[str, tuple[str | None, str | None]]:+ """``sha -> (attribution, agent_name)`` for the stored commits among *shas*."""+ out: dict[str, tuple[str | None, str | None]] = {}+ wanted = list(dict.fromkeys(shas))+ for i in range(0, len(wanted), 500):+ rows = await session.execute(+ select(GitCommit.sha, GitCommit.attribution, GitCommit.agent_name).where(+ GitCommit.repository_id == repository_id, GitCommit.sha.in_(wanted[i : i + 500])+ )+ )+ for sha, attribution, agent in rows.tuples():+ out[sha] = (attribution, agent)+ return out+++async def get_category_inputs(+ session: AsyncSession, repository_id: str, limit: int = 1000+) -> tuple[list[tuple[str, str, str | None]], list[tuple[str, str, str]]]:+ """``(sha, subject, category)`` per commit and ``(change_id, title, category)`` per change.++ Newest *limit* of each, so the read stays bounded as the tables grow.+ """+ commits = await session.execute(+ select(GitCommit.sha, GitCommit.subject, GitCommit.category)+ .where(GitCommit.repository_id == repository_id)+ .order_by(GitCommit.committed_at.desc().nulls_last())+ .limit(limit)+ )+ changes = await session.execute(+ select(Change.change_id, Change.title, Change.category)+ .where(Change.repository_id == repository_id)+ .order_by(Change.merged_at.desc().nulls_last())+ .limit(limit)+ )+ return list(commits.tuples().all()), list(changes.tuples().all())diff --git a/packages/core/src/repowise/core/persistence/crud/git.py b/packages/core/src/repowise/core/persistence/crud/git.pyindex f598ff95c..11d1a6bd2 100644--- a/packages/core/src/repowise/core/persistence/crud/git.py+++ b/packages/core/src/repowise/core/persistence/crud/git.py@@ -16,6 +16,7 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom ...co_change import CoChangePartner, parse_partnersfrom ..models import (+ Change,FixEvent,GitCommit,GitCommitFile,@@ -742,8 +743,8 @@ async def get_author_commit_counts(session: AsyncSession, repository_id: str) ->async def clear_attribution(session: AsyncSession, repository_id: str) -> None:"""Delete every AI attribution value derived into the index for a repository.- Commit labels and the per-file rollups go; git history, trailers and notes- in the repository are untouched. ``repowise attribution purge`` and the+ Commit labels, the per-file rollups and change provenance go; git+ history, trailers and notes in the repository are untouched. ``repowise attribution purge`` and the``attribution.enabled: false`` sweep below both use this."""await session.execute(@@ -770,6 +771,11 @@ async def clear_attribution(session: AsyncSession, repository_id: str) -> None:agent_line_model_json="{}",))+ await session.execute(+ update(Change)+ .where(Change.repository_id == repository_id)+ .values(provenance=None, provenance_agent=None, provenance_known=None)+ )async def clear_attribution_if_disabled(session: AsyncSession, repository_id: str) -> bool:diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.pyindex 03282d08c..f75fc52a1 100644--- a/packages/core/src/repowise/core/persistence/models.py+++ b/packages/core/src/repowise/core/persistence/models.py@@ -801,6 +801,71 @@ class GitCommit(Base):# local channel carries a model); NULL for human or non-trace commits.agent_model_id: Mapped[str | None] = mapped_column(String(64), nullable=True)attribution: Mapped[str | None] = mapped_column(String(16), nullable=True)+ # One EVOLUTION_CATEGORIES label from the subject; NULL on rows written+ # before it was stored. Update re-labels rows the classifier now reads+ # differently, so the column follows the classifier.+ category: Mapped[str | None] = mapped_column(String(16), nullable=True)++ created_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), nullable=False, default=_now_utc+ )+ updated_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), nullable=False, default=_now_utc, onupdate=_now_utc+ )+++class Change(Base):+ """One merged change (a PR, MR, Gerrit change or lone commit) on the main line.++ Reconstructed from git alone by :mod:`repowise.core.changes`: each+ first-parent commit of HEAD is one change; a merge commit's change also+ holds the commits its other parents brought in. ``change_id`` is the stable+ public id (``pr-123``, ``change-I…``, ``merge-<sha>``, ``commit-<sha>``).+ Forge metadata columns stay NULL (unknown) unless a metadata source filled+ them; ``metadata_source`` names it. Provenance columns are NULL while AI+ attribution is switched off.+ """++ __tablename__ = "changes"+ __table_args__ = (+ UniqueConstraint("repository_id", "change_id", name="uq_change"),+ Index("ix_changes_repo_merged", "repository_id", "merged_at"),+ )++ id: Mapped[str] = mapped_column(String(32), primary_key=True, default=_new_uuid)+ repository_id: Mapped[str] = mapped_column(+ String(32), ForeignKey("repositories.id", ondelete="CASCADE"), nullable=False+ )+ change_id: Mapped[str] = mapped_column(String(96), nullable=False)+ identity_kind: Mapped[str] = mapped_column(String(16), nullable=False)+ identity_value: Mapped[str] = mapped_column(String(64), nullable=False)+ # merge | squash | commit: how the change was read off the main line.+ shape: Mapped[str] = mapped_column(String(16), nullable=False)+ forge: Mapped[str] = mapped_column(String(16), nullable=False, default="generic")+ forge_ref: Mapped[str | None] = mapped_column(String(32), nullable=True)+ title: Mapped[str] = mapped_column(Text, nullable=False, default="")+ merged_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)+ head_sha: Mapped[str] = mapped_column(String(40), nullable=False)+ author_name: Mapped[str] = mapped_column(String(255), nullable=False, default="")+ author_email: Mapped[str] = mapped_column(String(255), nullable=False, default="")+ commit_shas_json: Mapped[str] = mapped_column(Text, nullable=False, default="[]")+ # [{"path", "added", "deleted"}] against the first parent; ``files_changed``+ # is the full count when the stored list is capped.+ files_json: Mapped[str] = mapped_column(Text, nullable=False, default="[]")+ files_changed: Mapped[int] = mapped_column(Integer, nullable=False, default=0)+ lines_added: Mapped[int] = mapped_column(Integer, nullable=False, default=0)+ lines_deleted: Mapped[int] = mapped_column(Integer, nullable=False, default=0)+ category: Mapped[str] = mapped_column(String(16), nullable=False, default="other")+ # agent | human_attested | unknown over the change's commits, with the+ # counts behind it (coverage = known / commits).+ provenance: Mapped[str | None] = mapped_column(String(16), nullable=True)+ provenance_agent: Mapped[int | None] = mapped_column(Integer, nullable=True)+ provenance_known: Mapped[int | None] = mapped_column(Integer, nullable=True)+ metadata_source: Mapped[str | None] = mapped_column(String(32), nullable=True)+ reviewers_json: Mapped[str | None] = mapped_column(Text, nullable=True)+ 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)created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=_now_utcdiff --git a/packages/core/src/repowise/core/pipeline/incremental.py b/packages/core/src/repowise/core/pipeline/incremental.pyindex 8eefecaea..f1cf43265 100644--- a/packages/core/src/repowise/core/pipeline/incremental.py+++ b/packages/core/src/repowise/core/pipeline/incremental.py@@ -1547,6 +1547,14 @@ async def persist_incremental_commits(# new capture never needs a re-index to become useful.with timed(timings, "persist.commits.offsets"):await reconcile_commit_offsets(session, repo_id, indexer)+ with timed(timings, "persist.commits.changes"):+ from repowise.core.changes.store import reconcile_categories, refresh_changes++ await refresh_changes(session, repo_id, repo_path, rebuild=False)+ try:+ await reconcile_categories(session, repo_id)+ except Exception as exc:+ logger.debug("category_reconcile_failed", error=str(exc))# Refresh the repo-level whole-history totals so age / commit / contributor# counts keep growing between full re-indexes (#730). Cheap git calls, anddiff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.pyindex 260de1d7b..d9947417f 100644--- a/packages/core/src/repowise/core/pipeline/persist.py+++ b/packages/core/src/repowise/core/pipeline/persist.py@@ -1845,6 +1845,8 @@ async def persist_git(result: Any, session: Any, repo_id: str) -> None:if commit_file_rows:await upsert_git_commit_files_bulk(session, repo_id, commit_file_rows)await clear_attribution_if_disabled(session, repo_id)+ if summary is not None:+ await _rebuild_changes(session, repo_id)# Per fix-commit x file rows (with their SZZ candidates). The prune keeps a# re-index of an already-indexed repo from leaving behind events that have@@ -1888,6 +1890,20 @@ async def persist_git(result: Any, session: Any, repo_id: str) -> None:)+async def _rebuild_changes(session: Any, repo_id: str) -> None:+ """Change records from the same history, after the commit labels they read."""+ from repowise.core.changes.store import refresh_changes+ from repowise.core.persistence.models import Repository++ try:+ repo = await session.get(Repository, repo_id)+ except Exception as exc: # pragma: no cover - defensive+ logger.debug("changes_repo_lookup_failed", repo_id=repo_id, error=str(exc))+ return+ if repo is not None and repo.local_path:+ await refresh_changes(session, repo_id, repo.local_path, rebuild=True)++async def replace_git_history(session: Any,repo_id: str,diff --git a/packages/server/src/repowise/server/app.py b/packages/server/src/repowise/server/app.pyindex 7407351f0..05a904e6f 100644--- a/packages/server/src/repowise/server/app.py+++ b/packages/server/src/repowise/server/app.py@@ -41,6 +41,7 @@ from repowise.server.routers import (actions,blast_radius,c4,+ changes,chat,claude_md,code_health,@@ -365,6 +366,7 @@ _ROUTERS = (c4,webhooks,git,+ changes,dead_code,doc_drift,code_health,diff --git a/packages/server/src/repowise/server/routers/changes.py b/packages/server/src/repowise/server/routers/changes.pynew file mode 100644index 000000000..6cc2420ab--- /dev/null+++ b/packages/server/src/repowise/server/routers/changes.py@@ -0,0 +1,70 @@+"""/api/repos/{repo_id}/changes — merged changes reconstructed from git."""++from __future__ import annotations++from fastapi import APIRouter, Depends, HTTPException, Query+from sqlalchemy.ext.asyncio import AsyncSession++from repowise.core.attribution import attribution_enabled+from repowise.core.changes.record import change_record+from repowise.core.persistence import crud+from repowise.server.deps import get_db_session, verify_api_key+from repowise.server.schemas.changes import (+ ChangeListResponse,+ ChangeRecord,+ summary_from_record,+)++router = APIRouter(+ prefix="/api/repos",+ tags=["changes"],+ dependencies=[Depends(verify_api_key)],+)++_MAX_PAGE = 200+++async def _attribution(session: AsyncSession, repo_id: str) -> bool:+ repo = await crud.get_repository(session, repo_id)+ if repo is None:+ raise HTTPException(status_code=404, detail="Repository not found")+ return attribution_enabled(repo.local_path)++[email protected]("/{repo_id}/changes", response_model=ChangeListResponse)+async def list_changes(+ repo_id: str,+ category: str | None = Query(None, description="One commit category, e.g. fix"),+ shape: str | None = Query(None, description="merge | squash | commit"),+ q: str | None = Query(None, description="Substring of the title, id or a file path"),+ limit: int = Query(50, ge=1, le=_MAX_PAGE),+ offset: int = Query(0, ge=0),+ session: AsyncSession = Depends(get_db_session),+) -> ChangeListResponse:+ """A page of changes, newest merged first."""+ attribution = await _attribution(session, repo_id)+ rows, total = await crud.list_changes(+ session, repo_id, category=category, shape=shape, q=q, limit=limit, offset=offset+ )+ return ChangeListResponse(+ items=[summary_from_record(change_record(r, attribution=attribution)) for r in rows],+ total=total,+ limit=limit,+ offset=offset,+ attribution=attribution,+ )++[email protected]("/{repo_id}/changes/{change_id}", response_model=ChangeRecord)+async def get_change(+ repo_id: str,+ change_id: str,+ session: AsyncSession = Depends(get_db_session),+) -> ChangeRecord:+ """One change by id (``pr-123``), or the change that landed a commit sha."""+ attribution = await _attribution(session, repo_id)+ row = await crud.get_change(session, repo_id, change_id)+ if row is None:+ raise HTTPException(status_code=404, detail="Change not found")+ record = change_record(row, attribution=attribution)+ return ChangeRecord(**record, commit_count=len(record["commits"]))diff --git a/packages/server/src/repowise/server/schemas/changes.py b/packages/server/src/repowise/server/schemas/changes.pynew file mode 100644index 000000000..6d968589a--- /dev/null+++ b/packages/server/src/repowise/server/schemas/changes.py@@ -0,0 +1,90 @@+"""Change Record response models.++The fields mirror ``repowise.core.changes.record.change_record``, the native+versioned JSON every surface serves. A list row leaves out the file and+commit lists and carries their counts.+"""++from __future__ import annotations++from pydantic import BaseModel+++class ChangeIdentity(BaseModel):+ """``pr`` | ``change_id`` | ``merge`` | ``commit``, first that applies."""++ kind: str+ value: str+++class ChangeAuthor(BaseModel):+ name: str+ email: str+++class ChangeFile(BaseModel):+ path: str+ added: int+ deleted: int+++class ChangeProvenance(BaseModel):+ """Three-state AI provenance over the change's commits, with its coverage."""++ label: str+ agent_commits: int+ human_attested_commits: int+ unknown_commits: int+ coverage: float | None = None+++class ChangeForgeMetadata(BaseModel):+ """Forge facts from a metadata source; ``None`` means unknown."""++ source: str | None = None+ reviewers: list[str] | None = None+ approvals: int | None = None+ labels: list[str] | None = None+ linked_issues: list[str] | None = None+++class ChangeSummary(BaseModel):+ schema_version: int+ id: str+ identity: ChangeIdentity+ shape: str+ forge: str+ forge_ref: str | None = None+ title: str+ merged_at: str | None = None+ head_sha: str+ author: ChangeAuthor+ commit_count: int+ files_changed: int+ lines_added: int+ lines_deleted: int+ category: str+ # Null while AI attribution is off, or on rows indexed before it.+ provenance: ChangeProvenance | None = None+++class ChangeRecord(ChangeSummary):+ commits: list[str]+ files: list[ChangeFile]+ metadata: ChangeForgeMetadata+++class ChangeListResponse(BaseModel):+ items: list[ChangeSummary]+ total: int+ limit: int+ offset: int+ #: False when ``attribution.enabled`` is off for the repository.+ attribution: bool+++def summary_from_record(record: dict) -> ChangeSummary:+ return ChangeSummary(+ **{k: v for k, v in record.items() if k in ChangeSummary.model_fields},+ commit_count=len(record["commits"]),+ )diff --git a/packages/types/package.json b/packages/types/package.jsonindex 2727dfa8f..d5b2ead91 100644--- a/packages/types/package.json+++ b/packages/types/package.json@@ -19,6 +19,7 @@"./symbols": "./src/symbols.ts","./chat": "./src/chat.ts","./cards": "./src/cards.ts",+ "./changes": "./src/changes.ts","./views": "./src/views.ts","./workspace": "./src/workspace.ts","./blast-radius": "./src/blast-radius.ts",diff --git a/packages/types/src/changes.ts b/packages/types/src/changes.tsnew file mode 100644index 000000000..2cccc9063--- /dev/null+++ b/packages/types/src/changes.ts@@ -0,0 +1,19 @@+/**+ * Change Records: one merged change (PR, MR, Gerrit change or lone commit)+ * reconstructed from git, as the native versioned JSON record.+ *+ * Generated from the server's response models+ * (`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.+ */+export type {+ ChangeAuthor,+ ChangeFile,+ ChangeForgeMetadata,+ ChangeIdentity,+ ChangeListResponse,+ ChangeProvenance,+ ChangeRecord,+ ChangeSummary,+} from "./generated/http.js";diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.tsindex 70f30a370..ca2a98ab5 100644--- a/packages/types/src/generated/http.ts+++ b/packages/types/src/generated/http.ts@@ -367,6 +367,11 @@ export interface CallersCalleesResponse {relations?: SymbolRelationGroup[];}+export interface ChangeAuthor {+ name: string;+ email: string;+}+/** The Kamei change-shape features the risk model scores. */export interface ChangeFeaturesResponse {la: number;@@ -378,6 +383,85 @@ export interface ChangeFeaturesResponse {exp: number | null;}+export interface ChangeFile {+ path: string;+ added: number;+ deleted: number;+}++/** Forge facts from a metadata source; ``None`` means unknown. */+export interface ChangeForgeMetadata {+ source?: string | null;+ reviewers?: string[] | null;+ approvals?: number | null;+ labels?: string[] | null;+ linked_issues?: string[] | null;+}++/** ``pr`` | ``change_id`` | ``merge`` | ``commit``, first that applies. */+export interface ChangeIdentity {+ kind: string;+ value: string;+}++export interface ChangeListResponse {+ items: ChangeSummary[];+ total: number;+ limit: number;+ offset: number;+ attribution: boolean;+}++/** Three-state AI provenance over the change's commits, with its coverage. */+export interface ChangeProvenance {+ label: string;+ agent_commits: number;+ human_attested_commits: number;+ unknown_commits: number;+ coverage?: number | null;+}++export interface ChangeRecord {+ schema_version: number;+ id: string;+ identity: ChangeIdentity;+ shape: string;+ forge: string;+ forge_ref?: string | null;+ title: string;+ merged_at?: string | null;+ head_sha: string;+ author: ChangeAuthor;+ commit_count: number;+ files_changed: number;+ lines_added: number;+ lines_deleted: number;+ category: string;+ provenance?: ChangeProvenance | null;+ commits: string[];+ files: ChangeFile[];+ metadata: ChangeForgeMetadata;+}++export interface ChangeSummary {+ schema_version: number;+ id: string;+ identity: ChangeIdentity;+ shape: string;+ forge: string;+ forge_ref?: string | null;+ title: string;+ merged_at?: string | null;+ head_sha: string;+ author: ChangeAuthor;+ commit_count: number;+ files_changed: number;+ lines_added: number;+ lines_deleted: number;+ category: string;+ provenance?: ChangeProvenance | null;+}+export interface ChangelogEntryModel {version: string;label?: string | null;diff --git a/packages/types/src/index.ts b/packages/types/src/index.tsindex 07dab22f5..5382d0484 100644--- a/packages/types/src/index.ts+++ b/packages/types/src/index.ts@@ -19,6 +19,7 @@ export * from "./doc-drift.js";export * from "./symbols.js";export * from "./chat.js";export * from "./cards.js";+export * from "./changes.js";export * from "./views.js";export * from "./workspace.js";export * from "./blast-radius.js";diff --git a/packages/ui/vitest.config.ts b/packages/ui/vitest.config.tsindex cdf60ab42..f801647e1 100644--- a/packages/ui/vitest.config.ts+++ b/packages/ui/vitest.config.ts@@ -32,6 +32,7 @@ export default defineConfig({"@repowise-dev/types/symbols": path.resolve(__dirname, "../types/src/symbols.ts"),"@repowise-dev/types/chat": path.resolve(__dirname, "../types/src/chat.ts"),"@repowise-dev/types/cards": path.resolve(__dirname, "../types/src/cards.ts"),+ "@repowise-dev/types/changes": path.resolve(__dirname, "../types/src/changes.ts"),"@repowise-dev/types/views": path.resolve(__dirname, "../types/src/views.ts"),"@repowise-dev/types/workspace": path.resolve(__dirname, "../types/src/workspace.ts"),"@repowise-dev/types/blast-radius": path.resolve(__dirname, "../types/src/blast-radius.ts"),diff --git a/packages/web/messages/en.json b/packages/web/messages/en.jsonindex 3a3025648..708fe288b 100644--- a/packages/web/messages/en.json+++ b/packages/web/messages/en.json@@ -107,6 +107,7 @@"refactoring": "Refactoring","files": "Files","commits": "Commits",+ "changes": "Changes","contributors": "Contributors","decisions": "Decisions","stats": "Stats",@@ -136,6 +137,7 @@"blastRadius": "Blast Radius","decisions": "Decisions","commits": "Commits",+ "changes": "Changes","owners": "Contributors","modules": "Modules","wiki": "Wiki",@@ -244,6 +246,35 @@"evolutionTitle": "How the work changed shape","evolutionDescription": "Commit categories over time, read off the subject line. Fixes carry the accent because that is the series this chart exists to show."},+ "changes": {+ "title": "Changes",+ "description": "Every merged change on the main line, read back from git: pull and merge requests, Gerrit changes and lone commits, with the files each one landed.",+ "emptyTitle": "No changes indexed yet",+ "emptyHint": "Changes are read from git history on the next index or update.",+ "emptyAction": "Go to overview",+ "change": "Change",+ "merged": "Merged",+ "category": "Category",+ "files": "Files",+ "lines": "Lines",+ "title_col": "Title",+ "provenance": "Provenance",+ "showing": "Showing {shown} of {total}",+ "newer": "Newer",+ "older": "Older",+ "allCategories": "All categories",+ "detailCommits": "Commits",+ "detailFiles": "Files",+ "detailMetadata": "Forge metadata",+ "source": "Source",+ "linkedIssues": "Linked issues",+ "approvals": "Approvals",+ "unknown": "Unknown",+ "coverage": "coverage {pct}%",+ "back": "All changes",+ "shape": "Shape",+ "head": "Head"+ },"architecture": {"tabs": {"map": "Map",diff --git a/packages/web/messages/zh-CN.json b/packages/web/messages/zh-CN.jsonindex ef7689104..4d1ca7b0a 100644--- a/packages/web/messages/zh-CN.json+++ b/packages/web/messages/zh-CN.json@@ -107,6 +107,7 @@"refactoring": "重构","files": "文件","commits": "提交",+ "changes": "变更","contributors": "贡献者","decisions": "决策","stats": "统计",@@ -136,6 +137,7 @@"blastRadius": "影响范围","decisions": "决策","commits": "提交",+ "changes": "变更","owners": "贡献者","modules": "模块","wiki": "维基",@@ -244,6 +246,35 @@"evolutionTitle": "工作形态如何变化","evolutionDescription": "按提交标题归类出的各类提交随时间的变化。修复类高亮显示,因为这张图存在的意义就是展示这一条序列。"},+ "changes": {+ "title": "变更",+ "description": "主线上每个已合并的变更,均从 git 历史读取:拉取请求、合并请求、Gerrit 变更和单独提交,以及每个变更带入的文件。",+ "emptyTitle": "尚未索引任何变更",+ "emptyHint": "变更会在下一次索引或更新时从 git 历史读取。",+ "emptyAction": "前往概览",+ "change": "变更",+ "merged": "合并时间",+ "category": "类别",+ "files": "文件",+ "lines": "行数",+ "title_col": "标题",+ "provenance": "来源",+ "showing": "显示 {shown} / {total}",+ "newer": "较新",+ "older": "较早",+ "allCategories": "全部类别",+ "detailCommits": "提交",+ "detailFiles": "文件",+ "detailMetadata": "代码托管平台元数据",+ "source": "来源",+ "linkedIssues": "关联的问题",+ "approvals": "批准数",+ "unknown": "未知",+ "coverage": "覆盖率 {pct}%",+ "back": "全部变更",+ "shape": "形式",+ "head": "头部提交"+ },"architecture": {"tabs": {"map": "地图",diff --git a/packages/web/src/app/repos/[id]/changes/[changeId]/page.tsx b/packages/web/src/app/repos/[id]/changes/[changeId]/page.tsxnew file mode 100644index 000000000..127ae2515--- /dev/null+++ b/packages/web/src/app/repos/[id]/changes/[changeId]/page.tsx@@ -0,0 +1,114 @@+import type { Metadata } from "next";+import Link from "next/link";+import { notFound } from "next/navigation";+import { GitPullRequest } from "lucide-react";+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 { changeLabel } from "@/components/changes/changes-table";+import { getChange } from "@/lib/api/changes";++interface Props {+ params: Promise<{ id: string; changeId: string }>;+}++export async function generateMetadata({ params }: Props): Promise<Metadata> {+ const { id, changeId } = await params;+ try {+ const change = await getChange(id, decodeURIComponent(changeId));+ return { title: `${changeLabel(change)} — Change` };+ } catch {+ return { title: "Change" };+ }+}++/** One Change Record: what landed, from which commits, with what provenance. */+export default async function ChangeDetailPage({ params }: Props) {+ const { id, changeId } = await params;+ const t = await getTranslations("views.changes");++ let change;+ try {+ change = await getChange(id, decodeURIComponent(changeId));+ } catch {+ notFound();+ }++ const meta = change.metadata;+ const prov = change.provenance;+ const facts: [string, string][] = [+ [t("shape"), change.shape],+ [t("category"), change.category],+ [t("merged"), change.merged_at ? formatDate(change.merged_at) : t("unknown")],+ [t("head"), change.head_sha.slice(0, 12)],+ [t("lines"), `+${change.lines_added} -${change.lines_deleted}`],+ ];+ if (prov) {+ const pct = prov.coverage == null ? null : Math.round(prov.coverage * 100);+ facts.push([+ t("provenance"),+ `${prov.label.replace("_", " ")}${pct == null ? "" : ` (${t("coverage", { pct })})`}`,+ ]);+ }++ return (+ <PageShell+ icon={<GitPullRequest />}+ title={`${changeLabel(change)} ${change.title}`}+ actions={+ <Link href={`/repos/${id}/changes`} className="text-xs hover:underline">+ {t("back")}+ </Link>+ }+ >+ <dl className="mb-6 grid grid-cols-2 gap-x-6 gap-y-2 text-sm sm:grid-cols-3">+ {facts.map(([k, v]) => (+ <div key={k}>+ <dt className="text-xs text-[var(--color-text-tertiary)]">{k}</dt>+ <dd className="font-mono text-xs text-[var(--color-text-primary)]">{v}</dd>+ </div>+ ))}+ </dl>++ <OverviewSection title={`${t("detailFiles")} (${change.files_changed})`}>+ <ul className="space-y-1 font-mono text-xs">+ {change.files.map((f) => (+ <li key={f.path} className="flex justify-between gap-4">+ <span className="truncate">{f.path}</span>+ <span className="shrink-0 tabular-nums">+ <span className="text-[var(--color-success)]">+{f.added}</span>{" "}+ <span className="text-[var(--color-error)]">-{f.deleted}</span>+ </span>+ </li>+ ))}+ </ul>+ </OverviewSection>++ <OverviewSection title={`${t("detailCommits")} (${change.commits.length})`}>+ <ul className="space-y-1 font-mono text-xs">+ {change.commits.map((sha) => (+ <li key={sha}>{sha}</li>+ ))}+ </ul>+ </OverviewSection>++ <OverviewSection title={t("detailMetadata")}>+ <dl className="grid grid-cols-2 gap-x-6 gap-y-2 text-xs sm:grid-cols-3">+ <div>+ <dt className="text-[var(--color-text-tertiary)]">{t("source")}</dt>+ <dd>{meta.source ?? t("unknown")}</dd>+ </div>+ <div>+ <dt className="text-[var(--color-text-tertiary)]">{t("linkedIssues")}</dt>+ <dd>{meta.linked_issues?.join(", ") ?? t("unknown")}</dd>+ </div>+ <div>+ <dt className="text-[var(--color-text-tertiary)]">{t("approvals")}</dt>+ <dd>{meta.approvals ?? t("unknown")}</dd>+ </div>+ </dl>+ </OverviewSection>+ </PageShell>+ );+}diff --git a/packages/web/src/app/repos/[id]/changes/page.tsx b/packages/web/src/app/repos/[id]/changes/page.tsxnew file mode 100644index 000000000..4b6d7e4f9--- /dev/null+++ b/packages/web/src/app/repos/[id]/changes/page.tsx@@ -0,0 +1,108 @@+import type { Metadata } from "next";+import Link from "next/link";+import { GitPullRequest } from "lucide-react";+import { getTranslations } from "next-intl/server";+import { PageShell } from "@repowise-dev/ui/shared/page-shell";+import { EmptyState } from "@repowise-dev/ui/shared/empty-state";+import { ChangesTable } from "@/components/changes/changes-table";+import { listChanges } from "@/lib/api/changes";++export const metadata: Metadata = { title: "Changes" };++const PAGE_SIZE = 50;+const CATEGORIES = ["feature", "fix", "refactor", "docs", "test", "deps", "chore", "other"];++/**+ * Merged changes, newest first. A server component: filters and paging are+ * query parameters, so every view is a link.+ */+export default async function ChangesPage({+ params,+ searchParams,+}: {+ params: Promise<{ id: string }>;+ searchParams: Promise<{ offset?: string; category?: string }>;+}) {+ const { id } = await params;+ const sp = await searchParams;+ const offset = Math.max(0, Number.parseInt(sp.offset ?? "0", 10) || 0);+ const category = CATEGORIES.includes(sp.category ?? "") ? sp.category : undefined;+ const base = `/repos/${id}/changes`;+ const t = await getTranslations("views.changes");++ let page;+ try {+ page = await listChanges(id, { limit: PAGE_SIZE, offset, category });+ } catch {+ page = null;+ }++ if (!page || (page.total === 0 && !category)) {+ return (+ <PageShell icon={<GitPullRequest />} title={t("title")} description={t("description")}>+ <EmptyState+ title={t("emptyTitle")}+ description={t("emptyHint")}+ action={{ label: t("emptyAction"), href: `/repos/${id}/overview` }}+ />+ </PageShell>+ );+ }++ const href = (next: { offset?: number; category?: string | undefined }) => {+ const q = new URLSearchParams();+ if (next.category) q.set("category", next.category);+ if (next.offset) q.set("offset", String(next.offset));+ const s = q.toString();+ return s ? `${base}?${s}` : base;+ };+ const chip =+ "rounded-full border px-2.5 py-0.5 text-xs transition-colors border-[var(--color-border-default)] hover:bg-[var(--color-bg-elevated)]";+ const active = "bg-[var(--color-bg-elevated)] text-[var(--color-text-primary)] font-medium";++ return (+ <PageShell icon={<GitPullRequest />} title={t("title")} description={t("description")}>+ <nav className="mb-4 flex flex-wrap gap-2" aria-label={t("category")}>+ <Link href={href({})} className={`${chip} ${category ? "" : active}`}>+ {t("allCategories")}+ </Link>+ {CATEGORIES.map((c) => (+ <Link+ key={c}+ href={href({ category: c })}+ className={`${chip} ${category === c ? active : ""}`}+ >+ {c}+ </Link>+ ))}+ </nav>+ <ChangesTable+ repoId={id}+ rows={page.items}+ showProvenance={page.attribution}+ labels={{+ change: t("change"),+ merged: t("merged"),+ category: t("category"),+ files: t("files"),+ lines: t("lines"),+ title: t("title_col"),+ provenance: t("provenance"),+ }}+ />+ <div className="mt-4 flex items-center justify-between text-xs text-[var(--color-text-secondary)]">+ <span>{t("showing", { shown: page.items.length, total: page.total })}</span>+ <span className="flex gap-3">+ {offset > 0 && (+ <Link href={href({ category, offset: Math.max(0, offset - PAGE_SIZE) })}>+ {t("newer")}+ </Link>+ )}+ {offset + PAGE_SIZE < page.total && (+ <Link href={href({ category, offset: offset + PAGE_SIZE })}>{t("older")}</Link>+ )}+ </span>+ </div>+ </PageShell>+ );+}diff --git a/packages/web/src/components/changes/changes-table.tsx b/packages/web/src/components/changes/changes-table.tsxnew file mode 100644index 000000000..ee45cfeda--- /dev/null+++ b/packages/web/src/components/changes/changes-table.tsx@@ -0,0 +1,98 @@+"use client";++import Link from "next/link";+import { ResponsiveTable, type ResponsiveColumn } from "@repowise-dev/ui/shared/responsive-table";+import { formatDate } from "@repowise-dev/ui/lib/format";+import type { ChangeSummary } from "@/lib/api/changes";++export interface ChangesTableLabels {+ change: string;+ merged: string;+ category: string;+ files: string;+ lines: string;+ title: string;+ provenance: string;+}++/** The change's short name: the forge ref when it has one, else a trimmed id. */+export function changeLabel(c: Pick<ChangeSummary, "forge_ref" | "id">): string {+ return c.forge_ref ?? (c.id.length > 19 ? c.id.slice(0, 19) : c.id);+}++export function ChangesTable({+ repoId,+ rows,+ labels,+ showProvenance,+}: {+ repoId: string;+ rows: ChangeSummary[];+ labels: ChangesTableLabels;+ showProvenance: boolean;+}) {+ const columns: ResponsiveColumn<ChangeSummary>[] = [+ {+ key: "id",+ header: labels.change,+ render: (c) => (+ <Link+ href={`/repos/${repoId}/changes/${encodeURIComponent(c.id)}`}+ className="font-mono text-xs text-[var(--color-accent-primary)] hover:underline"+ >+ {changeLabel(c)}+ </Link>+ ),+ },+ {+ key: "title",+ header: labels.title,+ cellClassName: "min-w-[220px] max-w-[520px] truncate",+ render: (c) => <span title={c.title}>{c.title}</span>,+ },+ {+ key: "merged_at",+ header: labels.merged,+ priority: 2,+ render: (c) => (+ <span className="text-xs text-[var(--color-text-secondary)]">+ {c.merged_at ? formatDate(c.merged_at) : ""}+ </span>+ ),+ },+ {+ key: "category",+ header: labels.category,+ priority: 2,+ render: (c) => <span className="text-xs">{c.category}</span>,+ },+ {+ key: "files",+ header: labels.files,+ align: "right",+ priority: 3,+ render: (c) => <span className="tabular-nums">{c.files_changed}</span>,+ },+ {+ key: "lines",+ header: labels.lines,+ align: "right",+ priority: 3,+ render: (c) => (+ <span className="font-mono text-xs tabular-nums">+ <span className="text-[var(--color-success)]">+{c.lines_added}</span>{" "}+ <span className="text-[var(--color-error)]">-{c.lines_deleted}</span>+ </span>+ ),+ },+ ];+ if (showProvenance) {+ columns.push({+ key: "provenance",+ header: labels.provenance,+ priority: 3,+ render: (c) => <span className="text-xs">{c.provenance?.label.replace("_", " ") ?? ""}</span>,+ });+ }+ return <ResponsiveTable columns={columns} rows={rows} rowKey={(c) => c.id} stacked="sm" />;+}diff --git a/packages/web/src/components/layout/nav-items.ts b/packages/web/src/components/layout/nav-items.tsindex da956b439..b45088a99 100644--- a/packages/web/src/components/layout/nav-items.ts+++ b/packages/web/src/components/layout/nav-items.ts@@ -18,6 +18,7 @@ import {FolderTree,GitCommitHorizontal,GitMerge,+ GitPullRequest,HeartPulse,LayoutDashboard,Layers,@@ -87,6 +88,7 @@ export function repoNavGroups(repoId: string): NavGroup[] {labelKey: "groupPeopleAndHistory",items: [{ label: "Commits", labelKey: "commits", href: `${base}/commits`, icon: GitCommitHorizontal },+ { label: "Changes", labelKey: "changes", href: `${base}/changes`, icon: GitPullRequest },{ label: "Contributors", labelKey: "contributors", href: `${base}/owners`, icon: Users },{ label: "Decisions", labelKey: "decisions", href: `${base}/decisions`, icon: Lightbulb },],diff --git a/packages/web/src/components/layout/repo-breadcrumb-label.ts b/packages/web/src/components/layout/repo-breadcrumb-label.tsindex 834f0cb26..dea0c8340 100644--- a/packages/web/src/components/layout/repo-breadcrumb-label.ts+++ b/packages/web/src/components/layout/repo-breadcrumb-label.ts@@ -16,6 +16,7 @@ const SEGMENT_LABELS: Record<string, string> = {"blast-radius": "Blast Radius",decisions: "Decisions",commits: "Commits",+ changes: "Changes",owners: "Contributors",modules: "Modules",wiki: "Wiki",@@ -55,6 +56,7 @@ export const SEGMENT_MESSAGE_KEYS: Record<string, string> = {"blast-radius": "blastRadius",decisions: "decisions",commits: "commits",+ changes: "changes",owners: "owners",modules: "modules",wiki: "wiki",diff --git a/packages/web/src/lib/api/changes.ts b/packages/web/src/lib/api/changes.tsnew file mode 100644index 000000000..15357c11b--- /dev/null+++ b/packages/web/src/lib/api/changes.ts@@ -0,0 +1,3 @@+import "./client";++export * from "@repowise-dev/api-client/changes";diff --git a/tests/unit/cli/test_changes_cmd.py b/tests/unit/cli/test_changes_cmd.pynew file mode 100644index 000000000..97151a942--- /dev/null+++ b/tests/unit/cli/test_changes_cmd.py@@ -0,0 +1,103 @@+"""`repowise changes list` and `show` against a real local index."""++from __future__ import annotations++import json+from datetime import UTC, datetime+from pathlib import Path++from click.testing import CliRunner++from repowise.cli.commands.changes_cmd import changes_group+from repowise.cli.helpers import run_async++HEAD = "c" * 40+++async def _store(repo_path: Path) -> None:+ from repowise.core.persistence import (+ create_engine,+ create_session_factory,+ get_session,+ init_db,+ upsert_repository,+ )+ from repowise.core.persistence.crud import upsert_changes++ (repo_path / ".repowise").mkdir(exist_ok=True)+ engine = create_engine(f"sqlite+aiosqlite:///{(repo_path / '.repowise' / 'wiki.db').as_posix()}")+ try:+ await init_db(engine)+ async with get_session(create_session_factory(engine)) as session:+ repo = await upsert_repository(session, name="repo", local_path=str(repo_path))+ await upsert_changes(+ session,+ repo.id,+ [+ {+ "change_id": "pr-5",+ "identity_kind": "pr",+ "identity_value": "5",+ "shape": "squash",+ "forge": "github",+ "forge_ref": "#5",+ "title": "fix: crash (#5)",+ "merged_at": datetime(2026, 3, 1, tzinfo=UTC),+ "head_sha": HEAD,+ "commit_shas_json": json.dumps([HEAD]),+ "files_json": json.dumps([{"path": "a.py", "added": 1, "deleted": 2}]),+ "files_changed": 1,+ "lines_added": 1,+ "lines_deleted": 2,+ "category": "fix",+ "metadata_source": "git",+ }+ ],+ )+ finally:+ await engine.dispose()+++def _repo(tmp_path: Path) -> Path:+ root = tmp_path / "repo"+ (root / ".git").mkdir(parents=True)+ run_async(_store(root))+ return root+++def test_list_and_show_formats(tmp_path):+ root = _repo(tmp_path)+ runner = CliRunner()++ listed = runner.invoke(changes_group, ["list", "--path", str(root), "--format", "json"])+ assert listed.exit_code == 0, listed.output+ data = json.loads(listed.output)+ assert data["total"] == 1 and data["changes"][0]["id"] == "pr-5"+ assert "files" not in data["changes"][0]++ table = runner.invoke(changes_group, ["list", "--path", str(root)])+ assert table.exit_code == 0 and "#5" in table.output++ shown = json.loads(+ runner.invoke(changes_group, ["show", "pr-5", "--path", str(root), "--format", "json"]).output+ )+ assert shown["schema_version"] == 1 and shown["files"][0]["path"] == "a.py"++ statement = json.loads(+ runner.invoke(+ changes_group, ["show", HEAD[:8], "--path", str(root), "--format", "in-toto"]+ ).output+ )+ assert statement["_type"] == "https://in-toto.io/Statement/v1"+ assert statement["subject"] == [{"name": HEAD, "digest": {"gitCommit": HEAD}}]+ assert statement["predicateType"] == "https://repowise.dev/ChangeRecord/v1"++ missing = runner.invoke(changes_group, ["show", "pr-9", "--path", str(root)])+ assert missing.exit_code == 1+++def test_no_index_exits_non_zero(tmp_path):+ root = tmp_path / "bare"+ (root / ".git").mkdir(parents=True)+ result = CliRunner().invoke(changes_group, ["list", "--path", str(root)])+ assert result.exit_code == 1 and "No index" in result.outputdiff --git a/tests/unit/cli/test_lazy_commands.py b/tests/unit/cli/test_lazy_commands.pyindex 6fdb42b57..2271d626b 100644--- a/tests/unit/cli/test_lazy_commands.py+++ b/tests/unit/cli/test_lazy_commands.py@@ -33,7 +33,7 @@ from repowise.core.registry import CLIRegistry, LazyCommand#: command is meant to require editing it._EXPECTED_NAMES = frozenset({- "agents", "ask", "attribution", "augment", "components", "config", "context", "corrections",+ "agents", "ask", "attribution", "augment", "changes", "components", "config", "context", "corrections","costs", "coverage","dead-code", "decision", "delete", "distill", "doc-drift", "doctor","expand",diff --git a/tests/unit/core/test_changes.py b/tests/unit/core/test_changes.pynew file mode 100644index 000000000..38d1abcab--- /dev/null+++ b/tests/unit/core/test_changes.py@@ -0,0 +1,422 @@+"""Change Records: reconstruction from git, the metadata seam, storage and export."""++from __future__ import annotations++import json+import os+import subprocess+from datetime import UTC, datetime+from pathlib import Path++import git as gitpython+import pytest++from repowise.core import attribution+from repowise.core.changes import (+ PREDICATE_TYPE,+ change_metadata_sources,+ change_record,+ in_toto_statement,+ reconstruct_changes,+)+from repowise.core.changes.reconstruct import change_identity, change_title+from repowise.core.changes.source import GitChangeMetadata+from repowise.core.changes.store import change_provenance, refresh_changes+from repowise.core.ingestion.git_indexer.commit_rows import build_commit_rows++GERRIT_ID = "I" + "a" * 40+++class _Repo:+ def __init__(self, root: Path) -> None:+ self.root = root+ self.clock = 1_700_000_000+ root.mkdir(parents=True)+ self.git("init", "-q", "-b", "main")+ self.git("config", "user.name", "Ann")+ self.git("config", "user.email", "[email protected]")+ self.git("config", "commit.gpgsign", "false")++ def git(self, *args: str, author: str | None = None) -> str:+ self.clock += 60+ env = {+ **os.environ,+ "GIT_AUTHOR_DATE": f"{self.clock} +0000",+ "GIT_COMMITTER_DATE": f"{self.clock} +0000",+ }+ if author:+ env["GIT_AUTHOR_NAME"] = author+ env["GIT_AUTHOR_EMAIL"] = f"{author.lower()}@example.com"+ return subprocess.run(+ ["git", *args], cwd=self.root, env=env, check=True, capture_output=True, text=True+ ).stdout.strip()++ def commit(self, path: str, message: str, *, author: str | None = None) -> str:+ file = self.root / path+ file.parent.mkdir(parents=True, exist_ok=True)+ file.write_text(f"{path} {self.clock}\n", encoding="utf-8")+ self.git("add", path)+ self.git("commit", "-q", "-m", message, author=author)+ return self.git("rev-parse", "HEAD")++ def merge(self, branch: str, message: str) -> str:+ self.git("merge", "-q", "--no-ff", branch, "-m", message)+ return self.git("rev-parse", "HEAD")++ def head(self) -> str:+ return self.git("rev-parse", "HEAD")+++def history(tmp_path: Path) -> tuple[_Repo, dict[str, str]]:+ """One main line holding every merge style the reconstruction reads."""+ r = _Repo(tmp_path / "repo")+ shas: dict[str, str] = {}+ shas["root"] = r.commit("README.md", "Initial commit")+ shas["squash"] = r.commit("src/a.py", "feat: add a (#12)")++ r.git("checkout", "-q", "-b", "feature")+ shas["f1"] = r.commit("src/b.py", "start b", author="Bob")+ shas["f2"] = r.commit("src/b_test.py", "test b", author="Carol")+ r.git("checkout", "-q", "main")+ shas["gh_merge"] = r.merge("feature", "Merge pull request #13 from bob/feature\n\nAdd the b feature")++ shas["lone"] = r.commit("src/c.py", "fix: c crashes on empty input")+ shas["gerrit"] = r.commit("src/d.py", f"Add d\n\nLonger text.\n\nChange-Id: {GERRIT_ID}")++ r.git("checkout", "-q", "-b", "gl")+ r.commit("src/e.py", "e work")+ r.git("checkout", "-q", "main")+ shas["gl_merge"] = r.merge(+ "gl",+ "Merge branch 'gl' into 'main'\n\nGitLab title\n\n"+ "See merge request grp/proj!7\n\nApproved-by: Dee <[email protected]>",+ )++ r.git("checkout", "-q", "-b", "az")+ r.commit("src/f.py", "f work")+ r.git("checkout", "-q", "main")+ shas["az_merge"] = r.merge("az", "Merged PR 21: Azure title")++ # Work done elsewhere and brought back by an unnamed merge: the squash+ # inside is its own change, the stray commit stays with the merge.+ r.git("checkout", "-q", "-b", "upstream")+ shas["up_squash"] = r.commit("src/g.py", "docs: g (#30)")+ shas["up_stray"] = r.commit("src/h.py", "h tweak")+ r.git("checkout", "-q", "main")+ shas["anon_merge"] = r.merge("upstream", "Merge branch 'main' of github.com:x/y")+ return r, shas+++def _changes(r: _Repo, forge: str = "github", **kw):+ repo = gitpython.Repo(r.root)+ try:+ return reconstruct_changes(repo, forge, limit=500, **kw)+ finally:+ repo.close()+++def _files(change) -> set[str]:+ return {p for p, _, _ in change.files}+++def test_every_merge_style_reads_back_as_one_change(history):+ r, shas = history+ by_id = {c.change_id: c for c in _changes(r)}++ squash = by_id["pr-12"]+ assert (squash.shape, squash.forge_ref, squash.commit_shas) == ("squash", "#12", [shas["squash"]])+ assert _files(squash) == {"src/a.py"} and squash.category == "feature"++ merge = by_id["pr-13"]+ assert merge.shape == "merge" and merge.head_sha == shas["gh_merge"]+ assert merge.title == "Add the b feature"+ assert merge.commit_shas == [shas["f2"], shas["f1"]]+ assert _files(merge) == {"src/b.py", "src/b_test.py"}+ assert merge.author_name == "Bob" # who opened the branch, not who merged it++ lone = by_id[f"commit-{shas['lone']}"]+ assert (lone.shape, lone.category, lone.forge_ref) == ("commit", "fix", None)++ gerrit = by_id[f"change-{GERRIT_ID}"]+ assert gerrit.identity_kind == "change_id" and _files(gerrit) == {"src/d.py"}++ gitlab = by_id["pr-7"]+ assert gitlab.title == "GitLab title" and _files(gitlab) == {"src/e.py"}++ azure = by_id["pr-21"]+ assert azure.title == "Azure title" and _files(azure) == {"src/f.py"}++ nested = by_id["pr-30"]+ assert nested.head_sha == shas["up_squash"] and _files(nested) == {"src/g.py"}+ anon = by_id[f"merge-{shas['anon_merge']}"]+ assert anon.commit_shas == [shas["up_stray"]] and _files(anon) == {"src/h.py"}++ assert f"commit-{shas['root']}" in by_id+ assert len(by_id) == 9+++def test_forge_ref_follows_the_repo_forge(history):+ r, _ = history+ by_id = {c.change_id: c for c in _changes(r, forge="gitlab")}+ assert by_id["pr-7"].forge_ref == "!7"+ assert by_id["pr-7"].forge == "gitlab"+++def test_merge_with_only_named_changes_is_dropped(tmp_path):+ r = _Repo(tmp_path / "repo")+ r.commit("a.py", "a")+ r.git("checkout", "-q", "-b", "up")+ up = r.commit("b.py", "b (#4)")+ r.git("checkout", "-q", "main")+ r.commit("c.py", "c")+ r.merge("up", "Merge branch 'main' of github.com:x/y")+ changes = _changes(r)+ assert [c.change_id for c in changes if c.shape == "merge"] == []+ assert {c.change_id: c.head_sha for c in changes}["pr-4"] == up+++def test_identity_order_pr_then_change_id_then_merge_then_commit():+ body = f"Text\n\nChange-Id: {GERRIT_ID}"+ assert change_identity("Add x (#5)", body, "s", False, "github")[:2] == ("pr", "5")+ assert change_identity("Add x", body, "s", False, "github")[:2] == ("change_id", GERRIT_ID)+ assert change_identity("Merge branch 'x'", "", "m", True, "github")[:2] == ("merge", "m")+ assert change_identity("Add x", "", "c", False, "github")[:2] == ("commit", "c")+++def test_title_skips_boilerplate_and_trailers():+ assert change_title("Merge pull request #1 from a/b", "Real title\n\nbody", True) == "Real title"+ assert change_title("Merge branch 'x' into 'main'", "See merge request g/p!3", True) == (+ "Merge branch 'x' into 'main'"+ )+ assert change_title("Merged PR 9: Fix it", "", True) == "Fix it"+ assert change_title("feat: x (#2)", "body", False) == "feat: x (#2)"+++def test_repeated_identity_gets_a_distinct_id_and_keeps_it(tmp_path):+ r = _Repo(tmp_path / "repo")+ first = r.commit("a.py", "fix: a (#8)")+ second = r.commit("b.py", "fix: a again (#8)")+ ids = {c.head_sha: c.change_id for c in _changes(r)}+ assert ids[first] == "pr-8"+ assert ids[second] == f"pr-8-{second[:12]}"+ # An update that re-reads the second keeps both ids where they were.+ again = _changes(r, since_sha=first, taken={"pr-8": first})+ assert [c.change_id for c in again] == [f"pr-8-{second[:12]}"]+++def test_since_reads_only_newer_and_rebuilds_off_history(history):+ r, shas = history+ newer = r.commit("z.py", "chore: z")+ assert [c.head_sha for c in _changes(r, since_sha=shas["anon_merge"])] == [newer]+ assert _changes(r, since_sha=newer) == []+ r.git("checkout", "-q", "-b", "side", shas["root"])+ assert _changes(r, since_sha=newer) is None+++def test_commit_rows_store_the_category():+ rows = build_commit_rows(+ [+ {"sha": "a", "author_name": "A", "author_email": "a@x", "ts": 1, "subject": "fix: x", "changes": []},+ {"sha": "b", "author_name": "A", "author_email": "a@x", "ts": 2, "subject": "docs: y", "changes": []},+ ]+ )+ assert {r["sha"]: r["category"] for r in rows} == {"a": "fix", "b": "docs"}+++def test_provenance_is_three_state_with_counts():+ labels = {+ "a": ("agent", "claude"),+ "h": ("human_attested", None),+ "u": ("unknown", None),+ "old": (None, "claude"), # written before the label: derived from agent_name+ }+ assert change_provenance(["a", "u"], labels) == ("agent", 1, 1)+ assert change_provenance(["h"], labels) == ("human_attested", 0, 1)+ assert change_provenance(["h", "u"], labels) == ("unknown", 0, 1)+ assert change_provenance(["h", "missing"], labels) == ("unknown", 0, 1)+ assert change_provenance(["old"], labels) == ("agent", 1, 1)+ assert change_provenance([], labels) == ("unknown", 0, 0)+++def test_metadata_seam_defaults_to_git_and_reads_trailers(history):+ r, _ = history+ assert isinstance(change_metadata_sources.get(), GitChangeMetadata)+ assert change_metadata_sources.default == "git"+ changes = _changes(r)+ meta = GitChangeMetadata().metadata(r.root, changes)+ assert meta["pr-7"].approvals == 1+ assert meta["pr-7"].reviewers is None and meta["pr-7"].labels is None+++def test_metadata_seam_takes_a_plugin(monkeypatch):+ class Forge:+ def metadata(self, repo_path, changes):+ return {}++ change_metadata_sources.register("test-forge", Forge())+ monkeypatch.setenv("REPOWISE_SEAM_CHANGE_METADATA", "test-forge")+ assert isinstance(change_metadata_sources.get(), Forge)+ monkeypatch.delenv("REPOWISE_SEAM_CHANGE_METADATA")+ assert isinstance(change_metadata_sources.get(), GitChangeMetadata)+++class _Row:+ def __init__(self, **kw):+ self.__dict__.update(kw)+++def _row(**over) -> _Row:+ base = dict(+ change_id="pr-13",+ identity_kind="pr",+ identity_value="13",+ shape="merge",+ forge="github",+ forge_ref="#13",+ title="Add b",+ merged_at=datetime(2026, 1, 2, tzinfo=UTC),+ head_sha="m" * 40,+ author_name="Bob",+ author_email="[email protected]",+ commit_shas_json=json.dumps(["b" * 40, "a" * 40]),+ files_json=json.dumps([{"path": "src/b.py", "added": 3, "deleted": 1}]),+ files_changed=1,+ lines_added=3,+ lines_deleted=1,+ category="feature",+ provenance="agent",+ provenance_agent=1,+ provenance_known=1,+ metadata_source="git",+ reviewers_json=None,+ approvals=None,+ labels_json=None,+ linked_issues_json=json.dumps(["#4"]),+ )+ base.update(over)+ return _Row(**base)+++def test_record_is_versioned_and_honours_attribution_off():+ record = change_record(_row())+ assert record["schema_version"] == 1+ assert record["identity"] == {"kind": "pr", "value": "13"}+ assert record["provenance"] == {+ "label": "agent",+ "agent_commits": 1,+ "human_attested_commits": 0,+ "unknown_commits": 1,+ "coverage": 0.5,+ }+ assert record["metadata"] == {+ "source": "git",+ "reviewers": None,+ "approvals": None,+ "labels": None,+ "linked_issues": ["#4"],+ }+ assert change_record(_row(), attribution=False)["provenance"] is None+ assert change_record(_row(provenance=None))["provenance"] is None+++def test_in_toto_statement_shape():+ record = change_record(_row())+ statement = in_toto_statement(record)+ assert statement["_type"] == "https://in-toto.io/Statement/v1"+ assert statement["predicateType"] == PREDICATE_TYPE+ assert [s["digest"] for s in statement["subject"]] == [+ {"gitCommit": "m" * 40},+ {"gitCommit": "b" * 40},+ {"gitCommit": "a" * 40},+ ]+ assert statement["predicate"] == record+++# ---------------------------------------------------------------------------+# Storage+# ---------------------------------------------------------------------------+++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)+++async def _db(tmp_path: Path, repo_root: Path):+ from repowise.core.persistence import (+ create_engine,+ create_session_factory,+ init_db,+ upsert_repository,+ )+ 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(repo_root))+ repo_id = repo.id+ return engine, factory, repo_id++[email protected]("_private_user_config")+async def test_refresh_rebuilds_then_extends(tmp_path, history):+ from repowise.core.persistence.crud import (+ get_change,+ list_changes,+ upsert_git_commits_bulk,+ )+ from repowise.core.persistence.database import get_session++ r, shas = history+ engine, factory, repo_id = await _db(tmp_path, r.root)+ try:+ async with get_session(factory) as session:+ await upsert_git_commits_bulk(+ session,+ repo_id,+ [+ {"sha": shas["f1"], "subject": "start b", "attribution": "agent", "agent_name": "claude"},+ {"sha": shas["f2"], "subject": "test b", "attribution": "unknown"},+ ],+ )+ assert await refresh_changes(session, repo_id, r.root, rebuild=True) == 9+ async with get_session(factory) as session:+ row = await get_change(session, repo_id, "pr-13")+ assert (row.provenance, row.provenance_agent, row.provenance_known) == ("agent", 1, 1)+ assert (await get_change(session, repo_id, shas["f1"][:10])).change_id == "pr-13"+ assert (await get_change(session, repo_id, "pr-7")).approvals == 1++ newer = r.commit("z.py", "chore: z (#40)")+ async with get_session(factory) as session:+ assert await refresh_changes(session, repo_id, r.root, rebuild=False) == 1+ rows, total = await list_changes(session, repo_id, limit=3)+ assert total == 10 and rows[0].head_sha == newer+ _, fixes = await list_changes(session, repo_id, category="fix")+ assert fixes == 1+ finally:+ await engine.dispose()++[email protected]("_private_user_config")+async def test_attribution_off_stores_no_provenance(tmp_path, history):+ from repowise.core.persistence.crud import get_change+ from repowise.core.persistence.database import get_session++ r, _ = history+ (r.root / ".repowise").mkdir()+ (r.root / ".repowise" / "config.yaml").write_text("attribution:\n enabled: false\n")+ engine, factory, repo_id = await _db(tmp_path, r.root)+ try:+ async with get_session(factory) as session:+ await refresh_changes(session, repo_id, r.root, rebuild=True)+ async with get_session(factory) as session:+ row = await get_change(session, repo_id, "pr-13")+ assert (row.provenance, row.provenance_agent, row.provenance_known) == (None, None, None)+ finally:+ await engine.dispose()diff --git a/tests/unit/persistence/test_models.py b/tests/unit/persistence/test_models.pyindex 8849bf352..c18254770 100644--- a/tests/unit/persistence/test_models.py+++ b/tests/unit/persistence/test_models.py@@ -310,6 +310,7 @@ def test_base_includes_all_models():"dead_code_findings","doc_drift_findings","doc_drift_references",+ "changes","decision_records","decision_evidence","decision_edges",diff --git a/tests/unit/server/conftest.py b/tests/unit/server/conftest.pyindex ed2bca92a..c8cc4385f 100644--- a/tests/unit/server/conftest.py+++ b/tests/unit/server/conftest.py@@ -30,6 +30,7 @@ def _create_test_app():from repowise.server.routers import (blast_radius,c4,+ changes,code_health,costs,dead_code,@@ -89,6 +90,7 @@ def _create_test_app():app.include_router(meta.router)app.include_router(webhooks.router)app.include_router(git.router)+ app.include_router(changes.router)app.include_router(files.router)app.include_router(dead_code.router)app.include_router(doc_drift.router)diff --git a/tests/unit/server/test_changes_routes.py b/tests/unit/server/test_changes_routes.pynew file mode 100644index 000000000..b90f7008b--- /dev/null+++ b/tests/unit/server/test_changes_routes.py@@ -0,0 +1,112 @@+"""GET /api/repos/{id}/changes and /changes/{change_id}."""++from __future__ import annotations++import json+from datetime import UTC, datetime+from pathlib import Path++import pytest+from httpx import AsyncClient++from repowise.core import attribution+from repowise.core.persistence import crud+from repowise.core.persistence.database import get_session+from tests.unit.server.conftest import create_test_repo++[email protected](autouse=True)+def _private_user_config(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ user_file = tmp_path / "home" / ".repowise" / "config.yaml"+ monkeypatch.setattr(attribution, "user_config_path", lambda: user_file)+++def _row(change_id: str, day: int, **over) -> dict:+ row = {+ "change_id": change_id,+ "identity_kind": "pr",+ "identity_value": change_id.removeprefix("pr-"),+ "shape": "squash",+ "forge": "github",+ "forge_ref": "#" + change_id.removeprefix("pr-"),+ "title": f"feat: change {change_id}",+ "merged_at": datetime(2026, 1, day, tzinfo=UTC),+ "head_sha": f"{day:02d}" + "a" * 38,+ "author_name": "Ann",+ "author_email": "[email protected]",+ "commit_shas_json": json.dumps([f"{day:02d}" + "a" * 38]),+ "files_json": json.dumps([{"path": "src/x.py", "added": 2, "deleted": 0}]),+ "files_changed": 1,+ "lines_added": 2,+ "lines_deleted": 0,+ "category": "feature",+ "provenance": "agent",+ "provenance_agent": 1,+ "provenance_known": 1,+ "metadata_source": "git",+ }+ row.update(over)+ return row+++async def _seed(app, repo_id: str) -> None:+ async with get_session(app.state.session_factory) as session:+ await crud.upsert_changes(+ session,+ repo_id,+ [+ _row("pr-1", 1),+ _row("pr-2", 2, category="fix", title="fix: crash"),+ _row("pr-3", 3, files_json=json.dumps([{"path": "docs/a.md", "added": 1, "deleted": 0}])),+ ],+ )+++async def test_list_is_newest_first_and_filters(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ await _seed(app, repo["id"])+ url = f"/api/repos/{repo['id']}/changes"++ page = (await client.get(url)).json()+ assert page["total"] == 3 and page["attribution"] is True+ assert [c["id"] for c in page["items"]] == ["pr-3", "pr-2", "pr-1"]+ first = page["items"][0]+ assert first["schema_version"] == 1 and first["commit_count"] == 1+ assert "files" not in first+ assert first["provenance"]["label"] == "agent"++ assert [c["id"] for c in (await client.get(url, params={"category": "fix"})).json()["items"]] == [+ "pr-2"+ ]+ assert [c["id"] for c in (await client.get(url, params={"q": "docs/a"})).json()["items"]] == [+ "pr-3"+ ]+++async def test_show_by_id_or_sha(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ await _seed(app, repo["id"])+ base = f"/api/repos/{repo['id']}/changes"++ record = (await client.get(f"{base}/pr-2")).json()+ assert record["files"] == [{"path": "src/x.py", "added": 2, "deleted": 0}]+ assert record["metadata"]["source"] == "git" and record["metadata"]["reviewers"] is None+ assert (await client.get(f"{base}/{'02' + 'a' * 8}")).json()["id"] == "pr-2"+ assert (await client.get(f"{base}/pr-99")).status_code == 404+ assert (await client.get("/api/repos/nope/changes")).status_code == 404+++async def test_attribution_off_hides_provenance(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ await _seed(app, repo["id"])+ config = Path(repo["local_path"]) / ".repowise" / "config.yaml"+ config.parent.mkdir(parents=True, exist_ok=True)+ config.write_text("attribution:\n enabled: false\n", encoding="utf-8")++ page = (await client.get(f"/api/repos/{repo['id']}/changes")).json()+ assert page["attribution"] is False+ assert 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