Skip to content

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

feat(report): change evidence pack for a period (#3815)

Raghav Chamadiya3c53e8144372
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.md
index 8fa05f0f1..d16ac3770 100644
--- a/docs/reference/CLI_REFERENCE.md
+++ b/docs/reference/CLI_REFERENCE.md
@@ -1665,7 +1665,7 @@ The web UI lists the same events on the repository's Events page, newest first.
One document a team hands to someone else, for a repo or every repo of a workspace: component posture, hotspots, bus factor per component, dead code by tier, measured and inferred test reach, contracts, governing decisions, provenance coverage with the agents and models named, and what moved since a snapshot a quarter older. Every item keeps the OpenSSF Scorecard check keys (`name`, `score` 0 to 10 or -1 inconclusive, `reason`, `details`, `documentation`) plus `method` and `basis`. A descriptive item (a count or a list) has `score: null`, and missing or held-back evidence is always -1, never a low score. The report is evidence about code and components, not a score of people: owners are counted, never ranked or named. JSON is canonical (`schema_version: 1`); the HTML is one file with inline CSS, no scripts and a policy that blocks every fetch, so it opens offline and prints as is.
```bash
-repowise report assessment [PATH] [--sections a,b] [--format json|markdown|html] [--out FILE] [--workspace | --no-workspace] [--repo ALIAS]
+repowise report assessment [PATH] [--sections a,b] [--format json|markdown|html|csv] [--out FILE] [--workspace | --no-workspace] [--repo ALIAS]
```
| Section | Measures | Basis |
@@ -1684,6 +1684,8 @@ repowise report assessment [PATH] [--sections a,b] [--format json|markdown|html]
`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.
+`repowise report changes [PATH] [--since DATE] [--until DATE] [--format json|markdown|html|csv] [--out FILE] [--refresh] [--no-build]` is the change-management evidence an audit asks for (SOC 2 CC8.1, ISO 27001 A.8.32, PCI DSS 6.5): for every change merged in the period, its components and owning teams, its review record (git holds none, so it reads "not recorded in git" unless `Approved-by` trailers or a `change-metadata` source supply one), measured and inferred reaching tests, the verdict of the condition rules in `.repowise/policies.yaml` ("no policy configured" without one; gate rules are not re-run), its provenance, and whether a later commit reverted it or named it as the cause of a fix. A period summary counts those answers and a method appendix states what git alone cannot attest; unknown is counted apart, never as a failure, and people are counted, never named. It shares one evidence pass with `changes export`, which builds and stores any missing checklist in the index, a few at a time, after printing to stderr how many it will build and roughly how long; `--no-build` reports kept checklists only and counts the rest as unknown.
+
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.py
index 0c8706121..ef9083ac2 100644
--- a/packages/cli/src/repowise/cli/commands/changes_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/changes_cmd.py
@@ -81,8 +81,24 @@ async def _show(root: Path, ref: str, *, evidence: bool, refresh: bool) -> dict
return record
-#: Changes read from the index per page during an export.
-_EXPORT_PAGE = 50
+def build_progress(position: int, total: int, change_id: str) -> None:
+ """One stderr line per checklist built, so a long period shows it is moving."""
+ click.echo(f"evidence {position}/{total}: {change_id}", err=True)
+
+
+def build_plan(to_build: int, total: int) -> None:
+ """Say up front how many checklists a period builds, and roughly how long."""
+ from repowise.core.changes.period import SECONDS_PER_BUILD
+
+ if not to_build:
+ return
+ minutes = to_build * SECONDS_PER_BUILD / 60
+ about = f"about {minutes:.0f} min" if minutes >= 1 else "under a minute"
+ click.echo(
+ f"building {to_build} of {total} evidence checklist(s), {about}; each is kept, "
+ "so a later run reads it back",
+ err=True,
+ )
async def _export(
@@ -94,40 +110,24 @@ 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, outcomes_key
+ from repowise.core.changes.period import PeriodRequest, period_evidence
from repowise.core.changes.record import change_record
- from repowise.core.persistence.crud import ChangeFilter, list_changes
async with repo_index_session(root) as opened:
if opened is None:
return None
session, repo_id = opened
on = attribution_enabled(root)
- # One HEAD and window for the whole export, read once.
- key = await outcomes_key(root)
done = 0
- while True:
- rows, total = await list_changes(
- session,
- repo_id,
- ChangeFilter(since=since, until=until),
- limit=_EXPORT_PAGE,
- offset=done,
- )
- for row in rows:
- done += 1
- if refresh or not row.evidence_json:
- click.echo(f"evidence {done}/{total}: {row.change_id}", err=True)
- record = change_record(row, attribution=on)
- record["evidence"] = (
- await change_evidence(session, repo_id, root, row, refresh=refresh, key=key)
- ).to_dict()
- # Kept as it goes, so an interrupted export resumes where it stopped.
- await session.commit()
- emit(record)
- session.expunge_all()
- if len(rows) < _EXPORT_PAGE:
- return done
+ request = PeriodRequest(
+ since=since, until=until, refresh=refresh, progress=build_progress, plan=build_plan
+ )
+ async for row, evidence in period_evidence(session, repo_id, root, request):
+ record = change_record(row, attribution=on)
+ record["evidence"] = evidence.to_dict()
+ emit(record)
+ done += 1
+ return done
_STATUS_STYLE = {"ok": "green", "attention": "yellow", "unknown": "dim"}
@@ -195,28 +195,19 @@ _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
import io
import json
+ from repowise.core.report.render import spreadsheet_cell
+
buf = io.StringIO()
writer = csv.writer(buf, lineterminator="\n")
for item in record["evidence"]["items"]:
writer.writerow(
- _cell(cell)
+ spreadsheet_cell(cell)
for cell in [
record["id"],
record["merged_at"] or "",
@@ -376,10 +367,10 @@ def changes_export(
) -> None:
"""Export the changes merged in a window, each with its evidence checklist.
- A change without a kept checklist has one built and kept first, which
- costs a few seconds per change (about 7 to 9s measured on a mid-size
- repository); kept checklists are read back at no cost. Records stream as
- they are ready, and progress goes to stderr.
+ A change without a kept checklist has one built and kept first, a few at
+ a time over one shared fix-history walk (about 3s per change measured on
+ a mid-size repository, from 6s one by one); kept checklists are read back
+ at no cost. Records stream a page at a time, and progress goes to stderr.
"""
import json
from datetime import UTC
diff --git a/packages/cli/src/repowise/cli/commands/report_assessment_cmd.py b/packages/cli/src/repowise/cli/commands/report_assessment_cmd.py
index d9d29116b..20a68420c 100644
--- a/packages/cli/src/repowise/cli/commands/report_assessment_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/report_assessment_cmd.py
@@ -30,7 +30,10 @@ def _targets(target: Any) -> list[tuple[str | None, Path]]:
return [(r.alias, (target.ws_root / r.path).resolve()) for r in target.ws_config.repos]
-async def _build(repos: list[tuple[str | None, Path]], sections: list, scope: dict) -> dict:
+async def _build(
+ repos: list[tuple[str | None, Path]], sections: list, scope: dict, **options: Any
+) -> dict:
+ """The document over *repos*; *options* go to each :class:`ReportContext`."""
from repowise.core.persistence.models import Repository
from repowise.core.report.build import assemble, collect_repo
from repowise.core.report.model import ReportContext
@@ -49,7 +52,12 @@ async def _build(repos: list[tuple[str | None, Path]], sections: list, scope: di
session, repo_id = opened
repo = await session.get(Repository, repo_id)
ctx = ReportContext(
- session, repo_id, root, alias=alias, head_commit=repo.head_commit if repo else None
+ session,
+ repo_id,
+ root,
+ alias=alias,
+ head_commit=repo.head_commit if repo else None,
+ **options,
)
parts.append(await collect_repo(ctx, sections))
return assemble(scope, parts)
@@ -81,6 +89,18 @@ def _scope(target: Any) -> tuple[list[tuple[str | None, Path]], dict]:
return repos, {"kind": "repo", "name": repos[0][1].name}
+def _renderer(fmt: str) -> Any:
+ """The renderer *fmt* names on the ``report-renderer`` seam; a usage error otherwise."""
+ from repowise.core.report.render import report_renderers
+
+ if fmt not in report_renderers.names:
+ raise click.BadParameter(
+ f"unknown format {fmt!r}; available: {', '.join(report_renderers.names)}",
+ param_hint="--format",
+ )
+ return report_renderers.get(fmt)
+
+
def _emit(text: str, fmt: str, out_path: str | None, document: dict) -> None:
"""Write or print the rendered report, then warn about any failed section."""
if out_path:
@@ -110,7 +130,7 @@ def _emit(text: str, fmt: str, out_path: str | None, document: dict) -> None:
"fmt",
default="markdown",
show_default=True,
- help="Renderer: json, markdown or html (or one a plugin registers).",
+ help="Renderer: json, markdown, html or csv (or one a plugin registers).",
)
@click.option("--out", "out_path", type=click.Path(dir_okay=False), help="Write to this file.")
@click.option("--workspace", "workspace_flag", is_flag=True, help="Cover every workspace repo.")
@@ -127,16 +147,10 @@ def assessment_command(
) -> None:
"""Assessment pack: components, hotspots, bus factor, dead code, test reach,
contracts, decisions, provenance and the quarter's moves, each with its basis."""
- from repowise.core.report.render import report_renderers
-
if not out_path:
silence_logs_for_machine_output_until_close() # stdout carries only the report
sections = _pick_sections(wanted)
- if fmt not in report_renderers.names:
- raise click.BadParameter(
- f"unknown format {fmt!r}; available: {', '.join(report_renderers.names)}",
- param_hint="--format",
- )
+ render = _renderer(fmt)
target = resolve_command_target(
path=path,
workspace_flag=workspace_flag,
@@ -146,4 +160,4 @@ def assessment_command(
target.notice(err_console, command="report assessment")
repos, scope = _scope(target)
document = run_async(_build(repos, sections, scope))
- _emit(report_renderers.get(fmt)(document), fmt, out_path, document)
+ _emit(render(document), fmt, out_path, document)
diff --git a/packages/cli/src/repowise/cli/commands/report_changes_cmd.py b/packages/cli/src/repowise/cli/commands/report_changes_cmd.py
new file mode 100644
index 000000000..86b670626
--- /dev/null
+++ b/packages/cli/src/repowise/cli/commands/report_changes_cmd.py
@@ -0,0 +1,114 @@
+"""``repowise report changes`` - change evidence for a period.
+
+Every change merged between ``--since`` and ``--until`` with whether it carries
+a review record, which tests reach it, the local change policy's verdict, the
+teams accountable for what it touched, its provenance and its outcomes, plus a
+period summary and a method appendix. Built the way ``report assessment``
+builds its document and rendered by the same renderers (JSON, Markdown, HTML,
+CSV). A change without a kept checklist has one built and stored first, as
+``repowise changes export`` does, unless ``--no-build``; the count to build,
+an estimate and progress go to stderr.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from datetime import UTC, datetime
+from typing import Any
+
+import click
+
+from repowise.cli.helpers import (
+ err_console,
+ resolve_command_target,
+ run_async,
+ silence_logs_for_machine_output_until_close,
+)
+
+
+@dataclass(frozen=True)
+class ChangesReportOptions:
+ """The command line of ``repowise report changes``, as click parses it."""
+
+ path: str | None = None
+ since: datetime | None = None
+ until: datetime | None = None
+ fmt: str = "markdown"
+ out_path: str | None = None
+ refresh: bool = False
+ no_build: bool = False
+ workspace_flag: bool = False
+ no_workspace: bool = False
+ repo_alias: str | None = None
+
+ def period(self) -> tuple[datetime | None, datetime | None]:
+ """``(since, until)`` in UTC; raises when the period is empty."""
+ since, until = (d.replace(tzinfo=UTC) if d else None for d in (self.since, self.until))
+ if since and until and since >= until:
+ raise click.BadParameter("--since must be before --until", param_hint="--since")
+ return since, until
+
+
[email protected]("path", required=False, type=click.Path(exists=True, file_okay=False))
+ "--since", type=click.DateTime(), default=None, help="Merged on or after this date (UTC)."
+)
[email protected]("--until", type=click.DateTime(), default=None, help="Merged before this date (UTC).")
+ "--format",
+ "fmt",
+ default="markdown",
+ show_default=True,
+ help="Renderer: json, markdown, html or csv (or one a plugin registers).",
+)
[email protected]("--out", "out_path", type=click.Path(dir_okay=False), help="Write to this file.")
[email protected]("--refresh", is_flag=True, help="Rebuild every evidence checklist in the period.")
+ "--no-build",
+ is_flag=True,
+ help="Build nothing: report kept checklists only and count the rest as unknown.",
+)
[email protected]("--workspace", "workspace_flag", is_flag=True, help="Cover every workspace repo.")
[email protected]("--no-workspace", is_flag=True, help="Force single-repo mode.")
[email protected]("--repo", "repo_alias", default=None, help="Workspace repo alias to cover.")
+def changes_command(**params: Any) -> None:
+ """Change evidence for a period: review record, reaching tests, policy result,
+ owning teams, provenance and outcomes of every change merged in it.
+
+ A change with no kept evidence checklist has one built and stored in the
+ index first (a few seconds each), unless --no-build is given.
+ """
+ from repowise.cli.commands.changes_cmd import build_plan, build_progress
+ from repowise.cli.commands.report_assessment_cmd import _build, _emit, _renderer, _scope
+ from repowise.core.changes.period import PeriodRequest
+ from repowise.core.report.build import available_sections
+
+ opts = ChangesReportOptions(**params)
+ # Building a checklist parses code, which logs; stdout carries only the report.
+ silence_logs_for_machine_output_until_close()
+ render = _renderer(opts.fmt)
+ since, until = opts.period()
+ target = resolve_command_target(
+ path=opts.path,
+ workspace_flag=opts.workspace_flag,
+ no_workspace_flag=opts.no_workspace,
+ repo_alias=opts.repo_alias,
+ )
+ target.notice(err_console, command="report changes")
+ repos, scope = _scope(target)
+ scope["period"] = {
+ "since": since.isoformat() if since else None,
+ "until": until.isoformat() if until else None,
+ }
+ request = PeriodRequest(
+ since=since,
+ until=until,
+ refresh=opts.refresh,
+ build=not opts.no_build,
+ plan=build_plan,
+ progress=build_progress,
+ )
+ document = run_async(_build(repos, available_sections("changes"), scope, period=request))
+ document["kind"] = "changes"
+ _emit(render(document), opts.fmt, opts.out_path, document)
diff --git a/packages/cli/src/repowise/cli/commands/report_cmd.py b/packages/cli/src/repowise/cli/commands/report_cmd.py
index bb28e6adc..3924d717f 100644
--- a/packages/cli/src/repowise/cli/commands/report_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/report_cmd.py
@@ -14,12 +14,13 @@ from repowise.core.registry import LazyCommand
_SUBCOMMANDS: tuple[str, ...] = (
"repowise.cli.commands.report_assessment_cmd:assessment_command",
"repowise.cli.commands.report_inventory_cmd:inventory_command",
+ "repowise.cli.commands.report_changes_cmd:changes_command",
)
@click.group("report")
def report_group() -> None:
- """Evidence reports built from the index: assessment, inventory."""
+ """Evidence reports built from the index: assessment, inventory, changes."""
for _target in _SUBCOMMANDS:
diff --git a/packages/cli/src/repowise/cli/commands/report_inventory_cmd.py b/packages/cli/src/repowise/cli/commands/report_inventory_cmd.py
index 90043858a..8195b071a 100644
--- a/packages/cli/src/repowise/cli/commands/report_inventory_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/report_inventory_cmd.py
@@ -23,7 +23,7 @@ from repowise.cli.helpers import (
"fmt",
default="markdown",
show_default=True,
- help="Renderer: json, markdown or html (or one a plugin registers).",
+ help="Renderer: json, markdown, html or csv (or one a plugin registers).",
)
@click.option("--out", "out_path", type=click.Path(dir_okay=False), help="Write to this file.")
@click.option("--workspace", "workspace_flag", is_flag=True, help="Cover every workspace repo.")
@@ -42,17 +42,13 @@ def inventory_command(
_build,
_emit,
_pick_sections,
+ _renderer,
_scope,
)
- from repowise.core.report.render import report_renderers
if not out_path:
silence_logs_for_machine_output_until_close() # stdout carries only the report
- if fmt not in report_renderers.names:
- raise click.BadParameter(
- f"unknown format {fmt!r}; available: {', '.join(report_renderers.names)}",
- param_hint="--format",
- )
+ render = _renderer(fmt)
sections = _pick_sections("inventory")
target = resolve_command_target(
path=path,
@@ -64,4 +60,4 @@ def inventory_command(
repos, scope = _scope(target)
document = run_async(_build(repos, sections, scope))
document["kind"] = "inventory"
- _emit(report_renderers.get(fmt)(document), fmt, out_path, document)
+ _emit(render(document), fmt, out_path, document)
diff --git a/packages/core/src/repowise/core/analysis/change_risk/fix_history.py b/packages/core/src/repowise/core/analysis/change_risk/fix_history.py
index 3a6b16c91..4a5ead622 100644
--- a/packages/core/src/repowise/core/analysis/change_risk/fix_history.py
+++ b/packages/core/src/repowise/core/analysis/change_risk/fix_history.py
@@ -165,15 +165,146 @@ def fix_pressure(
history = _walk(repo_path, sha, depth)
as_of = float(_git(["show", "-s", "--format=%ct", sha], repo_path, check=False).strip() or 0.0)
+ pressure = _decayed(history, as_of)
+ _remember(key, pressure)
+ return pressure
+
+
+def _decayed(history: dict[str, list[float]], as_of: float) -> dict[str, float]:
half_life = FIX_HALF_LIFE_DAYS * 86400.0
- pressure = {
+ return {
path: sum(0.5 ** (max(as_of - t, 0.0) / half_life) for t in stamps)
for path, stamps in history.items()
}
+
+
+def _remember(key: tuple, pressure: dict[str, float]) -> None:
if len(_PRESSURE_CACHE) >= _PRESSURE_CACHE_MAX:
_PRESSURE_CACHE.clear()
_PRESSURE_CACHE[key] = pressure
- return pressure
+
+
+class FixHistory:
+ """Every commit reachable from one ref, read by a single ``git log``.
+
+ Scoring many changes walks one deep history per change, each from its own
+ parent; :func:`prime_fix_pressure` answers all of them from this one walk,
+ over the same commits :func:`_walk` lists for each. The walk reads at most
+ twice *depth* commits, merges included; a history reaching past them is
+ left to :func:`_walk`. Raises ``subprocess.TimeoutExpired`` when git
+ outruns its timeout.
+ """
+
+ def __init__(self, repo_path: str, ref: str = "HEAD", *, depth: int = DEEP_WALK_LIMIT) -> None:
+ self.depth = depth
+ self.shallow = (
+ _git(["rev-parse", "--is-shallow-repository"], repo_path, check=False).strip()
+ == "true"
+ )
+ out = _git(
+ [
+ "log",
+ f"-n{2 * depth}",
+ "--format=%x1e%H%x1f%P%x1f%ct%x1f%s",
+ "--name-only",
+ "--end-of-options",
+ ref,
+ ],
+ repo_path,
+ check=False,
+ )
+ #: Shas in ``git log`` order.
+ self.order: list[str] = []
+ self.parents: dict[str, tuple[str, ...]] = {}
+ self.times: dict[str, float] = {}
+ #: Paths of each non-merge fix commit.
+ self.fixes: dict[str, list[str]] = {}
+ blocks = out.split("\x1e")
+ del out # the raw log is the largest thing held; keep only the parse
+ for block in blocks:
+ lines = block.strip("\n").split("\n")
+ head = lines[0].split("\x1f", 3)
+ if len(head) != 4:
+ continue
+ sha, parents, timestamp_raw, subject = head
+ try:
+ self.times[sha] = float(timestamp_raw)
+ except ValueError:
+ continue
+ self.order.append(sha)
+ self.parents[sha] = tuple(parents.split())
+ if len(self.parents[sha]) <= 1 and is_fix_commit(subject):
+ self.fixes[sha] = [p.strip() for p in lines[1:] if p.strip()]
+
+ def answers(self, sha: str) -> bool:
+ """Whether *sha* is in this walk at all (its history may still run past it)."""
+ return sha in self.parents
+
+ def _ancestors(self, sha: str, depth: int) -> set[str] | None:
+ """*sha* and every commit it reaches, or ``None`` once the walk cannot
+ hold them or more than *depth* of them are non-merge commits."""
+ seen = {sha}
+ todo = [sha]
+ listed = self._listed(sha)
+ while todo:
+ fresh = self._new_parents(todo.pop(), seen)
+ if fresh is None:
+ return None # past this walk: the history is not all here
+ seen.update(fresh)
+ todo.extend(fresh)
+ listed += sum(map(self._listed, fresh))
+ if listed > depth:
+ return None # past depth: where _walk cuts is left to _walk
+ return seen
+
+ def _listed(self, sha: str) -> bool:
+ """Whether ``git log --no-merges`` lists *sha* (it counts toward depth)."""
+ return len(self.parents[sha]) <= 1
+
+ def _new_parents(self, sha: str, seen: set[str]) -> list[str] | None:
+ """*sha*'s parents not yet *seen*, or ``None`` when one is past this walk."""
+ parents = self.parents[sha]
+ if any(p not in self.parents for p in parents):
+ return None
+ return [p for p in parents if p not in seen]
+
+ def _counted(self, sha: str) -> bool:
+ """Whether :func:`_walk` counts *sha* as a fix (a shallow boundary it skips)."""
+ return sha in self.fixes and not (self.shallow and not self.parents[sha])
+
+ def pressure(self, sha: str, depth: int | None = None) -> dict[str, float] | None:
+ """:func:`fix_pressure` at *sha*, or ``None`` when this walk cannot say
+ (*sha* is not in it, or its history runs past *depth* commits)."""
+ depth = self.depth if depth is None else depth
+ reach = self._ancestors(sha, depth) if sha in self.parents else None
+ if reach is None:
+ return None
+ history: dict[str, list[float]] = {}
+ for c in (c for c in self.order if c in reach and self._counted(c)):
+ for path in self.fixes[c]:
+ history.setdefault(path, []).append(self.times[c])
+ return _decayed(history, self.times[sha])
+
+
+def prime_fix_pressure(
+ repo_path: str, history: FixHistory, shas: Iterable[str], *, depth: int = DEEP_WALK_LIMIT
+) -> int:
+ """Memoize :func:`fix_pressure` at each of *shas* from *history*; how many were.
+
+ A sha the walk cannot answer is left out, and scoring it walks git as
+ before. Ceiling: the memo holds :data:`_PRESSURE_CACHE_MAX` entries, so a
+ caller primes at most that many before scoring them.
+ """
+ primed = 0
+ for sha in shas:
+ key = (repo_path, sha, depth)
+ pressure = _PRESSURE_CACHE.get(key)
+ if pressure is None:
+ pressure = history.pressure(sha, depth)
+ if pressure is not None:
+ _remember(key, pressure)
+ primed += 1
+ return primed
def fixes_reachable_from(repo_path: str, upto_ref: str, shas: Iterable[str]) -> set[str]:
diff --git a/packages/core/src/repowise/core/changes/period.py b/packages/core/src/repowise/core/changes/period.py
new file mode 100644
index 000000000..ef7a6da29
--- /dev/null
+++ b/packages/core/src/repowise/core/changes/period.py
@@ -0,0 +1,247 @@
+"""Every change merged in a period with its checklist, in one pass.
+
+:func:`period_evidence` is the one reader ``repowise changes export`` and
+``repowise report changes`` share. The period's changes are fixed up front
+(ids only), so changes indexed while it runs neither shift nor repeat a page.
+A kept checklist is read back as
+:func:`~repowise.core.changes.collect.change_evidence` reads it (its outcomes
+follow HEAD); a missing one is built and kept. What every build would repeat
+is done once for the period: the HEAD and window outcomes are read at, and the
+deep fix-history walk the risk item stands on (one ``git log`` primes every
+change's walk, see
+:func:`~repowise.core.analysis.change_risk.fix_history.prime_fix_pressure`).
+Builds in a page run side by side, each on its own read session, and each is
+kept the moment it finishes, so an interrupt or a failed build loses only the
+builds still running. A checklist another writer kept meanwhile (the server,
+an outcomes merge) is never overwritten: it is read back instead.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import subprocess
+from collections.abc import AsyncIterator, Callable, Sequence
+from dataclasses import dataclass
+from datetime import datetime
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+import structlog
+
+from repowise.core.changes import collect
+from repowise.core.changes.evidence import ChangeEvidence
+
+logger = structlog.get_logger(__name__)
+
+#: Changes read per page; at most the fix-pressure memo's size.
+PAGE = 16
+#: Checklists built at once. Most of a build is git and parsing in worker
+#: threads, so more than a few contend for the interpreter rather than help.
+DEFAULT_CONCURRENCY = 4
+#: Wall seconds per checklist built at :data:`DEFAULT_CONCURRENCY`, measured on
+#: a mid-size repository (rw-demo, 32 changes); used only for an estimate.
+SECONDS_PER_BUILD = 3.0
+#: Pages in a row the fix-history walk may answer nothing before it is dropped.
+_PRIME_MISSES = 3
+
+#: ``(position in the period, changes in the period, change id)`` per build.
+Progress = Callable[[int, int, str], None]
+#: ``(checklists to build, changes in the period)``, told once before any build.
+Plan = Callable[[int, int], None]
+
+
+@dataclass(frozen=True)
+class PeriodRequest:
+ """Which changes a period pass reads, and how it builds missing checklists.
+
+ *since* is inclusive and *until* exclusive, on ``merged_at``; ``None``
+ leaves that side open. *refresh* rebuilds every checklist; without *build*
+ nothing is built, and a change with no kept checklist comes with ``None``.
+ *plan* is told how many checklists will be built before the first starts;
+ *progress* is told about each build.
+ """
+
+ since: datetime | None = None
+ until: datetime | None = None
+ refresh: bool = False
+ build: bool = True
+ concurrency: int = DEFAULT_CONCURRENCY
+ progress: Progress | None = None
+ plan: Plan | None = None
+
+
+@dataclass(frozen=True)
+class _Pass:
+ """One period pass over one repository's open index."""
+
+ session: Any
+ repo_id: str
+ root: Path
+ request: PeriodRequest
+ total: int
+
+
+class _Prime:
+ """One fix-history walk for the period, primed page by page."""
+
+ def __init__(self, root: str) -> None:
+ self.root = root
+ self.history: Any = None
+ self.useful = True
+ self.misses = 0
+
+ def _walk(self) -> Any:
+ """The period's walk, read on first use; ``None`` (given up) once git fails."""
+ from repowise.core.analysis.change_risk.fix_history import FixHistory
+
+ if self.history is None and self.useful:
+ try:
+ self.history = FixHistory(self.root)
+ except (OSError, subprocess.SubprocessError) as exc:
+ logger.debug("period_fix_history_failed", error=str(exc))
+ self.useful = False
+ return self.history if self.useful else None
+
+ def __call__(self, rows: Sequence[Any]) -> None:
+ from repowise.core.analysis.change_risk.fix_history import prime_fix_pressure
+
+ history = self._walk()
+ if history is None:
+ return
+ parents = [p[0] for r in rows if (p := history.parents.get(r.head_sha))]
+ if not parents or prime_fix_pressure(self.root, history, parents):
+ self.misses = 0
+ return
+ self.misses += 1
+ # Older changes reach fewer commits, so a miss can be followed by hits;
+ # but once a page's oldest change lies outside the walk, so do all older.
+ self.useful = self.misses < _PRIME_MISSES and history.answers(rows[-1].head_sha)
+
+
+async def _keep(run: _Pass, row: Any, evidence: ChangeEvidence) -> ChangeEvidence:
+ """Keep *evidence* unless another writer kept a checklist since *row* was
+ read; then that one is what the change has, and is returned."""
+ from sqlalchemy import select
+ from sqlalchemy.orm.attributes import set_committed_value
+
+ from repowise.core.persistence.crud import keep_evidence_if_unchanged
+ from repowise.core.persistence.crud.changes import dump_evidence
+ from repowise.core.persistence.models import Change
+
+ raw = dump_evidence(evidence.to_dict())
+ if not await keep_evidence_if_unchanged(
+ run.session, run.repo_id, row.change_id, raw, expected=row.evidence_json
+ ):
+ raw = (
+ await run.session.execute(
+ select(Change.evidence_json).where(
+ Change.repository_id == run.repo_id, Change.change_id == row.change_id
+ )
+ )
+ ).scalar_one_or_none()
+ evidence = collect.cached_evidence(SimpleNamespace(evidence_json=raw)) or evidence
+ await run.session.commit()
+ set_committed_value(row, "evidence_json", raw)
+ return evidence
+
+
+async def _build_page(
+ run: _Pass, rows: Sequence[Any], position: Callable[[Any], int]
+) -> dict[str, ChangeEvidence]:
+ """Build *rows* side by side, keeping each as it finishes. A failed build
+ is raised once the others in flight have finished and been kept."""
+ from sqlalchemy.ext.asyncio import AsyncSession
+
+ gate = asyncio.Semaphore(max(1, run.request.concurrency))
+ write = asyncio.Lock() # the caller's session takes one writer at a time
+ progress = run.request.progress
+
+ async def one(row: Any) -> tuple[str, ChangeEvidence]:
+ async with gate, AsyncSession(run.session.bind, expire_on_commit=False) as reader:
+ evidence = await collect.build_stored_evidence(reader, run.repo_id, run.root, row)
+ async with write:
+ evidence = await _keep(run, row, evidence)
+ if progress is not None:
+ progress(position(row), run.total, row.change_id)
+ return row.change_id, evidence
+
+ done = await asyncio.gather(*(one(r) for r in rows), return_exceptions=True)
+ failed = [d for d in done if isinstance(d, BaseException)]
+ if failed:
+ raise failed[0]
+ return dict(done) # type: ignore[arg-type]
+
+
+async def _page_rows(run: _Pass, ids: list[str]) -> list[Any]:
+ """The rows of *ids*, in that order, read in one query; one deleted meanwhile drops out."""
+ from repowise.core.persistence.crud import ChangeFilter, list_changes
+
+ found, _ = await list_changes(
+ run.session, run.repo_id, ChangeFilter(change_ids=ids), limit=None
+ )
+ by_id = {r.change_id: r for r in found}
+ return [by_id[cid] for cid in ids if cid in by_id]
+
+
+async def _read_kept(
+ run: _Pass, rows: Sequence[Any], key: Any
+) -> dict[str, ChangeEvidence | None]:
+ """Each row's kept checklist (``None`` when none is kept), from the page
+ already read. Only a checklist whose outcomes were read at another HEAD
+ is read again, since that needs git for the change."""
+ kept = {r.change_id: collect.cached_evidence(r) for r in rows}
+ stale = [
+ r
+ for r in rows
+ if kept[r.change_id] is not None
+ and await collect.outcomes_stale(run.root, kept[r.change_id], key)
+ ]
+ for row in stale:
+ kept[row.change_id] = await collect.change_evidence(
+ run.session, run.repo_id, run.root, row, key=key
+ )
+ return kept
+
+
+async def period_evidence(
+ session: Any, repo_id: str, repo_root: Path | str, request: PeriodRequest
+) -> AsyncIterator[tuple[Any, ChangeEvidence | None]]:
+ """``(row, checklist)`` for each change *request* names, newest first."""
+ from repowise.core.persistence.crud import ChangeFilter, list_change_keys
+
+ keys = await list_change_keys(
+ session, repo_id, ChangeFilter(since=request.since, until=request.until)
+ )
+ run = _Pass(session, repo_id, Path(repo_root), request, len(keys))
+ if request.plan is not None:
+ to_build = sum(request.refresh or not kept for _cid, kept in keys)
+ request.plan(to_build if request.build else 0, run.total)
+ key = await collect.outcomes_key(run.root)
+ prime = _Prime(str(run.root))
+ for start in range(0, run.total, PAGE):
+ ids = [cid for cid, _kept in keys[start : start + PAGE]]
+ rows = await _page_rows(run, ids)
+ missing = [r for r in rows if request.refresh or collect.cached_evidence(r) is None]
+ built: dict[str, ChangeEvidence] = {}
+ if missing and request.build:
+ await asyncio.to_thread(prime, missing)
+ built = await _build_page(
+ run, missing, lambda r, s=start, ids=ids: s + ids.index(r.change_id) + 1
+ )
+ kept = await _read_kept(run, [r for r in rows if r.change_id not in built], key)
+ await session.commit()
+ for row in rows:
+ yield row, built.get(row.change_id) or kept.get(row.change_id)
+ session.expunge_all()
+
+
+__all__ = [
+ "DEFAULT_CONCURRENCY",
+ "PAGE",
+ "SECONDS_PER_BUILD",
+ "PeriodRequest",
+ "Plan",
+ "Progress",
+ "period_evidence",
+]
diff --git a/packages/core/src/repowise/core/persistence/crud/changes.py b/packages/core/src/repowise/core/persistence/crud/changes.py
index 4e7bc6d86..68e3419ba 100644
--- a/packages/core/src/repowise/core/persistence/crud/changes.py
+++ b/packages/core/src/repowise/core/persistence/crud/changes.py
@@ -168,6 +168,41 @@ async def count_checklists_built(
return int(built), int(changes)
+async def list_change_keys(
+ session: AsyncSession, repository_id: str, where: ChangeFilter | None = None
+) -> list[tuple[str, bool]]:
+ """``(change_id, checklist kept)`` of every change matching *where*, newest
+ merged first. Ids only, so a long period is fixed up front for little."""
+ rows = await session.execute(
+ select(Change.change_id, Change.evidence_json.is_not(None))
+ .where(*_filters(repository_id, where or ChangeFilter()))
+ .order_by(Change.merged_at.desc().nulls_last(), Change.change_id)
+ )
+ return [(cid, bool(kept)) for cid, kept in rows.tuples()]
+
+
+async def keep_evidence_if_unchanged(
+ session: AsyncSession,
+ repository_id: str,
+ change_id: str,
+ evidence_json: str,
+ *,
+ expected: str | None,
+) -> bool:
+ """Store *evidence_json* only while the kept checklist is still *expected*
+ (``None``: none kept); whether it was written. Another writer's checklist,
+ kept meanwhile, is never overwritten."""
+ from sqlalchemy import update
+
+ still = Change.evidence_json.is_(None) if expected is None else Change.evidence_json == expected
+ result = await session.execute(
+ update(Change)
+ .where(Change.repository_id == repository_id, Change.change_id == change_id, still)
+ .values(evidence_json=evidence_json)
+ )
+ return result.rowcount == 1
+
+
async def get_change(session: AsyncSession, repository_id: str, ref: str) -> Change | None:
"""A change by its id, or the newest change that landed a commit (a sha of 7+ hex)."""
found = await find_changes(session, repository_id, ref, limit=1)
diff --git a/packages/core/src/repowise/core/report/build.py b/packages/core/src/repowise/core/report/build.py
index 715eb21f3..b1ba05306 100644
--- a/packages/core/src/repowise/core/report/build.py
+++ b/packages/core/src/repowise/core/report/build.py
@@ -31,14 +31,16 @@ NOTICE = (
)
-def available_sections() -> list[tuple[str, Section]]:
- """Every registered section, local ones and plugins', in report order."""
+def available_sections(report: str = "assessment") -> list[tuple[str, Section]]:
+ """Every registered section of the *report* kind, local ones and plugins', in report order."""
import repowise.core.report.sections # noqa: F401 (registers the local sections)
from repowise.core.registry.plugins import load_plugins
load_plugins()
pairs = [(name, report_sections.get(name)) for name in report_sections.names]
- return sorted(pairs, key=lambda p: (p[1].order, p[0]))
+ return sorted(
+ ((n, s) for n, s in pairs if s.report == report), key=lambda p: (p[1].order, p[0])
+ )
async def _index_entry(ctx: ReportContext) -> dict[str, Any]:
diff --git a/packages/core/src/repowise/core/report/change_answers.py b/packages/core/src/repowise/core/report/change_answers.py
new file mode 100644
index 000000000..b0b8dcfef
--- /dev/null
+++ b/packages/core/src/repowise/core/report/change_answers.py
@@ -0,0 +1,362 @@
+"""One change's answers for the ``changes`` report, read from its record and checklist.
+
+Whether the change carries a review record, which tests reach it, the local
+change policy's verdict, which teams are accountable for what it touched,
+which agent or model produced it, and whether a later commit reverted it or
+named it as the cause of a fix. The checklist is read as data: an unknown item
+stays unknown, never a negative. People are never named: owners are teams,
+reviewers are counted.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Any
+
+#: The questions completeness is judged on; review is reported on its own,
+#: since git alone never records it.
+ANSWERS = ("accountable", "tests", "policy", "outcome")
+
+#: Why every answer reads unknown for a change whose checklist was not built.
+NOT_KEPT = "no checklist kept; run without --no-build to build it"
+
+
+@dataclass(frozen=True)
+class EntryContext:
+ """What every change in a period is read against."""
+
+ #: The parsed ``.repowise/policies.yaml``, or ``None``.
+ policy: Any = None
+ #: Why the policy file could not be read, when it could not.
+ policy_error: str | None = None
+ #: The declared ownership (:class:`~repowise.core.ownership.directory.DeclaredOwnership`).
+ declared: Any = None
+ #: ``{sha: (agent, model)}`` for the agent-marked commits of the period.
+ agents: dict[str, tuple[str, str | None]] = field(default_factory=dict)
+ attribution: bool = True
+
+
+def _known(item: dict[str, Any] | None) -> bool:
+ return item is not None and item.get("status") != "unknown"
+
+
+def _reason(item: dict[str, Any] | None, fallback: str = "not known") -> str:
+ if item is None:
+ return "not in the checklist"
+ said = [d["reason"] for d in item.get("details") or () if isinstance(d, dict) and d.get("reason")]
+ return said[0] if said else fallback
+
+
+def unknown(reason: str) -> dict[str, Any]:
+ return {"status": "unknown", "basis": "unresolved", "text": f"unknown ({reason})"}
+
+
+# -- accountability -----------------------------------------------------------
+
+
+def _component_teams(comps: dict[str, Any] | None) -> set[str]:
+ if not _known(comps):
+ return set()
+ return {r["owner"] for r in comps.get("details") or () if r.get("owner")}
+
+
+def _owner_refs(owners: dict[str, Any], declared: Any) -> tuple[set[str], set[str], int]:
+ """``(teams, individuals, unowned paths)`` from the owners item's rows."""
+ from repowise.core.ownership.directory import OwnerRef
+
+ teams: set[str] = set()
+ individuals: set[str] = set()
+ unowned = 0
+ for row in owners.get("details") or ():
+ name = row.get("owner")
+ if name is None:
+ unowned = len(row.get("paths") or ())
+ continue
+ # A component owner is a team name; a CODEOWNERS entry may be a person.
+ ref = declared.from_codeowners(name) if "@" in name else OwnerRef("team", name)
+ (teams if ref.kind == "team" else individuals).add(ref.name)
+ return teams, individuals, unowned
+
+
+def _accountable_text(teams: set[str], individuals: set[str], unowned: int) -> str:
+ parts = [f"team(s) {', '.join(sorted(teams))}" if teams else "no declared team"]
+ if individuals:
+ parts.append(f"{len(individuals)} individual or unresolved owner(s), not named")
+ if unowned:
+ parts.append(f"{unowned} path(s) with no declared owner")
+ return "; ".join(parts)
+
+
+def accountable(items: dict[str, Any], declared: Any) -> dict[str, Any]:
+ """Owning teams of what the change touched; individual owners are counted, never named."""
+ owners = items.get("owners")
+ teams = _component_teams(items.get("components_touched"))
+ individuals: set[str] = set()
+ unowned = 0
+ if _known(owners):
+ more, individuals, unowned = _owner_refs(owners, declared)
+ teams |= more
+ if not teams and not individuals and not _known(owners):
+ return unknown(_reason(owners))
+ return {
+ "status": "known",
+ "basis": "declared",
+ "teams": sorted(teams),
+ "individual_owners": len(individuals),
+ "unowned_paths": unowned,
+ "text": _accountable_text(teams, individuals, unowned),
+ }
+
+
+# -- review and tests -----------------------------------------------------------
+
+
+def review(meta: dict[str, Any]) -> dict[str, Any]:
+ source = meta.get("source") or "git"
+ approvals, reviewers = meta.get("approvals"), meta.get("reviewers")
+ if approvals is None and reviewers is None:
+ # Git records no approvals: unknown, never a missing review.
+ return {"status": "unknown", "basis": "unresolved", "source": source,
+ "text": f"not recorded in {source}"}
+ said = []
+ if approvals is not None:
+ said.append(f"{approvals} approval(s)")
+ if reviewers is not None:
+ said.append(f"{len(reviewers)} reviewer(s)")
+ where = "Approved-by trailers in git" if source == "git" else source
+ return {
+ "status": "known",
+ "basis": "declared",
+ "source": source,
+ "approvals": approvals,
+ "reviewers": None if reviewers is None else len(reviewers),
+ "text": f"{', '.join(said)} ({where})",
+ }
+
+
+def _tests_text(value: dict[str, Any]) -> str:
+ said = [
+ f"{value.get('measured', 0)} measured and {value.get('inferred', 0)} inferred "
+ "test(s) reach the change"
+ ]
+ if value.get("files_without_tests"):
+ said.append(f"{value['files_without_tests']} changed file(s) with no reaching test")
+ if value.get("files_unknown"):
+ said.append(f"{value['files_unknown']} changed file(s) not known")
+ return "; ".join(said)
+
+
+def tests(item: dict[str, Any] | None) -> dict[str, Any]:
+ if not _known(item):
+ return unknown(_reason(item, "no coverage map or graph answer for the changed files"))
+ value = item.get("value") if isinstance(item.get("value"), dict) else {}
+ if not item.get("details"):
+ return {"status": "known", "basis": item["basis"], "text": "no changed source file"}
+ return {
+ "status": "known",
+ "basis": item["basis"],
+ "measured": value.get("measured"),
+ "inferred": value.get("inferred"),
+ "files_without_tests": value.get("files_without_tests"),
+ "files_unknown": value.get("files_unknown"),
+ "text": _tests_text(value),
+ }
+
+
+# -- policy -------------------------------------------------------------------
+
+
+def _verdict(results: list[Any]) -> str:
+ from repowise.core.policy.rules import TRIGGERED, UNKNOWN
+
+ outcomes = [r.outcome for r in results]
+ if any(r.fails for r in results):
+ return "fail"
+ if TRIGGERED in outcomes:
+ return "warn"
+ return "unknown" if UNKNOWN in outcomes else "pass"
+
+
+def _verdict_text(verdict: str, results: list[Any], gate_note: str) -> str:
+ from repowise.core.policy.rules import NOT_APPLICABLE, PASSED, TRIGGERED, UNKNOWN
+
+ outcomes = [r.outcome for r in results]
+ counts = [
+ (outcomes.count(TRIGGERED), "fired"),
+ (outcomes.count(PASSED), "passed"),
+ (outcomes.count(NOT_APPLICABLE), "not applicable"),
+ (outcomes.count(UNKNOWN), "not evaluated"),
+ ]
+ fired = [r.rule.name for r in results if r.outcome == TRIGGERED]
+ said = ", ".join(f"{n} {label}" for n, label in counts if n)
+ return f"{verdict} ({said}{'; fired: ' + ', '.join(fired) if fired else ''}){gate_note}"
+
+
+def policy_verdict(policy: Any, policy_error: str | None, evidence: dict[str, Any]) -> dict[str, Any]:
+ """The change against the condition rules of *policy*: ``pass``, ``warn``,
+ ``fail``, ``unknown`` (a rule could not be evaluated) or ``none`` (no policy).
+
+ Gate rules run a CI command over the live tree, so they are not re-run for
+ a past change and are listed as such.
+ """
+ from repowise.core.policy import Policy, evaluate
+
+ if policy_error:
+ return {"verdict": "unknown", "status": "unknown", "text": f"unknown ({policy_error})",
+ "rules": []}
+ if policy is None:
+ return {"verdict": "none", "status": "known", "text": "no policy configured", "rules": []}
+ gates = [r.name for r in policy.rules if r.gate]
+ rules = tuple(r for r in policy.rules if not r.gate)
+ gate_note = f"; gate rule(s) {', '.join(gates)} not re-run for a past change" if gates else ""
+ if not rules:
+ return {"verdict": "unknown", "status": "unknown", "rules": [], "gates_not_rerun": gates,
+ "text": f"unknown (the policy has only gate rules){gate_note}"}
+ results = evaluate(Policy(rules, policy.source), evidence)
+ verdict = _verdict(results)
+ return {
+ "verdict": verdict,
+ "status": "unknown" if verdict == "unknown" else "known",
+ "rules": [r.to_dict() for r in results],
+ "gates_not_rerun": gates,
+ "text": _verdict_text(verdict, results, gate_note),
+ }
+
+
+# -- provenance and outcomes ------------------------------------------------------
+
+
+def _named(commits: list[str], agents: dict[str, tuple[str, str | None]]) -> tuple[list[str], list[str]]:
+ """``(agents, models)`` the change's agent-marked commits name."""
+ marked = [agents[s] for s in commits if s in agents]
+ return sorted({a for a, _m in marked}), sorted({m for _a, m in marked if m})
+
+
+def _provenance_said(label: str, names: list[str], models: list[str]) -> str:
+ if label != "agent":
+ return "human-attested" if label == "human_attested" else "unknown"
+ said = f"agent: {', '.join(names) or 'unnamed agent'}"
+ return said + (f", model(s) {', '.join(models)}" if models else "")
+
+
+def provenance(
+ item: dict[str, Any] | None, commits: list[str], context: EntryContext
+) -> dict[str, Any]:
+ if not context.attribution:
+ return unknown("attribution is switched off for this repository")
+ value = (item or {}).get("value")
+ if not isinstance(value, dict) or "label" not in value:
+ # Its commits still count against coverage: unknown, never left out.
+ return {**unknown(_reason(item)), "commits": len(commits), "commits_known": 0}
+ label = value["label"]
+ known = int(value.get("agent_commits") or 0) + int(value.get("human_attested_commits") or 0)
+ total = known + int(value.get("unknown_commits") or 0)
+ names, models = _named(commits, context.agents)
+ return {
+ "status": "unknown" if label == "unknown" else "known",
+ "basis": "unresolved" if label == "unknown" else "measured",
+ "label": label,
+ "agents": names,
+ "models": models,
+ "commits": total,
+ "commits_known": known,
+ "coverage": value.get("coverage"),
+ "text": f"{_provenance_said(label, names, models)}; {known} of {total} commit(s) carry a provenance marker",
+ }
+
+
+def _link_text(link: dict[str, Any]) -> str:
+ later = link.get("change_id") or (link.get("sha") or "")[:12]
+ if link["kind"] != "revert":
+ return f"named as the cause by a later fix, {later}"
+ return f"reverted by {later}" + ("" if link.get("in_force") else " (revert undone since)")
+
+
+def outcome(item: dict[str, Any] | None) -> dict[str, Any]:
+ if not _known(item):
+ return unknown(_reason(item))
+ links = [d for d in item.get("details") or () if d.get("kind") in ("revert", "fix_reference")]
+ return {
+ "status": "known",
+ "basis": item.get("basis"),
+ "reverted": any(d["kind"] == "revert" and d.get("in_force") for d in links),
+ "fix_references": sum(d["kind"] == "fix_reference" for d in links),
+ "links": [
+ {"kind": d["kind"], "sha": d.get("sha"), "change_id": d.get("change_id")} for d in links
+ ],
+ "text": "; ".join(map(_link_text, links)) or "no later commit reverts it or names it as a cause",
+ }
+
+
+# -- the entry ------------------------------------------------------------------
+
+
+def _components(items: dict[str, Any]) -> list[dict[str, Any]]:
+ comps = items.get("components_touched")
+ if not _known(comps):
+ return []
+ return [{"name": r["name"], "team": r.get("owner")} for r in comps.get("details") or ()]
+
+
+def _checklist(evidence: dict[str, Any], kept: bool) -> dict[str, Any]:
+ counts = {"ok": 0, "attention": 0, "unknown": 0}
+ for item in evidence.get("items") or ():
+ counts[item["status"] if item["status"] in ("ok", "attention") else "unknown"] += 1
+ return {
+ "kept": kept,
+ **counts,
+ "generated_at": evidence.get("generated_at"),
+ "index_commit": evidence.get("index_commit"),
+ "items": [
+ {"kind": i["kind"], "status": i["status"], "basis": i["basis"]}
+ for i in evidence.get("items") or ()
+ ],
+ }
+
+
+def _answers(
+ record: dict[str, Any], evidence: dict[str, Any], kept: bool, context: EntryContext
+) -> dict[str, dict[str, Any]]:
+ items = {i["kind"]: i for i in evidence.get("items") or ()}
+ answers = {
+ "accountable": accountable(items, context.declared),
+ "review": review(record["metadata"]),
+ "tests": tests(items.get("reaching_tests")),
+ "policy": policy_verdict(context.policy, context.policy_error, evidence),
+ "provenance": provenance(items.get("provenance"), record["commits"], context),
+ "outcome": outcome(items.get("outcomes")),
+ }
+ if not kept:
+ for k in ("accountable", "tests", "outcome"):
+ answers[k] = unknown(NOT_KEPT)
+ answers["provenance"] = {**answers["provenance"], **unknown(NOT_KEPT)}
+ return answers
+
+
+def entry(
+ record: dict[str, Any], evidence: dict[str, Any] | None, context: EntryContext
+) -> dict[str, Any]:
+ """One change's answers, read from its record and checklist. No person is
+ named. With no checklist kept (*evidence* ``None``) every answer it would
+ give is unknown."""
+ kept = evidence is not None
+ evidence = evidence or {"items": []}
+ answers = _answers(record, evidence, kept, context)
+ return {
+ "id": record["id"],
+ "ref": record["forge_ref"] or record["id"],
+ "title": record["title"],
+ "merged_at": record["merged_at"],
+ "category": record["category"],
+ "head_sha": record["head_sha"],
+ "files_changed": record["files_changed"],
+ "lines_added": record["lines_added"],
+ "lines_deleted": record["lines_deleted"],
+ "components": _components({i["kind"]: i for i in evidence.get("items") or ()}),
+ **answers,
+ "complete": all(answers[k]["status"] == "known" for k in ANSWERS),
+ "checklist": _checklist(evidence, kept),
+ }
+
+
+__all__ = ["ANSWERS", "NOT_KEPT", "EntryContext", "entry", "policy_verdict", "review"]
diff --git a/packages/core/src/repowise/core/report/model.py b/packages/core/src/repowise/core/report/model.py
index ac5c05aa6..dbfeb4597 100644
--- a/packages/core/src/repowise/core/report/model.py
+++ b/packages/core/src/repowise/core/report/model.py
@@ -16,10 +16,13 @@ from __future__ import annotations
from collections.abc import Awaitable, Callable, Iterable
from dataclasses import dataclass, field
from pathlib import Path
-from typing import Any
+from typing import TYPE_CHECKING, Any
from repowise.core.registry.plugins import SeamRegistry
+if TYPE_CHECKING:
+ from repowise.core.changes.period import PeriodRequest
+
SCHEMA_VERSION = 1
INCONCLUSIVE = -1
#: ``measured`` (counted from the index), ``inferred`` (derived by a static
@@ -126,6 +129,10 @@ class ReportContext:
repo_root: Path
alias: str | None = None
head_commit: str | None = None
+ #: The period a ``changes`` report covers and how it builds missing
+ #: checklists (a :class:`~repowise.core.changes.period.PeriodRequest`);
+ #: ``None`` is every indexed change, building what is missing.
+ period: PeriodRequest | None = None
_cache: dict[str, Any] = field(default_factory=dict)
async def components(self) -> Any:
@@ -174,6 +181,8 @@ class Section:
collect: Callable[[ReportContext], Awaitable[list[dict[str, Any]] | None]]
#: Sections are listed by this, then by name.
order: int = 100
+ #: The report kind the section belongs to (``assessment``, ``changes``).
+ report: str = "assessment"
report_sections: SeamRegistry[Section] = SeamRegistry("report-section")
diff --git a/packages/core/src/repowise/core/report/render.py b/packages/core/src/repowise/core/report/render.py
index f879d4d9c..0d1567ec7 100644
--- a/packages/core/src/repowise/core/report/render.py
+++ b/packages/core/src/repowise/core/report/render.py
@@ -179,10 +179,63 @@ def render_html(document: dict[str, Any]) -> str:
return "\n".join(out) + "\n"
+_FORMULA_LEAD = ("=", "+", "-", "@", "\t", "\r")
+
+
+def spreadsheet_cell(value: Any) -> str:
+ """*value* as text safe to open in a spreadsheet: a leading formula sign is quoted.
+
+ Titles and evidence quote commit messages, which anyone can write.
+ """
+ text = "" if value is None else str(value)
+ return f"'{text}" if text.startswith(_FORMULA_LEAD) else text
+
+
+_CSV_COLUMNS = ("section", "repo", "check", "score", "basis", "reason", "details")
+
+
+def render_csv(document: dict[str, Any]) -> str:
+ """One row per check. A check whose ``data`` holds a ``row`` mapping (one
+ change, say) adds its keys as further columns, in first-seen order."""
+ import csv
+ import io
+
+ checks = [(s, c) for s in document["sections"] for c in s["checks"]]
+ extra: dict[str, None] = {}
+ for _section, c in checks:
+ extra.update(dict.fromkeys((c.get("data") or {}).get("row") or {}))
+ buf = io.StringIO()
+ writer = csv.writer(buf, lineterminator="\n")
+ writer.writerow([*_CSV_COLUMNS, *extra])
+ for section, c in checks:
+ row = (c.get("data") or {}).get("row") or {}
+ cells = [
+ section["id"],
+ section.get("repo"),
+ c["name"],
+ _score(c["score"]),
+ c["basis"],
+ c["reason"],
+ " | ".join(map(str, c["details"])),
+ *(row.get(k) for k in extra),
+ ]
+ writer.writerow(spreadsheet_cell(v) for v in cells)
+ return buf.getvalue()
+
+
report_renderers: SeamRegistry[Renderer] = SeamRegistry("report-renderer")
report_renderers.register("json", render_json, default=True)
report_renderers.register("markdown", render_markdown)
report_renderers.register("html", render_html)
-
-
-__all__ = ["Renderer", "render_html", "render_json", "render_markdown", "report_renderers"]
+report_renderers.register("csv", render_csv)
+
+
+__all__ = [
+ "Renderer",
+ "render_csv",
+ "render_html",
+ "render_json",
+ "render_markdown",
+ "report_renderers",
+ "spreadsheet_cell",
+]
diff --git a/packages/core/src/repowise/core/report/sections/changes.py b/packages/core/src/repowise/core/report/sections/changes.py
new file mode 100644
index 000000000..10f2fd030
--- /dev/null
+++ b/packages/core/src/repowise/core/report/sections/changes.py
@@ -0,0 +1,585 @@
+"""Change evidence for a period: the ``changes`` report.
+
+For every change merged between two dates: whether it carries a review
+record, which tests reach it, what the local change policy says, which teams
+are accountable for what it touched, which agent or model produced it, and
+whether a later commit reverted it or named it as the cause of a fix
+(:mod:`repowise.core.report.change_answers`). Then a period summary and a
+method appendix saying what git alone can and cannot attest.
+
+One evidence pass feeds all three sections:
+:func:`~repowise.core.changes.period.period_evidence`, the reader ``repowise
+changes export`` uses too, which builds and keeps any missing checklist.
+"""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime
+from typing import Any
+
+from repowise.core.report.change_answers import ANSWERS, EntryContext, entry
+from repowise.core.report.model import ReportContext, Section, capped, check, report_sections
+
+_CACHE_KEY = "change-period"
+
+_METHOD = (
+ "Change Records reconstructed from the main line's merge commits and squash refs, "
+ "each with its kept evidence checklist"
+)
+
+
+# -- the pass -----------------------------------------------------------------
+
+
+def _request(ctx: ReportContext) -> Any:
+ from repowise.core.changes.period import PeriodRequest
+
+ return ctx.period or PeriodRequest()
+
+
+async def _period(ctx: ReportContext) -> dict[str, Any]:
+ """The period's entries, read once for every section of the report."""
+ if _CACHE_KEY not in ctx._cache:
+ try:
+ ctx._cache[_CACHE_KEY] = await _read_period(ctx)
+ except Exception as exc: # each section reports it; none re-runs the pass
+ ctx._cache[_CACHE_KEY] = exc
+ got = ctx._cache[_CACHE_KEY]
+ if isinstance(got, Exception):
+ raise got
+ return got
+
+
+async def _read_period(ctx: ReportContext) -> dict[str, Any]:
+ from repowise.core.attribution import attribution_enabled
+ from repowise.core.changes.period import period_evidence
+ from repowise.core.changes.record import change_record
+ from repowise.core.changes.source import resolve_source
+ from repowise.core.ownership.directory import team_directories
+
+ policy, policy_error = _load_policy(ctx)
+ on = attribution_enabled(ctx.repo_root)
+ pairs = []
+ async for row, evidence in period_evidence(
+ ctx.session, ctx.repository_id, ctx.repo_root, _request(ctx)
+ ):
+ pairs.append((change_record(row, attribution=on), evidence and evidence.to_dict()))
+ wanted = {s for rec, _ in pairs for s in rec["commits"]}
+ context = EntryContext(
+ policy=policy,
+ policy_error=policy_error,
+ declared=team_directories.get().load(ctx.repo_root),
+ agents=await _agents(ctx, wanted) if on else {},
+ attribution=on,
+ )
+ return {
+ "entries": [entry(rec, ev, context) for rec, ev in pairs],
+ "policy": policy,
+ "policy_error": policy_error,
+ "attribution": on,
+ "metadata_source": resolve_source()[0],
+ "window": await _window(ctx),
+ }
+
+
+def _load_policy(ctx: ReportContext) -> tuple[Any, str | None]:
+ from repowise.core.policy import PolicyError, load_policy
+
+ try:
+ return load_policy(ctx.repo_root), None
+ except PolicyError as exc:
+ return None, f"{exc.source} is invalid: {'; '.join(exc.problems)}"
+
+
+async def _agents(ctx: ReportContext, wanted: set[str]) -> dict[str, tuple[str, str | None]]:
+ """``{sha: (agent, model)}`` for the agent-marked commits among *wanted*.
+
+ One query over the repository's commits that carry any agent mark (a small
+ set), kept to *wanted* here rather than in an ``IN`` list per batch.
+ """
+ from sqlalchemy import or_, select
+
+ from repowise.core.attribution import AGENT, commit_label
+ from repowise.core.persistence.models import GitCommit
+
+ rows = await ctx.session.execute(
+ select(
+ GitCommit.sha, GitCommit.attribution, GitCommit.agent_name, GitCommit.agent_model_id
+ ).where(
+ GitCommit.repository_id == ctx.repository_id,
+ or_(GitCommit.attribution == AGENT, GitCommit.agent_name.is_not(None)),
+ )
+ )
+ return {
+ sha: (agent or "unnamed agent", model)
+ for sha, attribution, agent, model in rows.tuples()
+ if sha in wanted and commit_label(attribution, agent) == AGENT
+ }
+
+
+def _utc(value: datetime) -> datetime:
+ return value if value.tzinfo else value.replace(tzinfo=UTC)
+
+
+async def _oldest_gap(ctx: ReportContext, oldest: Any) -> str | None:
+ """Why the period starts before the oldest change the index holds, if it does."""
+ import asyncio
+
+ from repowise.core.git_refs import resolve
+
+ since = _request(ctx).since
+ oldest_at = _utc(oldest[0])
+ if since is not None and since >= oldest_at:
+ return None
+ if not await asyncio.to_thread(resolve, str(ctx.repo_root), f"{oldest[1]}^"):
+ return None # the oldest change is the first commit: nothing is cut
+ return (
+ f"the index holds changes merged from {oldest_at.date()} on; earlier changes "
+ "in the period are not covered (raise commit_limit and re-index)"
+ )
+
+
+async def _head_gap(ctx: ReportContext, newest: datetime | None) -> str | None:
+ """Why changes after the indexed commit are missing, if the period reaches them."""
+ import asyncio
+
+ from repowise.core.git_refs import resolve
+
+ until = _request(ctx).until
+ if until is not None and newest is not None and until <= _utc(newest):
+ return None
+ head = await asyncio.to_thread(resolve, str(ctx.repo_root), "HEAD")
+ if not head or not ctx.head_commit or head == ctx.head_commit:
+ return None
+ return (
+ f"the index was built at {ctx.head_commit[:12]} and HEAD is {head[:12]}; changes "
+ "merged since are not covered until `repowise update` runs"
+ )
+
+
+async def _window(ctx: ReportContext) -> dict[str, Any]:
+ """Whether the index holds every change the period asks for.
+
+ The index keeps the newest ``commit_limit`` main-line commits, and only up
+ to the commit it was last built at.
+ """
+ from sqlalchemy import func, select
+
+ from repowise.core.persistence.models import Change
+
+ repo = Change.repository_id == ctx.repository_id
+ oldest = (
+ await ctx.session.execute(
+ select(Change.merged_at, Change.head_sha)
+ .where(repo, Change.merged_at.is_not(None))
+ .order_by(Change.merged_at.asc())
+ .limit(1)
+ )
+ ).first()
+ newest = await ctx.session.scalar(select(func.max(Change.merged_at)).where(repo))
+ gaps = [
+ gap
+ for gap in (
+ await _oldest_gap(ctx, oldest) if oldest is not None else None,
+ await _head_gap(ctx, newest),
+ )
+ if gap
+ ]
+ return {
+ "oldest": _utc(oldest[0]).isoformat() if oldest is not None else None,
+ "newest": _utc(newest).isoformat() if newest else None,
+ "gaps": gaps,
+ }
+
+
+# -- one change -----------------------------------------------------------------
+
+
+def _change_basis(e: dict[str, Any]) -> str:
+ if not e["complete"]:
+ return "unresolved"
+ return "inferred" if e["tests"].get("basis") == "inferred" else "measured"
+
+
+def _checklist_line(cl: dict[str, Any]) -> str:
+ if not cl["kept"]:
+ return "not built (--no-build)"
+ return (
+ f"{cl['ok']} ok, {cl['attention']} attention, {cl['unknown']} unknown; "
+ f"built {cl['generated_at']}"
+ )
+
+
+def _change_lines(e: dict[str, Any]) -> dict[str, str]:
+ comps = ", ".join(
+ f"{c['name']} ({'team ' + c['team'] if c['team'] else 'no declared team'})"
+ for c in e["components"]
+ )
+ return {
+ "components": comps or "none known",
+ "accountable": e["accountable"]["text"],
+ "review": e["review"]["text"],
+ "tests": e["tests"]["text"],
+ "policy": e["policy"]["text"],
+ "provenance": e["provenance"]["text"],
+ "outcome": e["outcome"]["text"],
+ "checklist": _checklist_line(e["checklist"]),
+ }
+
+
+def _change_check(e: dict[str, Any]) -> dict[str, Any]:
+ lines = _change_lines(e)
+ merged = (e["merged_at"] or "")[:10] or "unknown"
+ return check(
+ e["ref"],
+ reason=f"{merged} {e['category']}: {e['title']}",
+ details=[
+ f"{e['files_changed']} file(s), +{e['lines_added']}/-{e['lines_deleted']}",
+ *(f"{k}: {v}" for k, v in lines.items()),
+ ],
+ method=_METHOD,
+ basis=_change_basis(e),
+ data={
+ "change": e,
+ "row": {
+ "change": e["ref"],
+ "merged_at": e["merged_at"],
+ "title": e["title"],
+ "category": e["category"],
+ "teams": ", ".join(e["accountable"].get("teams") or ()),
+ **lines,
+ },
+ },
+ )
+
+
+# -- summary --------------------------------------------------------------------
+
+
+def _iso(value: datetime | None) -> str | None:
+ return value.isoformat() if value else None
+
+
+def _period_check(ctx: ReportContext, entries: list[dict[str, Any]]) -> dict[str, Any]:
+ request = _request(ctx)
+ since = request.since.date().isoformat() if request.since else "the oldest indexed change"
+ until = f"before {request.until.date().isoformat()}" if request.until else "to the newest"
+ by_category: dict[str, int] = {}
+ for e in entries:
+ by_category[e["category"]] = by_category.get(e["category"], 0) + 1
+ return check(
+ "changes-in-period",
+ reason=f"{len(entries)} change(s) merged from {since} {until}",
+ details=[f"{k}: {v}" for k, v in sorted(by_category.items())],
+ method=_METHOD,
+ basis="measured",
+ data={"changes": len(entries), "by_category": by_category,
+ "since": _iso(request.since), "until": _iso(request.until)},
+ )
+
+
+def _window_check(window: dict[str, Any]) -> dict[str, Any]:
+ return check(
+ "index-window",
+ reason="the index covers the whole period" if not window["gaps"]
+ else "the index does not cover the whole period",
+ details=window["gaps"],
+ method="the oldest and newest change the index holds, against the period and HEAD",
+ basis="unresolved" if window["gaps"] else "measured",
+ data=window,
+ )
+
+
+def _known_counts(entries: list[dict[str, Any]]) -> dict[str, int]:
+ return {k: sum(e[k]["status"] == "known" for e in entries) for k in (*ANSWERS, "review")}
+
+
+def _checklists_check(entries: list[dict[str, Any]]) -> dict[str, Any]:
+ n = len(entries)
+ complete = sum(e["complete"] for e in entries)
+ not_kept = sum(not e["checklist"]["kept"] for e in entries)
+ known = _known_counts(entries)
+ return check(
+ "checklists",
+ reason=(
+ f"{complete} of {n} change(s) answer every question; {n - complete} with at "
+ "least one unknown answer, which is missing evidence, not a failure"
+ ),
+ details=[
+ *(f"{k} known: {known[k]} of {n}" for k in ANSWERS),
+ *([f"no checklist kept: {not_kept} (built only without --no-build)"] if not_kept else []),
+ ],
+ method="accountable team, reaching tests, policy and outcome read from each checklist",
+ basis="measured",
+ data={"complete": complete, "changes": n, "known": known, "not_kept": not_kept},
+ )
+
+
+def _review_check(period: dict[str, Any], entries: list[dict[str, Any]]) -> dict[str, Any]:
+ n, source = len(entries), period["metadata_source"]
+ recorded = _known_counts(entries)["review"]
+ return check(
+ "review-records",
+ reason=(
+ f"{recorded} of {n} change(s) carry a review or approval record; "
+ f"{n - recorded} not recorded in {source}"
+ ),
+ method=f"approvals and reviewers from the {source!r} change metadata source",
+ basis="declared" if recorded else "unresolved",
+ data={"recorded": recorded, "changes": n, "source": source},
+ )
+
+
+def _policy_summary(period: dict[str, Any], entries: list[dict[str, Any]]) -> dict[str, Any]:
+ method = "the condition rules of .repowise/policies.yaml over each change's checklist"
+ if period["policy_error"]:
+ return check("policy", reason=period["policy_error"], method=method, basis="unresolved")
+ if period["policy"] is None:
+ return check(
+ "policy",
+ reason="no policy configured (.repowise/policies.yaml is absent)",
+ method=method,
+ basis="declared",
+ data={"configured": False},
+ )
+ counts = {v: 0 for v in ("pass", "warn", "fail", "unknown")}
+ for e in entries:
+ counts[e["policy"]["verdict"]] += 1
+ return check(
+ "policy",
+ reason=", ".join(f"{k} {v}" for k, v in counts.items()),
+ details=capped(
+ [f"{e['ref']}: {e['policy']['text']}" for e in entries
+ if e["policy"]["verdict"] in ("fail", "warn")]
+ ),
+ method=method,
+ basis="declared",
+ data={"configured": True, "source": period["policy"].source, **counts},
+ )
+
+
+def _outcome_summary(entries: list[dict[str, Any]]) -> dict[str, Any]:
+ reverted = [e["ref"] for e in entries if e["outcome"].get("reverted")]
+ named = [e["ref"] for e in entries if e["outcome"].get("fix_references")]
+ unknown = sum(e["outcome"]["status"] != "known" for e in entries)
+ return check(
+ "outcomes",
+ reason=(
+ f"{len(reverted)} reverted, {len(named)} named as the cause by a later fix, "
+ f"{unknown} not known"
+ ),
+ details=capped(
+ [f"reverted: {r}" for r in reverted] + [f"named by a later fix: {r}" for r in named]
+ ),
+ method="reverts that name the change and later commits naming it as the cause, only",
+ basis="declared",
+ data={"reverted": reverted, "fix_referenced": named, "unknown": unknown},
+ )
+
+
+def _component_summary(entries: list[dict[str, Any]]) -> dict[str, Any]:
+ per: dict[str, dict[str, Any]] = {}
+ untouched = 0
+ for e in entries:
+ untouched += not e["components"]
+ for c in e["components"]:
+ slot = per.setdefault(c["name"], {"changes": 0, "teams": set()})
+ slot["changes"] += 1
+ slot["teams"] |= {c["team"]} if c["team"] else set()
+ rows = sorted(per.items(), key=lambda kv: (-kv[1]["changes"], kv[0]))
+ return check(
+ "components",
+ reason=f"{len(per)} component(s) changed; {untouched} change(s) with no known component",
+ details=capped(
+ [
+ f"{name}: {v['changes']} change(s); "
+ + (f"team(s) {', '.join(sorted(v['teams']))}" if v["teams"] else "no declared team")
+ for name, v in rows
+ ]
+ ),
+ method="components each change's files resolve to, with the owning teams the catalog declares",
+ basis="declared",
+ data={
+ "components": {n: {"changes": v["changes"], "teams": sorted(v["teams"])} for n, v in rows},
+ "without_component": untouched,
+ },
+ )
+
+
+_PROVENANCE_METHOD = (
+ "public git markers (bot authors, trailers, footers, git-ai notes, Agent Trace files) "
+ "and opted-in capture; unknown is never counted as human"
+)
+
+
+def _provenance_totals(entries: list[dict[str, Any]]) -> dict[str, Any]:
+ """Commit coverage and the agents and models named; never a count or share of agent work."""
+ prov = [e["provenance"] for e in entries]
+ return {
+ "commits": sum(p.get("commits") or 0 for p in prov),
+ "known": sum(p.get("commits_known") or 0 for p in prov),
+ "agents": sorted({a for p in prov for a in p.get("agents") or ()}),
+ "models": sorted({m for p in prov for m in p.get("models") or ()}),
+ }
+
+
+def _provenance_summary(period: dict[str, Any], entries: list[dict[str, Any]]) -> dict[str, Any]:
+ if not period["attribution"]:
+ return check(
+ "provenance",
+ reason="attribution is switched off for this repository",
+ method=_PROVENANCE_METHOD,
+ basis="unresolved",
+ )
+ t = _provenance_totals(entries)
+ pct = f" ({round(100 * t['known'] / t['commits'])}%)" if t["commits"] else ""
+ named = [("agents", t["agents"]), ("models", t["models"])]
+ return check(
+ "provenance",
+ reason=f"{t['known']} of {t['commits']} commit(s) in the period carry a provenance marker{pct}",
+ details=[f"{kind} named: {', '.join(names)}" for kind, names in named if names],
+ method=_PROVENANCE_METHOD,
+ basis="measured" if t["known"] else "unresolved",
+ data=t,
+ )
+
+
+async def _collect_summary(ctx: ReportContext) -> list[dict[str, Any]]:
+ period = await _period(ctx)
+ entries: list[dict[str, Any]] = period["entries"]
+ return [
+ _period_check(ctx, entries),
+ _window_check(period["window"]),
+ _checklists_check(entries),
+ _review_check(period, entries),
+ _policy_summary(period, entries),
+ _outcome_summary(entries),
+ _component_summary(entries),
+ _provenance_summary(period, entries),
+ ]
+
+
+async def _collect_changes(ctx: ReportContext) -> list[dict[str, Any]] | None:
+ entries = (await _period(ctx))["entries"]
+ return [_change_check(e) for e in entries] or None
+
+
+# -- method appendix --------------------------------------------------------------
+
+_APPENDIX = "what this pack rests on and what it cannot attest"
+
+#: The appendix items whose wording does not depend on the run.
+_STATED = {
+ "tests": (
+ "Tests reaching a change come from an ingested coverage map (measured) or the call "
+ "and import graph (inferred), read from the index at the commit each checklist "
+ "names; an empty answer counts as no test only against a current coverage map."
+ ),
+ "accountability": (
+ "Owning teams come from the component catalog (spec.owner) and CODEOWNERS team "
+ "entries. Individual and unresolved owners are counted, never named; no person is "
+ "named, scored or ranked anywhere in this pack."
+ ),
+ "provenance": (
+ "Which agent or model produced a change is read from public git markers and "
+ "opted-in capture. A commit with no marker is unknown, never counted as human, and "
+ "no share of agent work is reported."
+ ),
+ "outcomes": (
+ "Only explicit links: reverts that name the change and later commits that name it "
+ "as the cause in their own words, read at HEAD. Nothing is inferred from blame."
+ ),
+ "not-attested": (
+ "Git alone cannot attest: approvals and who approved, the CI result at merge time, "
+ "deployment to production, or an emergency-change ticket. A merged change is not "
+ "proof of a production deploy; those records come from the forge, CI and deploy "
+ "systems."
+ ),
+}
+
+
+def _review_reason(source: str) -> str:
+ return (
+ "Git records no pull-request approvals or reviewers. Approved-by trailers (GitLab "
+ "merge commits) are read when present; any other change reads 'not recorded in "
+ f"git', which is unresolved and never a missing review. Source: {source!r}; a forge "
+ "metadata source registered on the change-metadata seam supplies approvals."
+ )
+
+
+def _policy_reason(period: dict[str, Any]) -> str:
+ policy = period["policy"]
+ if policy is None:
+ return (
+ period["policy_error"]
+ or "No .repowise/policies.yaml: no policy is configured, so no change was policy-checked."
+ )
+ gates = [r.name for r in policy.rules if r.gate]
+ return (
+ f"The condition rules of {policy.source} are evaluated now against each change's "
+ "kept checklist; a rule whose evidence is unknown is not evaluated. This is not the "
+ "verdict CI reached at merge time."
+ + (f" Gate rules ({', '.join(gates)}) run over the live tree and are not re-run." if gates else "")
+ )
+
+
+def _snapshot_reason(ctx: ReportContext) -> str:
+ head = (ctx.head_commit or "")[:12] or "the indexed commit"
+ return (
+ "Each checklist is kept from its first build, stamped with when it was built and "
+ f"the indexed commit it read ({head} for this report); outcomes are read again "
+ "whenever HEAD moves, and --refresh rebuilds every checklist."
+ )
+
+
+async def _collect_method(ctx: ReportContext) -> list[dict[str, Any]]:
+ period = await _period(ctx)
+ entries = period["entries"]
+ items = [
+ ("review", _review_reason(period["metadata_source"]),
+ "declared" if any(e["review"]["status"] == "known" for e in entries) else "unresolved"),
+ ("tests", _STATED["tests"],
+ "measured" if any(e["tests"].get("measured") for e in entries) else "inferred"),
+ ("policy", _policy_reason(period), "unresolved" if period["policy_error"] else "declared"),
+ ("accountability", _STATED["accountability"], "declared"),
+ ("provenance", _STATED["provenance"], "measured" if period["attribution"] else "unresolved"),
+ ("outcomes", _STATED["outcomes"], "declared"),
+ ("snapshot", _snapshot_reason(ctx), "measured"),
+ ("not-attested", _STATED["not-attested"], "unresolved"),
+ ]
+ return [check(name, reason=reason, method=_APPENDIX, basis=basis) for name, reason, basis in items]
+
+
+report_sections.register(
+ "change-summary",
+ Section(
+ title="Period summary",
+ summary="Changes merged in the period and how many of the audit questions each answers",
+ collect=_collect_summary,
+ order=10,
+ report="changes",
+ ),
+)
+report_sections.register(
+ "changes",
+ Section(
+ title="Changes",
+ summary=(
+ "Each merged change: components and owning teams, review record, reaching tests, "
+ "policy result, provenance and outcomes, each with its basis"
+ ),
+ collect=_collect_changes,
+ order=20,
+ report="changes",
+ ),
+)
+report_sections.register(
+ "change-method",
+ Section(
+ title="Method and basis",
+ summary="What each answer rests on, and what git alone cannot attest",
+ collect=_collect_method,
+ order=90,
+ report="changes",
+ ),
+)
diff --git a/tests/unit/analysis/test_change_risk_fix_history.py b/tests/unit/analysis/test_change_risk_fix_history.py
index 36823e15b..ef651ec72 100644
--- a/tests/unit/analysis/test_change_risk_fix_history.py
+++ b/tests/unit/analysis/test_change_risk_fix_history.py
@@ -380,3 +380,98 @@ def test_repo_without_fix_history_reports_nothing(tmp_path: Path) -> None:
assert result.fix_density == 0.0
assert result.hot_files == ()
assert result.fix_percentile is None
+
+
+def test_one_walk_primes_the_same_pressure_every_ref_would_walk(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from repowise.core.analysis.change_risk import fix_history
+
+ repo = tmp_path / "merges"
+ repo.mkdir()
+ _git(["init", "-q", "-b", "main"], repo)
+ _commit(repo, {"a.py": "a = 0\n", "b.py": "b = 0\n"}, "feat: seed")
+ _commit(repo, {"a.py": "a = 1\n"}, "fix: a breaks")
+ _git(["checkout", "-q", "-b", "side"], repo)
+ _commit(repo, {"b.py": "b = 1\n"}, "fix: b breaks on the side")
+ _git(["checkout", "-q", "main"], repo)
+ _commit(repo, {"a.py": "a = 2\n"}, "fix: a breaks again")
+ _git(["-c", "user.name=Dev", "-c", "[email protected]", "merge", "-q", "--no-ff", "side",
+ "-m", "Merge side"], repo)
+ _commit(repo, {"b.py": "b = 2\n"}, "feat: b grows")
+ shas = subprocess.run(
+ ["git", "rev-list", "--first-parent", "HEAD"], cwd=repo, check=True,
+ capture_output=True, text=True,
+ ).stdout.split()
+
+ history = fix_history.FixHistory(str(repo))
+ walked = {}
+ for sha in shas:
+ clear_fix_pressure_cache()
+ walked[sha] = fix_pressure(str(repo), sha)
+ clear_fix_pressure_cache()
+ assert fix_history.prime_fix_pressure(str(repo), history, shas) == len(shas)
+
+ def no_walk(*_a, **_k):
+ raise AssertionError("a primed ref walked git again")
+
+ monkeypatch.setattr(fix_history, "_walk", no_walk)
+ for sha in shas:
+ assert fix_pressure(str(repo), sha) == walked[sha]
+ assert walked[shas[0]]["b.py"] > 0 # the side branch's fix is reached through the merge
+ # A history past the walk limit answers nothing, and scoring walks git itself.
+ assert history.pressure(shas[0], depth=1) is None
+ assert history.pressure("f" * 40) is None
+
+
+def _merge_repo(repo: Path) -> list[str]:
+ """main with a merged side branch carrying a fix; first-parent shas, newest first."""
+ repo.mkdir()
+ _git(["init", "-q", "-b", "main"], repo)
+ _commit(repo, {"a.py": "a = 0\n", "b.py": "b = 0\n"}, "feat: seed")
+ _commit(repo, {"a.py": "a = 1\n"}, "fix: a breaks")
+ _git(["checkout", "-q", "-b", "side"], repo)
+ _commit(repo, {"b.py": "b = 1\n"}, "fix: b breaks on the side")
+ _git(["checkout", "-q", "main"], repo)
+ _commit(repo, {"a.py": "a = 2\n"}, "fix: a breaks again")
+ _git(["-c", "user.name=Dev", "-c", "[email protected]", "merge", "-q", "--no-ff", "side",
+ "-m", "Merge side"], repo)
+ _commit(repo, {"b.py": "b = 2\n"}, "fix: b breaks on main")
+ return subprocess.run(
+ ["git", "rev-list", "--first-parent", "HEAD"], cwd=repo, check=True,
+ capture_output=True, text=True,
+ ).stdout.split()
+
+
+def test_one_walk_matches_walk_on_a_shallow_clone(tmp_path: Path) -> None:
+ from repowise.core.analysis.change_risk import fix_history
+
+ source = tmp_path / "source"
+ _merge_repo(source)
+ shallow = tmp_path / "shallow"
+ subprocess.run(
+ ["git", "clone", "-q", "--depth=2", source.resolve().as_uri(), str(shallow)],
+ check=True, capture_output=True, text=True,
+ )
+ history = fix_history.FixHistory(str(shallow))
+ assert history.shallow
+ for sha in history.order:
+ clear_fix_pressure_cache()
+ assert history.pressure(sha) == fix_pressure(str(shallow), sha), sha
+
+
+def test_one_walk_answers_up_to_the_depth_limit_and_not_past_it(tmp_path: Path) -> None:
+ from repowise.core.analysis.change_risk import fix_history
+
+ repo = tmp_path / "limit"
+ head = _merge_repo(repo)[0]
+ listed = int(subprocess.run(
+ ["git", "rev-list", "--no-merges", "--count", head], cwd=repo, check=True,
+ capture_output=True, text=True,
+ ).stdout)
+ history = fix_history.FixHistory(str(repo))
+ assert history.pressure(head, listed) == fix_pressure(str(repo), head, depth=listed)
+ assert history.pressure(head, listed - 1) is None
+ # A walk capped below the history leaves older commits to _walk.
+ capped = fix_history.FixHistory(str(repo), depth=1)
+ assert capped.pressure(head) is None and not capped.answers(head + "x")
diff --git a/tests/unit/cli/test_changes_cmd.py b/tests/unit/cli/test_changes_cmd.py
index eea377fca..f55c62741 100644
--- a/tests/unit/cli/test_changes_cmd.py
+++ b/tests/unit/cli/test_changes_cmd.py
@@ -122,7 +122,11 @@ def _fake_evidence(monkeypatch):
],
)
+ async def _build(session, repo_id, root, row, **_k):
+ return await _evidence(session, repo_id, root, row)
+
monkeypatch.setattr(collect, "change_evidence", _evidence)
+ monkeypatch.setattr(collect, "build_stored_evidence", _build)
return calls
diff --git a/tests/unit/core/test_report_changes.py b/tests/unit/core/test_report_changes.py
new file mode 100644
index 000000000..8380b3919
--- /dev/null
+++ b/tests/unit/core/test_report_changes.py
@@ -0,0 +1,586 @@
+"""`repowise report changes`: the period pass, each change's answers, the
+policy verdict, the summary, the renderers and the CLI, over a fixture index."""
+
+from __future__ import annotations
+
+import csv
+import io
+import json
+from datetime import UTC, datetime
+from pathlib import Path
+
+import pytest
+from click.testing import CliRunner
+
+from repowise.core.changes.evidence import ChangeEvidence, EvidenceItem
+
+HEAD1, HEAD2, HEAD3 = "a" * 40, "b" * 40, "e" * 40
+SINCE, UNTIL = datetime(2026, 2, 1, tzinfo=UTC), datetime(2026, 4, 1, tzinfo=UTC)
+
+POLICY = """
+rules:
+ - name: pci-needs-tests
+ match: {components: {tags: [pci]}}
+ when: {reaching_tests: missing}
+ action: fail
+ - name: agent-review
+ when: {attribution: agent}
+ action: require_owner_review
+ - name: scan
+ gate: security
+"""
+
+
+def _change(cid: str, number: str, head: str, title: str, merged: datetime, category: str) -> dict:
+ return {
+ "change_id": cid,
+ "identity_kind": "pr",
+ "identity_value": number,
+ "shape": "squash",
+ "forge": "github",
+ "forge_ref": f"#{number}",
+ "title": title,
+ "merged_at": merged,
+ "head_sha": head,
+ "commit_shas_json": json.dumps([head]),
+ "files_json": json.dumps([{"path": "pay/a.py", "added": 3, "deleted": 1}]),
+ "files_changed": 1,
+ "lines_added": 3,
+ "lines_deleted": 1,
+ "category": category,
+ "metadata_source": "git",
+ "author_name": "Alice Example",
+ "author_email": "[email protected]",
+ }
+
+
+async def _seed(root: Path) -> None:
+ from repowise.core.persistence import (
+ create_engine,
+ create_session_factory,
+ get_session,
+ init_db,
+ upsert_repository,
+ )
+ from repowise.core.persistence.crud import upsert_changes
+ from repowise.core.persistence.models import GitCommit
+
+ (root / ".git").mkdir(parents=True, exist_ok=True)
+ (root / ".repowise").mkdir(exist_ok=True)
+ engine = create_engine(f"sqlite+aiosqlite:///{(root / '.repowise' / 'wiki.db').as_posix()}")
+ try:
+ await init_db(engine)
+ async with get_session(create_session_factory(engine)) as session:
+ repo = await upsert_repository(session, name="shop", local_path=str(root))
+ await upsert_changes(
+ session,
+ repo.id,
+ [
+ _change("pr-1", "1", HEAD1, '=HYPERLINK("http://x") fix', datetime(2026, 3, 1, tzinfo=UTC), "fix"),
+ _change("pr-2", "2", HEAD2, "feat: refunds", datetime(2026, 3, 5, tzinfo=UTC), "feature"),
+ _change("pr-3", "3", HEAD3, "fix: later", datetime(2026, 4, 2, tzinfo=UTC), "fix"),
+ ],
+ )
+ session.add(
+ GitCommit(
+ repository_id=repo.id,
+ sha=HEAD1,
+ author_name="Alice Example",
+ author_email="[email protected]",
+ committed_at=datetime(2026, 3, 1, tzinfo=UTC),
+ attribution="agent",
+ agent_name="claude",
+ agent_model_id="anthropic/claude-x",
+ )
+ )
+ finally:
+ await engine.dispose()
+
+
+def _gone(kind: str, label: str, reason: str) -> EvidenceItem:
+ return EvidenceItem(kind, label, "unknown", "unresolved", None, [{"reason": reason}], "test")
+
+
+def _evidence(change_id: str) -> ChangeEvidence:
+ """pr-1 answers everything; any other change answers nothing."""
+ if change_id != "pr-1":
+ items = [
+ _gone("components_touched", "Components touched", "no component holds the changed files"),
+ _gone("owners", "Declared owners", "the repository declares no owners"),
+ _gone("reaching_tests", "Tests reaching the change", "no test map"),
+ _gone("provenance", "AI provenance", "no attribution was stored"),
+ _gone("outcomes", "Outcomes since merge", "a shallow clone cuts off the history"),
+ ]
+ else:
+ items = [
+ EvidenceItem(
+ "components_touched", "Components touched", "ok", "declared", ["payments"],
+ [{"name": "payments", "source": "declared", "owner": "payments-team",
+ "criticality": "high", "tags": ["pci"], "files": ["pay/a.py"], "bus_factor": 1}],
+ "components",
+ ),
+ EvidenceItem(
+ "owners", "Declared owners", "ok", "declared", ["@acme/payments-team", "@alice"],
+ [{"owner": "@acme/payments-team", "paths": ["pay/a.py"]},
+ {"owner": "@alice", "paths": ["pay/a.py"]}],
+ "CODEOWNERS",
+ ),
+ EvidenceItem(
+ "suggested_reviewers", "Suggested reviewers", "ok", "inferred", ["Bob Person"],
+ [{"name": "Bob Person", "paths": ["pay/a.py"], "reasons": ["co-change"]}],
+ "git history",
+ ),
+ EvidenceItem(
+ "reaching_tests", "Tests reaching the change", "attention", "measured",
+ {"measured": 0, "inferred": 0, "files_without_tests": 1, "files_unknown": 0},
+ [{"path": "pay/a.py", "tests": [], "measured": True}],
+ "test impact",
+ ),
+ EvidenceItem(
+ "provenance", "AI provenance", "ok", "measured",
+ {"label": "agent", "agent_commits": 1, "human_attested_commits": 0,
+ "unknown_commits": 0, "coverage": 1.0},
+ [{"sha": HEAD1, "label": "agent", "tier": 2}],
+ "attribution",
+ ),
+ EvidenceItem(
+ "outcomes", "Outcomes since merge", "attention", "declared",
+ {"reverted": True, "reverts": 1, "fix_references": 0, "as_of": "", "days": 30},
+ [{"kind": "revert", "sha": "d" * 40, "change_id": "pr-9", "in_force": True,
+ "evidence": 'Revert "fix"'}],
+ "git history",
+ ),
+ ]
+ return ChangeEvidence(change_id, None, "2026-10-14T00:00:00+00:00", items, index_commit="c" * 40)
+
+
+def builds(monkeypatch: pytest.MonkeyPatch) -> list[str]:
+ """Stand in for the review; these tests are about the pack, not the checklist."""
+ from repowise.core.changes import collect
+
+ calls: list[str] = []
+
+ async def build(session, repo_id, root, row, **_k):
+ calls.append(row.change_id)
+ return _evidence(row.change_id)
+
+ monkeypatch.setattr(collect, "build_stored_evidence", build)
+ return calls
+
+
+def root(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ from repowise.cli.helpers import run_async
+
+ monkeypatch.delenv("REPOWISE_DB_URL", raising=False)
+ monkeypatch.delenv("REPOWISE_DATABASE_URL", raising=False)
+ root = (tmp_path / "shop").resolve()
+ run_async(_seed(root))
+ return root
+
+
+async def ctx(root: Path):
+ from repowise.core.changes.period import PeriodRequest
+ from repowise.core.persistence import create_engine, create_session_factory, get_session
+ from repowise.core.persistence.models import Repository
+ from repowise.core.report.model import ReportContext
+
+ engine = create_engine(f"sqlite+aiosqlite:///{(root / '.repowise' / 'wiki.db').as_posix()}")
+ async with get_session(create_session_factory(engine)) as session:
+ repo = (await session.execute(Repository.__table__.select())).first()
+ yield ReportContext(session, repo.id, root, period=PeriodRequest(since=SINCE, until=UNTIL))
+ await engine.dispose()
+
+
+def _over(ctx, **options):
+ """The period pass over the fixture window, with *options* on its request."""
+ from repowise.core.changes.period import PeriodRequest, period_evidence
+
+ request = PeriodRequest(since=SINCE, until=UNTIL, **options)
+ return period_evidence(ctx.session, ctx.repository_id, ctx.repo_root, request)
+
+
+async def _document(ctx) -> dict:
+ from repowise.core.report.build import assemble, available_sections, collect_repo
+
+ sections = available_sections("changes")
+ doc = assemble({"kind": "repo", "name": "shop"}, [await collect_repo(ctx, sections)])
+ doc["kind"] = "changes"
+ return doc
+
+
+def _section(doc: dict, sid: str) -> dict[str, dict]:
+ (section,) = [s for s in doc["sections"] if s["id"] == sid]
+ return {c["name"]: c for c in section["checks"]}
+
+
+# -- the period pass ----------------------------------------------------------
+
+
+async def test_period_builds_missing_checklists_once_and_keeps_them(ctx, builds):
+ from repowise.core.changes.collect import cached_evidence
+ from repowise.core.persistence.crud import get_change
+
+ seen: list[tuple[int, int, str]] = []
+ first = [
+ r.change_id
+ async for r, _e in _over(ctx, progress=lambda *a: seen.append(a),
+ )
+ ]
+ assert first == ["pr-2", "pr-1"] and sorted(builds) == ["pr-1", "pr-2"]
+ assert sorted(seen) == [(1, 2, "pr-2"), (2, 2, "pr-1")]
+ kept = cached_evidence(await get_change(ctx.session, ctx.repository_id, "pr-1"))
+ assert kept is not None and kept.item("outcomes") is not None
+
+ builds.clear()
+ again = [r.change_id async for r, _e in _over(ctx)]
+ assert again == ["pr-2", "pr-1"] and builds == []
+
+ _ = [r async for r in _over(ctx, refresh=True)]
+ assert sorted(builds) == ["pr-1", "pr-2"]
+
+
+# -- one change ---------------------------------------------------------------
+
+
+def _entry(change_id: str, policy=None, policy_error=None, attribution=True) -> dict:
+ from repowise.core.ownership.directory import DeclaredOwnership
+ from repowise.core.report.change_answers import EntryContext, entry
+
+ record = {
+ "id": change_id, "forge_ref": "#1", "title": "t", "merged_at": "2026-03-01T00:00:00+00:00",
+ "category": "fix", "head_sha": HEAD1, "commits": [HEAD1], "files_changed": 1,
+ "lines_added": 3, "lines_deleted": 1,
+ "metadata": {"source": "git", "reviewers": None, "approvals": None},
+ }
+ context = EntryContext(
+ policy=policy, policy_error=policy_error,
+ declared=DeclaredOwnership(codeowners_file=".github/CODEOWNERS"),
+ agents={HEAD1: ("claude", "anthropic/claude-x")}, attribution=attribution,
+ )
+ return entry(record, _evidence(change_id).to_dict(), context)
+
+
+def test_a_change_names_teams_and_counts_people():
+ e = _entry("pr-1")
+ assert e["accountable"]["teams"] == ["payments-team"]
+ assert e["accountable"]["individual_owners"] == 1
+ assert e["provenance"]["agents"] == ["claude"] and e["provenance"]["models"] == ["anthropic/claude-x"]
+ assert e["outcome"]["reverted"] is True and "reverted by pr-9" in e["outcome"]["text"]
+ assert e["tests"]["files_without_tests"] == 1 and e["complete"] is True
+ text = json.dumps(e)
+ for person in ("alice", "Alice", "Bob Person"):
+ assert person not in text
+
+
+def test_review_is_not_recorded_in_git_never_missing():
+ from repowise.core.report.change_answers import review as _review
+
+ e = _entry("pr-1")
+ assert e["review"] == {
+ "status": "unknown", "basis": "unresolved", "source": "git", "text": "not recorded in git",
+ }
+ trailers = _review({"source": "git", "approvals": 2, "reviewers": None})
+ assert trailers["status"] == "known" and "Approved-by" in trailers["text"]
+ forge = _review({"source": "acme-forge", "approvals": None, "reviewers": ["ana", "li"]})
+ assert forge["reviewers"] == 2 and "ana" not in json.dumps(forge)
+
+
+def test_unknown_evidence_stays_unknown_never_negative():
+ from repowise.core.policy import parse_policy
+
+ e = _entry("pr-2", policy=parse_policy(POLICY))
+ for key in ("accountable", "tests", "outcome", "provenance", "review"):
+ assert e[key]["status"] == "unknown", key
+ assert e["policy"]["verdict"] == "unknown" and e["complete"] is False
+ assert "reverted" not in e["outcome"] and e["provenance"]["commits"] == 1
+ assert "not recorded" in e["review"]["text"]
+
+
+def test_policy_evaluates_condition_rules_and_never_reruns_gates():
+ from repowise.core.policy import parse_policy
+ from repowise.core.report.change_answers import policy_verdict
+
+ policy = parse_policy(POLICY)
+ verdict = _entry("pr-1", policy=policy)["policy"]
+ assert verdict["verdict"] == "fail" and verdict["gates_not_rerun"] == ["scan"]
+ fired = {r["rule"]: r["outcome"] for r in verdict["rules"]}
+ assert fired == {"pci-needs-tests": "triggered", "agent-review": "triggered"}
+ assert policy_verdict(None, None, {})["verdict"] == "none"
+ assert policy_verdict(None, "bad file", {})["verdict"] == "unknown"
+ gates_only = parse_policy("rules:\n - name: scan\n gate: security\n")
+ assert policy_verdict(gates_only, None, {})["verdict"] == "unknown"
+ warn = parse_policy("rules:\n - name: agent-review\n when: {attribution: agent}\n action: warn\n")
+ assert _entry("pr-1", policy=warn)["policy"]["verdict"] == "warn"
+
+
+# -- the report ---------------------------------------------------------------
+
+
+async def test_summary_counts_the_period_by_change_and_component(ctx, builds):
+ (ctx.repo_root / ".repowise" / "policies.yaml").write_text(POLICY, encoding="utf-8")
+ doc = await _document(ctx)
+ assert [s["id"] for s in doc["sections"]] == ["change-summary", "changes", "change-method"]
+ summary = _section(doc, "change-summary")
+ assert summary["changes-in-period"]["data"]["changes"] == 2
+ assert summary["checklists"]["data"]["complete"] == 1
+ assert summary["review-records"]["basis"] == "unresolved"
+ assert summary["policy"]["data"] == {
+ "configured": True, "source": ".repowise/policies.yaml",
+ "pass": 0, "warn": 0, "fail": 1, "unknown": 1,
+ }
+ assert summary["outcomes"]["data"]["reverted"] == ["#1"]
+ assert summary["components"]["data"]["components"] == {
+ "payments": {"changes": 1, "teams": ["payments-team"]}
+ }
+ # Coverage and names, never a count or share of agent work.
+ assert summary["provenance"]["data"] == {
+ "commits": 2, "known": 1, "agents": ["claude"], "models": ["anthropic/claude-x"],
+ }
+ changes = _section(doc, "changes")
+ assert set(changes) == {"#1", "#2"}
+ assert changes["#2"]["basis"] == "unresolved" and changes["#2"]["score"] == -1
+ assert changes["#1"]["basis"] == "measured"
+
+
+async def test_no_policy_file_reads_no_policy_configured(ctx, builds):
+ doc = await _document(ctx)
+ assert "no policy configured" in _section(doc, "change-summary")["policy"]["reason"]
+ assert all(
+ c["data"]["change"]["policy"]["verdict"] == "none" for c in _section(doc, "changes").values()
+ )
+
+
+async def test_method_appendix_says_what_git_cannot_attest(ctx, builds):
+ method = _section(await _document(ctx), "change-method")
+ assert {"review", "tests", "policy", "accountability", "provenance", "outcomes",
+ "snapshot", "not-attested"} == set(method)
+ assert "not recorded in" in method["review"]["reason"]
+ assert method["not-attested"]["basis"] == "unresolved"
+
+
+async def test_renderers_present_the_same_pack(ctx, builds):
+ from repowise.core.report.render import report_renderers
+
+ doc = await _document(ctx)
+ page = report_renderers.get("html")(doc)
+ assert page.startswith("<!doctype html>") and "default-src 'none'" in page
+ assert "<script" not in page and "Method and basis" in page and "not recorded in git" in page
+ assert "Changes: shop" in report_renderers.get("markdown")(doc)
+
+ rows = list(csv.DictReader(io.StringIO(report_renderers.get("csv")(doc))))
+ by_check = {r["check"]: r for r in rows}
+ assert by_check["#1"]["review"] == "not recorded in git"
+ assert by_check["#1"]["teams"] == "payments-team"
+ # A commit message that opens as a formula is quoted.
+ assert by_check["#1"]["title"].startswith("'=HYPERLINK")
+ assert by_check["#1"]["reason"].startswith("2026-03-01")
+ assert by_check["changes-in-period"]["review"] == ""
+
+
+def test_spreadsheet_cells_quote_every_formula_lead():
+ from repowise.core.report.render import spreadsheet_cell
+
+ for lead in ("=", "+", "-", "@", "\t", "\r"):
+ assert spreadsheet_cell(f"{lead}x") == f"'{lead}x"
+ assert spreadsheet_cell("fix: x") == "fix: x" and spreadsheet_cell(None) == ""
+
+
+# -- CLI ------------------------------------------------------------------------
+
+
+def test_cli_writes_the_pack_and_reports_progress(root: Path, builds, tmp_path: Path) -> None:
+ from repowise.cli.main import cli
+
+ out = tmp_path / "pack.json"
+ runner = CliRunner(mix_stderr=False)
+ result = runner.invoke(
+ cli,
+ ["report", "changes", str(root), "--no-workspace", "--since", "2026-02-01",
+ "--until", "2026-04-01", "--format", "json", "--out", str(out)],
+ )
+ assert result.exit_code == 0, result.output
+ assert "evidence 1/2: pr-2" in result.stderr
+ doc = json.loads(out.read_text(encoding="utf-8"))
+ assert doc["kind"] == "changes" and doc["schema_version"] == 1
+ assert doc["scope"]["period"] == {"since": "2026-02-01T00:00:00+00:00",
+ "until": "2026-04-01T00:00:00+00:00"}
+ assert str(root) not in out.read_text(encoding="utf-8")
+
+ as_csv = runner.invoke(cli, ["report", "changes", str(root), "--no-workspace", "--format", "csv"])
+ assert as_csv.exit_code == 0 and as_csv.stdout.startswith("section,repo,check,score,basis")
+ assert builds.count("pr-3") == 1 # the open period took the third change too
+
+ bad = runner.invoke(
+ cli, ["report", "changes", str(root), "--no-workspace", "--since", "2026-04-01",
+ "--until", "2026-02-01"],
+ )
+ assert bad.exit_code != 0 and "--since must be before --until" in bad.output + bad.stderr
+
+
+# -- the pass under load, failure and other writers ---------------------------
+
+
+async def _add_changes(root: Path, changes: list[dict]) -> None:
+ """Write *changes* through an engine of their own, as another process would."""
+ from repowise.core.persistence import create_engine, create_session_factory, get_session
+ from repowise.core.persistence.crud import get_repository_by_path, upsert_changes
+
+ engine = create_engine(f"sqlite+aiosqlite:///{(root / '.repowise' / 'wiki.db').as_posix()}")
+ try:
+ async with get_session(create_session_factory(engine)) as session:
+ repo = await get_repository_by_path(session, str(root))
+ await upsert_changes(session, repo.id, changes)
+ finally:
+ await engine.dispose()
+
+
+async def _keep_elsewhere(root: Path, change_id: str, evidence: ChangeEvidence) -> None:
+ from repowise.core.changes.collect import save_evidence
+ from repowise.core.persistence import create_engine, create_session_factory, get_session
+ from repowise.core.persistence.crud import get_repository_by_path
+
+ engine = create_engine(f"sqlite+aiosqlite:///{(root / '.repowise' / 'wiki.db').as_posix()}")
+ try:
+ async with get_session(create_session_factory(engine)) as session:
+ repo = await get_repository_by_path(session, str(root))
+ await save_evidence(session, repo.id, change_id, evidence)
+ finally:
+ await engine.dispose()
+
+
+def _many(n: int) -> list[dict]:
+ return [
+ _change(f"pr-{100 + i}", str(100 + i), f"{100 + i:040x}", f"fix: {i}",
+ datetime(2026, 3, 10, i % 24, tzinfo=UTC), "fix")
+ for i in range(n)
+ ]
+
+
+async def test_many_concurrent_builds_on_disk_are_all_kept(ctx, monkeypatch):
+ import asyncio
+
+ from sqlalchemy import func, select
+
+ from repowise.core.changes import collect
+ from repowise.core.persistence.models import Change
+
+ await _add_changes(ctx.repo_root, _many(20))
+ running = peak = 0
+
+ async def build(session, repo_id, root, row, **_k):
+ nonlocal running, peak
+ running += 1
+ peak = max(peak, running)
+ # Each build reads the store on its own session while others write.
+ await session.execute(select(func.count()).select_from(Change))
+ await asyncio.sleep(0.01)
+ running -= 1
+ return _evidence(row.change_id)
+
+ monkeypatch.setattr(collect, "build_stored_evidence", build)
+ seen = []
+ got = [
+ r.change_id
+ async for r, e in _over(ctx, concurrency=6, progress=lambda *a: seen.append(a),
+ )
+ if e is not None
+ ]
+ assert len(got) == 22 and len(set(got)) == 22 and len(seen) == 22 and peak == 6
+ kept = await ctx.session.scalar(
+ select(func.count()).where(Change.evidence_json.is_not(None))
+ )
+ assert kept == 22
+
+
+async def test_a_failed_build_keeps_the_rest_of_its_page(ctx, monkeypatch):
+ from repowise.core.changes import collect
+ from repowise.core.persistence.crud import list_changes
+
+ async def build(session, repo_id, root, row, **_k):
+ if row.change_id == "pr-1":
+ raise RuntimeError("parse blew up")
+ return _evidence(row.change_id)
+
+ monkeypatch.setattr(collect, "build_stored_evidence", build)
+ with pytest.raises(RuntimeError, match="parse blew up"):
+ _ = [p async for p in _over(ctx)]
+ rows, _ = await list_changes(ctx.session, ctx.repository_id, limit=None)
+ kept = {r.change_id for r in rows if r.evidence_json}
+ assert kept == {"pr-2"}
+
+
+async def test_a_checklist_another_writer_kept_is_never_overwritten(ctx, monkeypatch):
+ from repowise.core.changes import collect
+ from repowise.core.persistence.crud import get_change
+
+ theirs = ChangeEvidence("pr-2", None, "2026-01-01T00:00:00+00:00",
+ [EvidenceItem("owners", "Declared owners", "ok", "declared", [], [], "server")])
+
+ async def build(session, repo_id, root, row, **_k):
+ if row.change_id == "pr-2": # the server kept one while this build ran
+ await _keep_elsewhere(root, "pr-2", theirs)
+ return _evidence(row.change_id)
+
+ monkeypatch.setattr(collect, "build_stored_evidence", build)
+ got = {r.change_id: e async for r, e in _over(ctx)}
+ assert got["pr-2"].generated_at == "2026-01-01T00:00:00+00:00"
+ ctx.session.expunge_all()
+ stored = collect.cached_evidence(await get_change(ctx.session, ctx.repository_id, "pr-2"))
+ assert stored.generated_at == "2026-01-01T00:00:00+00:00"
+
+
+async def test_the_period_is_fixed_before_the_first_build(ctx, monkeypatch):
+ from repowise.core.changes import collect, period
+
+ added: list[str] = []
+
+ async def build(session, repo_id, root, row, **_k):
+ # A newer change indexed mid-run must not shift the pages or repeat one.
+ if not added:
+ added.append(row.change_id)
+ await _add_changes(root, _many(1))
+ return _evidence(row.change_id)
+
+ monkeypatch.setattr(collect, "build_stored_evidence", build)
+ monkeypatch.setattr(period, "PAGE", 1) # a page per change, so a shift would show
+ got = [r.change_id async for r, _e in _over(ctx)]
+ assert got == ["pr-2", "pr-1"]
+
+
+def test_no_build_reports_kept_checklists_only(root: Path, builds, tmp_path: Path) -> None:
+ from repowise.cli.main import cli
+
+ out = tmp_path / "pack.json"
+ runner = CliRunner(mix_stderr=False)
+ result = runner.invoke(
+ cli,
+ ["report", "changes", str(root), "--no-workspace", "--since", "2026-02-01",
+ "--until", "2026-04-01", "--format", "json", "--out", str(out), "--no-build"],
+ )
+ assert result.exit_code == 0, result.output
+ assert builds == [] and "building" not in result.stderr
+ doc = json.loads(out.read_text(encoding="utf-8"))
+ summary = _section(doc, "change-summary")
+ assert summary["checklists"]["data"]["not_kept"] == 2
+ change = _section(doc, "changes")["#1"]["data"]["change"]
+ assert change["tests"]["status"] == "unknown" and "--no-build" in change["tests"]["text"]
+ assert change["checklist"]["kept"] is False
+
+ built = runner.invoke(cli, ["report", "changes", str(root), "--no-workspace",
+ "--since", "2026-02-01", "--until", "2026-04-01"])
+ assert "building 2 of 2 evidence checklist(s)" in built.stderr
+ assert "--no-build" in runner.invoke(cli, ["report", "changes", "--help"]).output
+
+
+def test_a_newline_in_a_title_survives_the_csv():
+ from repowise.core.report.render import render_csv
+
+ doc = {"sections": [{"id": "changes", "repo": None, "checks": [
+ {"name": "#1", "score": None, "basis": "measured", "reason": "line one\n=line two",
+ "details": ["a"], "data": {"row": {"title": "fix:\nsecond line"}}},
+ ]}]}
+ (row,) = list(csv.DictReader(io.StringIO(render_csv(doc))))
+ assert row["title"] == "fix:\nsecond line" and row["reason"] == "line one\n=line two"