Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(mcp): serve Change Records and attribution through MCP and chat views (#3784)

Raghav Chamadiya03c754a0e7dd
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.md
index 764e6c912..03782325f 100644
--- a/docs/agent/MCP_TOOLS.md
+++ b/docs/agent/MCP_TOOLS.md
@@ -161,8 +161,8 @@ A triage card for files, modules or symbols: summary, symbols with signatures an
| Parameter | Type | Default | Meaning |
|-----------|------|---------|---------|
-| `targets` | list[string] | required | File paths, module paths, `"path::Symbol"` ids, or `"component:<name>"` |
-| `include` | list[string] | none | Any of `full_doc`, `ownership`, `last_change`, `callers`, `callees`, `references`, `metrics`, `community`, `decisions`, `skeleton`, `health`, `doc_drift`, `symbols` |
+| `targets` | list[string] | required | File paths, module paths, `"path::Symbol"` ids, `"component:<name>"`, or `"change:<id>"` |
+| `include` | list[string] | none | Any of `full_doc`, `ownership`, `last_change`, `callers`, `callees`, `references`, `metrics`, `community`, `decisions`, `skeleton`, `health`, `doc_drift`, `symbols`, `changes`, `provenance` |
| `compact` | bool | `true` | `false` adds the structure block, imports and docstrings |
| `repo` | string | default repo | Workspace repo alias. `"all"` is not supported (returns an error) |
@@ -170,6 +170,8 @@ A triage card for files, modules or symbols: summary, symbols with signatures an
A `component:<name>` target returns the component's declared context (owner, system, criticality, tags) and `facts` rolled up over its files: health, hotspots, bus factor, test reach and dead code, each with a `basis` (`measured`, `inferred` or `unavailable`). Components come from [`.repowise/components.yaml`](../reference/CONFIG.md#repowisecomponentsyaml) or are derived from the index. `include` does not apply to component targets; health and dead code leave out files in gated languages and say how many.
+A `change:<id>` target (`change:pr-123`, or a commit sha the change landed) returns the [Change Record](../reference/CLI_REFERENCE.md#repowise-changes): title, forge ref, `merged_at`, category, files and provenance with its coverage. On a file target, `changes` lists the newest Change Records that touched it, and `provenance` gives the file's commits by source (agent, human-attested, unknown) with coverage; the agent share is withheld below 30% coverage. With attribution off, `provenance` reads `{"unavailable": "attribution_off"}` and change rows carry none.
+
A file's compact symbol list holds its top 15 symbols: types (classes, interfaces, structs, traits, enums, type aliases, impls, modules) first, then functions and methods, then the rest, each group by centrality. `symbols_truncated` gives the total, and `include=["symbols"]` lists them all. When the response budget trims the list further, it keeps symbols by kind and name match, not centrality. A row without `symbol_id` is `path::name`; methods and overload variants carry theirs, so pass a row's id to `get_symbol` when it has one.
`full_doc` returns the page as `content_md`, plus `digest_md` on pages that carry an agent digest: the questions the page answers, its concept index, public API and git signals. Both are dropped first when the response is over budget. `skeleton` renders a file with bodies elided: every signature, the imports, and the bodies of its most central symbols, with line ranges on every elision. `doc_drift` lists the documents that name the file and whether they carry drift. An empty `callers` or `callees` list comes with a `*_basis` saying how much of that language's calls the graph resolved; read it before concluding nothing calls a symbol.
@@ -242,7 +244,7 @@ What history says about touching a file: hotspot score, bug-fix record, owners,
|-----------|------|---------|---------|
| `targets` | list[string] | `changed_files` | File paths to assess |
| `changed_files` | list[string] | none | Files in a change; switches on PR mode |
-| `include` | list[string] | none | `graph` (typed dependents, consumers, cross-repo links), `churn`, `owners` (owner percentages, bus factor, contributor count), `tests` (typed `test_recommendations` in PR mode), `blast` (`pr_blast_radius` in PR mode), `scales` (units and calibration, identical per call) |
+| `include` | list[string] | none | `graph` (typed dependents, consumers, cross-repo links), `churn`, `owners` (owner percentages, bus factor, contributor count), `tests` (typed `test_recommendations` in PR mode), `blast` (`pr_blast_radius` in PR mode), `scales` (units and calibration, identical per call), `changes` (each file's newest Change Records) |
| `repo` | string | default repo | Workspace repo alias. `"all"` is not supported |
**Key return fields:** per file: `hotspot_score` (0 to 1), `health_score` (0 to 10), `dependents_count`, `co_change_partners` (`file_path`, `support`, `conf_ab`, `has_import_link`), `primary_owner` (detailed owner metrics are opt-in under `include=["owners"]`), test gaps, `security_signals`. In PR mode, `directive` with `may_break`, `missing_cochanges`, `tests_to_run` (the same selection `repowise impacted-tests` makes), `tests_to_run_basis` (`measured`, `inferred` or `none`), `tests_run_all` (with `tests_run_all_reasons` when every test must run), `tests_to_update` (test files to edit, each with a `name_pair`, `imports` or `co_change` reason), `coverage`, `recommended_reviewers`, `next_calls`, and `reach` (`localized`, `moderate` or `broad`; `null` when no structural score was computed). `include=["blast"]` adds `pr_blast_radius`; the raw 0 to 10 `structural_impact_score` and its scale appear there only with `include=["blast", "scales"]`. `missing_tests` appears only when coverage can back it. A target naming no indexed file returns `resolved: false` with a reason, never zeroed counts.
@@ -307,7 +309,7 @@ The architecture map: summary, key modules, entry points, layers, code and git h
| Parameter | Type | Default | Meaning |
|-----------|------|---------|---------|
-| `include` | list[string] | none | Any of `content` (full essay), `outline` (wiki page tree), `tour` (guided tour and reading order), `decisions`, `graph` (community clusters), `ownership` (top owners), `components` (declared and derived components with file counts) |
+| `include` | list[string] | none | Any of `content` (full essay), `outline` (wiki page tree), `tour` (guided tour and reading order), `decisions`, `graph` (community clusters), `ownership` (top owners), `components` (declared and derived components with file counts), `changes` (Change Records by category and week, and the agent share of changes with coverage) |
| `repo` | string | default repo | Workspace repo alias, or `"all"` for the cross-repo topology |
**Key return fields:** `title`, `content_md` (summary section by default), `key_modules`, `entry_points`, `architecture` (layers in stack order, plus `dependencies`: the ten heaviest package-to-package edges with `from`, `to`, `verb` and `weight`, and `edges_total` when more exist; absent in a single-package repo), `code_health`, `git_health`, `next_actions`, `more` (names the opt-in blocks), and a `workspace` footer in workspace mode.
diff --git a/docs/reference/MCP_RESPONSE_FIELDS.md b/docs/reference/MCP_RESPONSE_FIELDS.md
index 49e02f3b1..cb6e758c3 100644
--- a/docs/reference/MCP_RESPONSE_FIELDS.md
+++ b/docs/reference/MCP_RESPONSE_FIELDS.md
@@ -9,6 +9,7 @@ The field dictionary for every repowise MCP tool response. [MCP_TOOLS.md](../age
- [Truncation and recovery](#truncation-and-recovery)
- [Ignored arguments](#ignored-arguments)
- [Next-call shape](#next-call-shape)
+- [Workspace routing](#workspace-routing)
- Per tool: [get_answer](#get_answer) · [get_context](#get_context) · [get_symbol](#get_symbol) · [search_codebase](#search_codebase) · [get_risk](#get_risk) · [get_change_risk](#get_change_risk) · [get_why](#get_why) · [get_overview](#get_overview) · [get_health](#get_health) · [get_dead_code](#get_dead_code) · [list_repos](#list_repos) · [workspace tools](#workspace-tools)
---
@@ -119,6 +120,19 @@ Every suggested follow-up (`get_health`'s `fix_first.lead.next_call`, the refact
---
+## Workspace routing
+
+In workspace mode `get_context`, `get_symbol`, `get_risk` and `get_health` serve a path (or `alias:path`) from the repo that has it, when no `repo` is passed.
+
+| Field | Meaning |
+|-------|---------|
+| `repo` | On a `get_context` card, or at the top of a `get_symbol`, `get_risk` or `get_health` response: the alias that answered, present when the target was routed away from the default repo |
+| `candidates` | On a target present in several repos (per card, or top level in `get_symbol`): their aliases, beside an `error` naming the `alias:path` form to pass. Nothing is guessed |
+| `routes` | On a refusal from a one-repo tool whose targets span repos: per target, `{"repo": alias}` or `{"candidates": [...]}`, with the per-repo calls named in `error` |
+| `hint` | On a target no workspace repo has: points at `search_codebase(query=..., repo="all")` |
+
+---
+
## `get_answer`
| Field | Meaning |
@@ -157,7 +171,13 @@ Per target, under `targets`:
| `cross_repo` | Workspace mode: `co_changes_with` partners in other repos and contract `consumers` / `providers` |
| `*_basis` | Beside an empty `callers`, `callees` or `used_by`: the language, how many call edges the index resolved for it, and the share that are guesses. An empty list means no resolved edge, not proof of none |
-Opt-in blocks: `full_doc`, `ownership` (primary owner, bus factor, contributor count), `last_change`, `callers`, `callees`, `metrics` (PageRank, betweenness, percentiles), `community`, `skeleton`, `health`, `doc_drift`, `symbols` (every symbol of a file).
+Opt-in blocks: `full_doc`, `ownership` (primary owner, bus factor, contributor count), `last_change`, `callers`, `callees`, `metrics` (PageRank, betweenness, percentiles), `community`, `skeleton`, `health`, `doc_drift`, `symbols` (every symbol of a file), `changes`, `provenance`.
+
+**changes.** On a file target, `recent_changes` lists the newest five Change Records whose files include it, each `{id, ref, title, merged_at, category, provenance}`; `ref` is the forge's number (`#123`, `!12`) and is absent for an unnamed change, and `provenance` is `{label, coverage}` (`agent`, `human_attested` or `unknown`; absent when the change was stored without a label or attribution is off). `recent_changes_total` appears when more touched the file. The newest 500 candidate changes are read, and a change stores only its first 1,000 files, so a file past either limit can be missing from the list.
+
+**provenance.** A file's commits by source: `agent_commits`, `human_attested_commits`, `unknown_commits`, `coverage` (known over all commits), `agent_share` (agent over known commits) and a one-line `summary`. Below 30% coverage `agent_share` is null with `suppressed_reason: "coverage_below_floor"`, and the agent and human-attested counts are left out. Unknown is never counted as human. With attribution off the block is `{"unavailable": "attribution_off"}`.
+
+**Change targets.** A `change:<id>` target (an id such as `pr-123`, or a commit sha the change landed) returns `type: "change"`, `id`, `ref`, `title`, `merged_at`, `category`, `shape` (`merge`, `squash`, `commit`), `head_sha`, `commit_count`, `files_changed`, `lines_added`, `lines_deleted`, `files` (paths, the first 25 with `files_total` and an omission ref past that), `linked_issues` when the messages close any, and `provenance`: `{label, agent_commits, human_attested_commits, unknown_commits, coverage}`, `{"unavailable": "attribution_off"}`, or `{"unavailable": "not_recorded"}` for a change stored while attribution was off. An unknown id returns `error` naming the id forms; a short sha that starts commits in several changes returns `error` with their ids as `candidates`.
**Skeleton.** Sliced from the index's stored symbol bounds, with no parsing at query time: every signature, the import preamble, and the bodies of the top symbols ranked by centrality, hotspot and query match. Elision markers carry 1-indexed line ranges, so you can read any part back.
@@ -217,7 +237,7 @@ Per file:
| `resolved`, `unresolved_reason` | A target naming no indexed file: `unsupported_target_kind` (a `module:` id), `directory`, `not_indexed`, `no_such_path`. Counts are omitted, never zeroed |
| `signal_tier`, `signal_tier_reason` | `"history"` on a file indexed for commit history only (docs, config, query and other non-code files): the card carries commit counts, `last_commit_at`, `trend`, owner and `security_signals`, and omits hotspot, co-change, dependents and classification rather than zeroing them |
-Opt-in blocks: `owners` adds `owner_pct`, `owner_line_pct`, `recent_owner`, `recent_owner_pct`, `bus_factor` and `contributor_count`. `tests` adds the PR directive's typed `test_recommendations`, and `blast` adds `pr_blast_radius`, the PR dossier behind the directive (transitive files, co-change warnings, test gaps, the structural score; reviewers stay in the directive). `graph` adds typed `dependents` (direct versus transitive), `consumers` (typed contract consumers only), `cross_repo_links`, `impact_surface` and `direct_risks`, with `relationship_analysis` distinguishing an empty analysis from an unavailable or partial one. `churn` adds `change_magnitude`, `risk_type` and `change_pattern`. `scales` adds the unit, range and calibration of every scalar; it is identical on every call, so ask once. A multi-target call also carries `global_hotspots`.
+Opt-in blocks: `changes` adds `recent_changes` (and `recent_changes_total`), shaped as in `get_context`. `owners` adds `owner_pct`, `owner_line_pct`, `recent_owner`, `recent_owner_pct`, `bus_factor` and `contributor_count`. `tests` adds the PR directive's typed `test_recommendations`, and `blast` adds `pr_blast_radius`, the PR dossier behind the directive (transitive files, co-change warnings, test gaps, the structural score; reviewers stay in the directive). `graph` adds typed `dependents` (direct versus transitive), `consumers` (typed contract consumers only), `cross_repo_links`, `impact_surface` and `direct_risks`, with `relationship_analysis` distinguishing an empty analysis from an unavailable or partial one. `churn` adds `change_magnitude`, `risk_type` and `change_pattern`. `scales` adds the unit, range and calibration of every scalar; it is identical on every call, so ask once. A multi-target call also carries `global_hotspots`.
**PR mode** (`changed_files` passed). The response starts with `directive`:
@@ -309,7 +329,9 @@ The `candidates` and `history` lanes shed first under budget pressure, so an abs
| `more` | Names the opt-in blocks |
| `workspace` | Workspace mode footer |
-Opt-in blocks: `outline` (wiki page tree, two levels), `tour` (`guided_tour`, `reading_order`), `decisions` (`key_decisions`), `graph` (`community_summary`), `ownership` (`knowledge_map`). They are not computed unless named.
+Opt-in blocks: `outline` (wiki page tree, two levels), `tour` (`guided_tour`, `reading_order`), `decisions` (`key_decisions`), `graph` (`community_summary`), `ownership` (`knowledge_map`), `components`, `changes`. They are not computed unless named.
+
+**changes.** Change Records over a 90-day `window` ending at the newest merged change (`since`, `until`): `total`, `by_category` (largest first), `by_week` (`{week, changes}` per week starting Monday, zero weeks included) and `provenance` over changes: `agent_changes`, `human_attested_changes`, `unknown_changes`, `coverage`, `agent_share` and `summary`. Below 30% coverage `agent_share` is null with `suppressed_reason`, and the agent and human-attested counts are left out. A change stored without a label counts as unknown, never human. `{"total": 0}` when no Change Records are stored; `provenance` is `{"unavailable": "attribution_off"}` with attribution off. Grouped by change and category only, never by person.
---
diff --git a/packages/core/src/repowise/core/persistence/crud/changes.py b/packages/core/src/repowise/core/persistence/crud/changes.py
index 33c2fe56d..10049be2a 100644
--- a/packages/core/src/repowise/core/persistence/crud/changes.py
+++ b/packages/core/src/repowise/core/persistence/crud/changes.py
@@ -96,29 +96,41 @@ async def list_changes(
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)."""
+ """A change by its id, or the newest change that landed a commit (a sha of 7+ hex)."""
+ found = await find_changes(session, repository_id, ref, limit=1)
+ return found[0] if found else None
+
+
+async def find_changes(
+ session: AsyncSession, repository_id: str, ref: str, *, limit: int = 2
+) -> list[Change]:
+ """Changes *ref* names, newest first: the one with that id, else up to
+ *limit* that landed a commit starting with *ref* (7+ hex). More than one
+ means a short sha is ambiguous.
+ """
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
+ if row is not None:
+ return [row]
+ if len(ref) < 7 or any(c not in "0123456789abcdef" for c in ref.lower()):
+ return []
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)
+ rows = 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),
+ ),
)
- ).scalar_one_or_none()
+ .order_by(Change.merged_at.desc().nulls_last())
+ .limit(limit)
+ )
+ return list(rows.scalars().all())
async def get_commit_labels(
diff --git a/packages/server/src/repowise/server/chat_views.py b/packages/server/src/repowise/server/chat_views.py
index d514c36c9..a6d14e3c6 100644
--- a/packages/server/src/repowise/server/chat_views.py
+++ b/packages/server/src/repowise/server/chat_views.py
@@ -708,3 +708,113 @@ def risk_hotspots_view(artifact: ViewArtifact, options: Mapping[str, Any]) -> di
rows=rows,
total_rows=total,
)
+
+
+def _changes_block(artifact: ViewArtifact) -> Mapping[str, Any]:
+ block = artifact.data.get("changes")
+ if not isinstance(block, Mapping) or not block.get("total"):
+ raise ViewError(
+ 'this result has no change records; call get_overview(include=["changes"])'
+ )
+ return block
+
+
+def _window(block: Mapping[str, Any]) -> str:
+ window = block.get("window")
+ days = window.get("days") if isinstance(window, Mapping) else None
+ return f" over the last {days} days of merged changes" if isinstance(days, int) else ""
+
+
+@register_view_builder(
+ "changes.by_category",
+ description="Merged changes per category (feature, fix, ...).",
+ artifact_types={"overview"},
+ options=frozenset(),
+)
+def changes_by_category_view(artifact: ViewArtifact, options: Mapping[str, Any]) -> dict[str, Any]:
+ block = _changes_block(artifact)
+ by_category = block.get("by_category")
+ rows = [
+ {"category": category, "changes": count}
+ for category, count in (by_category.items() if isinstance(by_category, Mapping) else ())
+ if isinstance(count, int) and not isinstance(count, bool)
+ ]
+ return _chart(
+ title="Changes by category",
+ summary=f"{sum(r['changes'] for r in rows)} changes{_window(block)}.",
+ basis=_basis("measured", "git history"),
+ x=("category", "Category"),
+ series=[("changes", "Changes")],
+ unit="changes",
+ rows=rows,
+ )
+
+
+@register_view_builder(
+ "changes.by_week",
+ description="Merged changes per week.",
+ artifact_types={"overview"},
+ options=frozenset(),
+)
+def changes_by_week_view(artifact: ViewArtifact, options: Mapping[str, Any]) -> dict[str, Any]:
+ block = _changes_block(artifact)
+ weeks = block.get("by_week")
+ rows = [
+ {"week": w["week"], "changes": w["changes"]}
+ for w in (weeks if isinstance(weeks, list) else ())
+ if isinstance(w, Mapping)
+ and isinstance(w.get("week"), str)
+ and isinstance(w.get("changes"), int)
+ and not isinstance(w.get("changes"), bool)
+ ][-VIEW_LIMITS["chart_points"] :]
+ return _chart(
+ chart_type="line",
+ title="Changes per week",
+ summary=f"{len(rows)} weeks{_window(block)}, oldest first.",
+ basis=_basis("measured", "git history"),
+ x=("week", "Week of"),
+ series=[("changes", "Changes")],
+ unit="changes",
+ rows=rows,
+ )
+
+
+_PROVENANCE_BANDS = (
+ ("agent", "agent_changes"),
+ ("human attested", "human_attested_changes"),
+ ("unknown", "unknown_changes"),
+)
+
+
+@register_view_builder(
+ "changes.provenance",
+ description="Merged changes by source: agent, human-attested, unknown.",
+ artifact_types={"overview"},
+ options=frozenset(),
+ coverage_metric="attribution",
+)
+def changes_provenance_view(artifact: ViewArtifact, options: Mapping[str, Any]) -> dict[str, Any]:
+ block = _changes_block(artifact)
+ provenance = block.get("provenance")
+ if not isinstance(provenance, Mapping) or "coverage" not in provenance:
+ raise ViewError("attribution is off for this repository", code="attribution_off")
+ # Unknown is its own band, never folded into human.
+ rows = [
+ {"source": label, "changes": provenance[key]}
+ for label, key in _PROVENANCE_BANDS
+ if isinstance(provenance.get(key), int) and not isinstance(provenance.get(key), bool)
+ ]
+ part = _chart(
+ chart_type="donut",
+ title="Changes by source",
+ summary=f"{sum(r['changes'] for r in rows)} changes{_window(block)}.",
+ basis=_basis("measured", "git attribution markers"),
+ x=("source", "Source"),
+ series=[("changes", "Changes")],
+ unit="changes",
+ rows=rows,
+ )
+ coverage = provenance.get("coverage")
+ if isinstance(coverage, (int, float)) and not isinstance(coverage, bool):
+ part["coverage"] = {"metric": "attribution", "ratio": coverage}
+ return part
diff --git a/packages/server/src/repowise/server/mcp_server/_changes.py b/packages/server/src/repowise/server/mcp_server/_changes.py
new file mode 100644
index 000000000..85a3a523f
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/_changes.py
@@ -0,0 +1,286 @@
+"""Change Records on the MCP surface.
+
+``change:<id>`` cards for get_context, recent changes per file behind
+``include=["changes"]`` (get_context, get_risk) and the get_overview change
+summary. All of it is opt-in.
+
+Provenance follows :mod:`repowise.core.attribution`: three-state, coverage
+beside every share, unknown never counted as human, and nothing about AI while
+attribution is off for the repo.
+"""
+
+from __future__ import annotations
+
+import json
+from collections import Counter
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+from sqlalchemy import func, or_, select
+
+from repowise.core.attribution import (
+ AGENT,
+ HUMAN_ATTESTED,
+ attribution_enabled,
+ attribution_share,
+ file_share,
+)
+from repowise.core.changes.record import change_record
+from repowise.core.persistence.crud import find_changes
+from repowise.core.persistence.models import Change, GitMetadata
+from repowise.core.persistence.sql import LIKE_ESCAPE, escape_like
+from repowise.server.mcp_server._budget import OmissionCollector, cap_collection
+
+CHANGE_PREFIX = "change:"
+#: Recent changes listed per file; ``recent_changes_total`` counts the rest.
+FILE_CHANGES_CAP = 5
+#: Newest candidate rows scanned per call for recent changes. Ceiling: a file
+#: whose changes all sit past this many newer candidates lists none.
+_FILE_SCAN_CAP = 500
+#: Files a change card lists; the rest go to the omission store.
+_CARD_FILES_CAP = 25
+OVERVIEW_WINDOW_DAYS = 90
+_ATTRIBUTION_OFF = {"unavailable": "attribution_off"}
+
+
+def is_change_target(target: str) -> bool:
+ return target.startswith(CHANGE_PREFIX)
+
+
+def _iso(value: datetime | None) -> str | None:
+ if value is None:
+ return None
+ return (value if value.tzinfo else value.replace(tzinfo=UTC)).isoformat()
+
+
+def _row_provenance(row: Any) -> dict[str, Any] | None:
+ """``{label, coverage}``: the compact form for list rows."""
+ if row.provenance is None or row.provenance_known is None:
+ return None
+ commits = len(json.loads(row.commit_shas_json or "[]"))
+ return {
+ "label": row.provenance,
+ "coverage": round(row.provenance_known / commits, 4) if commits else None,
+ }
+
+
+def change_row(row: Any, attribution: bool) -> dict[str, Any]:
+ """One change as a list row: id, ref, title, merged_at, category, provenance."""
+ out: dict[str, Any] = {"id": row.change_id}
+ if row.forge_ref:
+ out["ref"] = row.forge_ref
+ out.update(title=row.title, merged_at=_iso(row.merged_at), category=row.category)
+ if attribution and (prov := _row_provenance(row)) is not None:
+ out["provenance"] = prov
+ return out
+
+
+# -- get_context: change:<id> targets ------------------------------------------
+
+
+async def change_cards(
+ session: Any, repository: Any, targets: list[str], collector: OmissionCollector
+) -> dict[str, dict[str, Any]]:
+ """Cards for ``change:<id>`` targets; an id or a commit sha the change landed."""
+ attribution = attribution_enabled(repository.local_path)
+ cards: dict[str, dict[str, Any]] = {}
+ for target in targets:
+ ref = target[len(CHANGE_PREFIX) :].strip()
+ found = await find_changes(session, repository.id, ref) if ref else []
+ if len(found) != 1:
+ cards[target] = _change_miss(target, ref, found)
+ continue
+ row = found[0]
+ record = change_record(row, attribution=attribution)
+ card: dict[str, Any] = {"target": target, "type": "change", "id": record["id"]}
+ if record["forge_ref"]:
+ card["ref"] = record["forge_ref"]
+ card.update(
+ title=record["title"],
+ merged_at=record["merged_at"],
+ category=record["category"],
+ shape=record["shape"],
+ head_sha=record["head_sha"],
+ commit_count=len(record["commits"]),
+ files_changed=record["files_changed"],
+ lines_added=record["lines_added"],
+ lines_deleted=record["lines_deleted"],
+ )
+ cap_collection(
+ card,
+ "files",
+ [f["path"] for f in record["files"]],
+ _CARD_FILES_CAP,
+ collector,
+ label=f"{record['id']} files beyond cap={_CARD_FILES_CAP}",
+ )
+ if not attribution:
+ card["provenance"] = dict(_ATTRIBUTION_OFF)
+ else:
+ # Stored while attribution was off: no label to report.
+ card["provenance"] = record["provenance"] or {"unavailable": "not_recorded"}
+ linked = record["metadata"]["linked_issues"]
+ if linked:
+ card["linked_issues"] = linked
+ cards[target] = card
+ return cards
+
+
+def _change_miss(target: str, ref: str, found: list[Any]) -> dict[str, Any]:
+ if found:
+ return {
+ "target": target,
+ "error": f"{ref!r} starts commits in several changes; name one.",
+ "candidates": [f"{CHANGE_PREFIX}{r.change_id}" for r in found],
+ }
+ return {
+ "target": target,
+ "error": (
+ f"No change {ref!r}. Ids: pr-123 (a PR or MR number), change-I<hex> "
+ "(a Gerrit Change-Id), merge-<sha> or commit-<sha>; a commit sha "
+ "of 7+ characters also works."
+ ),
+ }
+
+
+# -- include=["changes"]: recent changes touching a file -----------------------
+
+
+def _touches(path: str) -> Any:
+ # A coarse prefilter: SQLite's LIKE folds ASCII case, so the stored file
+ # list is checked exactly in :func:`file_changes`.
+ needle = escape_like(f'"path": {json.dumps(path)}')
+ return Change.files_json.like(f"%{needle}%", escape=LIKE_ESCAPE)
+
+
+async def file_changes(
+ session: Any, repository: Any, paths: list[str], *, attribution: bool
+) -> dict[str, dict[str, Any]]:
+ """Per path: ``recent_changes`` (newest first, capped) and, past the cap,
+ ``recent_changes_total``. One query for every path.
+
+ Ceiling: a change keeps only its first ``MAX_STORED_FILES`` files, and the
+ newest ``_FILE_SCAN_CAP`` candidate rows are read.
+ """
+ wanted = list(dict.fromkeys(paths))
+ if not wanted:
+ return {}
+ rows = (
+ await session.execute(
+ select(Change)
+ .where(Change.repository_id == repository.id, or_(*(_touches(p) for p in wanted)))
+ .order_by(Change.merged_at.desc().nulls_last(), Change.change_id)
+ .limit(_FILE_SCAN_CAP)
+ )
+ ).scalars().all()
+ hits: dict[str, list[Any]] = {p: [] for p in wanted}
+ for row in rows:
+ try:
+ files = {f.get("path") for f in json.loads(row.files_json or "[]")}
+ except (TypeError, ValueError, AttributeError):
+ continue
+ for path in wanted:
+ if path in files:
+ hits[path].append(row)
+ out: dict[str, dict[str, Any]] = {}
+ for path, matched in hits.items():
+ block: dict[str, Any] = {
+ "recent_changes": [change_row(r, attribution) for r in matched[:FILE_CHANGES_CAP]]
+ }
+ if len(matched) > FILE_CHANGES_CAP:
+ block["recent_changes_total"] = len(matched)
+ out[path] = block
+ return out
+
+
+# -- include=["provenance"]: a file's three-state attribution ------------------
+
+
+def file_provenance(meta: Any | None, attribution: bool) -> dict[str, Any]:
+ """The file's commits by source, with coverage and the honest agent share."""
+ if not attribution:
+ return dict(_ATTRIBUTION_OFF)
+ if meta is None:
+ return {"unavailable": "no_git_history"}
+ share = file_share(
+ meta.agent_commit_count, meta.attribution_known_count, meta.commit_count_total
+ )
+ return _share_block(share, unit="commits")
+
+
+def _share_block(share: Any, *, unit: str) -> dict[str, Any]:
+ block: dict[str, Any] = {}
+ # A withheld share keeps no agent or human counts: they would restate it.
+ if not share.suppressed_reason:
+ block[f"agent_{unit}"] = share.agent
+ block[f"human_attested_{unit}"] = share.human_attested
+ block[f"unknown_{unit}"] = share.unknown
+ block["coverage"] = round(share.coverage, 4) if share.coverage is not None else None
+ block["agent_share"] = round(share.agent_share, 4) if share.agent_share is not None else None
+ if share.suppressed_reason:
+ block["suppressed_reason"] = share.suppressed_reason
+ if share.total:
+ block["summary"] = share.summary().replace("commits", unit)
+ return block
+
+
+async def load_file_meta(session: Any, repo_id: str, path: str) -> Any | None:
+ return (
+ await session.execute(
+ select(GitMetadata).where(
+ GitMetadata.repository_id == repo_id, GitMetadata.file_path == path
+ )
+ )
+ ).scalar_one_or_none()
+
+
+# -- get_overview(include=["changes"]) -----------------------------------------
+
+
+def _week(moment: datetime) -> str:
+ return (moment.date() - timedelta(days=moment.weekday())).isoformat()
+
+
+async def overview_changes(session: Any, repository: Any) -> dict[str, Any]:
+ """Changes by category and week, and the agent share of changes, over a window.
+
+ The window ends at the newest merged change, so an idle repository still
+ shows its last stretch of work; ``window`` names both ends.
+ """
+ until = (
+ await session.execute(
+ select(func.max(Change.merged_at)).where(Change.repository_id == repository.id)
+ )
+ ).scalar()
+ if until is None:
+ return {"total": 0}
+ until = until if until.tzinfo else until.replace(tzinfo=UTC)
+ since = until - timedelta(days=OVERVIEW_WINDOW_DAYS)
+ rows = (
+ await session.execute(
+ select(Change.merged_at, Change.category, Change.provenance).where(
+ Change.repository_id == repository.id, Change.merged_at >= since
+ )
+ )
+ ).all()
+ weeks: Counter[str] = Counter(
+ _week(m if m.tzinfo else m.replace(tzinfo=UTC)) for m, _, _ in rows
+ )
+ by_week, cursor = [], datetime.fromisoformat(_week(since)).date()
+ while cursor <= until.date():
+ by_week.append({"week": cursor.isoformat(), "changes": weeks.get(cursor.isoformat(), 0)})
+ cursor += timedelta(days=7)
+ block: dict[str, Any] = {
+ "window": {"days": OVERVIEW_WINDOW_DAYS, "since": _iso(since), "until": _iso(until)},
+ "total": len(rows),
+ "by_category": dict(Counter(c for _, c, _ in rows).most_common()),
+ "by_week": by_week,
+ }
+ if not attribution_enabled(repository.local_path):
+ block["provenance"] = dict(_ATTRIBUTION_OFF)
+ else:
+ # A change stored with no label (indexed while attribution was off) is unknown.
+ labels = Counter(p for _, _, p in rows)
+ share = attribution_share(labels[AGENT], labels[HUMAN_ATTESTED], len(rows))
+ block["provenance"] = _share_block(share, unit="changes")
+ return block
diff --git a/packages/server/src/repowise/server/mcp_server/_workspace_routing.py b/packages/server/src/repowise/server/mcp_server/_workspace_routing.py
index 600f63f6c..3d9966a56 100644
--- a/packages/server/src/repowise/server/mcp_server/_workspace_routing.py
+++ b/packages/server/src/repowise/server/mcp_server/_workspace_routing.py
@@ -7,8 +7,8 @@ a path from another repo silently answers about the default repo.
Rules, exact matches only:
- ``<alias>:<target>`` names the repo outright (``backend:src/app.py``,
- ``backend:src/app.py::App``). ``component:`` and ``module:`` stay target
- kinds, never repo prefixes.
+ ``backend:src/app.py::App``). ``component:``, ``change:`` and ``module:``
+ stay target kinds, never repo prefixes.
- A path, or the file part of ``path::Name`` / ``path:120-140``, is served by
the default repo when it exists there, as before. Otherwise it is routed to
the one other repo whose checkout has it; when several do, the candidates
@@ -36,7 +36,7 @@ from typing import Any
from repowise.server.mcp_server import _state
from repowise.server.mcp_server._query_shape import _LINE_SUFFIX_RE, _is_path
-_TARGET_KINDS = frozenset({"component", "module"})
+_TARGET_KINDS = frozenset({"component", "change", "module"})
@dataclass(frozen=True)
diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/context.py b/packages/server/src/repowise/server/mcp_server/tool_context/context.py
index 268c327cf..d221f084d 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_context/context.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_context/context.py
@@ -32,6 +32,9 @@ Optional ``include`` parameter widens the response:
- include=["health"] → code-health scores and biomarkers for the target
- include=["doc_drift"] → documents that name this file, and their drift
- include=["symbols"] → every symbol in a file card, not the ranked top 15
+ - include=["changes"] → recent Change Records touching a file target
+ - include=["provenance"]→ a file's commits by source (agent, human-attested,
+ unknown) with coverage and the honest agent share
An unrecognised key is dropped and named in ``ignored_arguments`` rather than
silently ignored: an unknown key otherwise produces exactly the response the
@@ -55,6 +58,7 @@ from repowise.core.registry import ToolRecipe
from repowise.core.registry import mcp_tool_registry as mcp
from repowise.server.mcp_server import _state
from repowise.server.mcp_server._budget import OmissionCollector
+from repowise.server.mcp_server._changes import change_cards, is_change_target
from repowise.server.mcp_server._components import component_cards, is_component_target
from repowise.server.mcp_server._episodes import enrich_episode_counts as _enrich_episodes
from repowise.server.mcp_server._helpers import (
@@ -100,6 +104,8 @@ _INCLUDE_BLOCKS = frozenset(
"health",
"doc_drift",
"symbols",
+ "changes",
+ "provenance",
}
)
@@ -128,9 +134,8 @@ async def get_context(
decision_record titles. A symbol row without symbol_id is path::name.
fix_history appears only on files with counted bug fixes (count, age,
bug_magnet); hotspot is churn. Either one is a cue to
- call get_risk. episodes counts the dated records bound to a target — what
- happened here and why — and appears only when there is at least one;
- get_why serves the bodies. A symbol target is counted as its file, and a
+ call get_risk. episodes counts the dated records bound to a target
+ (absent at zero); get_why serves the bodies. A symbol target is counted as its file, and a
module aggregates everything beneath it.
Batch targets in one call. No source bytes by default: pass
include=["skeleton"] for the whole file body-elided and line-verified in
@@ -144,11 +149,12 @@ async def get_context(
Include-gated blocks are projections, not omissions.
Args:
- targets: paths, "path::Symbol" ids, or "component:<name>".
+ targets: paths, "path::Symbol" ids, "component:<name>", or
+ "change:<id>" (pr-123 or a commit sha).
include: opt-in blocks: full_doc | ownership | last_change | callers
| callees | references | metrics | community | decisions | skeleton
| skeleton+ | health | doc_drift (docs naming this file)
- | symbols (all of a file's symbols, not the top 15).
+ | symbols (all, not the top 15) | changes | provenance.
compact: default True; False adds structure+imports+docstrings.
repo: usually omitted.
"""
@@ -202,11 +208,14 @@ async def get_context(
# batch. Any exception is converted below into a per-target error
# entry that carries "target", so the comprehension keyed on target
# below never KeyErrors.
- # Component targets resolve first, in turn on this session and from one
- # component load, so they never share the session with the gather.
+ # Component and change targets resolve first, in turn on this session,
+ # so they never share the session with the gather.
cards = await _component_cards(
session, repository, [t for t in targets if is_component_target(t)], ctx, exclude_spec
)
+ cards |= await _change_cards(
+ session, repository, [t for t in targets if is_change_target(t)], collector
+ )
gathered = await asyncio.gather(
*[
_resolve_one_target(
@@ -221,12 +230,12 @@ async def get_context(
as_of_ts=as_of_ts,
)
for t in targets
- if not is_component_target(t)
+ if t not in cards
],
return_exceptions=True,
)
rest = iter(gathered)
- raw_results = [cards[t] if is_component_target(t) else next(rest) for t in targets]
+ raw_results = [cards[t] if t in cards else next(rest) for t in targets]
# One batched read for every target that asked for it, on the session
# they share, and a no-op for every call that did not. Deliberately
@@ -349,3 +358,15 @@ async def _component_cards(
)
except Exception as exc:
return {t: exc for t in targets}
+
+
+async def _change_cards(
+ session: Any, repository: Any, targets: list[str], collector: OmissionCollector
+) -> dict[str, Any]:
+ """Cards for the batch's ``change:`` targets; a failure becomes each one's error."""
+ if not targets:
+ return {}
+ try:
+ return await change_cards(session, repository, targets, collector)
+ except Exception as exc:
+ return {t: exc for t in targets}
diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/targets.py b/packages/server/src/repowise/server/mcp_server/tool_context/targets.py
index f124bec53..5ca5b3b5c 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_context/targets.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_context/targets.py
@@ -46,6 +46,7 @@ from repowise.core.persistence.models import (
)
from repowise.server.mcp_server._basis import call_resolution_basis, same_file_basis
from repowise.server.mcp_server._budget import OmissionCollector, cap_collection
+from repowise.server.mcp_server._changes import file_changes, file_provenance, load_file_meta
from repowise.server.mcp_server._edit_sites import reference_edit_set
from repowise.server.mcp_server._helpers import (
LIKE_ESCAPE,
@@ -1225,6 +1226,21 @@ async def _resolve_one_target(
last_change["days_ago"] = None
result_data["last_change"] = last_change
+ # --- Change Records and provenance (file targets, opt-in) ---
+ if include and target_type == "file" and file_path_for_git and include & {
+ "changes",
+ "provenance",
+ }:
+ attribution = attribution_enabled(repository.local_path)
+ if "changes" in include:
+ found = await file_changes(
+ session, repository, [file_path_for_git], attribution=attribution
+ )
+ result_data.update(found[file_path_for_git])
+ if "provenance" in include:
+ meta = await load_file_meta(session, repo_id, file_path_for_git) if attribution else None
+ result_data["provenance"] = file_provenance(meta, attribution)
+
# --- Decisions ---
if include is None or "decisions" in include:
# Acceptance is authority, not the status column. The lanes match
diff --git a/packages/server/src/repowise/server/mcp_server/tool_overview/tool.py b/packages/server/src/repowise/server/mcp_server/tool_overview/tool.py
index e0fd943cb..43705a3d4 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_overview/tool.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_overview/tool.py
@@ -16,6 +16,7 @@ from repowise.core.persistence.models import GitMetadata
from repowise.core.registry import mcp_tool_registry as mcp
from repowise.server.mcp_server import _state
from repowise.server.mcp_server._budget import OmissionCollector
+from repowise.server.mcp_server._changes import overview_changes
from repowise.server.mcp_server._components import component_list
from repowise.server.mcp_server._helpers import (
_get_exclude_spec,
@@ -68,9 +69,8 @@ async def get_overview(repo: str | None = None, include: list[str] | None = None
``next_actions`` (top work for the week and quarter).
Skip it on later calls; go straight to ``get_context`` / ``get_answer``.
- Compact by default: ``content_md`` carries only the overview essay's summary
- section, and the outline, onboarding, ownership and graph blocks ship only
- on request. The response's ``more`` field names them.
+ Compact by default: ``content_md`` carries only the essay's summary
+ section; other blocks ship on request, named in ``more``.
Defaults fit 24,000 chars; nonempty ``include`` uses 32,000. Reductions
carry counts and recovery status in ``_meta``.
@@ -92,6 +92,7 @@ async def get_overview(repo: str | None = None, include: list[str] | None = None
``"graph"`` — ``community_summary``, code-community clusters.
``"ownership"`` — ``knowledge_map``: top 3 owners by files owned.
``"components"`` — component list with file counts.
+ ``"changes"`` — changes by category, week and source, with coverage.
"""
if repo == "all":
return await _workspace_overview()
@@ -116,6 +117,8 @@ async def get_overview(repo: str | None = None, include: list[str] | None = None
exclude_spec=exclude_spec,
collector=collector,
)
+ if "changes" in want:
+ result["changes"] = await overview_changes(session, repository)
# Made once per session, so this is where the full scope that every
# other response's compact projection points at is worth its bytes.
diff --git a/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py b/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py
index 40f05b5e9..256c2ce2c 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py
@@ -23,6 +23,7 @@ from repowise.core.registry import ToolRecipe
from repowise.core.registry import mcp_tool_registry as mcp
from repowise.core.support_paths import is_doc_or_config_path
from repowise.server.mcp_server._budget import OmissionCollector, cap_collection
+from repowise.server.mcp_server._changes import file_changes
from repowise.server.mcp_server._episodes import enrich_episode_counts as _enrich_episodes
from repowise.server.mcp_server._helpers import (
_get_exclude_spec,
@@ -107,8 +108,9 @@ _TARGET_CARD_INCLUDES: dict[str, tuple[str, ...]] = {
_BLAST_INCLUDES: dict[str, tuple[str, ...]] = {"graph": ("direct_risks",)}
#: Per-field units and calibration. Identical on every call, so it is opt-in.
#: ``tests`` adds the PR directive's typed ``test_recommendations`` rows and
-#: ``blast`` the ``pr_blast_radius`` dossier.
-_INCLUDE_BLOCKS = frozenset(_TARGET_CARD_INCLUDES) | {"blast", "scales", "tests"}
+#: ``blast`` the ``pr_blast_radius`` dossier, ``changes`` each file's recent
+#: Change Records.
+_INCLUDE_BLOCKS = frozenset(_TARGET_CARD_INCLUDES) | {"blast", "scales", "tests", "changes"}
def _drop_opt_in_blocks(response: dict, include: set[str]) -> None:
@@ -347,6 +349,24 @@ async def _enrich_cards(
await asyncio.to_thread(_enrich_episodes, scored, ctx.path)
+async def _attach_changes(results: list[dict], ctx: Any) -> None:
+ """Each resolved card's recent Change Records (``include=["changes"]``)."""
+ from repowise.core.attribution import attribution_enabled
+
+ async with get_session(ctx.session_factory) as session:
+ repository = await _get_repo(session)
+ attribution = attribution_enabled(repository.local_path)
+ root = served_root(repository, ctx.path)
+ cards = {
+ normalize_target_path(card["target"], repo_root=root): card
+ for card in results
+ if card.get("resolved") is not False
+ }
+ found = await file_changes(session, repository, list(cards), attribution=attribution)
+ for path, card in cards.items():
+ card.update(found[path])
+
+
async def _change_tests(ctx: Any, paths: list[str]) -> ChangeTests:
"""The selection for a change known by its paths, and the tests importing them.
@@ -430,9 +450,8 @@ async def get_risk(
reach (source depends on target), ``consumers`` require typed contract links,
and ``co_change_partners`` are historical correlation only. Those counts
are a floor over the indexed graph. Structural reach is not proof of
- runtime breakage. The response also includes security
- findings. Pass changed_files for PR mode: the response leads with a
- directive block (may_break, missing_cochanges, missing_tests,
+ runtime breakage. Security findings are included. Pass changed_files for PR mode: the response leads with
+ ``directive`` (may_break, missing_cochanges, missing_tests,
tests_to_run, tests_to_update) — read it first. ``tests_to_run_basis`` says
measured or inferred. To score a commit or ``base..head`` range instead,
use ``get_change_risk``.
@@ -452,7 +471,7 @@ async def get_risk(
repo: usually omitted.
changed_files: PR-changed files for blast-radius mode.
include: opt-in blocks - "graph", "churn", "owners", "tests" (typed test
- rows), "blast", "scales" (units and calibration).
+ rows), "blast", "scales" (units, calibration), "changes".
"""
if repo == "all":
return _unsupported_repo_all("get_risk")
@@ -498,6 +517,8 @@ async def get_risk(
ctx, targets, changed_files, exclude_spec, collector, include_graph
)
await _enrich_cards(evidence.results, ctx, evidence.repository.id, collector, include_graph)
+ if "changes" in include_set:
+ await _attach_changes(evidence.results, ctx)
# The budget sheds cards from the tail, so docs and config cards go last.
cards = evidence.results
diff --git a/tests/unit/server/mcp/test_changes_mcp.py b/tests/unit/server/mcp/test_changes_mcp.py
new file mode 100644
index 000000000..6fa23d636
--- /dev/null
+++ b/tests/unit/server/mcp/test_changes_mcp.py
@@ -0,0 +1,384 @@
+"""Change Records and attribution on the MCP surface.
+
+``change:<id>`` targets and ``include=["changes", "provenance"]`` in get_context,
+``include=["changes"]`` in get_risk and get_overview. Default responses,
+get_why's included, stay byte-identical.
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+from datetime import UTC, datetime
+from pathlib import Path
+
+import pytest
+from sqlalchemy import update
+
+from repowise.core import attribution
+from repowise.core.persistence import crud
+from repowise.core.persistence.models import GitMetadata
+
+_FULL = {
+ "abc1234": "abc1234" + "0" * 33,
+ "def5678": "def5678" + "0" * 33,
+} # commits the fixture's get_why archaeology names
+
+
[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, files: list[str], **over) -> dict:
+ sha = over.pop("sha", f"{day:02d}" + "b" * 38)
+ number = change_id.removeprefix("pr-")
+ row = {
+ "change_id": change_id,
+ "identity_kind": "pr",
+ "identity_value": number,
+ "shape": "squash",
+ "forge": "github",
+ "forge_ref": f"#{number}",
+ "title": f"feat: change {number}",
+ "merged_at": datetime(2026, 3, day, tzinfo=UTC),
+ "head_sha": sha,
+ "author_name": "Ann",
+ "author_email": "[email protected]",
+ "commit_shas_json": json.dumps([sha]),
+ "files_json": json.dumps([{"path": p, "added": 1, "deleted": 0} for p in files]),
+ "files_changed": len(files),
+ "lines_added": len(files),
+ "lines_deleted": 0,
+ "category": "feature",
+ "provenance": "agent",
+ "provenance_agent": 1,
+ "provenance_known": 1,
+ "metadata_source": "git",
+ }
+ row.update(over)
+ return row
+
+
+_ROWS = [
+ _row("pr-1", 1, ["src/auth/service.py"], sha=_FULL["def5678"], title="Add JWT support"),
+ _row(
+ "pr-2",
+ 2,
+ ["src/auth/service.py", "src/db/models.py"],
+ category="fix",
+ title="fix: token refresh",
+ provenance="human_attested",
+ provenance_agent=0,
+ ),
+ _row(
+ "pr-3",
+ 3,
+ ["src/auth/service.pyc"], # a longer path never matches src/auth/service.py
+ provenance="unknown",
+ provenance_agent=0,
+ provenance_known=0,
+ ),
+ _row(
+ "pr-4",
+ 15,
+ ["src/auth/service.py"],
+ sha=_FULL["abc1234"],
+ title="Merge pull request #4 from ann/auth",
+ provenance=None,
+ provenance_agent=None,
+ provenance_known=None,
+ ),
+]
+
+
+async def _seed(session, rows=_ROWS) -> None:
+ await crud.upsert_changes(session, "repo1", rows)
+ await session.commit()
+
+
+def _without_meta(payload: dict) -> str:
+ return json.dumps({k: v for k, v in payload.items() if k != "_meta"}, sort_keys=True)
+
+
+def _attribution_off(root: Path) -> None:
+ (root / ".repowise").mkdir(exist_ok=True)
+ (root / ".repowise" / "config.yaml").write_text(
+ "attribution:\n enabled: false\n", encoding="utf-8"
+ )
+
+
+# -- get_context ----------------------------------------------------------------
+
+
+async def test_change_target_card(setup_mcp, session):
+ from repowise.server.mcp_server import get_context
+
+ await _seed(session)
+ result = await get_context(
+ targets=["change:pr-2", "change:def5678", "change:pr-4", "change:pr-99"]
+ )
+ card = result["targets"]["change:pr-2"]
+ assert card["type"] == "change"
+ assert (card["id"], card["ref"], card["title"]) == ("pr-2", "#2", "fix: token refresh")
+ assert card["merged_at"].startswith("2026-03-02")
+ assert card["category"] == "fix"
+ assert card["files"] == ["src/auth/service.py", "src/db/models.py"]
+ assert card["provenance"] == {
+ "label": "human_attested",
+ "agent_commits": 0,
+ "human_attested_commits": 1,
+ "unknown_commits": 0,
+ "coverage": 1.0,
+ }
+ # A commit sha resolves to the change that landed it.
+ assert result["targets"]["change:def5678"]["id"] == "pr-1"
+ assert result["targets"]["change:pr-4"]["provenance"] == {"unavailable": "not_recorded"}
+ miss = result["targets"]["change:pr-99"]["error"]
+ assert "No change 'pr-99'" in miss and "change-I" in miss and "MR" in miss
+ assert "Ann" not in json.dumps(card)
+
+
+async def test_change_card_withholds_provenance_when_attribution_is_off(
+ setup_mcp, session, tmp_path
+):
+ from repowise.server.mcp_server import get_context
+
+ await _seed(session)
+ _attribution_off(tmp_path)
+ card = (await get_context(targets=["change:pr-1"]))["targets"]["change:pr-1"]
+ assert card["provenance"] == {"unavailable": "attribution_off"}
+
+
+async def test_file_card_lists_recent_changes_on_request(setup_mcp, session):
+ from repowise.server.mcp_server import get_context
+
+ await _seed(session)
+ card = (await get_context(targets=["src/auth/service.py"], include=["changes"]))["targets"][
+ "src/auth/service.py"
+ ]
+ rows = card["recent_changes"]
+ assert [r["id"] for r in rows] == ["pr-4", "pr-2", "pr-1"] # never pr-3's .pyc
+ assert rows[1] == {
+ "id": "pr-2",
+ "ref": "#2",
+ "title": "fix: token refresh",
+ "merged_at": rows[1]["merged_at"],
+ "category": "fix",
+ "provenance": {"label": "human_attested", "coverage": 1.0},
+ }
+ assert "provenance" not in rows[0] # stored without a label
+ assert "recent_changes_total" not in card
+
+
+async def test_recent_changes_are_capped_with_their_total(setup_mcp, session):
+ from repowise.server.mcp_server import get_context
+
+ await _seed(session, [_row(f"pr-{n}", n, ["src/db/models.py"]) for n in range(1, 9)])
+ card = (await get_context(targets=["src/db/models.py"], include=["changes"]))["targets"][
+ "src/db/models.py"
+ ]
+ assert [r["id"] for r in card["recent_changes"]] == ["pr-8", "pr-7", "pr-6", "pr-5", "pr-4"]
+ assert card["recent_changes_total"] == 8
+
+
+async def test_file_provenance_carries_coverage_and_withholds_below_the_floor(
+ setup_mcp, session, tmp_path
+):
+ from repowise.server.mcp_server import get_context
+
+ await session.execute(
+ update(GitMetadata)
+ .where(GitMetadata.file_path == "src/auth/service.py")
+ .values(agent_commit_count=6, attribution_known_count=21)
+ )
+ await session.execute(
+ update(GitMetadata)
+ .where(GitMetadata.file_path == "src/db/models.py")
+ .values(agent_commit_count=1, attribution_known_count=2)
+ )
+ await session.commit()
+ result = await get_context(
+ targets=["src/auth/service.py", "src/db/models.py"], include=["provenance"]
+ )
+ covered = result["targets"]["src/auth/service.py"]["provenance"]
+ assert covered["agent_commits"] == 6
+ assert covered["human_attested_commits"] == 15
+ assert covered["unknown_commits"] == 21
+ assert covered["coverage"] == 0.5
+ assert covered["agent_share"] == round(6 / 21, 4)
+ withheld = result["targets"]["src/db/models.py"]["provenance"]
+ assert withheld["agent_share"] is None
+ assert withheld["suppressed_reason"] == "coverage_below_floor"
+ assert withheld["unknown_commits"] == 13 # unknown is its own band
+ # A withheld share carries no counts that would restate it.
+ assert "agent_commits" not in withheld and "human_attested_commits" not in withheld
+
+ _attribution_off(tmp_path)
+ off = await get_context(targets=["src/auth/service.py"], include=["provenance"])
+ assert off["targets"]["src/auth/service.py"]["provenance"] == {
+ "unavailable": "attribution_off"
+ }
+
+
+def test_change_is_a_target_kind_not_a_repo_alias():
+ from repowise.server.mcp_server._workspace_routing import _route_one
+
+ route = _route_one("change:pr-1", {"change": Path("/x")}, "main", False)
+ assert (route.repo, route.local, route.routed) == ("main", "change:pr-1", False)
+
+
+# -- get_risk -------------------------------------------------------------------
+
+
+async def test_risk_lists_recent_changes_on_request(setup_mcp, session):
+ from repowise.server.mcp_server import get_risk
+
+ await _seed(session)
+ result = await get_risk(targets=["src/db/models.py"], include=["changes"])
+ card = result["targets"]["src/db/models.py"]
+ assert [r["id"] for r in card["recent_changes"]] == ["pr-2"]
+ assert "ignored_arguments" not in result
+
+
+# -- get_overview ---------------------------------------------------------------
+
+
+async def test_overview_changes_by_category_week_and_agent_share(setup_mcp, session):
+ from repowise.server.mcp_server import get_overview
+
+ await _seed(session)
+ block = (await get_overview(include=["changes"]))["changes"]
+ assert block["total"] == 4
+ assert block["window"]["days"] == 90
+ assert block["window"]["until"].startswith("2026-03-15")
+ assert block["by_category"] == {"feature": 3, "fix": 1}
+ weeks = {w["week"]: w["changes"] for w in block["by_week"]}
+ assert weeks["2026-02-23"] == 1 and weeks["2026-03-02"] == 2 and weeks["2026-03-09"] == 1
+ assert sum(weeks.values()) == 4
+ prov = block["provenance"]
+ # Two of four changes have a known source: unknown never counts as human.
+ assert (prov["agent_changes"], prov["human_attested_changes"], prov["unknown_changes"]) == (
+ 1,
+ 1,
+ 2,
+ )
+ assert prov["coverage"] == 0.5 and prov["agent_share"] == 0.5
+ assert "covered changes" in prov["summary"]
+
+
+async def test_overview_agent_share_is_withheld_below_the_floor(setup_mcp, session):
+ from repowise.server.mcp_server import get_overview
+
+ rows = [_row(f"pr-{n}", n, ["src/x.py"], provenance="unknown", provenance_known=0) for n in range(1, 5)]
+ rows.append(_row("pr-5", 5, ["src/x.py"]))
+ await _seed(session, rows)
+ prov = (await get_overview(include=["changes"]))["changes"]["provenance"]
+ assert prov["coverage"] == 0.2
+ assert prov["agent_share"] is None
+ assert prov["suppressed_reason"] == "coverage_below_floor"
+ assert "agent_changes" not in prov and "human_attested_changes" not in prov
+ assert prov["unknown_changes"] == 4
+
+
+async def test_overview_changes_without_records(setup_mcp):
+ from repowise.server.mcp_server import get_overview
+
+ assert (await get_overview(include=["changes"]))["changes"] == {"total": 0}
+
+
+async def test_a_short_sha_in_several_changes_lists_candidates(setup_mcp, session):
+ from repowise.server.mcp_server import get_context
+
+ await _seed(
+ session,
+ [
+ _row("pr-1", 1, ["a.py"], sha="cafe123" + "1" * 33),
+ _row("pr-2", 2, ["a.py"], sha="cafe123" + "2" * 33),
+ ],
+ )
+ result = await get_context(targets=["change:cafe123", "change:cafe1232"])
+ card = result["targets"]["change:cafe123"]
+ assert "several changes" in card["error"]
+ assert sorted(card["candidates"]) == ["change:pr-1", "change:pr-2"]
+ assert result["targets"]["change:cafe1232"]["id"] == "pr-2"
+
+
+async def test_recent_changes_match_the_exact_path_only(setup_mcp, session):
+ """LIKE wildcards and SQLite's ASCII case folding never widen the match."""
+ from repowise.core.persistence.models import Repository
+ from repowise.server.mcp_server._changes import file_changes
+
+ await _seed(
+ session,
+ [
+ _row("pr-1", 1, ["src/a_b.py"]),
+ _row("pr-2", 2, ["src/aXb.py"]),
+ _row("pr-3", 3, ["src/100%.py"]),
+ _row("pr-4", 4, ["src/100x.py"]),
+ _row("pr-5", 5, ["src/A_B.py"]),
+ ],
+ )
+ repository = await session.get(Repository, "repo1")
+ found = await file_changes(
+ session, repository, ["src/a_b.py", "src/100%.py"], attribution=True
+ )
+ ids = {path: [r["id"] for r in block["recent_changes"]] for path, block in found.items()}
+ assert ids == {"src/a_b.py": ["pr-1"], "src/100%.py": ["pr-3"]}
+
+
+async def test_risk_reads_every_cards_changes_in_one_query(setup_mcp, session, monkeypatch):
+ from repowise.server.mcp_server import _changes, get_risk
+
+ await _seed(session)
+ calls = []
+ original = _changes.file_changes
+
+ async def counted(*args, **kwargs):
+ calls.append(args[2])
+ return await original(*args, **kwargs)
+
+ module = sys.modules["repowise.server.mcp_server.tool_risk.get_risk"]
+ monkeypatch.setattr(module, "file_changes", counted)
+ result = await get_risk(targets=["src/auth/service.py", "src/db/models.py"], include=["changes"])
+ assert len(calls) == 1 and sorted(calls[0]) == ["src/auth/service.py", "src/db/models.py"]
+ assert [r["id"] for r in result["targets"]["src/db/models.py"]["recent_changes"]] == ["pr-2"]
+
+
+# -- defaults never grow ----------------------------------------------------------
+
+
+async def test_default_responses_are_byte_identical_with_change_records(setup_mcp, session):
+ from repowise.server.mcp_server import get_context, get_overview, get_risk, get_why
+
+ async def defaults() -> list[str]:
+ return [
+ _without_meta(await get_context(targets=["src/auth/service.py"])),
+ _without_meta(await get_risk(targets=["src/auth/service.py"])),
+ _without_meta(await get_overview()),
+ _without_meta(await get_why(query="src/auth/service.py")),
+ ]
+
+ before = await defaults()
+ await _seed(session)
+ await session.execute(
+ update(GitMetadata)
+ .where(GitMetadata.file_path == "src/auth/service.py")
+ .values(attribution_known_count=21)
+ )
+ await session.commit()
+ assert await defaults() == before
diff --git a/tests/unit/server/mcp/test_risk.py b/tests/unit/server/mcp/test_risk.py
index 6236b4d51..ac7d26551 100644
--- a/tests/unit/server/mcp/test_risk.py
+++ b/tests/unit/server/mcp/test_risk.py
@@ -860,7 +860,7 @@ async def test_get_risk_names_an_unknown_include_rather_than_applying_it(setup_m
{
"argument": "include",
"values": ["nonsense"],
- "valid": ["blast", "churn", "graph", "owners", "scales", "tests"],
+ "valid": ["blast", "changes", "churn", "graph", "owners", "scales", "tests"],
}
]
diff --git a/tests/unit/server/test_chat_views.py b/tests/unit/server/test_chat_views.py
index c12688e20..e1504310b 100644
--- a/tests/unit/server/test_chat_views.py
+++ b/tests/unit/server/test_chat_views.py
@@ -322,6 +322,71 @@ def test_attribution_below_the_floor_is_refused_with_its_coverage(ratio, refused
assert turn.parts[0]["coverage"]["ratio"] == ratio
+def _overview_changes(coverage: float = 0.5, /, **provenance: Any) -> dict:
+ return {
+ "changes": {
+ "window": {"days": 90, "since": "2025-12-15T00:00:00+00:00", "until": "2026-03-15"},
+ "total": 4,
+ "by_category": {"feature": 3, "fix": 1},
+ "by_week": [{"week": "2026-03-02", "changes": 3}, {"week": "2026-03-09", "changes": 1}],
+ "provenance": provenance
+ or {
+ "agent_changes": 1,
+ "human_attested_changes": 1,
+ "unknown_changes": 2,
+ "coverage": coverage,
+ "agent_share": 0.5,
+ },
+ }
+ }
+
+
+def test_changes_by_category_and_week_plot_the_source_counts():
+ data = _overview_changes()
+ part = _build(data, "overview", "get_overview", "changes.by_category")
+ assert part["data"]["rows"] == [
+ {"category": "feature", "changes": 3},
+ {"category": "fix", "changes": 1},
+ ]
+ assert "90 days" in part["summary"]
+ week = _build(data, "overview", "get_overview", "changes.by_week")
+ assert week["chart_type"] == "line"
+ assert _series(week, "changes") == [3, 1]
+
+
+def test_changes_provenance_keeps_unknown_as_its_own_band():
+ part = _build(_overview_changes(), "overview", "get_overview", "changes.provenance")
+ assert part["chart_type"] == "donut"
+ assert part["data"]["rows"] == [
+ {"source": "agent", "changes": 1},
+ {"source": "human attested", "changes": 1},
+ {"source": "unknown", "changes": 2},
+ ]
+ assert part["coverage"] == {"metric": "attribution", "ratio": 0.5}
+
+
+ ("data", "code", "coverage"),
+ [
+ (_overview_changes(0.2), "insufficient_coverage", 0.2),
+ (
+ _overview_changes(unknown_changes=4, coverage=0.2, agent_share=None),
+ "insufficient_coverage",
+ 0.2,
+ ),
+ (_overview_changes(unavailable="attribution_off"), "attribution_off", None),
+ ({"changes": {"total": 0}}, "view_unavailable", None),
+ ],
+)
+def test_changes_provenance_is_refused_without_enough_coverage(data, code, coverage):
+ turn = TurnViews()
+ stamped = turn.record("get_overview", {}, data, artifact_type="overview")
+ result = turn.show({"artifact_id": stamped[ARTIFACT_ID_FIELD], "view": "changes.provenance"})
+ assert result["error_code"] == code
+ assert result.get("coverage") == coverage
+ assert turn.parts == []
+
+
def test_a_risk_score_is_never_a_chart_series():
@register_view_builder("test.risk_chart", description="never allowed", options=frozenset())
def _risk_chart(artifact, options):