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): outcomes on Change Records from explicit links only (#3812)
Raghav Chamadiya814c0e25d901
diff --git a/docs/architecture/bug-history.md b/docs/architecture/bug-history.mdindex 98bdf900d..6809ca548 100644--- a/docs/architecture/bug-history.md+++ b/docs/architecture/bug-history.md@@ -100,3 +100,16 @@ that concentration and mostly describes who authored the five largest commits.What ships answers "this code has broken before, recently, and roughly here".Nothing answers "and this commit caused it".++### Change outcomes: explicit links only++A Change Record's `outcomes` item (`core/changes/outcomes.py`) links a change+only to later commits that name it: reverts, by the decision-supersession+rules, and fixes that call it the cause in their own words. Hand-checked on 14+repositories, reverts held 16 of 16, with `Fixes: <sha>` trailers resolving to+the quoted commit 59 of 59 on the kernel. The kept phrases ("regression+from/in/since", "caused by", "broken by") were judged blind on 67 links from+django, pandas, litellm and langfuse: 67 of 67 named the change as the cause+(95% Wilson interval 94.6% to 100%; regression 47, caused by 12, broken by 8). `Fixes #N` (about 2 of+7), "introduced in #N" (about 5 of 14) and a fix commit quoting a sha (0 of+15) fell below 90% and are not read.diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.mdindex 02400a6f8..e9845ab7a 100644--- a/docs/reference/CLI_REFERENCE.md+++ b/docs/reference/CLI_REFERENCE.md@@ -1614,6 +1614,8 @@ Merged changes read back from git at each index and update: one per first-parent`show` also prints the change's evidence checklist: components touched, declared owners, suggested reviewers, reaching tests, contracts, consumers in other repos, decisions crossed, health delta, AI provenance and the diff size rank, each with a status (`ok`, `attention`, `unknown`) and the basis it rests on. The checklist is built on first read and kept on the change; `--refresh` rebuilds it. `export` writes every change merged in a `--since`/`--until` window (UTC, `--until` exclusive) with its checklist, streamed as JSON Lines (one record per line) or CSV rows (one row per change and item); building a missing checklist costs a few seconds per change. `list --needs-attention` keeps only changes whose kept checklist flags an item for attention; it reads checklists already built and builds none, so a change nobody has opened or exported is not listed.+The last item, `outcomes`, says what later history records about the change, and is read again whenever HEAD moves. It lists reverts that name the change and later commits that name it as the cause of what they fix in their own words (a `Fixes: <sha>` trailer, "regression from/in/since", "caused by", "broken by"), each quoting the message, and only from commits the change is an ancestor of. Beside those it reports how many of the change's files later received fix commits within 30 days (`changes.outcome_fix_days` in `.repowise/config.yaml`), a rate that says where fixes landed, never that the change caused them.+```bashrepowise changes list [--path PATH] [--category C] [--shape merge|squash|commit] [--grep TEXT] [--needs-attention] [--limit N] [--offset N] [--format table|json]repowise changes show REF [--path PATH] [--format table|json|in-toto] [--no-evidence] [--refresh]@@ -1664,12 +1666,13 @@ repowise report assessment [PATH] [--sections a,b] [--format json|markdown|html]| `test-reach` | Line coverage from ingested reports, and production files a test reaches, as separate items | `measured` and `inferred` || `contracts` | Contracts each component provides and their consumers in other repos | `measured` when the workspace store matches the indexed commit || `decisions` | Accepted decisions governing each component's files, and the stale ones | `declared` |+| `outcomes` | Changes a later commit reverted or named as the cause of what it fixed, in its own words, per component; read from the checklists already kept on Change Records, and left out when none is kept | `declared` || `provenance` | Commits in the last 90 indexed days with a known source (a count, not a score), and the agents and models named (listed, not counted) | `measured`, `declared`; `unresolved` with no markers || `trend` | What moved since a same-stamp snapshot at least 90 days older, by the `events` diff rules and only for the event kinds the repository has on | `measured` |`repowise report inventory [PATH]` renders the `inventory` section alone, with the same `--format`, `--out`, `--workspace`, `--no-workspace` and `--repo` options: the component inventory a software inventory review (PCI DSS 6.3.2) asks for. Its JSON `data` keeps every component's owner teams, languages, entry points and packages; the text lists the components with no declared owner team.-Basis `unresolved` means the evidence is missing. Each per-component section opens with one summary row counting components by outcome; a component gets its own item only when there is something to note (an ownership finding, a bus factor of 2 or less on a component the catalog gives a criticality or tags, hotspots, a stale decision, provided contracts, or unresolved or gated evidence), the rest are named in the summary, and the JSON `data` keeps every component's figures. Local paths are removed from every item. A section is a `Section` on `SeamRegistry("report-section")`: each module in `repowise/core/report/sections/` registers one, a plugin registers its own the same way, and a section whose data is absent returns `None` and is left out (an outcomes section is added this way once change outcomes exist). Renderers live on `SeamRegistry("report-renderer")` and are picked with `--format`. Modernization candidates are not reported, since no existing signal measures them.+Basis `unresolved` means the evidence is missing. Each per-component section opens with one summary row counting components by outcome; a component gets its own item only when there is something to note (an ownership finding, a bus factor of 2 or less on a component the catalog gives a criticality or tags, hotspots, a stale decision, provided contracts, or unresolved or gated evidence), the rest are named in the summary, and the JSON `data` keeps every component's figures. Local paths are removed from every item. A section is a `Section` on `SeamRegistry("report-section")`: each module in `repowise/core/report/sections/` registers one, a plugin registers its own the same way, and a section whose data is absent returns `None` and is left out, as `outcomes` is until a change's checklist has been opened. Renderers live on `SeamRegistry("report-renderer")` and are picked with `--format`. Modernization candidates are not reported, since no existing signal measures them.---diff --git a/packages/cli/src/repowise/cli/commands/changes_cmd.py b/packages/cli/src/repowise/cli/commands/changes_cmd.pyindex 69d5580d6..d9ead8d50 100644--- a/packages/cli/src/repowise/cli/commands/changes_cmd.py+++ b/packages/cli/src/repowise/cli/commands/changes_cmd.py@@ -5,7 +5,9 @@ evidence checklist, as the native versioned JSON record or, with``--format in-toto``, as an in-toto Statement v1; ``export`` writes everychange merged in a window with its checklist, as JSON Lines or CSV. All read theindex; ``repowise init`` or ``update`` fills it. A checklist is built on first-read (seconds per change) and kept on the change until ``--refresh``.+read (seconds per change) and kept on the change until ``--refresh``; its+``outcomes`` item (reverts, later fixes naming the change, the files' later+fix rate) is read again whenever HEAD has moved."""from __future__ import annotations@@ -92,7 +94,7 @@ async def _export() -> int | None:"""Emit each change in the window with its checklist, a page at a time; the count."""from repowise.core.attribution import attribution_enabled- from repowise.core.changes.collect import change_evidence+ from repowise.core.changes.collect import change_evidence, outcomes_keyfrom repowise.core.changes.record import change_recordfrom repowise.core.persistence.crud import ChangeFilter, list_changes@@ -101,6 +103,8 @@ async def _export(return Nonesession, repo_id = openedon = attribution_enabled(root)+ # One HEAD and window for the whole export, read once.+ key = await outcomes_key(root)done = 0while True:rows, total = await list_changes(@@ -116,7 +120,7 @@ async def _export(click.echo(f"evidence {done}/{total}: {row.change_id}", err=True)record = change_record(row, attribution=on)record["evidence"] = (- await change_evidence(session, repo_id, root, row, refresh=refresh)+ await change_evidence(session, repo_id, root, row, refresh=refresh, key=key)).to_dict()# Kept as it goes, so an interrupted export resumes where it stopped.await session.commit()@@ -144,10 +148,48 @@ def _print_checklist(evidence: dict) -> None:)console.print(table)console.print(f"[dim]generated {evidence['generated_at']}; `--refresh` rebuilds it.[/dim]")+ outcomes = next((i for i in evidence["items"] if i["kind"] == "outcomes"), None)+ if outcomes is not None and outcomes["status"] != "unknown":+ console.print("[bold]Outcomes[/bold]")+ for line in outcome_lines(outcomes):+ console.print(f" {escape(line)}")+++def outcome_lines(item: dict) -> list[str]:+ """The outcomes item in words: links quote their message, the rate states its basis."""+ lines = []+ for row in item["details"]:+ later = row.get("sha", "")[:12]+ if row.get("change_id"):+ later = f"{row['change_id']} ({later})"+ if row["kind"] == "revert":+ held = "" if row.get("in_force") else " (no longer in force)"+ lines.append(f"reverted by {later}{held}: {row['evidence']}")+ elif row["kind"] == "fix_reference":+ lines.append(+ f"referenced as the cause by a later fix, {later} (their words): \"{row['evidence']}\""+ )+ elif row["kind"] == "file_fix_rate":+ open_ = "" if row["window_complete"] else " (window still open)"+ lines.append(+ f"files later received fixes: {row['files_fixed']} of {row['files']}"+ f" within {row['days']} days{open_}"+ )+ if not any(r["kind"] in ("revert", "fix_reference") for r in item["details"]):+ lines.insert(0, "no later commit in this history reverts this change or names it as a cause")+ return linesdef _value_text(item: dict) -> str:value = item["value"]+ if item["kind"] == "outcomes" and isinstance(value, dict):+ rate = (+ f"{value['files_fixed']} of {value['files']} files fixed within {value['days']} days"+ if value.get("files") is not None+ else ""+ )+ said = f"{value['reverts']} revert(s), {value['fix_references']} cause reference(s)"+ return ", ".join(x for x in (said, rate) if x)if value is None:reasons = [d.get("reason") for d in item["details"] if d.get("reason")]return reasons[0] if reasons else ""@@ -172,6 +214,17 @@ _CSV_COLUMNS = ()+_FORMULA_LEAD = ("=", "+", "-", "@")+++def _cell(value: str) -> str:+ """*value* safe to open in a spreadsheet: a leading formula sign is quoted.++ Titles and evidence quote commit messages, which anyone can write.+ """+ return f"'{value}" if value.startswith(_FORMULA_LEAD) else value++def _csv_rows(record: dict) -> str:"""One CSV row per evidence item of *record*; ``value`` is its JSON."""import csv@@ -182,7 +235,8 @@ def _csv_rows(record: dict) -> str:writer = csv.writer(buf, lineterminator="\n")for item in record["evidence"]["items"]:writer.writerow(- [+ _cell(cell)+ for cell in [record["id"],record["merged_at"] or "",record["title"],diff --git a/packages/core/src/repowise/core/analysis/decisions/reverts.py b/packages/core/src/repowise/core/analysis/decisions/reverts.pyindex 307f89a1e..2b7e6d3d8 100644--- a/packages/core/src/repowise/core/analysis/decisions/reverts.py+++ b/packages/core/src/repowise/core/analysis/decisions/reverts.py@@ -60,6 +60,7 @@ logger = structlog.get_logger(__name__)__all__ = ["REVERT_SUPERSEDED_PREFIX",+ "HistoryUnreadableError","RevertLink","apply_revert_supersession","find_revert_links",@@ -95,6 +96,10 @@ _FIELD = "\x1f"_RECORD = "\x1e"+class HistoryUnreadableError(RuntimeError):+ """A git read :func:`find_revert_links` needs failed (``strict`` only)."""++@dataclass(frozen=True)class RevertLink:"""``revert`` undoes ``target``; ``rule`` is body | subject | pr.@@ -144,7 +149,9 @@ def _issue_keys(subject: str) -> set[str]:return {k.lower() for k in _ISSUE_KEY_RE.findall(_strip_pr_suffix(subject))}-def _changes(repo_path: Path | str, shas: set[str]) -> dict[str, dict[str, str]]:+def _changes(+ repo_path: Path | str, shas: set[str], *, strict: bool = False+) -> dict[str, dict[str, str]]:"""Path -> status letter (A, M, D, ...) per commit, against its first parent."""out: dict[str, dict[str, str]] = {}ordered = sorted(shas)@@ -161,6 +168,8 @@ def _changes(repo_path: Path | str, shas: set[str]) -> dict[str, dict[str, str]]f"--format={_RECORD}%H",*ordered[i : i + _CHANGES_BATCH],)+ if text is None and strict:+ raise HistoryUnreadableError("git could not list the files reverts touched")for block in (text or "").split(_RECORD):sha, _, rest = block.partition("\n")rows = (line.split("\t", 1) for line in rest.splitlines())@@ -169,8 +178,9 @@ def _changes(repo_path: Path | str, shas: set[str]) -> dict[str, dict[str, str]]return out-def _read_candidates(repo_path: Path | str, head: str) -> list[tuple[str, str, str]]:- """(sha, subject, body) of every commit whose message could fit a rule."""+def _read_candidates(repo_path: Path | str, head: str) -> list[tuple[str, str, str]] | None:+ """(sha, subject, body) of every commit whose message could fit a rule;+ ``None`` when git could not answer."""out = _git_out(repo_path,"log",@@ -181,8 +191,10 @@ def _read_candidates(repo_path: Path | str, head: str) -> list[tuple[str, str, s"--grep=This reverts commit [0-9a-f]{40}",f"--format=%H{_FIELD}%s{_FIELD}%b{_RECORD}",)+ if out is None:+ return Nonecandidates = []- for raw in (out or "").split(_RECORD):+ for raw in out.split(_RECORD):parts = raw.strip("\n").split(_FIELD)if len(parts) == 3 and parts[0]:candidates.append((parts[0].strip(), parts[1], parts[2]))@@ -334,13 +346,29 @@ class _Relands:return any(self.files(s) & target_files for s in self.same_issue_later(link))-def find_revert_links(repo_path: Path | str, head: str = "HEAD") -> list[RevertLink]:- """Every revert in *head*'s history matched to its target, ancestors only."""+def find_revert_links(+ repo_path: Path | str,+ head: str = "HEAD",+ *,+ forge: ForgeKind | None = None,+ strict: bool = False,+) -> list[RevertLink]:+ """Every revert in *head*'s history matched to its target, ancestors only.++ A git read that fails gives no links, or with *strict* raises+ :class:`HistoryUnreadableError`, so a caller can tell "none" from "unknown".+ """# Only messages that can fit a rule; the full history is read only if one# of them does.candidates = _read_candidates(repo_path, head)- hist = _History.read(repo_path, head, detect_forge(repo_path)) if candidates else None+ if candidates is None and strict:+ raise HistoryUnreadableError("git could not read the history for reverts")+ if not candidates:+ return []+ hist = _History.read(repo_path, head, forge or detect_forge(repo_path))if hist is None:+ if strict:+ raise HistoryUnreadableError("git could not read the history for reverts")return []proposed = [link for c in candidates for link in hist.match(*c)]relands = _Relands(hist, {link.revert for link in proposed})@@ -353,10 +381,12 @@ def find_revert_links(repo_path: Path | str, head: str = "HEAD") -> list[RevertLfor link in proposedfor sha in (link.target, link.revert, *relands.same_issue_later(link))},+ strict=strict,)- relands.head_paths = set(- (_git_out(repo_path, "ls-tree", "-r", "--name-only", head) or "").split("\n")- )+ tree = _git_out(repo_path, "ls-tree", "-r", "--name-only", head)+ if tree is None and strict:+ raise HistoryUnreadableError("git could not list the files at HEAD")+ relands.head_paths = set((tree or "").split("\n"))return [replace(link, relanded=relands.relanded(link))for link in proposeddiff --git a/packages/core/src/repowise/core/changes/__init__.py b/packages/core/src/repowise/core/changes/__init__.pyindex 3b3f48267..bbe65a1ae 100644--- a/packages/core/src/repowise/core/changes/__init__.py+++ b/packages/core/src/repowise/core/changes/__init__.py@@ -5,6 +5,8 @@ seam forge metadata comes through (git only by default), :mod:`.record` is theversioned JSON shape and its in-toto export, and :mod:`.store` keeps the``changes`` table in step with each index and update. :mod:`.evidence` is thechecklist attached to a record, and :mod:`.collect` gathers and caches it.+:mod:`.outcomes` reads what later history says about a change (reverts, fixes+that name it, its files' later fix rate) through the ``change-outcome`` seam."""from __future__ import annotationsdiff --git a/packages/core/src/repowise/core/changes/collect.py b/packages/core/src/repowise/core/changes/collect.pyindex 49d6f57ec..07c3bbbb1 100644--- a/packages/core/src/repowise/core/changes/collect.py+++ b/packages/core/src/repowise/core/changes/collect.py@@ -9,7 +9,10 @@ and :func:`change_evidence` does both. All end inA review costs seconds per change (the health comparison parses both sides),so it is computed on first read, never during an index or update, and kept:a merged change's checklist is a snapshot stamped with ``generated_at`` and-the ``index_commit`` it read, rebuilt only on request (``refresh``).+the ``index_commit`` it read, rebuilt only on request (``refresh``). The+``outcomes`` item is the exception: it describes history after the change, so+a kept checklist has that one item rebuilt when HEAD moves+(:func:`with_current_outcomes`), which costs one history read per HEAD."""from __future__ import annotations@@ -19,6 +22,7 @@ import jsonimport refrom collections.abc import Sequencefrom pathlib import Path+from types import SimpleNamespacefrom typing import TYPE_CHECKING, Anyimport structlog@@ -27,6 +31,7 @@ from repowise.core.changes.evidence import (EVIDENCE_SCHEMA_VERSION,ChangeEvidence,EvidenceInputs,+ EvidenceItem,Unavailable,build_change_evidence,)@@ -226,15 +231,28 @@ async def change_evidence(refresh: bool = False,risk: Any = None,health: Any = None,+ key: OutcomesKey | None = None,) -> ChangeEvidence:- """The stored change's checklist: the kept one, or built and kept now."""+ """The stored change's checklist: the kept one, or built and kept now.++ A kept one whose outcomes were read at another HEAD has that item read+ again and merged into what is stored (:func:`keep_outcomes`). *key* is the+ HEAD and window to read at, when the caller already has them.+ """+ from repowise.core.persistence.crud.changes import dump_evidence+if not refresh and (cached := cached_evidence(row)) is not None:- return cached+ key = key or await outcomes_key(repo_root)+ if not await outcomes_stale(repo_root, cached, key):+ return cached+ item = await outcomes_item(session, repo_id, repo_root, row, key)+ await session.flush()+ merged = await keep_outcomes(session, repo_id, row.change_id, item)+ session.expire(row, ["evidence_json"])+ return merged or with_item(cached, item)evidence = await build_stored_evidence(session, repo_id, repo_root, row, risk=risk, health=health)- from repowise.core.persistence.crud.changes import dump_evidence-row.evidence_json = dump_evidence(evidence.to_dict())await session.flush()return evidence@@ -256,6 +274,100 @@ async def stored_change_at(return row if row is not None and row.head_sha == sha else None+#: ``(HEAD sha, window days)``: what a kept ``outcomes`` item was read at.+OutcomesKey = tuple[str, int]+++async def outcomes_key(repo_root: Path | str) -> OutcomesKey:+ """The HEAD and window outcomes are read at now; ``""`` when there is no HEAD."""+ from repowise.core.changes.outcomes import fix_days+ from repowise.core.git_refs import resolve++ head = await asyncio.to_thread(resolve, str(repo_root), "HEAD")+ return head, fix_days(repo_root)+++def _stamp(item: EvidenceItem | None) -> OutcomesKey | None:+ if item is None:+ return None+ stamp = item.value if isinstance(item.value, dict) else (item.details or [{}])[0]+ return stamp.get("as_of"), stamp.get("days")+++async def outcomes_stale(+ repo_root: Path | str, evidence: ChangeEvidence, key: OutcomesKey | None = None+) -> bool:+ """Whether the kept ``outcomes`` item was read at another HEAD or window,+ or is missing (a checklist kept before the item existed)."""+ key = key or await outcomes_key(repo_root)+ return _stamp(evidence.item("outcomes")) != key+++async def outcomes_item(+ session: Any, repo_id: str, repo_root: Path | str, row: Any, key: OutcomesKey+) -> EvidenceItem:+ """The ``outcomes`` item for the stored change *row*, read at *key*."""+ from repowise.core.changes.evidence import _outcomes++ found = await _guard(_change_outcomes(session, repo_id, Path(repo_root), row, key))+ return _outcomes(EvidenceInputs(outcomes=found))+++def with_item(evidence: ChangeEvidence, item: EvidenceItem) -> ChangeEvidence:+ """*evidence* with *item* in place of its ``outcomes`` item."""+ from dataclasses import replace++ return replace(evidence, items=[i for i in evidence.items if i.kind != "outcomes"] + [item])+++async def with_current_outcomes(+ session: Any,+ repo_id: str,+ repo_root: Path | str,+ row: Any,+ evidence: ChangeEvidence,+ *,+ key: OutcomesKey | None = None,+) -> ChangeEvidence:+ """*evidence* with its ``outcomes`` item read at HEAD; the same object when it already was."""+ key = key or await outcomes_key(repo_root)+ if not await outcomes_stale(repo_root, evidence, key):+ return evidence+ item = await outcomes_item(session, repo_id, repo_root, row, key)+ if item == evidence.item("outcomes"):+ return evidence+ return with_item(evidence, item)+++async def keep_outcomes(+ session: Any, repo_id: str, change_id: str, item: EvidenceItem+) -> ChangeEvidence | None:+ """Merge *item* into the checklist stored now, touching no other item.++ The stored checklist is read again here, so a full rebuild kept while+ *item* was being read is not overwritten; one already holding outcomes+ read at the same HEAD and window is left as it is. ``None`` when no+ checklist is stored.+ """+ from sqlalchemy import select, update++ from repowise.core.persistence.crud.changes import dump_evidence+ from repowise.core.persistence.models import Change++ where = (Change.repository_id == repo_id, Change.change_id == change_id)+ raw = (await session.execute(select(Change.evidence_json).where(*where))).scalar_one_or_none()+ stored = cached_evidence(SimpleNamespace(evidence_json=raw))+ if stored is None:+ return None+ if _stamp(stored.item("outcomes")) == _stamp(item):+ return stored+ merged = with_item(stored, item)+ await session.execute(+ update(Change).where(*where).values(evidence_json=dump_evidence(merged.to_dict()))+ )+ return merged++def cached_evidence(row: Any) -> ChangeEvidence | None:"""The kept checklist, or ``None`` when there is none in this schema."""raw = getattr(row, "evidence_json", None)@@ -336,6 +448,13 @@ async def gather_inputs(consumers=consumers,decisions=await _guard(_decisions(session, repo_id, paths)),provenance=await _guard(_provenance(session, repo_id, repo_root, shas, row)),+ outcomes=(+ await _guard(+ _change_outcomes(session, repo_id, repo_root, row, await outcomes_key(repo_root))+ )+ if row is not None+ else Unavailable("not a merged change in the index")+ ),)@@ -630,6 +749,50 @@ async def _provenance(return {**block, "commits": commits}+async def _change_outcomes(+ session: Any, repo_id: str, repo_root: Path, row: Any, key: OutcomesKey+) -> dict[str, Any]:+ """Links to the change from later history, and its files' later fix rate.++ What git cannot answer reads unknown with the reason, stamped with *key*.+ """+ from repowise.core.changes.outcomes import (+ OutcomeUnknownError,+ file_fix_rate,+ outcome_links,+ target_of,+ )+ from repowise.core.git_refs import is_shallow+ from repowise.core.persistence.crud import get_change++ head, days = key+ stamp = {"as_of": head, "days": days}+ if not head:+ return {**stamp, "unknown": "the repository has no HEAD commit"}+ if await asyncio.to_thread(is_shallow, str(repo_root)):+ return {**stamp, "unknown": "a shallow clone cuts off the history outcomes are read from"}+ target = target_of(row)+ try:+ links = await asyncio.to_thread(outcome_links, repo_root, head, target)+ except OutcomeUnknownError as exc:+ return {**stamp, "unknown": str(exc)}+ rows = []+ for link in links:+ later = await get_change(session, repo_id, link.sha)+ rows.append({**link.to_dict(), "change_id": later.change_id if later else None})+ try:+ rate = await asyncio.to_thread(file_fix_rate, repo_root, head, target, days)+ rate_unknown = None+ except OutcomeUnknownError as exc:+ rate, rate_unknown = None, str(exc)+ return {+ **stamp,+ "links": rows,+ "file_fix_rate": rate,+ "file_fix_rate_unknown": rate_unknown,+ }++def _change_commits(repo_root: str, revspec: str | None, row: Any) -> list[str]:"""The change's commits: the stored list, else those *revspec* names."""from repowise.core.git_refs import _read, split_revspec@@ -654,6 +817,12 @@ __all__ = ["change_evidence","evidence_for_revspec","gather_inputs",+ "keep_outcomes",+ "outcomes_item",+ "outcomes_key",+ "outcomes_stale","save_evidence","stored_change_at",+ "with_current_outcomes",+ "with_item",]diff --git a/packages/core/src/repowise/core/changes/evidence.py b/packages/core/src/repowise/core/changes/evidence.pyindex be87d77d5..5b71d851c 100644--- a/packages/core/src/repowise/core/changes/evidence.py+++ b/packages/core/src/repowise/core/changes/evidence.py@@ -23,7 +23,14 @@ Detail rows a policy reads have fixed keys (the local change policy innothing knows;* ``contracts``: ``{path, breaking, ...}``;* ``provenance``: one row per commit, ``{sha, label, tier}``;-* ``decisions_crossed``: ``{id, title, authority, status, paths}``.+* ``decisions_crossed``: ``{id, title, authority, status, paths}``;+* ``outcomes``: one row per later link, ``{kind, sha, change_id, target_sha,+ rule, evidence, basis}`` (``kind`` is ``revert`` or ``fix_reference``; a+ revert adds ``in_force``), then one ``{kind: "file_fix_rate", basis:+ "measured", files, files_fixed, days, window_complete, fixed}`` row, or+ ``{kind: "file_fix_rate", basis: "unresolved", reason}`` when it could not+ be counted. An unknown item's one row carries ``as_of`` and ``days``. Unlike+ the rest, this item follows HEAD: it is rebuilt when new commits arrive."""from __future__ import annotations@@ -54,6 +61,7 @@ KINDS: tuple[str, ...] = ("health_delta","provenance","risk_score",+ "outcomes",)@@ -161,6 +169,10 @@ class EvidenceInputs:#: The provenance summary (``label``, counts, ``coverage``) plus#: ``commits``: ``[{sha, label, tier}]``.provenance: Mapping[str, Any] | Unavailable | None = None+ #: ``{as_of, days, links: [link row], file_fix_rate: row | None,+ #: file_fix_rate_unknown: reason | None}`` for a merged change+ #: (:mod:`.outcomes`), or ``{as_of, days, unknown: reason}``.+ outcomes: Mapping[str, Any] | Unavailable | None = Nonedef _now() -> str:@@ -204,6 +216,7 @@ def build_change_evidence(_health(bundle),_provenance(inputs),_risk(bundle),+ _outcomes(inputs),]return ChangeEvidence(change_id=change_id,@@ -463,6 +476,57 @@ def _risk(bundle: ChangeReviewBundle) -> EvidenceItem:)+def _outcomes(inputs: EvidenceInputs) -> EvidenceItem:+ kind, label, source = "outcomes", "Outcomes since merge", "git history"+ if reason := _missing(inputs.outcomes):+ return _unknown(kind, label, reason, source)+ block: Mapping[str, Any] = inputs.outcomes # type: ignore[assignment]+ stamp = {"as_of": block.get("as_of"), "days": block.get("days")}+ if block.get("unknown"):+ # Stamped, so a kept unknown is read again only once HEAD moves.+ return EvidenceItem(+ kind, label, "unknown", "unresolved", None, [{"reason": block["unknown"], **stamp}], source+ )+ links = [dict(r) for r in block.get("links") or ()]+ rate = block.get("file_fix_rate")+ value = _outcomes_value(block, links, rate)+ # A rate never asks for a look on its own: it says where fixes landed, not why.+ return EvidenceItem(+ kind,+ label,+ "attention" if value["reverted"] or value["fix_references"] else "ok",+ "declared" if links or rate is None else "measured",+ value,+ links + _rate_rows(rate, block.get("file_fix_rate_unknown")),+ source,+ )+++def _outcomes_value(+ block: Mapping[str, Any], links: list[dict[str, Any]], rate: Mapping[str, Any] | None+) -> dict[str, Any]:+ reverts = [r for r in links if r["kind"] == "revert"]+ return {+ "reverted": any(r.get("in_force") for r in reverts),+ "reverts": len(reverts),+ "fix_references": sum(r["kind"] == "fix_reference" for r in links),+ "files_fixed": rate["files_fixed"] if rate else None,+ "files": rate["files"] if rate else None,+ "days": block.get("days"),+ "window_complete": rate["window_complete"] if rate else None,+ "as_of": block.get("as_of"),+ }+++def _rate_rows(rate: Mapping[str, Any] | None, unknown: str | None) -> list[dict[str, Any]]:+ """The file fix rate as one detail row, or why it could not be counted."""+ if rate:+ return [{"kind": "file_fix_rate", "basis": "measured", **rate}]+ if unknown:+ return [{"kind": "file_fix_rate", "basis": "unresolved", "reason": unknown}]+ return []++__all__ = ["EVIDENCE_SCHEMA_VERSION","KINDS",diff --git a/packages/core/src/repowise/core/changes/outcomes.py b/packages/core/src/repowise/core/changes/outcomes.pynew file mode 100644index 000000000..7199f4018--- /dev/null+++ b/packages/core/src/repowise/core/changes/outcomes.py@@ -0,0 +1,564 @@+"""What happened to a merged change afterwards, from links a reader can check.++Two kinds of link, each quoting the message that makes it:++- ``revert``: a later commit reverts the change, matched by the rules in+ :mod:`repowise.core.analysis.decisions.reverts` (partial reverts never match);+- ``fix_reference``: a later commit names the change as the cause of what it+ fixes, in its own words: a ``Fixes: <sha>`` trailer, ``regression+ from/in/since``, ``caused by``, ``broken by/in/since``.++Each phrase was hand-checked on 14 repositories before it was kept. Looser+forms read well and named the wrong thing, so they are not read: ``Fixes #N``+(mostly an issue number, or a typo for one), ``introduced in #N`` (as often a+feature a later change builds on), and a fix commit quoting a sha (mostly a+revert or a squashed branch log).++A reference resolves only to a change it names unambiguously (a number on a+forge where issues and changes share one sequence, ``!N`` on GitLab, a sha+that is unique in the history), and only from a commit the change is an+ancestor of. Links to another repository's changes (URLs) are not read.++Beside the links, :func:`file_fix_rate` measures how many of the change's+files later received fix commits within N days: a rate with its basis, never+a claim that the change caused them. No link is inferred from blame (SZZ was+measured below its gate and not shipped; docs/architecture/bug-history.md).++Link kinds are providers on ``SeamRegistry("change-outcome")``. Every+registered provider runs, the local git ones first; a forge-backed provider+(a PR's linked follow-ups) registers another under its own name.+"""++from __future__ import annotations++import re+import threading+from collections.abc import Sequence+from dataclasses import dataclass, field+from datetime import datetime, timedelta+from pathlib import Path+from typing import Any, Protocol++from repowise.core.registry.plugins import SeamRegistry, load_plugins++#: The window :func:`file_fix_rate` counts in, unless ``changes.outcome_fix_days`` says.+DEFAULT_FIX_DAYS = 30+_MAX_FIX_DAYS = 365+_FRAGMENT_WIDTH = 200++REVERT = "revert"+FIX_REFERENCE = "fix_reference"++#: Forges that number issues and changes in one sequence, so ``#N`` names at+#: most one of them. GitLab (``!N``), Azure and Bitbucket number them apart.+_SHARED_NUMBERING = frozenset({"github", "generic"})++_FIELD = "\x1f"+_RECORD = "\x1e"++# ``#N``, GitLab's ``!N``, or a sha of 7 to 40 hex digits.+_REF = r"(#\d{1,9}|!\d{1,9}|\b[0-9a-f]{7,40}\b)"+# Words may wrap onto the next line, never across a blank one: a phrase that+# ends one paragraph says nothing about the reference opening the next.+_S = r"(?:[ \t]+|[ \t]*\n[ \t]*)"+_NOUN = rf"(?:(?:commit|change|pr|pull request|merge request|mr){_S})?"+_RULES: tuple[tuple[str, re.Pattern[str]], ...] = (+ # The kernel convention: ``Fixes: <sha> ("subject")`` names the commit that+ # introduced the bug.+ ("fixes_trailer", re.compile(r"^Fixes:[ \t]+([0-9a-f]{7,40})\b", re.I | re.M)),+ (+ "regression",+ re.compile(+ rf"\bregress(?:ion|ed)?{_S}(?:introduced{_S})?(?:from|in|since|by){_S}{_NOUN}{_REF}",+ re.I,+ ),+ ),+ ("caused_by", re.compile(rf"\bcaused{_S}by{_S}{_NOUN}{_REF}", re.I)),+ ("broken_by", re.compile(rf"\b(?:broken|broke){_S}(?:by|in|since){_S}{_NOUN}{_REF}", re.I)),+)+++@dataclass(frozen=True, slots=True)+class OutcomeTarget:+ """The change outcomes are read for."""++ change_id: str+ head_sha: str+ commit_shas: tuple[str, ...]+ identity_kind: str+ identity_value: str+ forge: str+ forge_ref: str | None+ merged_at: datetime | None+ files: tuple[str, ...]++ @property+ def revert_targets(self) -> set[str]:+ """Commits whose revert undoes the whole change, not one commit of many."""+ shas = {self.head_sha}+ if len(self.commit_shas) == 1:+ shas.add(self.commit_shas[0])+ return shas++ @property+ def own(self) -> set[str]:+ return {self.head_sha, *self.commit_shas}+++@dataclass(frozen=True, slots=True)+class OutcomeLink:+ """A later commit that names the change, and the words it names it in."""++ kind: str+ #: The later commit.+ sha: str+ #: The change's commit it names.+ target_sha: str+ #: The message fragment that makes the link, verbatim.+ evidence: str+ #: Which rule matched (``body``/``subject``/``pr`` for a revert, a phrase for a reference).+ rule: str+ basis: str = "declared"+ #: Revert only: the revert still holds at HEAD (not itself reverted, the change not re-landed).+ in_force: bool | None = None+ #: The stored change the later commit landed in, filled by the caller.+ change_id: str | None = None++ def to_dict(self) -> dict[str, Any]:+ out = {+ "kind": self.kind,+ "sha": self.sha,+ "change_id": self.change_id,+ "target_sha": self.target_sha,+ "rule": self.rule,+ "evidence": self.evidence,+ "basis": self.basis,+ }+ if self.kind == REVERT:+ out["in_force"] = self.in_force+ return out+++class ChangeOutcomeProvider(Protocol):+ def links(self, repo_path: Path, head: str, change: OutcomeTarget) -> Sequence[OutcomeLink]:+ """Links to *change* from history up to *head*; none found is ``[]``.++ Raise :class:`OutcomeUnknownError` when the source cannot be read, so the+ item reads unknown instead of none.+ """+ ...+++class OutcomeUnknownError(Exception):+ """What could not be read, said as a reason; the item reads unknown, never none."""+++def _git_out(repo_path: Path | str, *args: str) -> str:+ """Git's stdout; a failure or timeout raises :class:`OutcomeUnknownError`."""+ from repowise.core.analysis.decisions.reverts import _git_out as read++ out = read(repo_path, *args)+ if out is None:+ raise OutcomeUnknownError(f"git could not answer `git {args[0]}` for this repository")+ return out+++def _fragment(text: str, start: int, end: int) -> str:+ """The line holding ``text[start:end]``, trimmed to a readable width."""+ lo = text.rfind("\n", 0, start) + 1+ hi = text.find("\n", end)+ line = text[lo : hi if hi >= 0 else len(text)].strip()+ return line if len(line) <= _FRAGMENT_WIDTH else line[: _FRAGMENT_WIDTH - 1] + "…"+++# One build per key at a time, shared by every thread that asks; a failed+# build raises to each caller and is not kept. The last few HEADs stay.+_INDEX_KEEP = 4+_index_lock = threading.Lock()+_index: dict[tuple[str, ...], Any] = {}+_index_locks: dict[tuple[str, ...], threading.Lock] = {}+++def _once(key: tuple[str, ...], build: Any) -> Any:+ with _index_lock:+ lock = _index_locks.setdefault(key, threading.Lock())+ with lock:+ with _index_lock:+ if key in _index:+ return _index[key]+ value = build()+ with _index_lock:+ _index[key] = value+ while len(_index) > _INDEX_KEEP:+ old = next(iter(_index))+ _index.pop(old)+ _index_locks.pop(old, None)+ return value+++def _forge(name: str) -> Any:+ from repowise.core.forges import ForgeKind++ try:+ return ForgeKind(name)+ except ValueError:+ return ForgeKind.GENERIC+++# -- reverts -------------------------------------------------------------------+++def _revert_index(+ repo_path: str, head: str, forge: str+) -> tuple[dict[str, list[Any]], frozenset[str], dict[str, str]]:+ """``(links by target, targets reverted at HEAD, revert subjects)``, once per HEAD."""++ def build() -> tuple[dict[str, list[Any]], frozenset[str], dict[str, str]]:+ from repowise.core.analysis.decisions.reverts import (+ HistoryUnreadableError,+ find_revert_links,+ reverted_at_head,+ )++ try:+ links = find_revert_links(repo_path, head, forge=_forge(forge), strict=True)+ except HistoryUnreadableError as exc:+ raise OutcomeUnknownError(str(exc)) from exc+ by_target: dict[str, list[Any]] = {}+ for link in links:+ by_target.setdefault(link.target, []).append(link)+ subjects: dict[str, str] = {}+ if links:+ raw = _git_out(+ repo_path,+ "log",+ "--no-walk=unsorted",+ f"--format=%H{_FIELD}%s",+ *dict.fromkeys(link.revert for link in links),+ )+ for line in raw.splitlines():+ sha, _, subject = line.partition(_FIELD)+ subjects[sha.strip()] = subject+ return by_target, frozenset(reverted_at_head(links)), subjects++ return _once(("revert", repo_path, head, forge), build)+++class GitRevertOutcomes:+ """Reverts that name the change, by the decision-supersession rules."""++ def links(self, repo_path: Path, head: str, change: OutcomeTarget) -> list[OutcomeLink]:+ by_target, in_force, subjects = _revert_index(str(repo_path), head, change.forge)+ out = []+ for target in sorted(change.revert_targets):+ for link in by_target.get(target, ()):+ said = (+ f"This reverts commit {target}"+ if link.rule == "body"+ else subjects.get(link.revert, "")+ )+ out.append(+ OutcomeLink(+ REVERT,+ link.revert,+ target,+ said,+ link.rule,+ in_force=target in in_force,+ )+ )+ return out+++# -- references ----------------------------------------------------------------+++@dataclass+class _References:+ """Every cause phrase in *head*'s history, keyed by what it names."""++ hist: Any+ shas: list[str] = field(default_factory=list)+ #: ``"#12"`` / ``"!12"`` / a sha token -> ``[(commit, rule, fragment)]``.+ by_token: dict[str, list[tuple[str, str, str]]] = field(default_factory=dict)++ def holder(self, number: str) -> str | None:+ """The one commit that *is* change *number*, leaving out reverts and re-lands.++ ``Revert "x (#5)" (#6)`` and ``Reland x (#5)`` carry the number without+ being that change; two other holders make it ambiguous.+ """+ from repowise.core.analysis.decisions.reverts import (+ _CONVENTIONAL_RE,+ _RELAND_WORD_RE,+ _SUBJECT_RE,+ )++ held = [+ sha+ for sha in self.hist.by_pr.get(number, ())+ if not (+ _SUBJECT_RE.match(subject := self.hist.subject_of.get(sha, ""))+ or _CONVENTIONAL_RE.match(subject)+ or _RELAND_WORD_RE.search(subject)+ )+ ]+ return held[0] if len(held) == 1 else None+++def _reference_index(repo_path: str, head: str, forge: str) -> _References:+ def build() -> _References:+ from repowise.core.analysis.decisions.reverts import _History++ raw = _git_out(+ repo_path,+ "log",+ "--topo-order",+ head,+ f"--format=%H{_FIELD}%P{_FIELD}%s{_FIELD}%b{_RECORD}",+ )+ hist = _History(forge=_forge(forge))+ refs = _References(hist)+ for record in raw.split(_RECORD):+ fields = record.strip("\n").split(_FIELD, 3)+ if len(fields) != 4 or not fields[0]:+ continue+ sha, parents, subject, body = fields+ hist._add(sha, parents, subject, body)+ message = f"{subject}\n\n{body}" # git always parts them with a blank line+ named: set[str] = set()+ for rule, pattern in _RULES:+ for m in pattern.finditer(message):+ token = m.group(1).lower()+ if token not in named:+ named.add(token)+ frag = _fragment(message, m.start(), m.end())+ refs.by_token.setdefault(token, []).append((sha, rule, frag))+ refs.shas = sorted(hist.position)+ return refs++ return _once(("reference", repo_path, head, forge), build)+++_Hit = tuple[str, str, str, str] # (later commit, target sha, rule, fragment)+++def _number_hits(refs: _References, change: OutcomeTarget) -> list[_Hit]:+ """References by the change's number, when its own commit is the one holding it."""+ number = change.identity_value if change.identity_kind == "pr" else None+ if number is None or refs.holder(number) not in change.own:+ return []+ tokens = []+ if change.forge in _SHARED_NUMBERING:+ tokens.append(f"#{number}")+ if change.forge == "gitlab":+ tokens.append(f"!{number}")+ # Ceiling: Azure Repos also writes ``!N`` for a pull request; it is not+ # read until it is measured there.+ return [+ (c, change.head_sha, r, f) for token in tokens for c, r, f in refs.by_token.get(token, ())+ ]+++def _sha_hits(refs: _References, change: OutcomeTarget) -> list[_Hit]:+ """References by a sha that is unique in the history and one of the change's own."""+ from repowise.core.analysis.decisions.reverts import _resolve++ own = change.own+ hits: list[_Hit] = []+ for token, rows in refs.by_token.items():+ if token[0] in "#!" or not any(s.startswith(token) for s in own):+ continue+ full = _resolve(token, refs.shas) # unique in the history, or nothing+ if full in own:+ hits += [(c, full, r, f) for c, r, f in rows]+ return hits+++class GitReferenceOutcomes:+ """Later commits whose message names the change as what they fix."""++ def links(self, repo_path: Path, head: str, change: OutcomeTarget) -> list[OutcomeLink]:+ refs = _reference_index(str(repo_path), head, change.forge)+ if change.head_sha not in refs.hist.position:+ raise OutcomeUnknownError("the change is not in HEAD's history")+ own = change.own+ out: dict[str, OutcomeLink] = {}+ for commit, target, rule, frag in _number_hits(refs, change) + _sha_hits(refs, change):+ if commit in own or commit in out or not refs.hist.is_ancestor(target, commit):+ continue+ out[commit] = OutcomeLink(FIX_REFERENCE, commit, target, frag, rule)+ return sorted(out.values(), key=lambda link: refs.hist.position[link.sha], reverse=True)+++change_outcome_providers: SeamRegistry[ChangeOutcomeProvider] = SeamRegistry("change-outcome")+change_outcome_providers.register("git-revert", GitRevertOutcomes())+change_outcome_providers.register("git-reference", GitReferenceOutcomes())+++def outcome_links(repo_path: Path | str, head: str, change: OutcomeTarget) -> list[OutcomeLink]:+ """Links from every registered provider, in registration order.++ A provider that cannot read raises :class:`OutcomeUnknownError`, and so does this.+ """+ out: list[OutcomeLink] = []+ seen: set[tuple[str, str]] = set()+ load_plugins()+ for name in change_outcome_providers.names:+ for link in change_outcome_providers.get(name).links(Path(repo_path), head, change):+ if (link.kind, link.sha) not in seen:+ seen.add((link.kind, link.sha))+ out.append(link)+ return out+++# -- file fix rate -------------------------------------------------------------+++def fix_days(repo_path: Path | str) -> int:+ """``changes.outcome_fix_days`` from the repo config (1 to 365), else the default."""+ from repowise.core.repo_config import load_repo_config++ try:+ raw = (load_repo_config(repo_path).get("changes") or {}).get("outcome_fix_days")+ days = int(raw) if raw is not None else DEFAULT_FIX_DAYS+ except (TypeError, ValueError, AttributeError):+ return DEFAULT_FIX_DAYS+ return days if 1 <= days <= _MAX_FIX_DAYS else DEFAULT_FIX_DAYS+++#: Paths per ``git log -- <paths>`` call, well under Windows' command-line limit.+_PATH_BATCH = 100+++def _fix_commits_touching(+ repo_path: Path | str,+ head: str,+ files: list[str],+ start: int,+ end: int,+) -> list[tuple[str, set[str]]]:+ """``(sha, paths)`` of fix commits with ``start < ts <= end`` touching *files*."""+ from repowise.core.ingestion.git_indexer._constants import is_fix_commit++ found: list[tuple[str, set[str]]] = []+ for i in range(0, len(files), _PATH_BATCH):+ batch = files[i : i + _PATH_BATCH]+ # Bounded by date; the caller keeps the change's descendants. Not+ # ``--ancestry-path`` with ``--since``: the date cut stops the walk+ # before it reaches the change, and nothing qualifies.+ raw = _git_out(+ repo_path,+ "--literal-pathspecs",+ "log",+ "--no-merges",+ f"--since=@{start}",+ f"--until=@{end}",+ "--name-only",+ f"--format={_RECORD}%H{_FIELD}%ct{_FIELD}%s",+ head,+ "--",+ *batch,+ )+ wanted = set(batch)+ for record in raw.split(_RECORD):+ header, _, names = record.strip("\n").partition("\n")+ parts = header.split(_FIELD)+ if len(parts) != 3 or not parts[1].isdigit():+ continue+ sha, ts, subject = parts+ if start < int(ts) <= end and is_fix_commit(subject):+ touched = wanted.intersection(names.splitlines())+ if touched:+ found.append((sha, touched))+ return found+++def file_fix_rate(+ repo_path: Path | str, head: str, change: OutcomeTarget, days: int+) -> dict[str, Any]:+ """How many of the change's files a later fix commit touched within *days*.++ A fix is a commit the fix category holds (``is_fix_commit``, the rule every+ fix count uses) that descends from the change. Paths are matched as the+ change left them; a later rename is not followed. Raises+ :class:`OutcomeUnknownError` when there is nothing to count or git cannot answer.++ Ceiling: one date-bounded ``git log`` per 100 of the change's files; an+ export of thousands of changes pays it per change.+ """+ if change.merged_at is None:+ raise OutcomeUnknownError("the change has no merge time to count a window from")+ if not change.files:+ raise OutcomeUnknownError("the change lists no files")+ refs = _reference_index(str(repo_path), head, change.forge)+ if change.head_sha not in refs.hist.position:+ raise OutcomeUnknownError("the change is not in HEAD's history")+ start = int(change.merged_at.timestamp())+ end = int((change.merged_at + timedelta(days=days)).timestamp())+ files = sorted(set(change.files))+ fixed: dict[str, list[str]] = {}+ commits: set[str] = set()+ for sha, touched in _fix_commits_touching(repo_path, head, files, start, end):+ if sha == change.head_sha or not refs.hist.is_ancestor(change.head_sha, sha):+ continue+ commits.add(sha)+ for path in touched:+ fixed.setdefault(path, []).append(sha)+ head_ts = _git_out(repo_path, "log", "-1", "--format=%ct", head).strip()+ return {+ "files": len(files),+ "files_fixed": len(fixed),+ "days": days,+ "fix_commits": len(commits),+ "window_complete": head_ts.isdigit() and int(head_ts) >= end,+ "fixed": [{"path": p, "fixes": shas} for p, shas in sorted(fixed.items())],+ }+++def target_of(row: Any) -> OutcomeTarget:+ """The :class:`OutcomeTarget` for a stored ``changes`` row."""+ import json++ def _load(raw: str | None) -> list[Any]:+ try:+ return list(json.loads(raw or "[]"))+ except (TypeError, ValueError):+ return []++ merged = row.merged_at+ if merged is not None and merged.tzinfo is None: # SQLite drops tzinfo; the column is UTC+ from datetime import UTC++ merged = merged.replace(tzinfo=UTC)+ return OutcomeTarget(+ change_id=row.change_id,+ head_sha=row.head_sha,+ commit_shas=tuple(_load(row.commit_shas_json)),+ identity_kind=row.identity_kind,+ identity_value=row.identity_value,+ forge=row.forge,+ forge_ref=row.forge_ref,+ merged_at=merged,+ files=tuple(+ f["path"] for f in _load(row.files_json) if isinstance(f, dict) and f.get("path")+ ),+ )+++__all__ = [+ "DEFAULT_FIX_DAYS",+ "FIX_REFERENCE",+ "REVERT",+ "ChangeOutcomeProvider",+ "GitReferenceOutcomes",+ "GitRevertOutcomes",+ "OutcomeLink",+ "OutcomeTarget",+ "OutcomeUnknownError",+ "change_outcome_providers",+ "file_fix_rate",+ "fix_days",+ "outcome_links",+ "target_of",+]diff --git a/packages/core/src/repowise/core/report/sections/outcomes.py b/packages/core/src/repowise/core/report/sections/outcomes.pynew file mode 100644index 000000000..0ebc1c089--- /dev/null+++ b/packages/core/src/repowise/core/report/sections/outcomes.py@@ -0,0 +1,159 @@+"""Change outcomes: merged changes a later commit reverted or named as the+cause of what it fixed, in that commit's own words, rolled up per component.++Read from the checklists already kept on Change Records, never built here: a+change's outcomes are read the first time its checklist is opened (CLI, web,+REST, MCP). With none kept the section is left out. No link is inferred from+blame, and a file fix rate is never read as a cause.+"""++from __future__ import annotations++import json+from typing import Any++from repowise.core.report.model import (+ ReportContext,+ Section,+ capped,+ check,+ component_summary,+ report_sections,+)++_METHOD = (+ "reverts that name the change and later commits that call it the cause in their own "+ "words, from the outcomes kept on each change's checklist (read when it was last opened, "+ "so they can predate the newest commits)"+)+_FLAGGED = "reverted or named as the cause by a later fix"+++def _outcomes(raw: str | None) -> dict[str, Any] | None:+ """The kept ``outcomes`` item of one checklist, when it was read and known."""+ if not raw:+ return None+ try:+ items = json.loads(raw).get("items") or []+ except (TypeError, ValueError, AttributeError):+ return None+ item = next((i for i in items if isinstance(i, dict) and i.get("kind") == "outcomes"), None)+ return item if item and item.get("status") != "unknown" else None+++def _files(files_json: str | None) -> list[str]:+ try:+ return [f["path"] for f in json.loads(files_json or "[]") if f.get("path")]+ except (TypeError, ValueError, AttributeError):+ return []+++def _read_change(+ change_id: str, title: str, files_json: str | None, item: dict[str, Any]+) -> tuple[dict[str, Any], list[str]]:+ """One change's figures and its detail lines, from its kept outcomes item."""+ links = [d for d in item.get("details") or () if d.get("kind") in ("revert", "fix_reference")]+ reverted = any(d["kind"] == "revert" and d.get("in_force") for d in links)+ named = [d for d in links if d["kind"] == "fix_reference"]+ lines = [f"reverted: {change_id} {title}"] if reverted else []+ for d in named:+ said = d.get("evidence", "")+ lines.append(f'{change_id} named by a later fix, in its words: "{said}"')+ figures = {"reverted": reverted, "cause_references": len(named), "files": _files(files_json)}+ return figures, lines+++async def _kept_outcomes(ctx: ReportContext) -> tuple[int, dict[str, dict[str, Any]], list[str]]:+ """``(indexed changes, figures by change, detail lines)`` over the kept checklists."""+ from sqlalchemy import func, select++ from repowise.core.persistence.models import Change++ repo = Change.repository_id == ctx.repository_id+ total = await ctx.session.scalar(select(func.count()).where(repo))+ rows = (+ await ctx.session.execute(+ select(Change.change_id, Change.title, Change.files_json, Change.evidence_json)+ .where(repo, Change.evidence_json.is_not(None))+ .order_by(Change.merged_at.desc().nulls_last(), Change.change_id)+ )+ ).all()+ read: dict[str, dict[str, Any]] = {}+ lines: list[str] = []+ for change_id, title, files_json, evidence_json in rows:+ item = _outcomes(evidence_json)+ if item is not None:+ read[change_id], said = _read_change(change_id, title, files_json, item)+ lines += said+ return total, read, lines+++async def _per_component(+ ctx: ReportContext, read: dict[str, dict[str, Any]], flagged: list[str]+) -> dict[str, dict[str, list[str]]]:+ """Each component's read and flagged changes, by the files they touched."""+ found = await ctx.components()+ owner_of: dict[str, list[str]] = {}+ for comp in found.resolved.components:+ for path in found.resolved.files.get(comp.name, ()):+ owner_of.setdefault(path, []).append(comp.name)+ figures: dict[str, dict[str, list[str]]] = {}+ for change_id, v in read.items():+ for name in sorted({n for p in v["files"] for n in owner_of.get(p, ())}):+ slot = figures.setdefault(name, {"read": [], "flagged": []})+ slot["read"].append(change_id)+ if change_id in flagged:+ slot["flagged"].append(change_id)+ return figures+++async def collect(ctx: ReportContext) -> list[dict[str, Any]] | None:+ total, read, lines = await _kept_outcomes(ctx)+ if not read:+ return None+ flagged = [c for c, v in read.items() if v["reverted"] or v["cause_references"]]+ summary = check(+ "outcomes",+ reason=(+ f"{len(flagged)} of {len(read)} change(s) with outcomes read were {_FLAGGED}; "+ f"outcomes are read for {len(read)} of {total} indexed change(s)"+ ),+ details=capped(lines),+ method=_METHOD,+ basis="declared",+ data={+ "changes": total,+ "read": len(read),+ "flagged": flagged,+ "by_change": {+ c: {k: v[k] for k in ("reverted", "cause_references")} for c, v in read.items()+ },+ },+ )+ figures = await _per_component(ctx, read, flagged)+ marked = sorted(n for n, f in figures.items() if f["flagged"])+ quiet = sorted(n for n, f in figures.items() if not f["flagged"])+ components = component_summary(+ "outcomes:components",+ outcomes={f"with a change {_FLAGGED}": len(marked), "nothing to note": len(quiet)},+ quiet=quiet,+ named={_FLAGGED: marked},+ method=_METHOD,+ basis="declared",+ data={"components": figures},+ )+ return [summary, components]+++report_sections.register(+ "outcomes",+ Section(+ title="Change outcomes",+ summary=(+ "Merged changes a later commit reverted or named as the cause of what it fixed, "+ "in its own words, per component."+ ),+ collect=collect,+ order=85,+ ),+)diff --git a/packages/server/src/repowise/server/routers/changes.py b/packages/server/src/repowise/server/routers/changes.pyindex 1fe09e0df..4358c75d7 100644--- a/packages/server/src/repowise/server/routers/changes.py+++ b/packages/server/src/repowise/server/routers/changes.py@@ -13,8 +13,13 @@ from repowise.core.changes.collect import (build_stored_evidence,cached_evidence,evidence_summary,+ keep_outcomes,list_needing_attention,+ outcomes_item,+ outcomes_key,+ outcomes_stale,save_evidence,+ with_item,)from repowise.core.changes.evidence import ChangeEvidencefrom repowise.core.changes.record import change_record@@ -42,7 +47,9 @@ _MAX_PAGE = 200EVIDENCE_WAIT_SECONDS = 15.0#: One build per change at a time, shared by every request that asks.-_BUILDS: dict[tuple[str, str], asyncio.Task[ChangeEvidence]] = {}+#: Keyed by ``(repo, change, "full" | "outcomes")``: a refresh asked while+#: only outcomes are being read starts its own full build.+_BUILDS: dict[tuple[str, str, str], asyncio.Task[ChangeEvidence]] = {}async def _attribution(session: AsyncSession, repo_id: str) -> bool:@@ -117,10 +124,15 @@ async def get_change(record = change_record(row, attribution=attribution)if evidence:kept = None if refresh else cached_evidence(row)+ repo = await crud.get_repository(session, repo_id)+ # A kept checklist is current but for ``outcomes``, which follows HEAD.+ task = None+ factory = resolve_request_session_factory(request)if kept is None:- repo = await crud.get_repository(session, repo_id)- factory = resolve_request_session_factory(request)task = _build(factory, repo_id, row.change_id, repo.local_path)+ elif await outcomes_stale(repo.local_path, kept):+ task = _build(factory, repo_id, row.change_id, repo.local_path, kept)+ if task is not None:try:kept = await asyncio.wait_for(asyncio.shield(task), EVIDENCE_WAIT_SECONDS)except TimeoutError:@@ -130,12 +142,26 @@ async def get_change(return ChangeRecord(**record, commit_count=len(record["commits"]))-def _build(factory: Any, repo_id: str, change_id: str, root: str) -> asyncio.Task[ChangeEvidence]:- """The running build for this change, or a new one; a finished build leaves the map."""- key = (repo_id, change_id)+def _build(+ factory: Any, repo_id: str, change_id: str, root: str, kept: ChangeEvidence | None = None+) -> asyncio.Task[ChangeEvidence]:+ """The running build for this change, or a new one; a finished build leaves the map.++ Without *kept* the whole checklist is built. With it only its outcomes are+ read again, unless a full build is already running, which reads them too.+ """+ full = (repo_id, change_id, "full")+ if kept is not None and full in _BUILDS:+ return _BUILDS[full]+ key = full if kept is None else (repo_id, change_id, "outcomes")task = _BUILDS.get(key)if task is None:- task = asyncio.create_task(_build_and_keep(factory, repo_id, change_id, root))+ job = (+ _build_and_keep(factory, repo_id, change_id, root)+ if kept is None+ else _outcomes_and_keep(factory, repo_id, change_id, root, kept)+ )+ task = asyncio.create_task(job)_BUILDS[key] = tasktask.add_done_callback(lambda _t: _BUILDS.pop(key, None))return task@@ -149,3 +175,16 @@ async def _build_and_keep(factory: Any, repo_id: str, change_id: str, root: str)async with get_session(factory) as session:await save_evidence(session, repo_id, change_id, evidence)return evidence+++async def _outcomes_and_keep(+ factory: Any, repo_id: str, change_id: str, root: str, kept: ChangeEvidence+) -> ChangeEvidence:+ """Read the outcomes item, then merge only it into what is stored by then."""+ key = await outcomes_key(root)+ async with get_session(factory) as session:+ row = await crud.get_change(session, repo_id, change_id)+ item = await outcomes_item(session, repo_id, root, row, key)+ async with get_session(factory) as session:+ merged = await keep_outcomes(session, repo_id, change_id, item)+ return merged or with_item(kept, item)diff --git a/packages/types/src/changes.ts b/packages/types/src/changes.tsindex b78e55c2e..ac7129c5b 100644--- a/packages/types/src/changes.ts+++ b/packages/types/src/changes.ts@@ -45,5 +45,6 @@ export const EVIDENCE_KINDS = ["health_delta","provenance","risk_score",+ "outcomes",] as const;export type EvidenceKind = (typeof EVIDENCE_KINDS)[number];diff --git a/packages/web/messages/en.json b/packages/web/messages/en.jsonindex 755c2a533..d044ddced 100644--- a/packages/web/messages/en.json+++ b/packages/web/messages/en.json@@ -280,6 +280,14 @@"evidenceUnavailable": "The evidence checklist could not be built for this change.","evidenceBuilding": "The evidence checklist is still being built. Reload the page in a moment.","evidenceGenerated": "Generated {date}",+ "detailOutcomes": "Outcomes",+ "outcomesRevertedBy": "Reverted by",+ "outcomesNoLongerInForce": "no longer in force",+ "outcomesCause": "Referenced as the cause by a later fix (their words):",+ "outcomesFileRate": "Files later received fixes: {fixed} of {total} within {days} days",+ "outcomesWindowOpen": "window still open",+ "outcomesNone": "No later commit in this history reverts this change or names it as a cause.",+ "outcomesNote": "Links come only from later commits that name this change. The file rate says where fixes landed, not what caused them.","statusOk": "ok","statusAttention": "attention","statusUnknown": "unknown",diff --git a/packages/web/messages/zh-CN.json b/packages/web/messages/zh-CN.jsonindex 6ae7e094d..07c7f0efd 100644--- a/packages/web/messages/zh-CN.json+++ b/packages/web/messages/zh-CN.json@@ -280,6 +280,14 @@"evidenceUnavailable": "无法为此变更生成证据清单。","evidenceBuilding": "证据清单仍在生成中,请稍后重新加载页面。","evidenceGenerated": "生成于 {date}",+ "detailOutcomes": "后续结果",+ "outcomesRevertedBy": "被以下提交回滚",+ "outcomesNoLongerInForce": "已不再生效",+ "outcomesCause": "后续修复将其称为原因(原话):",+ "outcomesFileRate": "之后收到修复的文件:{days} 天内 {total} 个中有 {fixed} 个",+ "outcomesWindowOpen": "窗口尚未结束",+ "outcomesNone": "在此历史中,没有后续提交回滚此变更或将其称为原因。",+ "outcomesNote": "链接只来自明确提到此变更的后续提交。文件比率说明修复落在哪里,而不是由什么引起。","statusOk": "正常","statusAttention": "需关注","statusUnknown": "未知",diff --git a/packages/web/src/app/repos/[id]/changes/[changeId]/outcomes-messages.test.ts b/packages/web/src/app/repos/[id]/changes/[changeId]/outcomes-messages.test.tsnew file mode 100644index 000000000..6bc2c4178--- /dev/null+++ b/packages/web/src/app/repos/[id]/changes/[changeId]/outcomes-messages.test.ts@@ -0,0 +1,30 @@+import { describe, expect, it } from "vitest";+import en from "../../../../../../messages/en.json";+import zhCN from "../../../../../../messages/zh-CN.json";++const placeholders = (text: string) => [...text.matchAll(/\{(\w+)\}/g)].map((m) => m[1]).sort();++// The catalogs nest other groups (categories); only the flat outcome strings are read.+const enMessages = en.views.changes as unknown as Record<string, string>;+const zhMessages = zhCN.views.changes as unknown as Record<string, string>;++describe("Outcomes copy", () => {+ const enKeys = Object.keys(enMessages).filter(+ (k) => k.startsWith("outcomes") || k === "detailOutcomes",+ );++ it("has every key in both catalogs with the same placeholders", () => {+ expect(enKeys.length).toBeGreaterThan(0);+ for (const key of enKeys) {+ expect(zhMessages[key], key).toBeTypeOf("string");+ expect(placeholders(zhMessages[key]), key).toEqual(placeholders(enMessages[key]));+ }+ });++ it("never says a change caused anything", () => {+ for (const key of enKeys) {+ const text = enMessages[key];+ expect(text.replace("not what caused them", "")).not.toMatch(/\bcaused\b/i);+ }+ });+});diff --git a/packages/web/src/app/repos/[id]/changes/[changeId]/page.tsx b/packages/web/src/app/repos/[id]/changes/[changeId]/page.tsxindex c4f02c351..c3601bb36 100644--- a/packages/web/src/app/repos/[id]/changes/[changeId]/page.tsx+++ b/packages/web/src/app/repos/[id]/changes/[changeId]/page.tsx@@ -46,8 +46,72 @@ function valueText(item: EvidenceItem): string {return String(value);}-/** The evidence checklist, streamed in: the first read of a change builds it. */-async function EvidenceChecklist({ repoId, changeId }: { repoId: string; changeId: string }) {+type Row = Record<string, unknown>;++/** What later history says about the change, in the later commits' own words. */+async function Outcomes({ item, repoId }: { item: EvidenceItem; repoId: string }) {+ const t = await getTranslations("views.changes");+ if (item.status === "unknown") {+ return <p className="text-xs text-[var(--color-text-tertiary)]">{valueText(item)}</p>;+ }+ const rows = item.details as Row[];+ const links = rows.filter((r) => r.kind === "revert" || r.kind === "fix_reference");+ const rate = rows.find((r) => r.kind === "file_fix_rate");+ const later = (r: Row) => {+ const sha = String(r.sha ?? "").slice(0, 12);+ const id = typeof r.change_id === "string" ? r.change_id : null;+ if (!id) return <span className="font-mono">{sha}</span>;+ return (+ <Link href={`/repos/${repoId}/changes/${encodeURIComponent(id)}`} className="hover:underline">+ {id} <span className="font-mono">{sha}</span>+ </Link>+ );+ };+ return (+ <>+ <ul className="space-y-2 text-xs">+ {links.length === 0 && (+ <li className="text-[var(--color-text-secondary)]">{t("outcomesNone")}</li>+ )}+ {links.map((r) => (+ <li key={`${String(r.kind)}-${String(r.sha)}`} className="space-y-0.5">+ <div className="text-[var(--color-text-primary)]">+ {r.kind === "revert" ? t("outcomesRevertedBy") : t("outcomesCause")} {later(r)}+ {r.kind === "revert" && r.in_force === false && (+ <span className="text-[var(--color-text-tertiary)]">+ {" "}+ ({t("outcomesNoLongerInForce")})+ </span>+ )}+ </div>+ <blockquote className="border-l-2 border-[var(--color-border-default)] pl-2 text-[var(--color-text-secondary)]">+ {String(r.evidence ?? "")}+ </blockquote>+ </li>+ ))}+ {rate && (+ <li className="text-[var(--color-text-primary)]">+ {t("outcomesFileRate", {+ fixed: Number(rate.files_fixed),+ total: Number(rate.files),+ days: Number(rate.days),+ })}+ {rate.window_complete === false && (+ <span className="text-[var(--color-text-tertiary)]">+ {" "}+ ({t("outcomesWindowOpen")})+ </span>+ )}+ </li>+ )}+ </ul>+ <p className="mt-2 text-xs text-[var(--color-text-tertiary)]">{t("outcomesNote")}</p>+ </>+ );+}++/** The evidence checklist and the outcomes, streamed in: the first read of a change builds them. */+async function EvidenceSections({ repoId, changeId }: { repoId: string; changeId: string }) {const t = await getTranslations("views.changes");let evidence;let building = false;@@ -60,30 +124,42 @@ async function EvidenceChecklist({ repoId, changeId }: { repoId: string; changeI}if (!evidence) {return (- <p className="text-xs text-[var(--color-text-tertiary)]">- {t(building ? "evidenceBuilding" : "evidenceUnavailable")}- </p>+ <OverviewSection title={t("detailEvidence")}>+ <p className="text-xs text-[var(--color-text-tertiary)]">+ {t(building ? "evidenceBuilding" : "evidenceUnavailable")}+ </p>+ </OverviewSection>);}+ const outcomes = evidence.items.find((i) => i.kind === "outcomes");return (<>- <ul className="divide-y divide-[var(--color-border-default)] text-xs">- {evidence.items.map((item) => (- <li key={item.kind} className="flex flex-wrap items-baseline gap-x-3 gap-y-1 py-2">- <span className="w-full shrink-0 font-medium text-[var(--color-text-primary)] sm:w-48">- {item.label}- </span>- <Badge variant={STATUS_VARIANT[item.status]}>{t(STATUS_KEY[item.status])}</Badge>- <span className="text-[var(--color-text-tertiary)]">{item.basis}</span>- <span className="min-w-[10rem] flex-1 break-words text-[var(--color-text-secondary)]">- {valueText(item)}- </span>- </li>- ))}- </ul>- <p className="mt-2 text-xs text-[var(--color-text-tertiary)]">- {t("evidenceGenerated", { date: formatDate(evidence.generated_at) })}- </p>+ <OverviewSection title={t("detailEvidence")}>+ <ul className="divide-y divide-[var(--color-border-default)] text-xs">+ {evidence.items+ .filter((item) => item !== outcomes)+ .map((item) => (+ <li key={item.kind} className="flex flex-wrap items-baseline gap-x-3 gap-y-1 py-2">+ <span className="w-full shrink-0 font-medium text-[var(--color-text-primary)] sm:w-48">+ {item.label}+ </span>+ <Badge variant={STATUS_VARIANT[item.status]}>{t(STATUS_KEY[item.status])}</Badge>+ <span className="text-[var(--color-text-tertiary)]">{item.basis}</span>+ <span className="min-w-[10rem] flex-1 break-words text-[var(--color-text-secondary)]">+ {valueText(item)}+ </span>+ </li>+ ))}+ </ul>+ <p className="mt-2 text-xs text-[var(--color-text-tertiary)]">+ {t("evidenceGenerated", { date: formatDate(evidence.generated_at) })}+ </p>+ </OverviewSection>+ {outcomes && (+ <OverviewSection title={t("detailOutcomes")}>+ <Outcomes item={outcomes} repoId={repoId} />+ </OverviewSection>+ )}</>);}@@ -136,15 +212,15 @@ export default async function ChangeDetailPage({ params }: Props) {))}</dl>- <OverviewSection title={t("detailEvidence")}>- <Suspense- fallback={+ <Suspense+ fallback={+ <OverviewSection title={t("detailEvidence")}><p className="text-xs text-[var(--color-text-tertiary)]">{t("evidenceLoading")}</p>- }- >- <EvidenceChecklist repoId={id} changeId={decodeURIComponent(changeId)} />- </Suspense>- </OverviewSection>+ </OverviewSection>+ }+ >+ <EvidenceSections repoId={id} changeId={decodeURIComponent(changeId)} />+ </Suspense><OverviewSection title={`${t("detailFiles")} (${change.files_changed})`}><ul className="space-y-1 font-mono text-xs">diff --git a/tests/unit/cli/test_changes_cmd.py b/tests/unit/cli/test_changes_cmd.pyindex dd47f6a7e..eea377fca 100644--- a/tests/unit/cli/test_changes_cmd.py+++ b/tests/unit/cli/test_changes_cmd.py@@ -110,7 +110,7 @@ def _fake_evidence(monkeypatch):calls: list[str] = []- async def _evidence(session, repo_id, root, row, *, refresh=False):+ async def _evidence(session, repo_id, root, row, *, refresh=False, key=None):calls.append(row.change_id)return ChangeEvidence(change_id=row.change_id,@@ -208,3 +208,53 @@ def test_list_needs_attention_reads_kept_checklists_only(tmp_path):assert flagged["total"] == 1 and flagged["changes"][0]["id"] == "pr-5"features = json.loads(runner.invoke(changes_group, [*args, "--category", "feature"]).output)assert features["total"] == 0+++def test_outcomes_read_in_their_words_and_never_as_a_cause():+ from repowise.cli.commands.changes_cmd import outcome_lines++ item = {+ "kind": "outcomes",+ "status": "attention",+ "details": [+ {"kind": "revert", "sha": "b" * 40, "change_id": "pr-9", "evidence": 'Revert "x"', "in_force": False},+ {"kind": "fix_reference", "sha": "c" * 40, "change_id": None, "evidence": "regression from #5"},+ {"kind": "file_fix_rate", "files": 4, "files_fixed": 1, "days": 30, "window_complete": False},+ ],+ }+ assert outcome_lines(item) == [+ f'reverted by pr-9 ({"b" * 12}) (no longer in force): Revert "x"',+ f'referenced as the cause by a later fix, {"c" * 12} (their words): "regression from #5"',+ "files later received fixes: 1 of 4 within 30 days (window still open)",+ ]+ rate_only = {**item, "details": item["details"][2:]}+ assert outcome_lines(rate_only)[0].startswith("no later commit in this history reverts")+ assert not any("caused" in line for line in outcome_lines(item) + outcome_lines(rate_only))+++def test_csv_cells_that_open_as_formulas_are_quoted():+ import csv+ import io++ from repowise.cli.commands.changes_cmd import _csv_rows++ record = {+ "id": "pr-1",+ "merged_at": None,+ "title": '=HYPERLINK("http://x")',+ "evidence": {+ "items": [+ {+ "kind": "outcomes",+ "label": "@label",+ "status": "ok",+ "basis": "declared",+ "value": -1,+ "source": "+git",+ }+ ]+ },+ }+ (row,) = csv.reader(io.StringIO(_csv_rows(record)))+ assert row[2] == "'=HYPERLINK(\"http://x\")" and row[4] == "'@label"+ assert row[7] == "'-1" and row[8] == "'+git" and row[0] == "pr-1"diff --git a/tests/unit/core/test_change_outcomes.py b/tests/unit/core/test_change_outcomes.pynew file mode 100644index 000000000..b2da7fb5d--- /dev/null+++ b/tests/unit/core/test_change_outcomes.py@@ -0,0 +1,506 @@+"""Outcomes of a merged change: reverts, fixes that name it, its files' later fix rate."""++from __future__ import annotations++import json+import os+import subprocess+from dataclasses import replace+from datetime import UTC, datetime+from pathlib import Path++import pytest++from repowise.core.changes.evidence import ChangeEvidence, EvidenceInputs, build_change_evidence+from repowise.core.changes.outcomes import (+ FIX_REFERENCE,+ REVERT,+ OutcomeLink,+ OutcomeTarget,+ change_outcome_providers,+ file_fix_rate,+ outcome_links,+)++DAY = 86_400+T0 = 1_767_225_600 # 2026-01-01T00:00:00Z+++def _git(root: Path, *args: str, at: int | None = None) -> str:+ env = {+ **os.environ,+ "GIT_AUTHOR_NAME": "Ann",+ "GIT_AUTHOR_EMAIL": "[email protected]",+ "GIT_COMMITTER_NAME": "Ann",+ "GIT_COMMITTER_EMAIL": "[email protected]",+ }+ if at is not None:+ env["GIT_AUTHOR_DATE"] = env["GIT_COMMITTER_DATE"] = f"@{at} +0000"+ return subprocess.run(+ ["git", *args], cwd=root, env=env, check=True, capture_output=True, text=True+ ).stdout.strip()+++def _commit(root: Path, files: dict[str, str], message: str, at: int) -> str:+ for path, text in files.items():+ (root / path).parent.mkdir(parents=True, exist_ok=True)+ (root / path).write_text(text, encoding="utf-8")+ _git(root, "add", ".")+ _git(root, "commit", "-q", "--allow-empty", "-m", message, at=at)+ return _git(root, "rev-parse", "HEAD")+++def root(tmp_path: Path) -> Path:+ root = tmp_path / "repo"+ root.mkdir()+ _git(root, "init", "-q", "-b", "main")+ _git(root, "config", "commit.gpgsign", "false")+ _commit(root, {"src/a.py": "a = 0\n", "src/b.py": "b = 0\n"}, "chore: seed", T0)+ return root+++def _target(root: Path, sha: str, number: str = "1", files=("src/a.py", "src/b.py")) -> OutcomeTarget:+ at = int(_git(root, "log", "-1", "--format=%ct", sha))+ return OutcomeTarget(+ change_id=f"pr-{number}",+ head_sha=sha,+ commit_shas=(sha,),+ identity_kind="pr",+ identity_value=number,+ forge="generic",+ forge_ref=f"#{number}",+ merged_at=datetime.fromtimestamp(at, tz=UTC),+ files=tuple(files),+ )+++def _head(root: Path) -> str:+ return _git(root, "rev-parse", "HEAD")+++def test_a_revert_that_names_the_change_links_to_it(root):+ change = _commit(root, {"src/a.py": "a = 1\n"}, "feat: a (#1)", T0 + DAY)+ revert = _commit(+ root, {"src/a.py": "a = 0\n"}, f'Revert "feat: a (#1)"\n\nThis reverts commit {change}.', T0 + 2 * DAY+ )+ links = outcome_links(root, _head(root), _target(root, change))+ assert [(link.kind, link.sha, link.target_sha, link.rule, link.in_force) for link in links] == [+ (REVERT, revert, change, "body", True)+ ]+ assert links[0].evidence == f"This reverts commit {change}"+ assert links[0].basis == "declared"+++def test_a_partial_revert_is_not_a_revert(root):+ change = _commit(root, {"src/a.py": "a = 1\n"}, "feat: a (#1)", T0 + DAY)+ _commit(+ root,+ {"src/a.py": "a = 0\n"},+ f'Partially revert "feat: a (#1)"\n\nThis reverts commit {change}.',+ T0 + 2 * DAY,+ )+ assert outcome_links(root, _head(root), _target(root, change)) == []+++ ("message", "rule"),+ [+ ("fix: guard empty input (regression from #1)", "regression"),+ ("fix: guard empty input\n\nA regression in {sha} left it unchecked.", "regression"),+ ("fix: guard empty input\n\nThe test failures were caused by\nPR #1 narrowing it.", "caused_by"),+ ("fix(tests): update tests broken by commit {short}", "broken_by"),+ ('fix: guard empty input\n\nFixes: {short} ("feat: a (#1)")', "fixes_trailer"),+ ],+)+def test_each_cause_phrase_links_in_its_own_words(root, message, rule):+ change = _commit(root, {"src/a.py": "a = 1\n"}, "feat: a (#1)", T0 + DAY)+ text = message.format(sha=change, short=change[:12])+ fix = _commit(root, {"src/a.py": "a = 2\n"}, text, T0 + 2 * DAY)+ links = outcome_links(root, _head(root), _target(root, change))+ assert [(link.kind, link.sha, link.target_sha, link.rule) for link in links] == [+ (FIX_REFERENCE, fix, change, rule)+ ]+ # The evidence is the author's line, verbatim.+ assert links[0].evidence in text+++ "message",+ [+ "fix: crash\n\nFixes #1", # mostly an issue number+ "fix: carry it forward\n\nThe option introduced in #1 is kept.", # a feature, not a cause+ "fix: crash\n\nSame class of bug {short} fixed once already.", # a quoted sha+ "test: the regression\n\nSince #1 a plain logger raises.", # across a blank line+ ],+)+def test_forms_measured_below_the_gate_are_not_read(root, message):+ change = _commit(root, {"src/a.py": "a = 1\n"}, "feat: a (#1)", T0 + DAY)+ _commit(root, {"src/a.py": "a = 2\n"}, message.format(short=change[:12]), T0 + 2 * DAY)+ assert outcome_links(root, _head(root), _target(root, change)) == []+++def test_a_reference_from_a_commit_the_change_is_not_an_ancestor_of_is_rejected(root):+ base = _head(root)+ change = _commit(root, {"src/a.py": "a = 1\n"}, "feat: a (#1)", T0 + DAY)+ _git(root, "checkout", "-q", "-b", "side", base)+ _commit(root, {"src/c.py": "c = 1\n"}, "fix: c (regression from #1)", T0 + 2 * DAY)+ _git(root, "checkout", "-q", "main")+ _git(root, "merge", "-q", "--no-ff", "-m", "Merge branch 'side'", "side", at=T0 + 3 * DAY)+ assert outcome_links(root, _head(root), _target(root, change)) == []+++def test_a_sha_names_the_change_only_when_it_is_the_changes_own(root):+ change = _commit(root, {"src/a.py": "a = 1\n"}, "feat: a (#1)", T0 + DAY)+ other = _commit(root, {"src/b.py": "b = 1\n"}, "feat: b (#2)", T0 + 2 * DAY)+ _commit(root, {"src/b.py": "b = 2\n"}, f"fix: b (regression from {other[:10]})", T0 + 3 * DAY)+ assert outcome_links(root, _head(root), _target(root, change)) == []+ assert [link.target_sha for link in outcome_links(root, _head(root), _target(root, other, "2"))] == [+ other+ ]+++def test_file_fix_rate_counts_fixes_within_the_window_with_its_basis(root):+ change = _commit(root, {"src/a.py": "a = 1\n", "src/b.py": "b = 1\n"}, "feat: a and b (#1)", T0 + DAY)+ inside = _commit(root, {"src/a.py": "a = 2\n"}, "fix: a crash", T0 + 5 * DAY)+ _commit(root, {"src/b.py": "b = 2\n"}, "feat: more b", T0 + 6 * DAY) # not a fix+ _commit(root, {"src/b.py": "b = 3\n"}, "fix: b crash", T0 + 40 * DAY) # after the window+ rate = file_fix_rate(root, _head(root), _target(root, change), 30)+ assert rate == {+ "files": 2,+ "files_fixed": 1,+ "days": 30,+ "fix_commits": 1,+ "window_complete": True,+ "fixed": [{"path": "src/a.py", "fixes": [inside]}],+ }+ # Fixes landed, not caused: the rate never names a link.+ assert outcome_links(root, _head(root), _target(root, change)) == []+++def test_file_fix_rate_says_when_the_window_is_still_open(root):+ change = _commit(root, {"src/a.py": "a = 1\n"}, "feat: a (#1)", T0 + DAY)+ _commit(root, {"src/a.py": "a = 2\n"}, "fix: a crash", T0 + 3 * DAY)+ rate = file_fix_rate(root, _head(root), _target(root, change, files=("src/a.py",)), 30)+ assert rate["files_fixed"] == 1 and rate["window_complete"] is False+++def test_a_registered_provider_plugs_in_after_the_local_ones(root):+ change = _commit(root, {"src/a.py": "a = 1\n"}, "feat: a (#1)", T0 + DAY)++ class ForgeLinks:+ def links(self, repo_path, head, target):+ return [OutcomeLink(FIX_REFERENCE, "f" * 40, target.head_sha, "linked follow-up", "forge")]++ assert change_outcome_providers.names[:2] == ["git-revert", "git-reference"]+ change_outcome_providers.register("forge-test", ForgeLinks())+ try:+ links = outcome_links(root, _head(root), _target(root, change))+ finally:+ change_outcome_providers._impls.pop("forge-test")+ assert [(link.sha, link.rule) for link in links] == [("f" * 40, "forge")]+++def _outcomes_block(root: Path, change: str) -> dict:+ target = _target(root, change)+ head = _head(root)+ return {+ "as_of": head,+ "days": 30,+ "links": [link.to_dict() for link in outcome_links(root, head, target)],+ "file_fix_rate": file_fix_rate(root, head, target, 30),+ }+++def test_the_outcomes_item_round_trips_and_leaves_policy_rules_as_they_were(root):+ from repowise.core.policy import evaluate, parse_policy+ from tests.unit.core.test_change_evidence import _bundle, _full_inputs++ change = _commit(root, {"src/a.py": "a = 1\n"}, "feat: a (#1)", T0 + DAY)+ _commit(+ root, {"src/a.py": "a = 0\n"}, f'Revert "feat: a (#1)"\n\nThis reverts commit {change}.', T0 + 2 * DAY+ )+ inputs = replace(_full_inputs(), outcomes=_outcomes_block(root, change))+ record = build_change_evidence(_bundle(["src/a.py"]), inputs, change_id="pr-1", revspec="r").to_dict()+ item = next(i for i in record["items"] if i["kind"] == "outcomes")+ assert item["status"] == "attention" and item["basis"] == "declared"+ assert item["value"]["reverted"] is True and item["value"]["reverts"] == 1+ assert [d["kind"] for d in item["details"]] == ["revert", "file_fix_rate"]+ assert item["details"][-1]["basis"] == "measured"+ data = json.loads(json.dumps(record))+ assert ChangeEvidence.from_dict(data).to_dict() == data+ policy = parse_policy(+ """\+rules:+ - name: decision+ when:+ decision_crossed: true+ action: warn+"""+ )+ assert evaluate(policy, data)[0].outcome == "triggered"+++def test_no_link_and_no_rate_reads_ok_not_unknown():+ from tests.unit.core.test_change_evidence import _bundle++ inputs = EvidenceInputs(outcomes={"as_of": "h", "days": 30, "links": [], "file_fix_rate": None})+ item = build_change_evidence(_bundle(["src/a.py"]), inputs, change_id="c", revspec="r").item(+ "outcomes"+ )+ assert (item.status, item.basis) == ("ok", "declared")+ assert item.value["files"] is None and item.value["as_of"] == "h"+++async def test_kept_outcomes_follow_head(root):+ from types import SimpleNamespace++ from repowise.core.changes.collect import outcomes_stale, with_current_outcomes+ from repowise.core.changes.evidence import EvidenceItem, _outcomes++ change = _commit(root, {"src/a.py": "a = 1\n"}, "feat: a (#1)", T0 + DAY)+ block = _outcomes_block(root, change)++ kept = ChangeEvidence(+ change_id="pr-1",+ revspec=change,+ generated_at="2026-01-02T00:00:00+00:00",+ items=[EvidenceItem("health_delta", "Health delta", "ok", "measured"), _outcomes(EvidenceInputs(outcomes=block))],+ )+ assert not await outcomes_stale(root, kept)+ revert = _commit(+ root, {"src/a.py": "a = 0\n"}, f'Revert "feat: a (#1)"\n\nThis reverts commit {change}.', T0 + 2 * DAY+ )+ assert await outcomes_stale(root, kept)++ class _Session:+ async def execute(self, *_a, **_k):+ return SimpleNamespace(scalar_one_or_none=lambda: None, scalars=lambda: SimpleNamespace(all=list))++ row = SimpleNamespace(+ change_id="pr-1",+ head_sha=change,+ commit_shas_json=json.dumps([change]),+ identity_kind="pr",+ identity_value="1",+ forge="generic",+ forge_ref="#1",+ merged_at=datetime.fromtimestamp(T0 + DAY, tz=UTC),+ files_json=json.dumps([{"path": "src/a.py", "added": 1, "deleted": 1}]),+ )+ current = await with_current_outcomes(_Session(), "r", root, row, kept)+ assert current is not kept and current.item("health_delta") == kept.item("health_delta")+ outcomes = current.item("outcomes")+ assert outcomes.value["as_of"] == revert and outcomes.value["reverted"] is True+ assert await with_current_outcomes(_Session(), "r", root, row, current) is current+++# -- number resolution -------------------------------------------------------+++def test_a_number_two_commits_hold_names_neither(root):+ change = _commit(root, {"src/a.py": "a = 1\n"}, "feat: a (#1)", T0 + DAY)+ _commit(root, {"src/b.py": "b = 1\n"}, "feat: b, cherry-picked (#1)", T0 + 2 * DAY)+ _commit(root, {"src/a.py": "a = 2\n"}, "fix: a (regression from #1)", T0 + 3 * DAY)+ assert outcome_links(root, _head(root), _target(root, change)) == []+++def test_a_number_held_by_another_commit_does_not_name_this_change(root):+ _commit(root, {"src/b.py": "b = 1\n"}, "feat: b (#1)", T0 + DAY)+ mine = _commit(root, {"src/a.py": "a = 1\n"}, "feat: a", T0 + 2 * DAY)+ _commit(root, {"src/a.py": "a = 2\n"}, "fix: a (regression from #1)", T0 + 3 * DAY)+ assert outcome_links(root, _head(root), _target(root, mine)) == []+++def test_reverts_and_relands_do_not_make_a_number_ambiguous(root):+ change = _commit(root, {"src/a.py": "a = 1\n"}, "feat: a (#1)", T0 + DAY)+ _commit(+ root,+ {"src/a.py": "a = 0\n"},+ f'Revert "feat: a (#1)" (#2)\n\nThis reverts commit {change}.',+ T0 + 2 * DAY,+ )+ _commit(root, {"src/a.py": "a = 1\n"}, "Reland feat: a (#1)", T0 + 3 * DAY)+ fix = _commit(root, {"src/a.py": "a = 3\n"}, "fix: a (regression from #1)", T0 + 4 * DAY)+ links = outcome_links(root, _head(root), _target(root, change))+ assert [link.sha for link in links if link.kind == FIX_REFERENCE] == [fix]+ assert [link.kind for link in links].count(REVERT) == 1+++def test_gitlab_reads_bang_numbers_and_not_hashes(root):+ change = _commit(root, {"src/a.py": "a = 1\n"}, "feat: a (!1)", T0 + DAY)+ _commit(root, {"src/a.py": "a = 2\n"}, "fix: a (regression from #1)", T0 + 2 * DAY)+ fix = _commit(root, {"src/a.py": "a = 3\n"}, "fix: a (regression from !1)", T0 + 3 * DAY)+ target = replace(_target(root, change), forge="gitlab", forge_ref="!1")+ assert [link.sha for link in outcome_links(root, _head(root), target)] == [fix]+++def test_a_short_sha_two_commits_share_names_neither():+ from repowise.core.analysis.decisions.reverts import _History+ from repowise.core.changes import outcomes++ own, other, later = "abcdef1" + "0" * 33, "abcdef1" + "f" * 33, "1" * 40+ hist = _History()+ for sha, parents in ((later, own), (other, own), (own, "")):+ hist._add(sha, parents, "x", "")+ refs = outcomes._References(hist, sorted(hist.position))+ refs.by_token["abcdef1"] = [(later, "regression", "regression from abcdef1")]+ key = ("reference", "repo-x", "head-x", "generic")+ outcomes._index[key] = refs+ try:+ change = OutcomeTarget("commit-x", own, (own,), "commit", own, "generic", None, None, ())+ assert outcomes.GitReferenceOutcomes().links(Path("repo-x"), "head-x", change) == []+ refs.by_token["abcdef10"] = [(later, "regression", "regression from abcdef10")]+ found = outcomes.GitReferenceOutcomes().links(Path("repo-x"), "head-x", change)+ assert [link.target_sha for link in found] == [own]+ finally:+ outcomes._index.pop(key, None)+++# -- what cannot be read reads unknown -----------------------------------------+++def test_a_failed_git_read_is_unknown_and_not_kept(root, monkeypatch):+ from repowise.core.analysis.decisions import reverts+ from repowise.core.changes.outcomes import OutcomeUnknownError++ change = _commit(root, {"src/a.py": "a = 1\n"}, "feat: a (#1)", T0 + DAY)+ real = reverts._git_out+ monkeypatch.setattr(reverts, "_git_out", lambda *_a, **_k: None)+ with pytest.raises(OutcomeUnknownError):+ outcome_links(root, _head(root), _target(root, change))+ with pytest.raises(OutcomeUnknownError):+ file_fix_rate(root, _head(root), _target(root, change), 30)+ monkeypatch.setattr(reverts, "_git_out", real)+ assert outcome_links(root, _head(root), _target(root, change)) == []+++def test_nothing_to_count_reads_unknown_with_a_reason(root):+ from repowise.core.changes.outcomes import OutcomeUnknownError++ change = _commit(root, {"src/a.py": "a = 1\n"}, "feat: a (#1)", T0 + DAY)+ with pytest.raises(OutcomeUnknownError, match="no files"):+ file_fix_rate(root, _head(root), _target(root, change, files=()), 30)+ with pytest.raises(OutcomeUnknownError, match="no merge time"):+ file_fix_rate(root, _head(root), replace(_target(root, change), merged_at=None), 30)+++class _Session:+ """Enough of a session for ``get_change`` to find nothing."""++ async def execute(self, *_a, **_k):+ from types import SimpleNamespace++ return SimpleNamespace(+ scalar_one_or_none=lambda: None, scalars=lambda: SimpleNamespace(all=list)+ )+++def _row(sha: str, *, files=("src/a.py",)):+ from types import SimpleNamespace++ return SimpleNamespace(+ change_id="pr-1",+ head_sha=sha,+ commit_shas_json=json.dumps([sha]),+ identity_kind="pr",+ identity_value="1",+ forge="generic",+ forge_ref="#1",+ merged_at=datetime.fromtimestamp(T0 + DAY, tz=UTC),+ files_json=json.dumps([{"path": p, "added": 1, "deleted": 0} for p in files]),+ )+++async def test_unknown_items_are_stamped_so_they_are_not_read_every_time(root, tmp_path):+ from repowise.core.changes.collect import outcomes_item, outcomes_key, outcomes_stale++ change = _commit(root, {"src/a.py": "a = 1\n"}, "feat: a (#1)", T0 + DAY)+ shallow = tmp_path / "shallow"+ _git(tmp_path, "clone", "-q", "--depth", "1", root.as_uri(), str(shallow))+ key = await outcomes_key(shallow)+ item = await outcomes_item(_Session(), "r", shallow, _row(_head(shallow)), key)+ assert (item.status, item.basis) == ("unknown", "unresolved")+ reason = "a shallow clone cuts off the history outcomes are read from"+ assert item.details == [{"reason": reason, "as_of": key[0], "days": 30}]+ kept = ChangeEvidence("pr-1", None, "2026-01-02T00:00:00+00:00", [item])+ assert not await outcomes_stale(shallow, kept)++ key = await outcomes_key(root)+ no_files = await outcomes_item(_Session(), "r", root, _row(change, files=()), key)+ rate = [d for d in no_files.details if d["kind"] == "file_fix_rate"]+ assert rate == [+ {"kind": "file_fix_rate", "basis": "unresolved", "reason": "the change lists no files"}+ ]+ assert no_files.value["files"] is None and no_files.status == "ok"+++def test_fix_days_reads_the_config_within_bounds(tmp_path):+ from repowise.core.changes.outcomes import DEFAULT_FIX_DAYS, fix_days++ cfg = tmp_path / ".repowise" / "config.yaml"+ cfg.parent.mkdir()+ assert fix_days(tmp_path) == DEFAULT_FIX_DAYS == 30+ for raw, want in (("45", 45), ("1", 1), ("365", 365), ("0", 30), ("366", 30), ("soon", 30)):+ cfg.write_text(f"changes:\n outcome_fix_days: {raw}\n", encoding="utf-8")+ assert fix_days(tmp_path) == want, raw+ cfg.write_text("changes: 12\n", encoding="utf-8")+ assert fix_days(tmp_path) == 30+++# -- keeping ---------------------------------------------------------------------+++async def test_a_legacy_checklist_gains_outcomes_and_a_merge_keeps_a_newer_rebuild(+ tmp_path, root+):+ from repowise.core.changes.collect import (+ cached_evidence,+ change_evidence,+ keep_outcomes,+ outcomes_item,+ outcomes_key,+ save_evidence,+ )+ from repowise.core.changes.evidence import EvidenceItem+ from repowise.core.persistence.crud import get_change+ from repowise.core.persistence.database import get_session+ from tests.unit.core.test_change_evidence import _index++ head = _commit(root, {"src/a.py": "a = 1\n"}, "feat: a and web (#7)", T0 + DAY)+ engine, factory, repo_id = await _index(tmp_path, root, head)+ health = EvidenceItem("health_delta", "Health delta", "ok", "measured", {"introduced": 0})+ legacy = ChangeEvidence("pr-7", head, "2026-01-01T00:00:00+00:00", [health])+ try:+ async with get_session(factory) as session:+ await save_evidence(session, repo_id, "pr-7", legacy)+ async with get_session(factory) as session:+ row = await get_change(session, repo_id, "pr-7")+ got = await change_evidence(session, repo_id, root, row)+ assert [i.kind for i in got.items] == ["health_delta", "outcomes"]+ assert got.generated_at == legacy.generated_at+ async with get_session(factory) as session:+ stored = cached_evidence(await get_change(session, repo_id, "pr-7"))+ assert stored.to_dict() == got.to_dict()++ # An outcomes read that finishes after a full rebuild was kept merges+ # into the rebuild, and one read at the same HEAD is not written twice.+ key = await outcomes_key(root)+ async with get_session(factory) as session:+ row = await get_change(session, repo_id, "pr-7")+ item = await outcomes_item(session, repo_id, root, row, key)+ rebuilt = ChangeEvidence("pr-7", head, "2026-02-01T00:00:00+00:00", [health])+ async with get_session(factory) as session:+ await save_evidence(session, repo_id, "pr-7", rebuilt)+ async with get_session(factory) as session:+ merged = await keep_outcomes(session, repo_id, "pr-7", item)+ assert merged.generated_at == rebuilt.generated_at+ assert [i.kind for i in merged.items] == ["health_delta", "outcomes"]+ async with get_session(factory) as session:+ again = await keep_outcomes(session, repo_id, "pr-7", item)+ assert again.to_dict() == merged.to_dict()+ finally:+ await engine.dispose()diff --git a/tests/unit/core/test_report.py b/tests/unit/core/test_report.pyindex 72f74a533..519c5acb7 100644--- a/tests/unit/core/test_report.py+++ b/tests/unit/core/test_report.py@@ -304,6 +304,53 @@ async def test_decisions_per_component_with_stale(ctx, monkeypatch):}+async def test_outcomes_are_left_out_until_a_checklist_kept_them(ctx):+ import repowise.core.report.sections # noqa: F401+ from repowise.core.persistence.crud import upsert_changes++ def change(cid: str, path: str, outcomes: dict | None) -> dict:+ items = [] if outcomes is None else [outcomes]+ return {+ "change_id": cid,+ "identity_kind": "pr",+ "identity_value": cid[3:],+ "shape": "squash",+ "title": f"feat: {cid}",+ "head_sha": cid[3:].rjust(40, "a"),+ "files_json": json.dumps([{"path": path, "added": 1, "deleted": 0}]),+ "evidence_json": json.dumps({"items": items}) if outcomes is not None else None,+ }++ assert await report_sections.get("outcomes").collect(ctx) is None+ revert = {"kind": "revert", "sha": "r" * 40, "evidence": "This reverts commit x", "in_force": True}+ cause = {"kind": "fix_reference", "sha": "f" * 40, "evidence": "regression from #2"}+ item = lambda *links: {"kind": "outcomes", "status": "ok", "details": list(links)} # noqa: E731+ unknown = {"kind": "outcomes", "status": "unknown", "details": [{"reason": "shallow"}]}+ await upsert_changes(+ ctx.session,+ ctx.repository_id,+ [+ change("pr-1", "api/a.py", item(revert)),+ change("pr-2", "web/W.java", item(cause)),+ change("pr-3", "api/b.py", item()),+ change("pr-4", "api/b.py", unknown),+ change("pr-5", "api/a.py", None),+ ],+ )+ await ctx.session.flush()+ items = await _section("outcomes", ctx)+ top = items["outcomes"]+ assert (top["basis"], top["score"]) == ("declared", None)+ assert top["data"]["read"] == 3 and top["data"]["changes"] == 5+ assert sorted(top["data"]["flagged"]) == ["pr-1", "pr-2"]+ assert "reverted: pr-1 feat: pr-1" in top["details"]+ assert any("regression from #2" in d for d in top["details"])+ comps = items["outcomes:components"]+ assert comps["data"]["components"]["api"] == {"read": ["pr-1", "pr-3"], "flagged": ["pr-1"]}+ assert set(items) == {"outcomes", "outcomes:components"}+ assert "caused" not in json.dumps(items)++async def test_provenance_names_agents_without_counting_them(ctx):items = await _section("provenance", ctx)cov = items["provenance:coverage"]diff --git a/tests/unit/server/mcp/test_change_risk.py b/tests/unit/server/mcp/test_change_risk.pyindex 83cf3f97f..6205541a7 100644--- a/tests/unit/server/mcp/test_change_risk.py+++ b/tests/unit/server/mcp/test_change_risk.py@@ -819,7 +819,10 @@ async def test_evidence_for_a_stored_change_is_its_kept_record(tmp_path, monkeypmonkeypatch.setattr(module, "_get_repo", _repo)# No filters of the caller's own: the same record `changes show` serves.same = await module.get_change_risk("HEAD", include=["evidence"])- assert same["evidence"] == kept+ # Kept as it was, but for the outcomes item, which follows HEAD.+ items = same["evidence"].pop("items")+ assert same["evidence"] == {k: v for k, v in kept.items() if k != "items"}+ assert [i["kind"] for i in items] == ["outcomes"]async def _broken(_session):raise OperationalError("SELECT 1", {}, Exception("database is locked"))diff --git a/tests/unit/server/test_changes_routes.py b/tests/unit/server/test_changes_routes.pyindex 4106ae2f8..cafc50b5e 100644--- a/tests/unit/server/test_changes_routes.py+++ b/tests/unit/server/test_changes_routes.py@@ -134,7 +134,12 @@ def _fake_build(monkeypatch, seen: list[str], gate=None):],)+ async def _current(_root, _evidence):+ return False+monkeypatch.setattr(route, "build_stored_evidence", _build)+ # These tests are about the checklist build; outcomes stay as built.+ monkeypatch.setattr(route, "outcomes_stale", _current)return route@@ -299,3 +304,79 @@ def test_evidence_summary_never_reads_missing_or_unknown_status_as_clean() -> No}empty = evidence_summary(SimpleNamespace(evidence_json=_checklist("pr-1")))assert empty is not None and (empty["ok"], empty["attention"], empty["unknown"]) == (0, 0, 0)+++def _fake_outcomes(monkeypatch, route, refreshed: list[str], gate=None) -> None:+ from repowise.core.changes.evidence import EvidenceItem++ async def _stale(_root, evidence, key=None):+ return evidence.item("outcomes") is None++ async def _key(_root):+ return ("h", 30)++ async def _item(session, repo_id, root, row, key):+ refreshed.append(row.change_id)+ if gate is not None:+ await gate.wait()+ value = {"as_of": key[0], "days": key[1]}+ return EvidenceItem("outcomes", "Outcomes since merge", "ok", "declared", value)++ monkeypatch.setattr(route, "outcomes_stale", _stale)+ monkeypatch.setattr(route, "outcomes_key", _key)+ monkeypatch.setattr(route, "outcomes_item", _item)+++async def test_kept_evidence_has_only_its_outcomes_read_again_when_head_moved(+ client: AsyncClient, app, monkeypatch+) -> None:+ seen: list[str] = []+ refreshed: list[str] = []+ route = _fake_build(monkeypatch, seen)+ _fake_outcomes(monkeypatch, route, refreshed)+ repo = await create_test_repo(client)+ await _seed(app, repo["id"])+ base = f"/api/repos/{repo['id']}/changes/pr-1"++ await client.get(base, params={"evidence": "true"})+ record = (await client.get(base, params={"evidence": "true"})).json()+ kinds = [i["kind"] for i in record["evidence"]["items"]]+ assert kinds == ["health_delta", "outcomes"] and seen == ["pr-1"] and refreshed == ["pr-1"]+ # Merged into what was stored: the next read rebuilds nothing.+ again = (await client.get(base, params={"evidence": "true"})).json()+ assert again["evidence"] == record["evidence"]+ assert seen == ["pr-1"] and refreshed == ["pr-1"]+++async def test_a_refresh_is_not_swallowed_by_an_outcomes_read_in_flight(+ client: AsyncClient, app, monkeypatch+) -> None:+ import asyncio++ seen: list[str] = []+ refreshed: list[str] = []+ gate = asyncio.Event()+ route = _fake_build(monkeypatch, seen)+ _fake_outcomes(monkeypatch, route, refreshed, gate)+ monkeypatch.setattr(route, "EVIDENCE_WAIT_SECONDS", 0.05)+ repo = await create_test_repo(client)+ await _seed(app, repo["id"])+ base = f"/api/repos/{repo['id']}/changes/pr-1"++ gate.set()+ await client.get(base, params={"evidence": "true"}) # full build, kept without outcomes+ gate.clear()+ waiting = (await client.get(base, params={"evidence": "true"})).json()+ assert waiting["evidence_building"] is True and refreshed == ["pr-1"]+ # The outcomes read is still running; a refresh runs its own full build.+ await client.get(base, params={"evidence": "true", "refresh": "true"})+ assert seen == ["pr-1", "pr-1"]+ gate.set()+ for _ in range(100):+ if not route._BUILDS:+ break+ await asyncio.sleep(0.01)+ done = (await client.get(base, params={"evidence": "true"})).json()+ assert [i["kind"] for i in done["evidence"]["items"]] == ["health_delta", "outcomes"]