Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix: make the change, events, chat and docs surfaces read what they mean (#3814)
Raghav Chamadiya2b6e113f4e5c
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.mdindex c40382a85..8fa05f0f1 100644--- a/docs/reference/CLI_REFERENCE.md+++ b/docs/reference/CLI_REFERENCE.md@@ -1656,6 +1656,8 @@ repowise events [--path PATH] [--since 7d|12h|ISO-DATE] [--kind KIND]... [--limiKinds: `ownership_shift`, `owner_inactive`, `bus_factor_drop` (critical components), `new_hotspot` (off by default), `contract_added`, `contract_broken`, `decision_stale`, `dead_code_growth`, `test_reach_drop`, `attribution_jump` (regulated components). The `events:` block in `.repowise/config.yaml` sets `enabled`, `retention_days` (365), `compact_after_days` (30; older runs keep one per week), per-kind switches under `kinds`, and the `sinks` to deliver to (`jsonl` by default, `stdout` for CI).+The web UI lists the same events on the repository's Events page, newest first. An empty list says why: `GET /api/repos/{id}/events` returns `snapshot_runs` and `empty_reason` (`baseline_only` until two snapshots exist, `nothing_moved`, or `no_match` under filters), and the same sentence this command prints as `empty_note`.+---### `repowise report assessment [PATH]`diff --git a/packages/cli/src/repowise/cli/commands/changes_cmd.py b/packages/cli/src/repowise/cli/commands/changes_cmd.pyindex d9ead8d50..0c8706121 100644--- a/packages/cli/src/repowise/cli/commands/changes_cmd.py+++ b/packages/cli/src/repowise/cli/commands/changes_cmd.py@@ -137,14 +137,16 @@ def _print_checklist(evidence: dict) -> None:from rich.markup import escapefrom rich.table import Table+ from repowise.core.changes.evidence import BASIS_TEXT, item_line, line_text+table = Table("Evidence", "Status", "Basis", "Value", title="Evidence checklist")for item in evidence["items"]:style = _STATUS_STYLE.get(item["status"], "")table.add_row(escape(item["label"]),f"[{style}]{item['status']}[/{style}]",- item["basis"],- escape(_value_text(item)),+ BASIS_TEXT.get(item["basis"], item["basis"]),+ escape(line_text(item_line(item))),)console.print(table)console.print(f"[dim]generated {evidence['generated_at']}; `--refresh` rebuilds it.[/dim]")@@ -180,27 +182,6 @@ def outcome_lines(item: dict) -> list[str]:return lines-def _value_text(item: dict) -> str:- value = item["value"]- if item["kind"] == "outcomes" and isinstance(value, dict):- rate = (- f"{value['files_fixed']} of {value['files']} files fixed within {value['days']} days"- if value.get("files") is not None- else ""- )- said = f"{value['reverts']} revert(s), {value['fix_references']} cause reference(s)"- return ", ".join(x for x in (said, rate) if x)- if value is None:- reasons = [d.get("reason") for d in item["details"] if d.get("reason")]- return reasons[0] if reasons else ""- if isinstance(value, list):- more = f" (+{len(value) - 6})" if len(value) > 6 else ""- return ", ".join(map(str, value[:6])) + more- if isinstance(value, dict):- return ", ".join(f"{k} {v}" for k, v in value.items() if v is not None and v != [])- return str(value)--_CSV_COLUMNS = ("change_id","merged_at",diff --git a/packages/cli/src/repowise/cli/commands/events_cmd.py b/packages/cli/src/repowise/cli/commands/events_cmd.pyindex 8c6e43543..f813b9e03 100644--- a/packages/cli/src/repowise/cli/commands/events_cmd.py+++ b/packages/cli/src/repowise/cli/commands/events_cmd.py@@ -38,22 +38,14 @@ def _parse_since(value: str | None) -> datetime | None:async def _read(root: Path, since: datetime | None, kinds: tuple[str, ...], limit: int):"""``(events, snapshot runs stored)``, or ``None`` without an index."""- from sqlalchemy import func, select-- from repowise.core.events.store import GAP_STAMP, list_events- from repowise.core.persistence.models import SnapshotRun+ from repowise.core.events.store import list_events, snapshot_run_countasync with repo_index_session(root) as opened:if opened is None:return Nonesession, repo_id = openedevents = await list_events(session, repo_id, since=since, kinds=kinds, limit=limit)- runs = await session.scalar(- select(func.count()).where(- SnapshotRun.repository_id == repo_id, ~SnapshotRun.stamp.startswith(GAP_STAMP)- )- )- return events, int(runs or 0)+ return events, await snapshot_run_count(session, repo_id)@click.command("events")@@ -89,16 +81,10 @@ def events_command(from rich.table import Tableif not events:+ from repowise.core.events.store import empty_events_reason+# An empty list is only news once two runs could be compared.- if runs < 2:- console.print(- f"No events yet: {runs} component snapshot(s) stored. Events are what "- "moved between two index runs in a row, so they start after the next "- "`repowise update` on a new commit."- )- else:- scope = " match these filters" if since or kinds else ""- console.print(f"No events{scope} across {runs} stored component snapshots.")+ console.print(empty_events_reason(runs, filtered=bool(since or kinds))[1])returntable = Table("When", "Kind", "Component", "Severity", "Evidence")for e in events:diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.pyindex eafc49e2c..8555f0297 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py@@ -292,18 +292,38 @@ def refresh_read_snapshots(repo_path: Any) -> None:overview and the dashboard read one row instead of rebuilding in each newprocess. A view no write has invalidated since is left as it is, so the"already up to date" path costs one primary-key read per view.- Best-effort: without a snapshot a reader builds live, as before.+ Best-effort: without a snapshot a reader builds live, as before. A+ snapshot that is not written is named with its error, here rather than in+ the core log, which an update keeps at ERROR."""from repowise.cli.helpers import repo_index_sessionfrom repowise.core.persistence.crud.analysis.actions import write_read_snapshots- async def _run() -> None:+ async def _run() -> list[tuple[str, Exception]]:async with repo_index_session(Path(repo_path)) as opened:- if opened is not None:- await write_read_snapshots(*opened)+ return [] if opened is None else await write_read_snapshots(*opened)- with contextlib.suppress(Exception):- run_async(_run())+ try:+ try:+ failed = run_async(_run())+ except Exception as exc:+ failed = [("read snapshots", exc)]+ for name, exc in failed:+ log.debug("read_snapshot_not_written", snapshot=name, error=repr(exc))+ console.print(f"[yellow]Snapshot not written: {_short_error(name, exc)}[/yellow]")+ except Exception: # reporting must never fail the update+ log.debug("read_snapshot_report_failed", exc_info=True)+++def _short_error(name: str, exc: BaseException) -> str:+ """``<snapshot>: <ErrorType>: <first line>``, cut to one line and escaped+ for Rich: an error text can hold markup brackets or a whole traceback."""+ from rich.markup import escape++ first = (str(exc).strip().splitlines() or [""])[0]+ if len(first) > 160:+ first = first[:159] + "…"+ return escape(f"{name}: {type(exc).__name__}" + (f": {first}" if first else ""))# A repair window that has grown past this many commits stopped being a repairdiff --git a/packages/cli/src/repowise/cli/commands/update_cmd/reporting.py b/packages/cli/src/repowise/cli/commands/update_cmd/reporting.pyindex 5ced26ca4..02e09da84 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd/reporting.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd/reporting.py@@ -279,6 +279,21 @@ def _dead_code_counts(return unreachable, unused+def _dead_code_line(dead_code_report: Any, changed_paths: list[str] | None = None) -> str:+ """The panel's dead-code line, naming its scope beside the repo-wide total.++ The run log prints the report's repo-wide total of every kind, so a+ scoped count shown bare would contradict it ("findings: 14" against+ "0 unreachable").+ """+ unreachable, unused = _dead_code_counts(dead_code_report, changed_paths)+ line = f"{unreachable} unreachable · {unused} unused exports"+ if changed_paths is None:+ return line+ total = len(dead_code_report.findings) if dead_code_report else 0+ return f"{line} in changed files" + (f" · {total} findings repo-wide" if total else "")++def show_full_completion(*,generated_pages: list,@@ -339,12 +354,10 @@ def show_index_only_completion("""render_degraded(degraded)graph = graph_builder.graph()- unreachable, unused = _dead_code_counts(dead_code_report, changed_paths)-metrics: list[tuple[str, str]] = [("Files changed", str(changed_count)),("Graph", f"{graph.number_of_nodes():,} nodes · {graph.number_of_edges():,} edges"),- ("Dead code", f"{unreachable} unreachable · {unused} unused exports"),+ ("Dead code", _dead_code_line(dead_code_report, changed_paths)),]if pages_rendered:metrics.append(("Wiki pages", f"{pages_rendered} re-rendered from structure"))diff --git a/packages/core/src/repowise/core/analysis/owners.py b/packages/core/src/repowise/core/analysis/owners.pyindex 9f26da065..b111b38e0 100644--- a/packages/core/src/repowise/core/analysis/owners.py+++ b/packages/core/src/repowise/core/analysis/owners.py@@ -77,6 +77,9 @@ class OwnerAccumulator:# Distinct commits in the 90 days before HEAD; None when the commit rows# are missing or do not reach back across the whole window.commit_count_90d: int | None = None+ # When the commit rows stop inside the window: this person's commits in+ # the part they cover, a floor of the 90-day count. None otherwise.+ commit_count_90d_at_least: int | None = Nonelines_added_90d_est: float = 0.0lines_deleted_90d_est: float = 0.0@@ -274,7 +277,8 @@ def _apply_commit_activity(Each owner's ``last_commit_at`` is the newest of their own commits; anowner with no row keeps the per-file value. The count stays ``None`` whenthere are no rows, or when the rows stop short of the window start and- are not the whole history (a capped sample would undercount).+ are not the whole history (a capped sample would undercount); an owner+ with commits in such a sample gets that count as a floor instead."""stamped: list[tuple[str, str, datetime]] = []for c in commits:@@ -302,6 +306,8 @@ def _apply_commit_activity(for key, acc in accs.items():if covers_window:acc.commit_count_90d = len(recent.get(key, ()))+ elif recent.get(key):+ acc.commit_count_90d_at_least = len(recent[key])if key in last:acc.last_commit_at = last[key]diff --git a/packages/core/src/repowise/core/changes/collect.py b/packages/core/src/repowise/core/changes/collect.pyindex 07c3bbbb1..7cfd356ce 100644--- a/packages/core/src/repowise/core/changes/collect.py+++ b/packages/core/src/repowise/core/changes/collect.py@@ -719,7 +719,7 @@ async def _provenance(return Unavailable("AI attribution is off for this repository")if not shas:return Unavailable("uncommitted work carries no commit markers")- stored: dict[str, tuple[str | None, str | None, int | None]] = {}+ stored: dict[str, tuple[str | None, str | None, int | None, str | None]] = {}for i in range(0, len(shas), 500):found = await session.execute(select(@@ -727,15 +727,19 @@ async def _provenance(GitCommit.attribution,GitCommit.agent_name,GitCommit.agent_autonomy_tier,+ GitCommit.agent_model_id,).where(GitCommit.repository_id == repo_id, GitCommit.sha.in_(shas[i : i + 500])))- for sha, attribution, agent, tier in found.tuples():- stored[sha] = (attribution, agent, tier)+ for sha, attribution, agent, tier, model in found.tuples():+ stored[sha] = (attribution, agent, tier, model)commits = []for sha in shas:- attribution, agent, tier = stored.get(sha, (None, None, None))+ attribution, agent, tier, model = stored.get(sha, (None, None, None, None))label = commit_label(attribution, agent) if sha in stored else UNKNOWN- commits.append({"sha": sha, "label": label, "tier": tier if label == "agent" else None})+ entry = {"sha": sha, "label": label, "tier": tier if label == "agent" else None}+ if label == "agent":+ entry.update({k: v for k, v in (("agent", agent), ("model", model)) if v})+ commits.append(entry)block = Noneif row is not None and row.provenance is not None:block = provenance_block(diff --git a/packages/core/src/repowise/core/changes/evidence.py b/packages/core/src/repowise/core/changes/evidence.pyindex 5b71d851c..b6aa6d763 100644--- a/packages/core/src/repowise/core/changes/evidence.py+++ b/packages/core/src/repowise/core/changes/evidence.py@@ -22,7 +22,8 @@ Detail rows a policy reads have fixed keys (the local change policy in``tests`` lists test ids, ``[]`` only for a measured absence, ``None`` whennothing knows;* ``contracts``: ``{path, breaking, ...}``;-* ``provenance``: one row per commit, ``{sha, label, tier}``;+* ``provenance``: one row per commit, ``{sha, label, tier}``, plus ``agent`` and+ ``model`` on an agent's commit when stored;* ``decisions_crossed``: ``{id, title, authority, status, paths}``;* ``outcomes``: one row per later link, ``{kind, sha, change_id, target_sha,rule, evidence, basis}`` (``kind`` is ``revert`` or ``fix_reference``; a@@ -88,10 +89,16 @@ class EvidenceItem:@classmethoddef from_dict(cls, data: Mapping[str, Any]) -> EvidenceItem:+ """Every reader of a kept checklist comes through here (``collect.cached_evidence``),+ so a stored status that a rule now derives differently is read as derived today."""+ status = data["status"]+ if data["kind"] == "reaching_tests" and data["basis"] != "unresolved":+ # Derived from the rows, so a kept checklist reads under the current rule.+ status = _tests_status(data.get("details") or [])return cls(kind=data["kind"],label=data["label"],- status=data["status"],+ status=status,basis=data["basis"],value=data.get("value"),details=list(data.get("details") or []),@@ -293,31 +300,8 @@ def _tests(bundle: ChangeReviewBundle, code: list[str]) -> EvidenceItem:return _unknown(kind, label, bundle.lane("tests").reason or "not gathered", source)by_basis = tests.get("recommendations_by_primary_basis") or {}files = {row["source_file"]: row for row in tests.get("files") or []}- coverage = tests.get("coverage") or {}- # An empty answer is a known absence only against a current measured map.- map_current = bool(coverage.get("map_present")) and (- (coverage.get("freshness") or {}).get("status") == "current"- )- rows: list[dict[str, Any]] = []- for path in sorted(set(code)):- row = files.get(path)- measured = list(row.get("measured_tests") or []) if row else []- found = sorted(set(measured) | set(row.get("inferred_tests") or [])) if row else []- if found:- reach: list[str] | None = found- elif row is not None and map_current:- reach = []- else:- reach = None- rows.append(- {- "path": path,- "tests": reach,- "measured": bool(measured) or reach == [],- "measured_tests": len(measured),- "inferred_tests": (row or {}).get("inferred_tests_total", 0),- }- )+ map_current = _map_current(tests.get("coverage") or {})+ rows = [_test_row(path, files.get(path), map_current) for path in sorted(set(code))]absent = sum(r["tests"] == [] for r in rows)unknown = sum(r["tests"] is None for r in rows)value = {@@ -331,7 +315,7 @@ def _tests(bundle: ChangeReviewBundle, code: list[str]) -> EvidenceItem:return EvidenceItem(kind,label,- "attention" if absent or unknown else "ok",+ _tests_status(rows),"measured" if rows and all(r["measured"] for r in rows) else "inferred",value,rows,@@ -339,6 +323,42 @@ def _tests(bundle: ChangeReviewBundle, code: list[str]) -> EvidenceItem:)+def _map_current(coverage: Mapping[str, Any]) -> bool:+ """An empty answer is a known absence only against a current measured map."""+ return bool(coverage.get("map_present")) and (+ (coverage.get("freshness") or {}).get("status") == "current"+ )+++def _test_row(path: str, row: Mapping[str, Any] | None, map_current: bool) -> dict[str, Any]:+ """One changed file's reaching tests: found, a known absence (``[]``), or ``None``."""+ measured = list(row.get("measured_tests") or []) if row else []+ found = sorted(set(measured) | set(row.get("inferred_tests") or [])) if row else []+ reach: list[str] | None+ if found:+ reach = found+ elif row is not None and map_current:+ reach = []+ else:+ reach = None+ return {+ "path": path,+ "tests": reach,+ "measured": bool(measured) or reach == [],+ "measured_tests": len(measured),+ "inferred_tests": (row or {}).get("inferred_tests_total", 0),+ }+++def _tests_status(rows: Sequence[Mapping[str, Any]]) -> Status:+ """Only a measured absence (``tests: []``) asks for a look; a file nothing+ knows about (``tests: None``) leaves the item partly known."""+ tests = [r.get("tests") for r in rows if isinstance(r, Mapping) and "path" in r]+ if any(t == [] for t in tests):+ return "attention"+ return "unknown" if any(t is None for t in tests) else "ok"++def _contracts(bundle: ChangeReviewBundle, inputs: EvidenceInputs) -> EvidenceItem:kind, label, source = "contracts", "Contracts touched", "workspace contracts"symbol = bundle.contracts if bundle.lane("contracts").state != "unsupported" else None@@ -527,7 +547,217 @@ def _rate_rows(rate: Mapping[str, Any] | None, unknown: str | None) -> list[dictreturn []+# -- value lines -------------------------------------------------------------++#: Names shown in a line before the rest are counted.+_LINE_NAMES = 6+++def _names(names: Sequence[Any]) -> dict[str, Any]:+ shown = [str(n) for n in names[:_LINE_NAMES]]+ return {"names": ", ".join(shown), "more": max(len(names) - len(shown), 0)}+++_Line = tuple[str, dict[str, Any]]+++def _named_list(kind: str, value: Any, rows: list[Mapping[str, Any]]) -> _Line | None:+ return (kind, {"count": len(value), **_names(value)}) if isinstance(value, list) else None+++def _owners_line(kind: str, value: Any, rows: list[Mapping[str, Any]]) -> _Line | None:+ if not isinstance(value, list):+ return None+ unowned = sum(len(r.get("paths") or ()) for r in rows if "owner" in r and r["owner"] is None)+ return kind, {"count": len(value), "unowned": unowned, **_names(value)}+++def _tests_line(kind: str, value: Any, rows: list[Mapping[str, Any]]) -> _Line:+ files = [r for r in rows if "path" in r]+ return kind, {+ "files": len(files),+ "reached": sum(bool(r.get("tests")) for r in files),+ "absent": sum(r.get("tests") == [] for r in files),+ "unknown": sum(r.get("tests") is None for r in files),+ }+++def _contracts_line(kind: str, value: Any, rows: list[Mapping[str, Any]]) -> _Line:+ breaking = value.get("breaking_symbols")+ key = "contracts" if breaking is not None else "contracts_unchecked"+ return key, {"touched": value.get("touched", 0), "breaking": breaking or 0}+++def _consumers_line(kind: str, value: Any, rows: list[Mapping[str, Any]]) -> _Line:+ return kind, {"links": value.get("links", 0), **_names(value.get("repos") or [])}+++def _decisions_line(kind: str, value: Any, rows: list[Mapping[str, Any]]) -> _Line:+ params = {"accepted": value.get("accepted", 0), "candidate": value.get("candidate", 0)}+ return (kind if any(params.values()) else "decisions_none"), params+++def _health_line(kind: str, value: Any, rows: list[Mapping[str, Any]]) -> _Line:+ params = {k: value.get(k, 0) for k in ("introduced", "worsened", "resolved")}+ return ("health_delta" if value.get("complete") else "health_delta_partial"), params+++def _provenance_line(kind: str, value: Any, rows: list[Mapping[str, Any]]) -> _Line:+ known = int(value.get("agent_commits") or 0) + int(value.get("human_attested_commits") or 0)+ commits = known + int(value.get("unknown_commits") or 0)+ # The label in the same plain words the change's facts use; agents and+ # models are named as provenance, never set against anything.+ label = str(value.get("label") or "unknown").replace("_", " ")+ named = sorted({str(r[k]) for r in rows for k in ("agent", "model") if r.get(k)})+ params = {"label": label, "known": known, "commits": commits}+ if named:+ return "provenance_named", {**params, "names": ", ".join(named)}+ return kind, params+++def _risk_line(kind: str, value: Any, rows: list[Mapping[str, Any]]) -> _Line:+ return kind, {"percentile": value.get("percentile")}+++def _outcomes_line(kind: str, value: Any, rows: list[Mapping[str, Any]]) -> _Line:+ params = {"reverts": value.get("reverts", 0), "references": value.get("fix_references", 0)}+ if value.get("files") is None:+ return "outcomes", params+ rate = {"fixed": value["files_fixed"], "files": value["files"], "days": value.get("days")}+ return "outcomes_rate", {**params, **rate}+++#: Each kind's line from its value and rows; ``None`` reads as unknown.+_LINES: dict[str, Any] = {+ "components_touched": _named_list,+ "suggested_reviewers": _named_list,+ "owners": _owners_line,+ "reaching_tests": _tests_line,+ "contracts": _contracts_line,+ "cross_repo_consumers": _consumers_line,+ "decisions_crossed": _decisions_line,+ "health_delta": _health_line,+ "provenance": _provenance_line,+ "risk_score": _risk_line,+ "outcomes": _outcomes_line,+}+++def item_line(item: Mapping[str, Any]) -> dict[str, Any]:+ """An item's value as ``{key, params}``, derived from its value and rows.++ Each surface words the line itself: the web from its message catalog, the+ CLI with :func:`line_text`. Derived on read, so a kept checklist gets it+ too. An item with no value reads ``unknown`` with the reason it carries.+ """+ kind, value = item["kind"], item.get("value")+ rows = [r for r in item.get("details") or () if isinstance(r, Mapping)]+ if value is None:+ reason = next((r["reason"] for r in rows if r.get("reason")), "")+ return {"key": "unknown", "params": {"reason": str(reason)}}+ build = _LINES.get(kind)+ line = build(kind, value, rows) if build else None+ if line is None:+ return {"key": "unknown", "params": {"reason": ""}}+ return {"key": line[0], "params": line[1]}+++def _n(count: int, one: str, many: str | None = None) -> str:+ return f"{count} {one if count == 1 else (many or one + 's')}"+++def _listed(p: Mapping[str, Any]) -> str:+ return p["names"] + (f" and {p['more']} more" if p["more"] else "")+++def _owners_text(key: str, p: Mapping[str, Any]) -> str:+ named = _listed(p) if p["count"] else "No declared owner"+ return named + (f"; {_n(p['unowned'], 'changed file')} without one" if p["unowned"] else "")+++def _tests_text(key: str, p: Mapping[str, Any]) -> str:+ if not p["files"]:+ return "No changed source file"+ parts = [f"{p['reached']} of {_n(p['files'], 'changed file')} reached by a test"]+ parts += [f"{p['absent']} with none"] * bool(p["absent"])+ parts += [f"{p['unknown']} not known"] * bool(p["unknown"])+ return "; ".join(parts)+++def _contracts_text(key: str, p: Mapping[str, Any]) -> str:+ touched = (+ _n(p["touched"], "workspace contract") + " touched"+ if p["touched"]+ else "No workspace contract touched"+ )+ if key == "contracts_unchecked":+ return f"{touched}; signatures not compared"+ broke = (+ _n(p["breaking"], "breaking signature change") if p["breaking"] else "no breaking signature change"+ )+ return f"{touched}; {broke}"+++def _health_text(key: str, p: Mapping[str, Any]) -> str:+ text = f"Findings: {p['introduced']} introduced, {p['worsened']} worsened, {p['resolved']} resolved"+ return text + (" (partial comparison)" if key == "health_delta_partial" else "")+++def _provenance_text(key: str, p: Mapping[str, Any]) -> str:+ text = f"provenance: {p['label']}, known for {p['known']} of {_n(p['commits'], 'commit')}"+ return text + (f" ({p['names']})" if key == "provenance_named" else "")+++def _outcomes_text(key: str, p: Mapping[str, Any]) -> str:+ text = f"{_n(p['reverts'], 'revert')}, {_n(p['references'], 'cause reference')}"+ if key == "outcomes_rate":+ text += f"; {p['fixed']} of {_n(p['files'], 'file')} fixed within {p['days']} days"+ return text+++#: Each line key in plain English, the CLI's wording of the web's catalog.+_TEXT: dict[str, Any] = {+ "unknown": lambda k, p: f"Not known: {p['reason']}" if p["reason"] else "Not known",+ "components_touched": lambda k, p: f"{_n(p['count'], 'component')}: {_listed(p)}",+ "suggested_reviewers": lambda k, p: _listed(p),+ "owners": _owners_text,+ "reaching_tests": _tests_text,+ "contracts": _contracts_text,+ "contracts_unchecked": _contracts_text,+ "cross_repo_consumers": lambda k, p: (+ f"{_n(p['links'], 'consumer')} in {_listed(p)}" if p["links"] else "No consumer in another repo"+ ),+ "decisions_none": lambda k, p: "No decision crossed",+ "decisions_crossed": lambda k, p: (+ f"{_n(p['accepted'], 'accepted decision')}, {_n(p['candidate'], 'candidate')}"+ ),+ "health_delta": _health_text,+ "health_delta_partial": _health_text,+ "provenance": _provenance_text,+ "provenance_named": _provenance_text,+ "risk_score": lambda k, p: f"Larger than {p['percentile']}% of recent commits",+ "outcomes": _outcomes_text,+ "outcomes_rate": _outcomes_text,+}+++def line_text(line: Mapping[str, Any]) -> str:+ """A :func:`item_line` in plain English, the CLI's wording of the web's catalog."""+ word = _TEXT.get(line["key"])+ return word(line["key"], line["params"]) if word else ""+++#: The basis in words; ``unresolved`` is what a reader calls not known.+BASIS_TEXT = {+ "measured": "measured",+ "inferred": "inferred",+ "declared": "declared",+ "unresolved": "not known",+}++__all__ = [+ "BASIS_TEXT","EVIDENCE_SCHEMA_VERSION","KINDS","ChangeEvidence",@@ -535,4 +765,6 @@ __all__ = ["EvidenceItem","Unavailable","build_change_evidence",+ "item_line",+ "line_text",]diff --git a/packages/core/src/repowise/core/changes/reconstruct.py b/packages/core/src/repowise/core/changes/reconstruct.pyindex b16563729..5e39b7293 100644--- a/packages/core/src/repowise/core/changes/reconstruct.py+++ b/packages/core/src/repowise/core/changes/reconstruct.py@@ -119,6 +119,22 @@ def change_title(subject: str, body: str, is_merge: bool) -> str:return subject+#: A squash title's trailing ``(#N)`` (GitHub) or ``(!N)`` (GitLab).+_OWN_REF_SUFFIX = re.compile(r"\s*\((?:#|!)(\d+)\)\s*$")+++def without_own_ref(title: str, number: str) -> str:+ """*title* less a trailing ``(#N)``/``(!N)`` naming its own change *number*.++ Surfaces print the ref beside the title, so the forge's suffix repeats it.+ A suffix naming another change stays.+ """+ m = _OWN_REF_SUFFIX.search(title)+ if m and m.group(1) == number and m.start() > 0:+ return title[: m.start()]+ return title++def change_identity(subject: str, body: str, sha: str, is_merge: bool, forge: ForgeKind | str) -> tuple[str, str, str | None]:@@ -390,6 +406,8 @@ class _Builder:else:shape = SHAPE_COMMITtitle = change_title(head.subject, head.body, head.is_merge)+ if kind == KIND_PR:+ title = without_own_ref(title, value)self.out.append(ReconstructedChange(change_id=change_id,diff --git a/packages/core/src/repowise/core/events/store.py b/packages/core/src/repowise/core/events/store.pyindex f7c24d02e..ce22369b9 100644--- a/packages/core/src/repowise/core/events/store.py+++ b/packages/core/src/repowise/core/events/store.py@@ -415,3 +415,35 @@ async def list_events(query = query.where(EngineEventRecord.kind.in_(list(kinds)))query = query.order_by(EngineEventRecord.occurred_at, EngineEventRecord.id).limit(limit)return [event_from_row(r) for r in await session.scalars(query)]+++async def snapshot_run_count(session: Any, repository_id: str) -> int:+ """Component snapshots stored for the repository, gap markers left out."""+ from sqlalchemy import func++ from repowise.core.persistence.models import SnapshotRun++ runs = await session.scalar(+ select(func.count()).where(+ SnapshotRun.repository_id == repository_id, ~SnapshotRun.stamp.startswith(GAP_STAMP)+ )+ )+ return int(runs or 0)+++def empty_events_reason(runs: int, *, filtered: bool) -> tuple[str, str]:+ """Why an event list is empty, as ``(code, sentence)``.++ ``baseline_only``: fewer than two snapshots, so nothing could be compared+ yet; ``no_match``: events exist but none pass the filters asked;+ ``nothing_moved``: runs were compared and nothing crossed a threshold.+ """+ if runs < 2:+ return "baseline_only", (+ f"No events yet: {runs} component snapshot(s) stored. Events are what "+ "moved between two index runs in a row, so they start after the next "+ "`repowise update` on a new commit."+ )+ if filtered:+ return "no_match", f"No events match these filters across {runs} stored component snapshots."+ return "nothing_moved", f"No events across {runs} stored component snapshots."diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/actions.py b/packages/core/src/repowise/core/persistence/crud/analysis/actions.pyindex 1a500b1c8..af2d87d88 100644--- a/packages/core/src/repowise/core/persistence/crud/analysis/actions.py+++ b/packages/core/src/repowise/core/persistence/crud/analysis/actions.py@@ -507,15 +507,19 @@ async def write_actions_snapshot(session: AsyncSession, repo_id: str) -> bool:)-async def write_read_snapshots(session: AsyncSession, repo_id: str) -> None:+async def write_read_snapshots(+ session: AsyncSession, repo_id: str+) -> list[tuple[str, Exception]]:"""Store the Fix first queue, then the actions view that quotes its head,then the run's component snapshot (:mod:`repowise.core.events`).For a writer whose stores are final for this run, on the session thatwrote them or a later one. Best-effort, each in its own savepoint: a view- that fails to build is built live on read instead.+ that fails to build is built live on read instead. Returns+ ``(snapshot, error)`` per snapshot not written, for a caller whose output+ the core log level hides."""- written = True+ failed: list[tuple[str, Exception]] = []for kind, write in (("fix_first", write_fix_first_snapshot),(SNAPSHOT_KIND, write_actions_snapshot),@@ -525,7 +529,8 @@ async def write_read_snapshots(session: AsyncSession, repo_id: str) -> None:await write(session, repo_id)except Exception as exc: # a reader builds live insteadlogger.warning("read snapshot %s not written: %s", kind, exc)- written = False+ failed.append((kind, exc))+ written = not failed# Built after this session's own writes, so its commit may keep them; a# kind that failed may have left an older row, which the commit drops.if written:@@ -538,6 +543,7 @@ async def write_read_snapshots(session: AsyncSession, repo_id: str) -> None:await record_snapshot(session, repo_id)except Exception as exc: # history skips a run; the index is unaffectedlogger.warning("component snapshot not written: %s", exc)+ failed.append(("component", exc))try: # so the next snapshot is a baseline, not a diff across the gapfrom repowise.core.events.store import record_gap@@ -545,6 +551,7 @@ async def write_read_snapshots(session: AsyncSession, repo_id: str) -> None:await record_gap(session, repo_id, "failed")except Exception as gap_exc:logger.warning("component snapshot gap not recorded: %s", gap_exc)+ return faileddef _view(ruled: dict[str, Any], states: dict[str, ActionStateRecord], now: datetime) -> dict:diff --git a/packages/core/src/repowise/core/persistence/crud/changes.py b/packages/core/src/repowise/core/persistence/crud/changes.pyindex 1518c5241..4e7bc6d86 100644--- a/packages/core/src/repowise/core/persistence/crud/changes.py+++ b/packages/core/src/repowise/core/persistence/crud/changes.py@@ -90,7 +90,11 @@ def _filters(repository_id: str, where: ChangeFilter) -> list[Any]:clauses = [Change.repository_id == repository_id]if where.attention:# A kept checklist with an attention item, in dump_evidence's layout; a- # prefilter only, since the text could sit inside an item's details.+ # prefilter only, since the text could sit inside an item's details,+ # and a stored status may read differently today (a kept reaching_tests+ # item is re-derived from its rows). Callers confirm each row through+ # ``collect.evidence_summary``, which parses with ``ChangeEvidence.from_dict``;+ # the re-derivation only ever lowers attention, so this stays a superset.clauses.append(Change.evidence_json.like(_ATTENTION_LIKE))if where.change_ids is not None:clauses.append(Change.change_id.in_(where.change_ids))diff --git a/packages/core/src/repowise/core/pipeline/incremental.py b/packages/core/src/repowise/core/pipeline/incremental.pyindex f1cf43265..55b5bdb6c 100644--- a/packages/core/src/repowise/core/pipeline/incremental.py+++ b/packages/core/src/repowise/core/pipeline/incremental.py@@ -923,7 +923,10 @@ def run_partial_analysis("the rest keep their previous verdict[/yellow]")if dead_code_report.total_findings:- log(f"Dead code findings: [yellow]{dead_code_report.total_findings}[/yellow]")+ log(+ f"Dead code findings: [yellow]{dead_code_report.total_findings}[/yellow]"+ " repo-wide, every kind"+ )except Exception as exc:log(f"[yellow]Dead code analysis skipped: {exc}[/yellow]")finally:diff --git a/packages/core/src/repowise/core/policy/rules.py b/packages/core/src/repowise/core/policy/rules.pyindex 06450d04b..e96e729ea 100644--- a/packages/core/src/repowise/core/policy/rules.py+++ b/packages/core/src/repowise/core/policy/rules.py@@ -23,7 +23,9 @@ source}]}``, and only these detail fields:An item whose status is ``unknown`` or whose basis is ``unresolved`` answersnothing, so a condition that needs it is unknown and the rule does not fire:-a missed policy hit is preferred to a false one. There are no risk-score+a missed policy hit is preferred to a false one. ``reaching_tests`` is the+exception: it is read per row unless its basis is ``unresolved``, since a+partly known item still answers for the files it knows. There are no risk-scoreconditions; change risk is not calibrated."""@@ -491,7 +493,9 @@ def _agent_tier(want, items, scope, matched) -> Check:def _reaching_tests(want, items, scope, matched) -> Check:item = items.get("reaching_tests")- if not _known(item):+ # Rows carry each file's answer, so a partly known item (``unknown`` with+ # a real basis) still decides the files in scope it knows about.+ if item is None or item.get("basis") == "unresolved":return None, "reaching tests are not known", [], "reaching_tests"rows = [r for r in _rows(item) if r.get("path") and (scope is None or r["path"] in scope)]# ``tests: []`` is a known absence; a missing or null list is not known.diff --git a/packages/core/src/repowise/core/report/sections/outcomes.py b/packages/core/src/repowise/core/report/sections/outcomes.pyindex 0ebc1c089..af5410646 100644--- a/packages/core/src/repowise/core/report/sections/outcomes.py+++ b/packages/core/src/repowise/core/report/sections/outcomes.py@@ -10,6 +10,7 @@ blame, and a file fix rate is never read as a cause.from __future__ import annotationsimport json+from types import SimpleNamespacefrom typing import Anyfrom repowise.core.report.model import (@@ -30,15 +31,16 @@ _FLAGGED = "reverted or named as the cause by a later fix"def _outcomes(raw: str | None) -> dict[str, Any] | None:- """The kept ``outcomes`` item of one checklist, when it was read and known."""- if not raw:- return None- try:- items = json.loads(raw).get("items") or []- except (TypeError, ValueError, AttributeError):- return None- item = next((i for i in items if isinstance(i, dict) and i.get("kind") == "outcomes"), None)- return item if item and item.get("status") != "unknown" else None+ """The kept ``outcomes`` item of one checklist, when it was read and known.++ Read through ``cached_evidence`` like every other reader of a kept+ checklist, so a stored status is read under the current rules.+ """+ from repowise.core.changes.collect import cached_evidence++ evidence = cached_evidence(SimpleNamespace(evidence_json=raw))+ item = evidence.item("outcomes") if evidence is not None else None+ return item.to_dict() if item is not None and item.status != "unknown" else Nonedef _files(files_json: str | None) -> list[str]:diff --git a/packages/server/src/repowise/server/chat_figures.py b/packages/server/src/repowise/server/chat_figures.pyindex 1b979c9ee..857eb433a 100644--- a/packages/server/src/repowise/server/chat_figures.py+++ b/packages/server/src/repowise/server/chat_figures.py@@ -22,6 +22,17 @@ Reading evidence is bounded: past ``MAX_NODES_PER_ARTIFACT`` or``MAX_CHARS_TOTAL`` overall, the rest is not read, and a figure that matchednothing read counts as not checked rather than flagged.+A figure no result holds may still be worked out from figures that are+there, and is then ``derived`` rather than flagged, but only where the answer+shows the working: a percentage whose clause writes its two terms next to+each other ("254 of 505 (50.3%)", "7/8"), a count whose clause writes the sum+out ("320 + 115 = 435"), or a share column of a markdown table whose rows,+at least two of them, are their count over one total the answer names+("Total: 505"). Every term must itself be held by a result, matches use the+precision shown and never the hedge allowance, and no other pairing of the+answer's numbers counts: two matched numbers that merely divide to the figure+do not make it derived.+A figure with no match is flagged, never removed. A matched one carries the``artifact_id`` of the tool result it came from, which is its citation.Offsets are UTF-16 code units so a browser can slice the text with them.@@ -31,7 +42,7 @@ from __future__ import annotationsimport bisectimport re-from collections.abc import Iterable+from collections.abc import Iterable, Iteratorfrom dataclasses import dataclass, fieldfrom typing import Any@@ -161,6 +172,8 @@ class Figure:end: intverified: boolartifact_id: str | None = None+ #: Worked out from matched figures of the answer rather than read in a result.+ derived: bool = Falsedef to_json(self) -> dict[str, Any]:out: dict[str, Any] = {@@ -171,6 +184,8 @@ class Figure:}if self.artifact_id:out["artifact_id"] = self.artifact_id+ if self.derived:+ out["derived"] = Truereturn out@@ -189,6 +204,8 @@ class FigureCheck:"figures_checked": len(self.figures),"figures_unverified": sum(not f.verified for f in self.figures),}+ if derived := sum(f.derived for f in self.figures):+ out["figures_derived"] = derivedif self.not_checked:out["figures_not_checked"] = self.not_checkedreturn out@@ -408,6 +425,171 @@ def _find(pool: _Pool, reading: _Reading, tolerance: float) -> str | None | boolreturn False+_NUM_TEXT = r"[0-9]{1,3}(?:,[0-9]{3})+(?:\.[0-9]+)?|[0-9]+(?:\.[0-9]+)?"+# A clause ends at a sentence stop, a semicolon, a colon or a line break.+_CLAUSE_BREAK = re.compile(r"(?<=[.!?])\s+|[;\n]|:\s")+# A ratio's two terms, next to each other: "254 of 505", "3 out of 4", "7/8".+_PAIR = re.compile(rf"(?<![\w.])({_NUM_TEXT})\s*(?:out of|of|/)\s*({_NUM_TEXT})", re.IGNORECASE)+# A sum written out: "320 + 115 = 435", "2 + 3, 5 in all".+_SUM = re.compile(+ rf"((?:(?:{_NUM_TEXT})\s*\+\s*)+(?:{_NUM_TEXT}))\s*"+ rf"(?:(?:=|,?\s*(?:for a total of|a total of|in total|in all|total of|total|across)\s*)\s*({_NUM_TEXT})"+ rf"|,?\s*({_NUM_TEXT})\s+(?:in all|in total|total)\b)",+ re.IGNORECASE,+)+# A figure the answer names as a total: "Total: 505", "505 in all".+_TOTAL = re.compile(+ rf"\b(?:total|in all|across)\b\W{{0,3}}({_NUM_TEXT})|({_NUM_TEXT})\s+(?:in all|in total|total)\b",+ re.IGNORECASE,+)+_PERCENT_CELL = re.compile(rf"^({_NUM_TEXT})\s?%$")+_COUNT_CELL = re.compile(rf"^({_NUM_TEXT})$")+++def _value(text: str) -> tuple[float, int]:+ raw = text.replace(",", "")+ return float(raw), len(raw.partition(".")[2])+++class _Held:+ """Whether a number the answer writes is one the tool results hold, at its shown precision."""++ def __init__(self, pools: list[_Pool], more: Any) -> None:+ self._pools = pools+ self._more = more # builds the earlier turns' pool on first need++ def __call__(self, text: str) -> bool:+ value, decimals = _value(text)+ reading = _Reading(value, False, decimals, None, 0)+ tolerance = 0.5 * 10.0**-decimals+ if any(_find(pool, reading, tolerance) is not False for pool in self._pools):+ return True+ extra = self._more()+ return extra is not None and _find(extra, reading, tolerance) is not False+++def _close(value: float, shown: float, decimals: int) -> bool:+ return abs(value - shown) <= 0.5 * 10.0**-decimals + 1e-9+++def _clauses(answer: str) -> list[tuple[int, int]]:+ spans, start = [], 0+ for m in _CLAUSE_BREAK.finditer(answer):+ spans.append((start, m.start()))+ start = m.end()+ spans.append((start, len(answer)))+ return spans+++def _derived_spans(answer: str, held: _Held) -> set[int]:+ """Start offsets of figures worked out from held figures the answer states.++ A percentage is derived when its clause writes its two terms next to each+ other ("N of M", "N out of M", "N/M"); a count when its clause writes the+ sum out ("a + b = c", "a + b, c in all"); and a share column of a table+ when at least two of its rows are their count over one total the answer+ names. Every term must be held; no other pairing of numbers counts.+ """+ out: set[int] = set()+ for lo, hi in _clauses(answer):+ clause = answer[lo:hi]+ out.update(lo + at for at in _ratio_spans(clause, held))+ out.update(lo + at for at in _sum_spans(clause, held))+ return out | _table_shares(answer, held)+++def _ratio_spans(clause: str, held: _Held) -> Iterator[int]:+ """Percentages in *clause* that one of its written-out ratios gives."""+ pairs = [+ (_value(m.group(1))[0], _value(m.group(2))[0])+ for m in _PAIR.finditer(clause)+ if held(m.group(1)) and held(m.group(2))+ ]+ if not pairs:+ return+ for m in _NUMBER.finditer(clause):+ if not clause.startswith(("%", " %"), m.end()):+ continue+ shown, decimals = _value(m.group())+ if any(0 < a <= b and _close(100.0 * a / b, shown, decimals) for a, b in pairs):+ yield m.start()+++def _sum_spans(clause: str, held: _Held) -> Iterator[int]:+ """Totals in *clause* whose written-out parts are held and add up to them."""+ for m in _SUM.finditer(clause):+ parts = re.findall(_NUM_TEXT, m.group(1))+ group = 2 if m.group(2) else 3+ total, _ = _value(m.group(group))+ if all(held(p) for p in parts) and sum(_value(p)[0] for p in parts) == total:+ yield m.start(group)+++def _named_totals(answer: str, held: _Held) -> set[float]:+ """Held figures the answer names as a total."""+ return {+ _value(t)[0]+ for m in _TOTAL.finditer(answer)+ if (t := m.group(1) or m.group(2)) and held(t)+ }+++_Row = list[tuple[int, str]]+++def _markdown_tables(answer: str) -> Iterator[list[_Row]]:+ """Each markdown table's rows as ``(offset, text)`` cells, separator rows left out."""+ table: list[_Row] = []+ offset = 0+ for line in answer.split("\n"):+ start, offset = offset, offset + len(line) + 1+ stripped = line.strip()+ if not stripped.startswith("|"):+ if table:+ yield table+ table = []+ continue+ if not set(stripped) <= set("|-: "):+ table.append(_cells(line, start))+ if table:+ yield table+++def _cells(line: str, start: int) -> _Row:+ cells, pos = [], start + line.index("|") + 1+ for cell in line.strip().strip("|").split("|"):+ cells.append((pos + len(cell) - len(cell.lstrip()), cell.strip()))+ pos += len(cell) + 1+ return cells+++def _column_hits(table: list[_Row], total: float, held: _Held) -> dict[int, list[int]]:+ """Per column, the share cells that are their row's count over *total*."""+ hits: dict[int, list[int]] = {}+ for row in table:+ counts = [_value(m.group(1))[0] for _, c in row if (m := _COUNT_CELL.match(c)) and held(c)]+ for col, (at, cell) in enumerate(row):+ if (pm := _PERCENT_CELL.match(cell)) is None:+ continue+ shown, decimals = _value(pm.group(1))+ if any(0 < c <= total and _close(100.0 * c / total, shown, decimals) for c in counts):+ hits.setdefault(col, []).append(at)+ return hits+++def _table_shares(answer: str, held: _Held) -> set[int]:+ """Share cells of markdown tables that are their row's count over a named total."""+ totals = _named_totals(answer, held)+ out: set[int] = set()+ for table in _markdown_tables(answer) if totals else ():+ for total in totals:+ # One row agreeing with a total is a coincidence a small table makes easily.+ for starts in _column_hits(table, total, held).values():+ if len(starts) >= 2:+ out.update(starts)+ return out++def _utf16_offsets(text: str) -> list[int] | None:"""Code-point index -> UTF-16 offset, or None when every character is in the BMP."""if all(ord(ch) < 0x10000 for ch in text):@@ -420,6 +602,50 @@ def _utf16_offsets(text: str) -> list[int] | None:return offsets+def _candidates(answer: str, question: str) -> list[tuple[int, _Reading]]:+ """The answer's figures: numbers that are not labels, code or the question's own."""+ asked = {abs(_read(question, m).value) for m in _NUMBER.finditer(question)}+ masks = _masked(answer)+ out: list[tuple[int, _Reading]] = []+ skipped_end = -1+ for match in _NUMBER.finditer(answer):+ start = match.start()+ reading = _read(answer, match)+ if _inside(masks, start, match.end()) or _not_a_figure(answer, start, reading, skipped_end):+ skipped_end = match.end()+ continue+ if abs(reading.value) not in asked:+ out.append((start, reading))+ return out+++class _Lookup:+ """This turn's evidence, then earlier turns' read only on first need."""++ def __init__(self, sources: Iterable[Any], earlier: Iterable[Any], expand: bool) -> None:+ self._budget = _Budget()+ self._expand = expand+ self._earlier_sources = list(earlier)+ self.pools = [_pool(sources, self._budget, expand)]++ def earlier(self) -> _Pool | None:+ if not self._earlier_sources:+ return None+ if len(self.pools) == 1:+ self.pools.append(_pool(self._earlier_sources, self._budget, self._expand))+ return self.pools[1]++ def find(self, reading: _Reading, tolerance: float) -> str | None | bool:+ found = _find(self.pools[0], reading, tolerance)+ if found is False and (extra := self.earlier()) is not None:+ found = _find(extra, reading, tolerance)+ return found++ @property+ def truncated(self) -> bool:+ return any(pool.truncated for pool in self.pools)++def check_figures(answer: str,sources: Iterable[tuple[str | None, Any]],@@ -436,37 +662,22 @@ def check_figures(check = FigureCheck()if not answer or not any(ch.isdigit() for ch in answer):return check- asked = {abs(_read(question, m).value) for m in _NUMBER.finditer(question)}- masks = _masked(answer)-- candidates: list[tuple[int, _Reading]] = []- skipped_end = -1- for match in _NUMBER.finditer(answer):- start = match.start()- reading = _read(answer, match)- if _inside(masks, start, match.end()) or _not_a_figure(- answer, start, reading, skipped_end- ):- skipped_end = match.end()- continue- if abs(reading.value) not in asked:- candidates.append((start, reading))+ candidates = _candidates(answer, question)if not candidates:return check- budget = _Budget()- expand = any(reading.unit is None for _, reading in candidates)- pools = [_pool(sources, budget, expand)]- earlier_sources = list(earlier)+ lookup = _Lookup(sources, earlier, expand=any(r.unit is None for _, r in candidates))+ looked = [+ (start, reading, lookup.find(reading, _tolerance(answer, start, reading)))+ for start, reading in candidates+ ]+ derivable: set[int] = set()+ if any(found is False for _, _, found in looked):+ derivable = _derived_spans(answer, _Held(lookup.pools[:1], lookup.earlier))utf16 = _utf16_offsets(answer)- for start, reading in candidates:- tolerance = _tolerance(answer, start, reading)- found = _find(pools[0], reading, tolerance)- if found is False and earlier_sources:- if len(pools) == 1:- pools.append(_pool(earlier_sources, budget, expand))- found = _find(pools[1], reading, tolerance)- if found is False and any(pool.truncated for pool in pools):+ for start, reading, found in looked:+ derived = found is False and not reading.signed and start in derivable+ if found is False and not derived and lookup.truncated:check.not_checked += 1continueend = reading.text_end@@ -475,8 +686,9 @@ def check_figures(text=answer[start:end],start=utf16[start] if utf16 else start,end=utf16[end] if utf16 else end,- verified=found is not False,+ verified=found is not False or derived,artifact_id=found if isinstance(found, str) else None,+ derived=derived,))return checkdiff --git a/packages/server/src/repowise/server/routers/changes.py b/packages/server/src/repowise/server/routers/changes.pyindex 8c45d1ccf..d3f1558af 100644--- a/packages/server/src/repowise/server/routers/changes.py+++ b/packages/server/src/repowise/server/routers/changes.py@@ -23,7 +23,7 @@ from repowise.core.changes.collect import (save_evidence,with_item,)-from repowise.core.changes.evidence import ChangeEvidence+from repowise.core.changes.evidence import ChangeEvidence, item_linefrom repowise.core.changes.record import change_recordfrom repowise.core.persistence import crudfrom repowise.core.persistence.database import get_session@@ -144,7 +144,10 @@ async def get_change(except TimeoutError:record["evidence_building"] = Trueif kept is not None:- record["evidence"] = kept.to_dict()+ wire = kept.to_dict()+ for item in wire["items"]:+ item["line"] = item_line(item)+ record["evidence"] = wirereturn ChangeRecord(**record, commit_count=len(record["commits"]))diff --git a/packages/server/src/repowise/server/routers/events.py b/packages/server/src/repowise/server/routers/events.pyindex b03ec14db..4792029a3 100644--- a/packages/server/src/repowise/server/routers/events.py+++ b/packages/server/src/repowise/server/routers/events.py@@ -8,7 +8,7 @@ from fastapi import APIRouter, Depends, HTTPException, Queryfrom sqlalchemy.ext.asyncio import AsyncSessionfrom repowise.core.events.model import KINDS, to_cloudevent-from repowise.core.events.store import list_events+from repowise.core.events.store import empty_events_reason, list_events, snapshot_run_countfrom repowise.core.persistence import crudfrom repowise.server.deps import get_db_session, verify_api_keyfrom repowise.server.schemas.events import CloudEvent, EventListResponse@@ -37,4 +37,11 @@ async def get_events(if since is not None and since.tzinfo is None:since = since.replace(tzinfo=UTC)events = await list_events(session, repo_id, since=since, kinds=kind, limit=limit)- return EventListResponse(events=[CloudEvent(**to_cloudevent(e)) for e in events])+ runs = await snapshot_run_count(session, repo_id)+ reason = None if events else empty_events_reason(runs, filtered=bool(since or kind))+ return EventListResponse(+ events=[CloudEvent(**to_cloudevent(e)) for e in events],+ snapshot_runs=runs,+ empty_reason=reason[0] if reason else None,+ empty_note=reason[1] if reason else None,+ )diff --git a/packages/server/src/repowise/server/routers/owners.py b/packages/server/src/repowise/server/routers/owners.pyindex 7495a3fd2..1061919fc 100644--- a/packages/server/src/repowise/server/routers/owners.py+++ b/packages/server/src/repowise/server/routers/owners.py@@ -51,6 +51,7 @@ def _to_list_entry(acc: _OwnerAccumulator, module_totals: dict[str, int]) -> Owndead_code_files_owned=len(acc.dead_code_files),dead_code_lines_owned=acc.dead_code_lines,commit_count_90d=acc.commit_count_90d,+ commit_count_90d_at_least=acc.commit_count_90d_at_least,last_commit_at=acc.last_commit_at,bus_factor_risk_files=acc.bus_factor_risk_files,)@@ -120,6 +121,7 @@ def _to_profile(acc: _OwnerAccumulator, module_totals: dict[str, int]) -> OwnerPdead_code_files_owned=len(acc.dead_code_files),dead_code_lines_owned=acc.dead_code_lines,commit_count_90d=acc.commit_count_90d,+ commit_count_90d_at_least=acc.commit_count_90d_at_least,last_commit_at=acc.last_commit_at,first_commit_at=acc.first_commit_at,bus_factor_risk_files=acc.bus_factor_risk_files,diff --git a/packages/server/src/repowise/server/schemas/changes.py b/packages/server/src/repowise/server/schemas/changes.pyindex 7eb16b305..ac31baddd 100644--- a/packages/server/src/repowise/server/schemas/changes.py+++ b/packages/server/src/repowise/server/schemas/changes.py@@ -70,6 +70,13 @@ class ChangeSummary(BaseModel):provenance: ChangeProvenance | None = None+class EvidenceLine(BaseModel):+ """An item's value as a message key and its parameters, for a client to word."""++ key: str+ params: dict[str, Any]++class EvidenceItem(BaseModel):"""One checklist row: what was found, whether it needs a look, how it is known."""@@ -80,6 +87,8 @@ class EvidenceItem(BaseModel):value: Any = Nonedetails: list[dict[str, Any]]source: str+ #: ``value`` for a reader (``repowise.core.changes.evidence.item_line``).+ line: EvidenceLine | None = Noneclass ChangeEvidence(BaseModel):diff --git a/packages/server/src/repowise/server/schemas/chat.py b/packages/server/src/repowise/server/schemas/chat.pyindex a561c7a69..c3878b9cb 100644--- a/packages/server/src/repowise/server/schemas/chat.py+++ b/packages/server/src/repowise/server/schemas/chat.py@@ -261,6 +261,8 @@ class ChatFigure(BaseModel):end: intverified: boolartifact_id: str | None = None+ #: Worked out from the answer's matched figures (a ratio or a sum), not read in a result.+ derived: bool = Falseclass ChatTurnResultResponse(BaseModel):diff --git a/packages/server/src/repowise/server/schemas/events.py b/packages/server/src/repowise/server/schemas/events.pyindex 954201eed..ce98c93d8 100644--- a/packages/server/src/repowise/server/schemas/events.py+++ b/packages/server/src/repowise/server/schemas/events.py@@ -7,7 +7,7 @@ stamp, and ``evidence`` with the figures that moved.from __future__ import annotations-from typing import Any+from typing import Any, Literalfrom pydantic import BaseModel@@ -26,3 +26,10 @@ class CloudEvent(BaseModel):class EventListResponse(BaseModel):events: list[CloudEvent]+ #: Component snapshots stored; events need two consecutive ones.+ snapshot_runs: int = 0+ #: Why ``events`` is empty (``repowise.core.events.store.empty_events_reason``);+ #: ``None`` when it is not.+ empty_reason: Literal["baseline_only", "no_match", "nothing_moved"] | None = None+ #: The same reason as a sentence, as ``repowise events`` prints it.+ empty_note: str | None = Nonediff --git a/packages/server/src/repowise/server/schemas/ownership.py b/packages/server/src/repowise/server/schemas/ownership.pyindex f042e6247..dd1e32cbd 100644--- a/packages/server/src/repowise/server/schemas/ownership.py+++ b/packages/server/src/repowise/server/schemas/ownership.py@@ -46,6 +46,8 @@ class OwnerListEntry(BaseModel):# Distinct commits by this person in the 90 days before HEAD; None when the# indexed commits do not cover the window.commit_count_90d: int | None+ # A floor of that count when the indexed commits stop inside the window.+ commit_count_90d_at_least: int | None = Nonelast_commit_at: datetime | Nonebus_factor_risk_files: int # files they own where bus_factor <= 1@@ -86,6 +88,7 @@ class OwnerProfileResponse(BaseModel):dead_code_files_owned: intdead_code_lines_owned: intcommit_count_90d: int | None+ commit_count_90d_at_least: int | None = Nonelast_commit_at: datetime | Nonefirst_commit_at: datetime | Nonebus_factor_risk_files: intdiff --git a/packages/types/src/chat.ts b/packages/types/src/chat.tsindex 3fb500551..703b9b324 100644--- a/packages/types/src/chat.ts+++ b/packages/types/src/chat.ts@@ -148,6 +148,8 @@ export interface ChatMessage {diagnostics?: {figures_checked?: number;figures_unverified?: number;+ /** Verified figures worked out from others (a ratio or a sum) rather than read. */+ figures_derived?: number;/** Figures left unchecked because the evidence was past the read cap. */figures_not_checked?: number;};diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.tsindex 61c2c4e1e..5c463f49c 100644--- a/packages/types/src/generated/http.ts+++ b/packages/types/src/generated/http.ts@@ -547,6 +547,7 @@ export interface ChatFigure {end: number;verified: boolean;artifact_id?: string | null;+ derived?: boolean;}export interface ChatMessageResponse {@@ -1598,6 +1599,9 @@ export interface EpisodeSummary {export interface EventListResponse {events: CloudEvent[];+ snapshot_runs?: number;+ empty_reason?: "baseline_only" | "no_match" | "nothing_moved" | null;+ empty_note?: string | null;}/** One checklist row: what was found, whether it needs a look, how it is known. */@@ -1609,6 +1613,13 @@ export interface EvidenceItem {value?: unknown;details: Record<string, unknown>[];source: string;+ line?: EvidenceLine | null;+}++/** An item's value as a message key and its parameters, for a client to word. */+export interface EvidenceLine {+ key: string;+ params: Record<string, unknown>;}/** The top-ranked evidence row, slimmed for list rows. */@@ -2600,6 +2611,7 @@ export interface OwnerListEntry {dead_code_files_owned: number;dead_code_lines_owned: number;commit_count_90d: number | null;+ commit_count_90d_at_least?: number | null;last_commit_at: string | null;bus_factor_risk_files: number;}@@ -2621,6 +2633,7 @@ export interface OwnerProfileResponse {dead_code_files_owned: number;dead_code_lines_owned: number;commit_count_90d: number | null;+ commit_count_90d_at_least?: number | null;last_commit_at: string | null;first_commit_at: string | null;bus_factor_risk_files: number;diff --git a/packages/types/src/owners.ts b/packages/types/src/owners.tsindex 7ac0778ab..6f0a9090c 100644--- a/packages/types/src/owners.ts+++ b/packages/types/src/owners.ts@@ -15,6 +15,8 @@ export interface OwnerListEntry {dead_code_lines_owned: number;/** Distinct commits in the 90 days before HEAD; null when the indexed commits do not cover the window. */commit_count_90d: number | null;+ /** A floor of that count when the indexed commits stop inside the window; null otherwise. */+ commit_count_90d_at_least?: number | null;last_commit_at: string | null;bus_factor_risk_files: number;}@@ -57,6 +59,8 @@ export interface OwnerProfile {dead_code_lines_owned: number;/** Distinct commits in the 90 days before HEAD; null when the indexed commits do not cover the window. */commit_count_90d: number | null;+ /** A floor of that count when the indexed commits stop inside the window; null otherwise. */+ commit_count_90d_at_least?: number | null;last_commit_at: string | null;first_commit_at: string | null;bus_factor_risk_files: number;diff --git a/packages/ui/__tests__/owners/owner-table.test.tsx b/packages/ui/__tests__/owners/owner-table.test.tsxnew file mode 100644index 000000000..30e16279b--- /dev/null+++ b/packages/ui/__tests__/owners/owner-table.test.tsx@@ -0,0 +1,40 @@+import { describe, it, expect } from "vitest";+import { render, screen } from "@testing-library/react";+import type { OwnerListEntry } from "@repowise-dev/types/owners";++import { OwnerTable } from "../../src/owners/owner-table";++const owner = (name: string, over: Partial<OwnerListEntry>): OwnerListEntry => ({+ key: name,+ name,+ email: null,+ files_owned: 3,+ hotspots_owned: 0,+ silo_modules: 0,+ dead_code_files_owned: 0,+ dead_code_lines_owned: 0,+ commit_count_90d: null,+ last_commit_at: null,+ bus_factor_risk_files: 0,+ ...over,+});++describe("OwnerTable commits 90d", () => {+ it("shows a floor when the indexed commits stop inside the window", () => {+ render(+ <OwnerTable+ sort="files_owned"+ owners={[+ owner("Ann", { commit_count_90d_at_least: 312 }),+ owner("Bea", { commit_count_90d: 7 }),+ owner("Cy", {}),+ ]}+ />,+ );+ const floor = screen.getByText("≥312");+ expect(floor.getAttribute("title")).toMatch(/stop inside the 90 days/);+ expect(screen.getByText("7")).toBeTruthy();+ // Unknown with no floor stays unknown, never zero.+ expect(screen.getAllByText("—").length).toBeGreaterThan(0);+ });+});diff --git a/packages/ui/src/owners/owner-directory.tsx b/packages/ui/src/owners/owner-directory.tsxindex fe2bcdaa2..6081b39f7 100644--- a/packages/ui/src/owners/owner-directory.tsx+++ b/packages/ui/src/owners/owner-directory.tsx@@ -106,11 +106,17 @@ export function OwnerDirectory({? sorted.filter((o) => (o.commit_count_90d ?? 0) > 0).length: null;const hotspots = sorted.reduce((s, o) => s + o.hotspots_owned, 0);- const commits90d = sorted.reduce((s, o) => s + (o.commit_count_90d ?? 0), 0);+ const commits90d = sorted.reduce(+ (s, o) => s + (o.commit_count_90d ?? o.commit_count_90d_at_least ?? 0),+ 0,+ );+ // Any floor makes the total a floor too.+ const commits90dFloor = sorted.some((o) => o.commit_count_90d == null && o.commit_count_90d_at_least);return {deadFiles,hotspots,commits90d,+ commits90dFloor,topName: sorted[0]?.name ?? null,topFiles: sorted[0]?.files_owned ?? 0,totalFiles,@@ -198,7 +204,10 @@ export function OwnerDirectory({},{label: "Commits 90d",- value: summary.commits90d > 0 ? summary.commits90d.toLocaleString() : "",+ value:+ summary.commits90d > 0+ ? `${summary.commits90dFloor ? "≥" : ""}${summary.commits90d.toLocaleString()}`+ : "",},{label: "Dead-code files",diff --git a/packages/ui/src/owners/owner-profile.tsx b/packages/ui/src/owners/owner-profile.tsxindex f412c88d8..401191efb 100644--- a/packages/ui/src/owners/owner-profile.tsx+++ b/packages/ui/src/owners/owner-profile.tsx@@ -143,7 +143,13 @@ export function OwnerProfileView({// exact six-digit figure would claim a precision the number does not have.const ribbon: RibbonStat[] = [// Null when the indexed commits do not reach back 90 days: not a zero.- { label: "Commits, 90d", value: owner.commit_count_90d?.toLocaleString() ?? "—" },+ {+ label: "Commits, 90d",+ // A floor when the indexed commits stop inside the window.+ value:+ owner.commit_count_90d?.toLocaleString() ??+ (owner.commit_count_90d_at_least ? `≥${owner.commit_count_90d_at_least.toLocaleString()}` : "—"),+ },{label: "Lines added",value: formatCompact(owner.lines_added_90d_est),diff --git a/packages/ui/src/owners/owner-table.tsx b/packages/ui/src/owners/owner-table.tsxindex 7a24d7fa9..e5142c431 100644--- a/packages/ui/src/owners/owner-table.tsx+++ b/packages/ui/src/owners/owner-table.tsx@@ -166,7 +166,11 @@ export function OwnerTable({markerTitle="Sole-owned files held by someone inactive for 90 days"/><Num value={o.dead_code_lines_owned} />- <Num value={o.commit_count_90d} />+ <Num+ value={o.commit_count_90d}+ atLeast={o.commit_count_90d_at_least}+ atLeastTitle="At least this many: the indexed commits stop inside the 90 days"+ /><td className="whitespace-nowrap py-2.5 pl-3 align-top text-[var(--color-text-tertiary)]">{formatRelativeTimeOrNull(o.last_commit_at) ?? "—"}</td>@@ -184,11 +188,16 @@ function Num({emphasis,marker,markerTitle,+ atLeast,+ atLeastTitle,}: {value: number | null;emphasis?: boolean;marker?: boolean;markerTitle?: string;+ /** A floor shown as "≥N" when `value` is unknown. */+ atLeast?: number | null | undefined;+ atLeastTitle?: string;}) {return (<td@@ -196,7 +205,13 @@ function Num({emphasis ? "font-semibold text-[var(--color-text-primary)]" : ""}`}>- {value != null && value > 0 ? value.toLocaleString() : <span className="text-[var(--color-text-tertiary)]">—</span>}+ {value != null && value > 0 ? (+ value.toLocaleString()+ ) : value == null && atLeast ? (+ <span title={atLeastTitle}>≥{atLeast.toLocaleString()}</span>+ ) : (+ <span className="text-[var(--color-text-tertiary)]">—</span>+ )}{marker && (<spantitle={markerTitle}diff --git a/packages/web/messages/en.json b/packages/web/messages/en.jsonindex d044ddced..4442a3558 100644--- a/packages/web/messages/en.json+++ b/packages/web/messages/en.json@@ -116,7 +116,8 @@"contracts": "Contracts","coChanges": "Co-Changes","groupPeopleAndHistory": "People & History",- "groupSettings": "Settings"+ "groupSettings": "Settings",+ "events": "Events"},"breadcrumb": {"overview": "Overview",@@ -147,7 +148,8 @@"settings": "Settings","knowledgeGraph": "Knowledge Graph","zoom": "Zoom Map",- "files": "Files"+ "files": "Files",+ "events": "Events"},"errors": {"workspaceErrorTitle": "Failed to load the workspace",@@ -317,6 +319,45 @@"deps": "deps","chore": "chore","other": "other"+ },+ "evidenceKinds": {+ "components_touched": "Components touched",+ "owners": "Declared owners",+ "suggested_reviewers": "Suggested reviewers",+ "reaching_tests": "Tests reaching the change",+ "contracts": "Contracts touched",+ "cross_repo_consumers": "Consumers in other repos",+ "decisions_crossed": "Decisions crossed",+ "health_delta": "Health delta",+ "provenance": "AI provenance",+ "risk_score": "Diff size rank",+ "outcomes": "Outcomes since merge"+ },+ "evidenceBasis": {+ "measured": "measured",+ "inferred": "inferred",+ "declared": "declared",+ "unresolved": "not known"+ },+ "evidenceLine": {+ "unknown": "Not known: {reason}",+ "unknownBare": "Not known",+ "components_touched": "{count, plural, one {# component} other {# components}}: {names}{more, plural, =0 {} other { and # more}}",+ "suggested_reviewers": "{names}{more, plural, =0 {} other { and # more}}",+ "owners": "{count, plural, =0 {No declared owner} other {{names}{more, plural, =0 {} other { and # more}}}}{unowned, plural, =0 {} one {; # changed file without one} other {; # changed files without one}}",+ "reaching_tests": "{files, plural, =0 {No changed source file} one {{reached} of # changed file reached by a test} other {{reached} of # changed files reached by a test}}{absent, plural, =0 {} other {; # with none}}{unknown, plural, =0 {} other {; # not known}}",+ "contracts": "{touched, plural, =0 {No workspace contract touched} one {# workspace contract touched} other {# workspace contracts touched}}; {breaking, plural, =0 {no breaking signature change} one {# breaking signature change} other {# breaking signature changes}}",+ "contracts_unchecked": "{touched, plural, =0 {No workspace contract touched} one {# workspace contract touched} other {# workspace contracts touched}}; signatures not compared",+ "cross_repo_consumers": "{links, plural, =0 {No consumer in another repo} one {# consumer in {names}{more, plural, =0 {} other { and # more}}} other {# consumers in {names}{more, plural, =0 {} other { and # more}}}}",+ "decisions_crossed": "{accepted, plural, one {# accepted decision} other {# accepted decisions}}, {candidate, plural, one {# candidate} other {# candidates}}",+ "decisions_none": "No decision crossed",+ "health_delta": "Findings: {introduced} introduced, {worsened} worsened, {resolved} resolved",+ "health_delta_partial": "Findings: {introduced} introduced, {worsened} worsened, {resolved} resolved (partial comparison)",+ "provenance": "provenance: {label}, known for {known} of {commits, plural, one {# commit} other {# commits}}",+ "provenance_named": "provenance: {label}, known for {known} of {commits, plural, one {# commit} other {# commits}} ({names})",+ "risk_score": "Larger than {percentile}% of recent commits",+ "outcomes": "{reverts, plural, one {# revert} other {# reverts}}, {references, plural, one {# cause reference} other {# cause references}}",+ "outcomes_rate": "{reverts, plural, one {# revert} other {# reverts}}, {references, plural, one {# cause reference} other {# cause references}}; {fixed} of {files, plural, one {# file} other {# files}} fixed within {days} days"}},"architecture": {@@ -534,6 +575,37 @@"breadcrumb": "Code Health","notFoundTitle": "Module not found","notFoundDescription": "The requested module path doesn't exist in this repository's index."+ },+ "events": {+ "title": "Events",+ "description": "What moved between two index runs in a row: owners, bus factor, hotspots, contracts, decisions, dead code, test reach and attribution, per component.",+ "repository": "Whole repository",+ "count": "{count, plural, one {# event} other {# events}}, newest first.",+ "emptyTitle": "No events yet",+ "baselineOnly": "{runs, plural, =0 {No component snapshot is stored yet.} one {One component snapshot is stored, the baseline.} other {# component snapshots are stored.}} Events are what moved between two index runs in a row, so they start after the next `repowise update` on a new commit.",+ "nothingMoved": "Nothing crossed a threshold across {runs} stored component snapshots.",+ "noMatch": "No event matches these filters across {runs} stored component snapshots.",+ "loadErrorTitle": "Could not load events",+ "loadErrorBody": "The event list could not be read from the server. Reload the page to try again.",+ "kinds": {+ "ownership_shift": "Declared owner changed",+ "owner_inactive": "Main owners stopped changing it",+ "bus_factor_drop": "Bus factor fell",+ "new_hotspot": "Files became hotspots",+ "contract_added": "Provided contract appeared",+ "contract_broken": "Contract with consumers disappeared",+ "decision_stale": "Governing decision went stale",+ "dead_code_growth": "Dead-code findings grew",+ "test_reach_drop": "Test reach fell",+ "attribution_jump": "Agent share moved sharply"+ },+ "severities": {+ "critical": "critical",+ "high": "high",+ "medium": "medium",+ "low": "low",+ "info": "info"+ }}},"settings": {diff --git a/packages/web/messages/zh-CN.json b/packages/web/messages/zh-CN.jsonindex 07c7f0efd..d9c0be4cd 100644--- a/packages/web/messages/zh-CN.json+++ b/packages/web/messages/zh-CN.json@@ -116,7 +116,8 @@"contracts": "契约","coChanges": "共变分析","groupPeopleAndHistory": "人员与历史",- "groupSettings": "设置"+ "groupSettings": "设置",+ "events": "事件"},"breadcrumb": {"overview": "概览",@@ -147,7 +148,8 @@"settings": "设置","knowledgeGraph": "知识图谱","zoom": "缩放地图",- "files": "文件"+ "files": "文件",+ "events": "事件"},"errors": {"workspaceErrorTitle": "无法加载工作区",@@ -317,6 +319,45 @@"deps": "依赖","chore": "杂务","other": "其他"+ },+ "evidenceKinds": {+ "components_touched": "涉及的组件",+ "owners": "声明的负责人",+ "suggested_reviewers": "建议的评审人",+ "reaching_tests": "覆盖此变更的测试",+ "contracts": "涉及的契约",+ "cross_repo_consumers": "其他仓库中的使用方",+ "decisions_crossed": "涉及的决策",+ "health_delta": "健康度变化",+ "provenance": "AI 来源",+ "risk_score": "差异规模排名",+ "outcomes": "合并后的结果"+ },+ "evidenceBasis": {+ "measured": "实测",+ "inferred": "推断",+ "declared": "声明",+ "unresolved": "未知"+ },+ "evidenceLine": {+ "unknown": "未知:{reason}",+ "unknownBare": "未知",+ "components_touched": "{count} 个组件:{names}{more, plural, =0 {} other {等另外 # 个}}",+ "suggested_reviewers": "{names}{more, plural, =0 {} other {等另外 # 人}}",+ "owners": "{count, plural, =0 {无声明的负责人} other {{names}{more, plural, =0 {} other {等另外 # 个}}}}{unowned, plural, =0 {} other {;# 个变更文件无负责人}}",+ "reaching_tests": "{files, plural, =0 {没有变更的源文件} other {# 个变更文件中有 {reached} 个被测试覆盖}}{absent, plural, =0 {} other {;# 个没有测试}}{unknown, plural, =0 {} other {;# 个未知}}",+ "contracts": "{touched, plural, =0 {未涉及工作区契约} other {涉及 # 个工作区契约}};{breaking, plural, =0 {无破坏性签名变更} other {# 个破坏性签名变更}}",+ "contracts_unchecked": "{touched, plural, =0 {未涉及工作区契约} other {涉及 # 个工作区契约}};未比较签名",+ "cross_repo_consumers": "{links, plural, =0 {其他仓库中没有使用方} other {# 个使用方,位于 {names}{more, plural, =0 {} other {等另外 # 个仓库}}}}",+ "decisions_crossed": "{accepted} 个已接受的决策,{candidate} 个候选决策",+ "decisions_none": "未涉及决策",+ "health_delta": "发现:新增 {introduced},恶化 {worsened},解决 {resolved}",+ "health_delta_partial": "发现:新增 {introduced},恶化 {worsened},解决 {resolved}(部分比较)",+ "provenance": "来源:{label},{commits} 个提交中已知 {known} 个",+ "provenance_named": "来源:{label},{commits} 个提交中已知 {known} 个({names})",+ "risk_score": "大于 {percentile}% 的近期提交",+ "outcomes": "{reverts} 次回滚,{references} 次被引为原因",+ "outcomes_rate": "{reverts} 次回滚,{references} 次被引为原因;{files} 个文件中有 {fixed} 个在 {days} 天内被修复"}},"architecture": {@@ -534,6 +575,37 @@"breadcrumb": "代码健康度","notFoundTitle": "未找到模块","notFoundDescription": "该仓库的索引中不存在请求的模块路径。"+ },+ "events": {+ "title": "事件",+ "description": "相邻两次索引之间发生的变化:按组件列出负责人、巴士系数、热点、契约、决策、死代码、测试覆盖与来源归属。",+ "repository": "整个仓库",+ "count": "共 {count} 个事件,按时间从新到旧。",+ "emptyTitle": "暂无事件",+ "baselineOnly": "{runs, plural, =0 {尚未存储组件快照。} =1 {已存储 1 个组件快照,作为基线。} other {已存储 # 个组件快照。}}事件是相邻两次索引之间的变化,因此会在下一次针对新提交运行 `repowise update` 之后开始出现。",+ "nothingMoved": "在已存储的 {runs} 个组件快照中,没有任何指标越过阈值。",+ "noMatch": "在已存储的 {runs} 个组件快照中,没有符合这些筛选条件的事件。",+ "loadErrorTitle": "无法加载事件",+ "loadErrorBody": "无法从服务器读取事件列表。请刷新页面重试。",+ "kinds": {+ "ownership_shift": "声明的负责人已变更",+ "owner_inactive": "主要负责人不再修改它",+ "bus_factor_drop": "巴士系数下降",+ "new_hotspot": "文件成为热点",+ "contract_added": "出现新的提供方契约",+ "contract_broken": "有使用方的契约消失",+ "decision_stale": "治理决策已过时",+ "dead_code_growth": "死代码发现增多",+ "test_reach_drop": "测试覆盖下降",+ "attribution_jump": "智能体占比大幅变化"+ },+ "severities": {+ "critical": "严重",+ "high": "高",+ "medium": "中",+ "low": "低",+ "info": "信息"+ }}},"settings": {diff --git a/packages/web/src/app/repos/[id]/changes/[changeId]/page.tsx b/packages/web/src/app/repos/[id]/changes/[changeId]/page.tsxindex c3601bb36..817f6512d 100644--- a/packages/web/src/app/repos/[id]/changes/[changeId]/page.tsx+++ b/packages/web/src/app/repos/[id]/changes/[changeId]/page.tsx@@ -9,7 +9,7 @@ import { OverviewSection } from "@repowise-dev/ui/overview";import { formatDate } from "@repowise-dev/ui/lib/format";import { Badge } from "@repowise-dev/ui/ui/badge";import type { EvidenceItem } from "@repowise-dev/types/changes";-import { changeLabel, commitsViewHref } from "@/lib/changes";+import { changeLabel, commitsViewHref, evidenceValueText, evidenceWord } from "@/lib/changes";import { getChange } from "@/lib/api/changes";interface Props {@@ -29,30 +29,13 @@ export async function generateMetadata({ params }: Props): Promise<Metadata> {const STATUS_VARIANT = { ok: "fresh", attention: "stale", unknown: "outline" } as const;const STATUS_KEY = { ok: "statusOk", attention: "statusAttention", unknown: "statusUnknown" } as const;-/** An item's value in one line; an unknown one shows why. */-function valueText(item: EvidenceItem): string {- const value = item.value;- if (value == null) {- const reason = item.details.find((d) => typeof d.reason === "string")?.reason;- return typeof reason === "string" ? reason : "";- }- if (Array.isArray(value)) return value.join(", ");- if (typeof value === "object") {- return Object.entries(value as Record<string, unknown>)- .filter(([, v]) => v != null && !(Array.isArray(v) && v.length === 0))- .map(([k, v]) => `${k.replaceAll("_", " ")} ${Array.isArray(v) ? v.join(", ") : String(v)}`)- .join(" · ");- }- return String(value);-}-type Row = Record<string, unknown>;/** What later history says about the change, in the later commits' own words. */async function Outcomes({ item, repoId }: { item: EvidenceItem; repoId: string }) {const t = await getTranslations("views.changes");if (item.status === "unknown") {- return <p className="text-xs text-[var(--color-text-tertiary)]">{valueText(item)}</p>;+ return <p className="text-xs text-[var(--color-text-tertiary)]">{evidenceValueText(t, item)}</p>;}const rows = item.details as Row[];const links = rows.filter((r) => r.kind === "revert" || r.kind === "fix_reference");@@ -141,12 +124,14 @@ async function EvidenceSections({ repoId, changeId }: { repoId: string; changeId.map((item) => (<li key={item.kind} className="flex flex-wrap items-baseline gap-x-3 gap-y-1 py-2"><span className="w-full shrink-0 font-medium text-[var(--color-text-primary)] sm:w-48">- {item.label}+ {evidenceWord(t, `evidenceKinds.${item.kind}`, item.label)}</span><Badge variant={STATUS_VARIANT[item.status]}>{t(STATUS_KEY[item.status])}</Badge>- <span className="text-[var(--color-text-tertiary)]">{item.basis}</span>+ <span className="text-[var(--color-text-tertiary)]">+ {evidenceWord(t, `evidenceBasis.${item.basis}`, item.basis)}+ </span><span className="min-w-[10rem] flex-1 break-words text-[var(--color-text-secondary)]">- {valueText(item)}+ {evidenceValueText(t, item)}</span></li>))}diff --git a/packages/web/src/app/repos/[id]/events/page.test.tsx b/packages/web/src/app/repos/[id]/events/page.test.tsxnew file mode 100644index 000000000..22ded0b39--- /dev/null+++ b/packages/web/src/app/repos/[id]/events/page.test.tsx@@ -0,0 +1,73 @@+// @vitest-environment jsdom++import { cleanup, render, screen } from "@testing-library/react";+import { createTranslator } from "next-intl";+import { afterEach, describe, expect, it, vi } from "vitest";+import messages from "../../../../../messages/en.json";+import type { CloudEvent, EventListResponse } from "@/lib/api/events";+import { repoNavItems } from "@/components/layout/nav-items";++const listEvents = vi.fn();+vi.mock("@/lib/api/events", () => ({ listEvents: (...a: unknown[]) => listEvents(...a) }));+vi.mock("next-intl/server", () => ({+ getTranslations: async (namespace: string) =>+ createTranslator({ locale: "en", messages, namespace: namespace as never }),+}));++import EventsPage from "./page";++function event(id: string, kind: string, time: string, component?: string): CloudEvent {+ return {+ specversion: "1.0",+ id,+ source: "/repos/r1",+ type: `dev.repowise.${kind}.0.1.0`,+ time,+ datacontenttype: "application/json",+ subject: component ? `component:${component}` : null,+ data: {+ "repowise.kind": kind,+ "repowise.severity": "high",+ ...(component ? { "repowise.component": component } : {}),+ },+ };+}++async function show(reply: EventListResponse) {+ listEvents.mockResolvedValue(reply);+ render(await EventsPage({ params: Promise.resolve({ id: "r1" }) }));+}++afterEach(() => {+ cleanup();+ listEvents.mockReset();+});++describe("/repos/[id]/events", () => {+ it("lists events newest first with kind, component and severity in words", async () => {+ await show({+ events: [+ event("1", "new_hotspot", "2026-10-01T00:00:00Z", "core"),+ event("2", "bus_factor_drop", "2026-10-02T00:00:00Z"),+ ],+ snapshot_runs: 3,+ });+ const rows = screen.getAllByRole("listitem").map((li) => li.textContent);+ expect(rows[0]).toContain("Bus factor fell");+ expect(rows[0]).toContain("Whole repository");+ expect(rows[1]).toContain("Files became hotspots");+ expect(rows[1]).toContain("core");+ expect(rows[1]).toContain("high");+ expect(rows.join(" ")).not.toMatch(/new_hotspot|repowise\./);+ });++ it("says why an empty list is empty", async () => {+ await show({ events: [], snapshot_runs: 1, empty_reason: "baseline_only" });+ expect(screen.getByText(/One component snapshot is stored, the baseline/)).toBeTruthy();+ expect(screen.getByText(/start after the next `repowise update` on a new commit/)).toBeTruthy();+ });++ it("is reachable from the repo navigation", () => {+ expect(repoNavItems("r1").map((i) => i.href)).toContain("/repos/r1/events");+ });+});diff --git a/packages/web/src/app/repos/[id]/events/page.tsx b/packages/web/src/app/repos/[id]/events/page.tsxnew file mode 100644index 000000000..1e8d02e53--- /dev/null+++ b/packages/web/src/app/repos/[id]/events/page.tsx@@ -0,0 +1,81 @@+import type { Metadata } from "next";+import { History } from "lucide-react";+import { getTranslations } from "next-intl/server";+import { PageShell } from "@repowise-dev/ui/shared/page-shell";+import { ApiError } from "@repowise-dev/ui/shared/api-error";+import { EmptyState } from "@repowise-dev/ui/shared/empty-state";+import { formatDate } from "@repowise-dev/ui/lib/format";+import { Badge } from "@repowise-dev/ui/ui/badge";+import { listEvents, type CloudEvent } from "@/lib/api/events";+import { evidenceWord, type ChangesTranslator } from "@/lib/changes";++export const metadata: Metadata = { title: "Events" };++const SEVERITY_VARIANT: Record<string, "stale" | "outline"> = {+ critical: "stale",+ high: "stale",+};++function field(event: CloudEvent, key: string): string {+ const value = event.data[key];+ return typeof value === "string" ? value : "";+}++/**+ * Typed events between consecutive index runs, newest first. An empty list+ * says why (the server's `empty_reason`), so a baseline-only index never reads+ * as a quiet one.+ */+export default async function EventsPage({ params }: { params: Promise<{ id: string }> }) {+ const { id } = await params;+ const t = (await getTranslations("views.events")) as unknown as ChangesTranslator;+ // The API reads oldest first, up to its 1000 ceiling; shown newest first.+ // Events are a few per index run, so the ceiling is years of history. Past+ // it the list needs the API to page newest first.+ const page = await listEvents(id, { limit: 1000 }).catch(() => null);++ let body;+ if (page === null) {+ // A failed read is an error, never an empty (quiet-looking) list.+ body = <ApiError title={t("loadErrorTitle")} message={t("loadErrorBody")} />;+ } else if (page.events.length === 0) {+ const reason = page.empty_reason ?? "baseline_only";+ const key = { baseline_only: "baselineOnly", nothing_moved: "nothingMoved", no_match: "noMatch" }[reason];+ body = <EmptyState title={t("emptyTitle")} description={t(key, { runs: page.snapshot_runs ?? 0 })} />;+ } else {+ body = (+ <>+ <ul className="divide-y divide-[var(--color-border-default)] text-xs">+ {[...page.events].reverse().map((e) => {+ const kind = field(e, "repowise.kind");+ const severity = field(e, "repowise.severity");+ const component = field(e, "repowise.component");+ return (+ <li key={e.id} className="flex flex-wrap items-baseline gap-x-3 gap-y-1 py-2">+ <time dateTime={e.time} className="w-full shrink-0 text-[var(--color-text-tertiary)] sm:w-28">+ {formatDate(e.time)}+ </time>+ <span className="min-w-[10rem] flex-1 font-medium text-[var(--color-text-primary)]">+ {evidenceWord(t, `kinds.${kind}`, kind)}+ </span>+ <span className="text-[var(--color-text-secondary)]">{component || t("repository")}</span>+ <Badge variant={SEVERITY_VARIANT[severity] ?? "outline"}>+ {evidenceWord(t, `severities.${severity}`, severity)}+ </Badge>+ </li>+ );+ })}+ </ul>+ <p className="mt-2 text-xs text-[var(--color-text-tertiary)]">+ {t("count", { count: page.events.length })}+ </p>+ </>+ );+ }++ return (+ <PageShell icon={<History />} title={t("title")} description={t("description")}>+ {body}+ </PageShell>+ );+}diff --git a/packages/web/src/components/docs/docs-explorer.tsx b/packages/web/src/components/docs/docs-explorer.tsxindex b2397f465..d49246491 100644--- a/packages/web/src/components/docs/docs-explorer.tsx+++ b/packages/web/src/components/docs/docs-explorer.tsx@@ -1,6 +1,6 @@"use client";-import { useState, useCallback, useEffect, useMemo } from "react";+import { useState, useCallback, useEffect, useLayoutEffect, useMemo } from "react";import useSWR from "swr";import { useSearchParams, useRouter } from "next/navigation";import { BookOpen, PanelLeftClose, PanelLeft, Search } from "lucide-react";@@ -64,18 +64,20 @@ export function DocsExplorer({ repoId }: DocsExplorerProps) {// and retrying a 404 just delays the empty state.{ revalidateOnFocus: false, shouldRetryOnError: false },);- const [treePanelOpen, setTreePanelOpen] = useState(() => {- if (typeof window === "undefined") return true;- return window.matchMedia("(min-width: 768px)").matches;- });- // The rail defaults to whether the layout can afford it, not to `true`.- // Mirrors the 2xl breakpoint the reader uses to place its sections; a manual- // toggle wins from then on, same contract as the app sidebar's route-based- // collapse.- const [sidebarOpen, setSidebarOpen] = useState(() => {- if (typeof window === "undefined") return true;- return window.matchMedia("(min-width: 1536px)").matches;- });+ // Both panels default to whether the layout can afford them, not to `true`:+ // the tree from md, the rail from the 2xl breakpoint the reader uses to place+ // its sections. A manual toggle wins from then on, same contract as the app+ // sidebar's route-based collapse. The server cannot see the viewport, so the+ // default is CSS until hydration: `null` renders the tree hidden below md and+ // as a column from md (the rail is already `hidden 2xl:block`), and a phone+ // never paints an open drawer. The layout effect then takes the breakpoint+ // as state before paint; reading it during render failed hydration.+ const [treePanelOpen, setTreePanelOpen] = useState<boolean | null>(null);+ const [sidebarOpen, setSidebarOpen] = useState(true);+ useLayoutEffect(() => {+ setTreePanelOpen(window.matchMedia("(min-width: 768px)").matches);+ setSidebarOpen(window.matchMedia("(min-width: 1536px)").matches);+ }, []);const [searchOpen, setSearchOpen] = useState(false);const [isExporting, setIsExporting] = useState(false);const searchParams = useSearchParams();@@ -246,9 +248,11 @@ export function DocsExplorer({ repoId }: DocsExplorerProps) {<divclassName={cn("bg-[var(--color-bg-surface)] transition-all duration-200 shrink-0 overflow-y-auto",- treePanelOpen- ? "absolute inset-y-0 left-0 z-30 w-full md:static md:w-[288px]"- : "w-0 overflow-hidden",+ treePanelOpen === null+ ? "absolute inset-y-0 left-0 z-30 w-full hidden md:static md:block md:w-[288px]"+ : treePanelOpen+ ? "absolute inset-y-0 left-0 z-30 w-full md:static md:w-[288px]"+ : "w-0 overflow-hidden",)}>{isLoading ? (@@ -336,13 +340,22 @@ export function DocsExplorer({ repoId }: DocsExplorerProps) {<buttononClick={() => setTreePanelOpen((o) => !o)}aria-label={treePanelOpen ? t("explorer.hideTree") : t("explorer.showTree")}- aria-expanded={treePanelOpen}+ aria-expanded={treePanelOpen ?? undefined}className={cn("absolute top-3.5 z-20 rounded-md p-1 text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)] hover:bg-[var(--color-bg-elevated)] transition-colors",- treePanelOpen ? "hidden md:block left-[292px]" : "left-1",+ treePanelOpen === null+ ? "left-1 md:left-[292px]"+ : treePanelOpen+ ? "hidden md:block left-[292px]"+ : "left-1",)}>- {treePanelOpen ? (+ {treePanelOpen === null ? (+ <>+ <PanelLeft className="h-3.5 w-3.5 md:hidden" />+ <PanelLeftClose className="hidden h-3.5 w-3.5 md:block" />+ </>+ ) : treePanelOpen ? (<PanelLeftClose className="h-3.5 w-3.5" />) : (<PanelLeft className="h-3.5 w-3.5" />diff --git a/packages/web/src/components/docs/docs-viewer.tsx b/packages/web/src/components/docs/docs-viewer.tsxindex 188af1e5c..69bceab0f 100644--- a/packages/web/src/components/docs/docs-viewer.tsx+++ b/packages/web/src/components/docs/docs-viewer.tsx@@ -161,6 +161,9 @@ function DocsSidebar({ repoId, targetPath }: { repoId: string; targetPath: strin);}+/** Page types whose `target_path` is a file or a `file::symbol` id. */+const SIGNAL_PAGE_TYPES = new Set(["file_page", "symbol_spotlight", "api_contract", "infra_page"]);+/*** Consolidated "At a glance" signals for a file page — hotspot, ownership,* churn, bus factor — pulled from the git-metadata endpoint so the reader@@ -351,10 +354,11 @@ export function DocsViewer({);const targetPath = page?.target_path ?? "";- // Decided by page type, not path shape: a module page's target is a- // directory, which every row below would answer with nothing, and the- // reader already gives module pages their own history card.- const showSignals = !!targetPath && page?.page_type !== "module_page";+ // Decided by page type, not path shape: only these target a file or a+ // symbol. Any other target (the repo overview's repo name, a module's+ // directory, a cycle id) is no file, so every row below asked the API for+ // it and got a 404; module pages already have their own history card.+ const showSignals = !!targetPath && SIGNAL_PAGE_TYPES.has(page?.page_type ?? "");// Security findings only make sense for real source files.const isFilePath =showSignals &&diff --git a/packages/web/src/components/layout/nav-items.ts b/packages/web/src/components/layout/nav-items.tsindex da956b439..58985b636 100644--- a/packages/web/src/components/layout/nav-items.ts+++ b/packages/web/src/components/layout/nav-items.ts@@ -19,6 +19,7 @@ import {GitCommitHorizontal,GitMerge,HeartPulse,+ History,LayoutDashboard,Layers,Lightbulb,@@ -87,6 +88,7 @@ export function repoNavGroups(repoId: string): NavGroup[] {labelKey: "groupPeopleAndHistory",items: [{ label: "Commits", labelKey: "commits", href: `${base}/commits`, icon: GitCommitHorizontal },+ { label: "Events", labelKey: "events", href: `${base}/events`, icon: History },{ label: "Contributors", labelKey: "contributors", href: `${base}/owners`, icon: Users },{ label: "Decisions", labelKey: "decisions", href: `${base}/decisions`, icon: Lightbulb },],diff --git a/packages/web/src/components/layout/repo-breadcrumb-label.ts b/packages/web/src/components/layout/repo-breadcrumb-label.tsindex dea0c8340..8af5363b3 100644--- a/packages/web/src/components/layout/repo-breadcrumb-label.ts+++ b/packages/web/src/components/layout/repo-breadcrumb-label.ts@@ -17,6 +17,7 @@ const SEGMENT_LABELS: Record<string, string> = {decisions: "Decisions",commits: "Commits",changes: "Changes",+ events: "Events",owners: "Contributors",modules: "Modules",wiki: "Wiki",@@ -57,6 +58,7 @@ export const SEGMENT_MESSAGE_KEYS: Record<string, string> = {decisions: "decisions",commits: "commits",changes: "changes",+ events: "events",owners: "owners",modules: "modules",wiki: "wiki",diff --git a/packages/web/src/lib/api/events.ts b/packages/web/src/lib/api/events.tsnew file mode 100644index 000000000..db5dace29--- /dev/null+++ b/packages/web/src/lib/api/events.ts@@ -0,0 +1,3 @@+import "./client";++export * from "@repowise-dev/api-client/events";diff --git a/packages/web/src/lib/changes.test.ts b/packages/web/src/lib/changes.test.tsnew file mode 100644index 000000000..2d02f26ff--- /dev/null+++ b/packages/web/src/lib/changes.test.ts@@ -0,0 +1,75 @@+import { describe, expect, it } from "vitest";+import { createTranslator } from "next-intl";+import type { EvidenceItem } from "@repowise-dev/types/changes";+import { type ChangesTranslator, evidenceValueText, evidenceWord } from "./changes";+import en from "../../messages/en.json";+import zhCN from "../../messages/zh-CN.json";++/** One line per key the server's `item_line` can send, with its numbers. */+const LINES: [string, Record<string, unknown>][] = [+ ["unknown", { reason: "not gathered for this change" }],+ ["unknown", { reason: "" }],+ ["components_touched", { count: 2, names: "core, web", more: 0 }],+ ["suggested_reviewers", { count: 8, names: "a, b, c, d, e, f", more: 2 }],+ ["owners", { count: 1, names: "@core", more: 0, unowned: 3 }],+ ["owners", { count: 0, names: "", more: 0, unowned: 1 }],+ ["reaching_tests", { files: 23, reached: 22, absent: 0, unknown: 1 }],+ ["reaching_tests", { files: 0, reached: 0, absent: 0, unknown: 0 }],+ ["contracts", { touched: 0, breaking: 0 }],+ ["contracts_unchecked", { touched: 2, breaking: 0 }],+ ["cross_repo_consumers", { links: 3, names: "web", more: 0 }],+ ["decisions_crossed", { accepted: 1, candidate: 2 }],+ ["decisions_none", { accepted: 0, candidate: 0 }],+ ["health_delta", { introduced: 1, worsened: 0, resolved: 2 }],+ ["health_delta_partial", { introduced: 0, worsened: 0, resolved: 0 }],+ ["provenance", { label: "human attested", known: 3, commits: 4 }],+ ["provenance_named", { label: "agent", known: 1, commits: 1, names: "claude-code, claude-opus-4-5" }],+ ["risk_score", { percentile: 97.5 }],+ ["outcomes", { reverts: 0, references: 1 }],+ ["outcomes_rate", { reverts: 1, references: 0, fixed: 2, files: 5, days: 90 }],+];++function item(key: string, params: Record<string, unknown>): EvidenceItem {+ return {+ kind: "reaching_tests",+ label: "Tests reaching the change",+ status: "unknown",+ basis: "inferred",+ value: null,+ details: [],+ source: "test impact",+ line: { key, params },+ };+}++describe.each([+ ["en", en],+ ["zh-CN", zhCN],+])("evidence lines in %s", (locale, messages) => {+ const t = createTranslator({+ locale,+ messages,+ namespace: "views.changes",+ }) as unknown as ChangesTranslator;++ it.each(LINES)("words %s without raw keys or booleans", (key, params) => {+ const text = evidenceValueText(t, item(key, params));+ expect(text).not.toBe("");+ expect(text).not.toMatch(/[{}_]|true|false|undefined|null/);+ });++ it("labels and bases come from the catalog", () => {+ expect(evidenceWord(t, "evidenceKinds.reaching_tests", "x")).not.toBe("x");+ expect(evidenceWord(t, "evidenceBasis.unresolved", "unresolved")).not.toBe("unresolved");+ expect(evidenceWord(t, "evidenceKinds.not_a_kind", "Server label")).toBe("Server label");+ });+});++it("says how many changed files a test reaches and how many are not known", () => {+ const t = createTranslator({ locale: "en", messages: en, namespace: "views.changes" });+ const text = evidenceValueText(+ t as unknown as ChangesTranslator,+ item("reaching_tests", { files: 23, reached: 22, absent: 0, unknown: 1 }),+ );+ expect(text).toBe("22 of 23 changed files reached by a test; 1 not known");+});diff --git a/packages/web/src/lib/changes.ts b/packages/web/src/lib/changes.tsindex 85d2e7288..24949a14a 100644--- a/packages/web/src/lib/changes.ts+++ b/packages/web/src/lib/changes.ts@@ -3,7 +3,7 @@* alike. Kept out of the client table module: a server component cannot call* a function exported from a "use client" file.*/-import type { ChangeListItem } from "@repowise-dev/types/changes";+import type { ChangeListItem, EvidenceItem } from "@repowise-dev/types/changes";/** The change's short name: the forge ref when it has one, else a trimmed id. */export function changeLabel(c: Pick<ChangeListItem, "forge_ref" | "id">): string {@@ -46,3 +46,24 @@ export const CHANGE_CATEGORIES = ["feature", "fix", "refactor", "docs", "test",export function categoryLabel(t: (key: string) => string, category: string): string {return CHANGE_CATEGORIES.includes(category) ? t(`categories.${category}`) : category;}++/** A `views.changes` translator that can also say whether it holds a key. */+export type ChangesTranslator = ((key: string, values?: Record<string, string | number>) => string) & {+ has: (key: string) => boolean;+};++/** An evidence item's value in one line, worded from the server's `line`; an unknown one says why. */+export function evidenceValueText(t: ChangesTranslator, item: EvidenceItem): string {+ const line = item.line;+ if (!line) return "";+ const params = line.params as Record<string, string | number>;+ if (line.key === "unknown" && !params.reason) return t("evidenceLine.unknownBare");+ const key = `evidenceLine.${line.key}`;+ // A key this build does not know (a newer server) shows nothing rather than a raw id.+ return t.has(key) ? t(key, params) : "";+}++/** An evidence label or basis from the catalog, falling back to the server's text. */+export function evidenceWord(t: ChangesTranslator, key: string, fallback: string): string {+ return t.has(key) ? t(key) : fallback;+}diff --git a/tests/unit/analysis/test_owner_activity_from_commits.py b/tests/unit/analysis/test_owner_activity_from_commits.pyindex c3e661151..a89c12665 100644--- a/tests/unit/analysis/test_owner_activity_from_commits.py+++ b/tests/unit/analysis/test_owner_activity_from_commits.py@@ -114,6 +114,10 @@ async def test_a_sample_that_stops_inside_the_window_is_unknown(three_author_represults, [], summary.commit_rows, summary.repo_totals.total_commit_count)assert {a.commit_count_90d for a in accs.values() if a.key} == {None}+ # What the sample holds is a floor for the authors in it, and nothing for the rest.+ floors = {a.key: a.commit_count_90d_at_least for a in accs.values() if a.key}+ assert floors["[email protected]"] == 2+ assert floors.get("[email protected]") is None@pytest.mark.asynciodiff --git a/tests/unit/cli/test_read_snapshot_refresh.py b/tests/unit/cli/test_read_snapshot_refresh.pyindex dc245cbd5..85da8cfba 100644--- a/tests/unit/cli/test_read_snapshot_refresh.py+++ b/tests/unit/cli/test_read_snapshot_refresh.py@@ -80,3 +80,34 @@ def test_the_up_to_date_outcome_refreshes_the_views(tmp_path: Path, monkeypatch))_invoke_update(repo)assert calls.get("views") == 1+++def test_a_snapshot_not_written_is_named_with_its_error(tmp_path: Path, monkeypatch, capsys) -> None:+ """The update keeps the core log at ERROR, so the refresh says what failed itself."""+ from contextlib import asynccontextmanager++ from repowise.cli import helpers+ from repowise.core.persistence.crud.analysis import actions++ @asynccontextmanager+ async def opened(_root):+ yield (object(), "r1")++ async def failing(_session, _repo_id):+ return [("component", TypeError("key must be bytes [red]x[/red]\n long traceback"))]++ monkeypatch.setattr(helpers, "repo_index_session", opened)+ monkeypatch.setattr(actions, "write_read_snapshots", failing)+ refresh_read_snapshots(tmp_path)+ shown = [ln for ln in capsys.readouterr().out.splitlines() if ln.startswith("Snapshot not written")]+ # Escaped, first line only; the full error goes to the debug log.+ assert shown == ["Snapshot not written: component: TypeError: key must be bytes [red]x[/red]"]++ @asynccontextmanager+ async def broken(_root):+ raise OSError("database is locked")+ yield++ monkeypatch.setattr(helpers, "repo_index_session", broken)+ refresh_read_snapshots(tmp_path)+ assert "read snapshots: OSError: database is locked" in capsys.readouterr().outdiff --git a/tests/unit/cli/test_update_reporting.py b/tests/unit/cli/test_update_reporting.pyindex fef478507..6ae68ae17 100644--- a/tests/unit/cli/test_update_reporting.py+++ b/tests/unit/cli/test_update_reporting.py@@ -301,3 +301,16 @@ class TestDeadCodeCountsAreScopedToTheUpdate:def test_a_missing_report_counts_as_nothing(self):assert reporting._dead_code_counts(None, ["changed.py"]) == (0, 0)++ def test_the_panel_line_names_its_scope_beside_the_repo_wide_total(self):+ # The run log prints the repo-wide total; the scoped line must not contradict it.+ assert reporting._dead_code_line(self._report(), ["changed.py"]) == (+ "1 unreachable · 1 unused exports in changed files · 4 findings repo-wide"+ )+ assert reporting._dead_code_line(self._report(), ["other.py"]) == (+ "0 unreachable · 0 unused exports in changed files · 4 findings repo-wide"+ )+ assert reporting._dead_code_line(None, ["changed.py"]) == (+ "0 unreachable · 0 unused exports in changed files"+ )+ assert reporting._dead_code_line(self._report(), None) == "2 unreachable · 2 unused exports"diff --git a/tests/unit/core/test_change_evidence.py b/tests/unit/core/test_change_evidence.pyindex aea704d74..104214db7 100644--- a/tests/unit/core/test_change_evidence.py+++ b/tests/unit/core/test_change_evidence.py@@ -2,6 +2,7 @@from __future__ import annotations+import dataclassesimport jsonimport osimport subprocess@@ -26,8 +27,11 @@ from repowise.core.changes.evidence import (KINDS,ChangeEvidence,EvidenceInputs,+ EvidenceItem,Unavailable,build_change_evidence,+ item_line,+ line_text,)@@ -174,7 +178,8 @@ def test_statuses_follow_the_facts():assert by["owners"].details[-1] == {"owner": None, "paths": ["src/b.py"]}assert by["suggested_reviewers"].value == ["Bob"] and "score" not in by["suggested_reviewers"].details[0]tests = by["reaching_tests"]- assert tests.status == "attention" and tests.basis == "inferred"+ # One file reached, one nobody knows about: partly known, never a gap.+ assert tests.status == "unknown" and tests.basis == "inferred"assert tests.value == {"measured": 0,"inferred": 1,@@ -196,6 +201,63 @@ def test_statuses_follow_the_facts():assert by["risk_score"].status == "ok" and by["risk_score"].value == {"percentile": 97.5}+def test_a_kept_checklist_reads_reaching_tests_under_the_current_rule():+ """A checklist kept before the rule changed said attention for an unknown file."""+ item = {+ "kind": "reaching_tests",+ "label": "Tests reaching the change",+ "status": "attention",+ "basis": "inferred",+ "value": {"files_without_tests": 0, "files_unknown": 1},+ "details": [{"path": "a.py", "tests": ["t"]}, {"path": "b.py", "tests": None}],+ "source": "test impact",+ }+ assert EvidenceItem.from_dict(item).status == "unknown"+ absent = {**item, "details": [*item["details"], {"path": "c.py", "tests": []}]}+ assert EvidenceItem.from_dict(absent).status == "attention"++ # The needs-attention list confirms its SQL prefilter through the same parse.+ from repowise.core.changes.collect import evidence_summary+ from repowise.core.persistence.crud.changes import dump_evidence++ kept = {"schema_version": 1, "generated_at": "2026-10-14T00:00:00+00:00", "items": [item]}+ row = SimpleNamespace(evidence_json=dump_evidence(kept))+ assert evidence_summary(row)["attention"] == 0+++def test_every_item_reads_as_a_plain_line():+ """Each kind words its value; no raw key, boolean or dict reaches a reader."""+ bundle = _bundle(+ ["src/a.py", "src/b.py"],+ health=_delta([_finding()]),+ tests=_tests({"src/a.py": "inferred", "src/b.py": "unknown"}),+ risk=SimpleNamespace(percentile=97.5, baseline_sample_size=200),+ )+ inputs = dataclasses.replace(_full_inputs(), code_paths=None)+ evidence = build_change_evidence(bundle, inputs, change_id="c", revspec="r").to_dict()+ lines = {i["kind"]: line_text(item_line(i)) for i in evidence["items"]}++ assert lines["reaching_tests"] == "1 of 2 changed files reached by a test; 1 not known"+ assert lines["components_touched"] == "1 component: core"+ assert lines["owners"] == "@team-core; 1 changed file without one"+ assert lines["contracts"] == "1 workspace contract touched; signatures not compared"+ assert lines["decisions_crossed"] == "1 accepted decision, 0 candidates"+ assert lines["cross_repo_consumers"] == "No consumer in another repo"+ assert lines["risk_score"] == "Larger than 97.5% of recent commits"+ assert lines["outcomes"].startswith("Not known: ")+ assert lines["provenance"] == "provenance: agent, known for 0 of 0 commits"+ named = item_line(+ {+ "kind": "provenance",+ "value": {"label": "agent", "agent_commits": 1, "human_attested_commits": 0, "unknown_commits": 0},+ "details": [{"sha": "s", "label": "agent", "tier": 2, "agent": "claude-code", "model": "opus"}],+ }+ )+ assert line_text(named) == "provenance: agent, known for 1 of 1 commit (claude-code, opus)"+ for text in lines.values():+ assert text and not any(w in text for w in ("True", "False", "None", "_", "{"))++def test_unknown_provenance_stays_unknown_and_unavailable_inputs_name_why():inputs = EvidenceInputs(owners=Unavailable("could not be read: OSError"),diff --git a/tests/unit/core/test_changes.py b/tests/unit/core/test_changes.pyindex 6e8d6de42..4596dfa72 100644--- a/tests/unit/core/test_changes.py+++ b/tests/unit/core/test_changes.py@@ -19,7 +19,7 @@ from repowise.core.changes import (in_toto_statement,reconstruct_changes,)-from repowise.core.changes.reconstruct import change_identity, change_title+from repowise.core.changes.reconstruct import change_identity, change_title, without_own_reffrom repowise.core.changes.source import GitChangeMetadatafrom repowise.core.changes.store import change_provenance, refresh_changesfrom repowise.core.ingestion.git_indexer.commit_rows import build_commit_rows@@ -127,6 +127,7 @@ def test_every_merge_style_reads_back_as_one_change(history):squash = by_id["pr-12"]assert (squash.shape, squash.forge_ref, squash.commit_shas) == ("squash", "#12", [shas["squash"]])assert _files(squash) == {"src/a.py"} and squash.category == "feature"+ assert not squash.title.endswith("(#12)") # surfaces print the ref beside itmerge = by_id["pr-13"]assert merge.shape == "merge" and merge.head_sha == shas["gh_merge"]@@ -199,6 +200,15 @@ def test_title_skips_boilerplate_and_trailers():assert change_title(subject, "#123 Fix foo\n", True) == "#123 Fix foo"+def test_title_drops_only_its_own_ref_suffix():+ assert without_own_ref("feat(x): add y (#3792)", "3792") == "feat(x): add y"+ assert without_own_ref("Fix the parser (!41)", "41") == "Fix the parser"+ # Another change's number, or a title that is only the ref, stays.+ assert without_own_ref("revert: z (#12)", "13") == "revert: z (#12)"+ assert without_own_ref("(#5)", "5") == "(#5)"+ assert without_own_ref("feat: (#5) in the middle", "5") == "feat: (#5) in the middle"++def test_repeated_identity_gets_a_distinct_id_and_keeps_it(tmp_path):r = _Repo(tmp_path / "repo")first = r.commit("a.py", "fix: a (#8)")diff --git a/tests/unit/core/test_report.py b/tests/unit/core/test_report.pyindex 519c5acb7..604336f58 100644--- a/tests/unit/core/test_report.py+++ b/tests/unit/core/test_report.py@@ -318,7 +318,19 @@ async def test_outcomes_are_left_out_until_a_checklist_kept_them(ctx):"title": f"feat: {cid}","head_sha": cid[3:].rjust(40, "a"),"files_json": json.dumps([{"path": path, "added": 1, "deleted": 0}]),- "evidence_json": json.dumps({"items": items}) if outcomes is not None else None,+ # A kept checklist as the store writes it; the section reads it as every reader does.+ "evidence_json": json.dumps(+ {+ "schema_version": 1,+ "generated_at": "2026-10-14T00:00:00+00:00",+ "items": [+ {"label": "Outcomes since merge", "basis": "declared", "source": "git history", **i}+ for i in items+ ],+ }+ )+ if outcomes is not None+ else None,}assert await report_sections.get("outcomes").collect(ctx) is Nonediff --git a/tests/unit/persistence/test_read_snapshots.py b/tests/unit/persistence/test_read_snapshots.pyindex d7e193c3a..ef95e16ce 100644--- a/tests/unit/persistence/test_read_snapshots.py+++ b/tests/unit/persistence/test_read_snapshots.py@@ -317,9 +317,11 @@ async def test_a_failed_view_write_leaves_nothing_stale(async_session, monkeypatmonkeypatch.setattr(actions_loader, "write_actions_snapshot", broken)await _triage(async_session, rid)- await write_read_snapshots(async_session, rid)+ failed = await write_read_snapshots(async_session, rid)await async_session.commit()assert await _snapshot_rows(async_session) == 0+ # Named for the caller, whose output hides the core log.+ assert [(name, str(exc)) for name, exc in failed] == [("actions", "build failed")]async def test_a_rolled_back_savepoint_still_invalidates(async_session) -> None:diff --git a/tests/unit/server/golden/ownership_rollups.json b/tests/unit/server/golden/ownership_rollups.jsonindex 42b2c6990..dd59240eb 100644--- a/tests/unit/server/golden/ownership_rollups.json+++ b/tests/unit/server/golden/ownership_rollups.json@@ -11,6 +11,7 @@"dead_code_files_owned": 1,"dead_code_lines_owned": 12,"commit_count_90d": 2,+ "commit_count_90d_at_least": null,"last_commit_at": "2026-08-01T12:00:00Z","bus_factor_risk_files": 1},@@ -24,6 +25,7 @@"dead_code_files_owned": 0,"dead_code_lines_owned": 0,"commit_count_90d": 1,+ "commit_count_90d_at_least": null,"last_commit_at": "2026-07-01T00:00:00Z","bus_factor_risk_files": 1},@@ -37,6 +39,7 @@"dead_code_files_owned": 1,"dead_code_lines_owned": 30,"commit_count_90d": 0,+ "commit_count_90d_at_least": null,"last_commit_at": "2020-03-03T00:00:00Z","bus_factor_risk_files": 1}@@ -57,6 +60,7 @@"dead_code_files_owned": 1,"dead_code_lines_owned": 12,"commit_count_90d": 2,+ "commit_count_90d_at_least": null,"last_commit_at": "2026-08-01T12:00:00Z","bus_factor_risk_files": 1},@@ -70,6 +74,7 @@"dead_code_files_owned": 0,"dead_code_lines_owned": 0,"commit_count_90d": 1,+ "commit_count_90d_at_least": null,"last_commit_at": "2026-07-01T00:00:00Z","bus_factor_risk_files": 1},@@ -83,6 +88,7 @@"dead_code_files_owned": 1,"dead_code_lines_owned": 30,"commit_count_90d": 0,+ "commit_count_90d_at_least": null,"last_commit_at": "2020-03-03T00:00:00Z","bus_factor_risk_files": 1}@@ -102,6 +108,7 @@"dead_code_files_owned": 1,"dead_code_lines_owned": 12,"commit_count_90d": 2,+ "commit_count_90d_at_least": null,"last_commit_at": "2026-08-01T12:00:00Z","first_commit_at": "2025-01-02T03:04:05Z","bus_factor_risk_files": 1,@@ -181,6 +188,7 @@"dead_code_files_owned": 0,"dead_code_lines_owned": 0,"commit_count_90d": 1,+ "commit_count_90d_at_least": null,"last_commit_at": "2026-07-01T00:00:00Z","first_commit_at": "2025-01-02T03:04:05Z","bus_factor_risk_files": 1,@@ -260,6 +268,7 @@"dead_code_files_owned": 1,"dead_code_lines_owned": 30,"commit_count_90d": 0,+ "commit_count_90d_at_least": null,"last_commit_at": "2020-03-03T00:00:00Z","first_commit_at": "2019-03-03T00:00:00Z","bus_factor_risk_files": 1,diff --git a/tests/unit/server/test_changes_routes.py b/tests/unit/server/test_changes_routes.pyindex 750f6c8d7..135ae056c 100644--- a/tests/unit/server/test_changes_routes.py+++ b/tests/unit/server/test_changes_routes.py@@ -166,6 +166,11 @@ async def test_detail_carries_evidence_only_when_asked_and_keeps_it("value": {"introduced": 0},"details": [],"source": "change health",+ # Worded by the client from a key and its numbers.+ "line": {+ "key": "health_delta_partial",+ "params": {"introduced": 0, "worsened": 0, "resolved": 0},+ },}# Kept: the next read builds nothing; refresh builds again.again = (await client.get(base, params={"evidence": "true"})).json()diff --git a/tests/unit/server/test_chat_figures.py b/tests/unit/server/test_chat_figures.pyindex d482c7599..8acf3817c 100644--- a/tests/unit/server/test_chat_figures.py+++ b/tests/unit/server/test_chat_figures.py@@ -151,3 +151,89 @@ def test_evidence_past_the_read_cap_leaves_unmatched_figures_not_checked(monkeyp"figures_unverified": 0,"figures_not_checked": 1,}+++_COUNTS = [+ (+ "a1",+ {+ "total": 505,+ "by_category": {+ "fix": 320, "feature": 115, "refactor": 36, "docs": 15, "test": 11, "chore": 7,+ "other": 1,+ },+ "agent": 254,+ "unknown": 251,+ "files": 12,+ "functions": 40,+ "modules": 3,+ "files_changed": 10,+ "owners": 2,+ "tracked": 4,+ },+ )+]+++def _derived(answer: str) -> list[tuple[str, bool, bool]]:+ return [(f.text, f.verified, f.derived) for f in check_figures(answer, _COUNTS).figures]+++def _flag(answer: str, figure: str) -> tuple[bool, bool]:+ return next((v, d) for t, v, d in _derived(answer) if t == figure)+++_WALK_TABLE = """Total: 505 changes++| Category | Changes | Share |+|---|---|---|+| Fix | 320 | 63.4% |+| Feature | 115 | 22.8% |+| Refactor | 36 | 7.1% |+| Docs | 15 | 3.0% |+| Test | 11 | 2.2% |+| Chore | 7 | 1.4% |+| Other | 1 | 0.2% |+"""+++def test_the_walks_share_column_is_derived():+ shares = [(t, v) for t, v, _ in _derived(_WALK_TABLE) if t.endswith("%")]+ assert shares and all(v for _, v in shares), shares+ assert _flag(_WALK_TABLE, "63.4%") == (True, True)+ assert _flag(_WALK_TABLE, "0.2%") == (True, True)+ assert check_figures(_WALK_TABLE, _COUNTS).diagnostics()["figures_derived"] >= 2+++def test_a_ratio_written_as_its_two_terms_is_derived():+ assert _flag("Provenance was available for 254 of 505 changes (50.3%).", "50.3%") == (True, True)+ assert _flag("254 out of 505, or 50%.", "50%") == (True, True)+++def test_a_sum_written_out_is_derived():+ assert _flag("Fix and feature: 320 + 115 = 435.", "435") == (True, True)+ assert _flag("320 + 115, 435 in all.", "435") == (True, True)+++ ("answer", "figure"),+ [+ # Two matched numbers that divide to the figure, not written as a ratio.+ ("It changed 12 files and 40 functions; 30% of them are hotspots.", "30%"),+ ("It changed 12 files and 40 functions, 30% of them hotspots.", "30%"),+ # Coincidental small integers.+ ("There are 2 owners and 4 tracked files, so 50% is covered.", "50%"),+ # A total that is not the sum written out.+ ("10 files in 3 modules, 13 total.", "13"),+ # The terms sit in another clause.+ ("Total 505.\nFix: 320, or 63%.", "63%"),+ ("Total: 505.\nFix had 320. That is 63.4% of the work.", "63.4%"),+ # A wrong share, and a share whose terms are not held.+ ("254 of 505 changes (41.0%).", "41.0%"),+ ("77 of 505 changes (15.2%).", "15.2%"),+ # One table row agreeing with a total is not a column.+ ("Total: 4\n\n| a | 2 | 50% |\n| b | 1 | 10% |", "50%"),+ ],+)+def test_a_figure_without_its_working_is_still_flagged(answer, figure):+ assert _flag(answer, figure) == (False, False)diff --git a/tests/unit/server/test_events_routes.py b/tests/unit/server/test_events_routes.pyindex f80a40944..2abf6a9c2 100644--- a/tests/unit/server/test_events_routes.py+++ b/tests/unit/server/test_events_routes.py@@ -58,3 +58,18 @@ async def test_events_are_cloudevents_oldest_first(client: AsyncClient, app) ->assert [e["id"] for e in only] == [f"{1:032d}"]assert (await client.get(url, params={"kind": "nope"})).status_code == 422assert (await client.get("/api/repos/nope/events")).status_code == 404+++async def test_an_empty_list_says_why(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ url = f"/api/repos/{repo['id']}/events"++ empty = (await client.get(url)).json()+ assert empty["events"] == [] and empty["snapshot_runs"] == 0+ assert empty["empty_reason"] == "baseline_only"+ assert "start after the next `repowise update` on a new commit" in empty["empty_note"]++ await _seed(app, repo["id"])+ full = (await client.get(url)).json()+ assert full["empty_reason"] is None and full["empty_note"] is Nonediff --git a/tests/unit/test_policy_rules.py b/tests/unit/test_policy_rules.pyindex 1cea751d3..97151add1 100644--- a/tests/unit/test_policy_rules.py+++ b/tests/unit/test_policy_rules.py@@ -263,6 +263,21 @@ def test_a_file_nothing_knows_a_test_for_is_not_missing():assert fired.outcome == "triggered" and fired.locations == [("src/pay/refund.py", None, None)]+def test_a_partly_known_tests_item_still_answers_for_the_files_in_scope():+ """The checklist reads ``unknown`` when one changed file is not known; rows still decide."""+ policy = parse_policy(+ "rules: [{name: t, match: {components: {names: [payments]}}, when: {reaching_tests: present}, action: warn}]"+ )+ rows = [+ {"path": "src/pay/charge.py", "tests": ["t1"]},+ {"path": "src/pay/refund.py", "tests": ["t2"]},+ {"path": "docs/a.md", "tests": None},+ ]+ partial = _item("reaching_tests", rows, status="unknown", basis="inferred")+ (result,) = evaluate(policy, _evidence(_components(PAYMENTS), partial))+ assert result.outcome == "triggered"++def test_no_changed_source_file_in_scope_is_not_missing():policy = parse_policy("rules: [{name: t, when: {reaching_tests: missing}, action: fail}]")(result,) = evaluate(policy, _evidence(_tests()))