Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(report): repowise report assessment, an evidence pack per repo or workspace (#3805)
Raghav Chamadiya6447f2a55928
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.mdindex 2a2e31fda..dd9a6b009 100644--- a/docs/reference/CLI_REFERENCE.md+++ b/docs/reference/CLI_REFERENCE.md@@ -41,7 +41,8 @@ Grouped by what you're trying to do, not alphabetically. `PATH` and flag details[`coverage`](#repowise-coverage) ·[`components`](#repowise-components) ·[`changes`](#repowise-changes) ·-[`events`](#repowise-events)+[`events`](#repowise-events) ·+[`report assessment`](#repowise-report-assessment-path)**Decisions**[`decision`](#repowise-decision)@@ -1633,6 +1634,30 @@ Kinds: `ownership_shift`, `owner_inactive`, `bus_factor_drop` (critical componen---+### `repowise report assessment [PATH]`++One document a team hands to someone else, for a repo or every repo of a workspace: component posture, hotspots, bus factor per component, dead code by tier, measured and inferred test reach, contracts, governing decisions, provenance coverage with the agents and models named, and what moved since a snapshot a quarter older. Every item keeps the OpenSSF Scorecard check keys (`name`, `score` 0 to 10 or -1 inconclusive, `reason`, `details`, `documentation`) plus `method` and `basis`. A descriptive item (a count or a list) has `score: null`, and missing or held-back evidence is always -1, never a low score. The report is evidence about code and components, not a score of people: owners are counted, never ranked or named. JSON is canonical (`schema_version: 1`); the HTML is one file with inline CSS, no scripts and a policy that blocks every fetch, so it opens offline and prints as is.++```bash+repowise report assessment [PATH] [--sections a,b] [--format json|markdown|html] [--out FILE] [--workspace | --no-workspace] [--repo ALIAS]+```++| Section | Measures | Basis |+|---|---|---|+| `components` | Each component's NLOC-weighted health, catalog facts and `components ownership` findings | `measured`; `gated` on a language health is held back on |+| `hotspots` | Files with high recent churn, per component | `measured` |+| `bus-factor` | Fewest primary owners holding over half of each component's owned files; components at 1 or 2 are counted and named in the summary unless the catalog marks them | `measured`; `inferred` under five owned files |+| `dead-code` | Open findings by confidence tier; `safe_to_delete` is not used | `inferred`; `gated` for held-back languages |+| `test-reach` | Line coverage from ingested reports, and production files a test reaches, as separate items | `measured` and `inferred` |+| `contracts` | Contracts each component provides and their consumers in other repos | `measured` when the workspace store matches the indexed commit |+| `decisions` | Accepted decisions governing each component's files, and the stale ones | `declared` |+| `provenance` | Commits in the last 90 indexed days with a known source (a count, not a score), and the agents and models named (listed, not counted) | `measured`, `declared`; `unresolved` with no markers |+| `trend` | What moved since a same-stamp snapshot at least 90 days older, by the `events` diff rules and only for the event kinds the repository has on | `measured` |++Basis `unresolved` means the evidence is missing. Each per-component section opens with one summary row counting components by outcome; a component gets its own item only when there is something to note (an ownership finding, a bus factor of 2 or less on a component the catalog gives a criticality or tags, hotspots, a stale decision, provided contracts, or unresolved or gated evidence), the rest are named in the summary, and the JSON `data` keeps every component's figures. Local paths are removed from every item. A section is a `Section` on `SeamRegistry("report-section")`: each module in `repowise/core/report/sections/` registers one, a plugin registers its own the same way, and a section whose data is absent returns `None` and is left out (an outcomes section is added this way once change outcomes exist). Renderers live on `SeamRegistry("report-renderer")` and are picked with `--format`. Modernization candidates are not reported, since no existing signal measures them.++---+### `repowise distill <command>`Run a command and print a compact, reversible rendering of its output. Noisediff --git a/packages/cli/src/repowise/cli/commands/report_assessment_cmd.py b/packages/cli/src/repowise/cli/commands/report_assessment_cmd.pynew file mode 100644index 000000000..d9d29116b--- /dev/null+++ b/packages/cli/src/repowise/cli/commands/report_assessment_cmd.py@@ -0,0 +1,149 @@+"""``repowise report assessment`` - the assessment pack for a repo or workspace.++Reads the index only (no LLM, no network, no writes) and prints or writes one+document: JSON (canonical), Markdown or self-contained HTML. In a workspace it+covers every repo, or the one ``--repo`` names.+"""++from __future__ import annotations++from pathlib import Path+from typing import Any++import click++from repowise.cli.helpers import (+ err_console,+ repo_index_session,+ resolve_command_target,+ run_async,+ silence_logs_for_machine_output_until_close,+)+++def _targets(target: Any) -> list[tuple[str | None, Path]]:+ """``(alias, path)`` per repository the report covers."""+ if not target.is_workspace:+ return [(None, Path(target.repo_path).resolve())]+ if target.repo_filter is not None:+ return [(target.repo_filter, target.single_repo_path())]+ return [(r.alias, (target.ws_root / r.path).resolve()) for r in target.ws_config.repos]+++async def _build(repos: list[tuple[str | None, Path]], sections: list, scope: dict) -> dict:+ from repowise.core.persistence.models import Repository+ from repowise.core.report.build import assemble, collect_repo+ from repowise.core.report.model import ReportContext++ parts = []+ for alias, root in repos:+ async with repo_index_session(root) as opened:+ if opened is None:+ if scope["kind"] == "repo":+ raise click.ClickException(+ f"No index for {root}. Run `repowise init` there first."+ )+ entry = {"alias": alias, "name": root.name, "indexed": False}+ parts.append((entry, []))+ continue+ session, repo_id = opened+ repo = await session.get(Repository, repo_id)+ ctx = ReportContext(+ session, repo_id, root, alias=alias, head_commit=repo.head_commit if repo else None+ )+ parts.append(await collect_repo(ctx, sections))+ return assemble(scope, parts)+++def _pick_sections(wanted: str | None) -> list:+ """The registered sections, narrowed to *wanted* (comma-separated ids)."""+ from repowise.core.report.build import available_sections++ sections = available_sections()+ if not wanted:+ return sections+ names = [n.strip() for n in wanted.split(",") if n.strip()]+ known = dict(sections)+ unknown = [n for n in names if n not in known]+ if unknown:+ raise click.BadParameter(+ f"unknown section(s) {', '.join(unknown)}; available: {', '.join(known)}",+ param_hint="--sections",+ )+ return [(n, s) for n, s in sections if n in names]+++def _scope(target: Any) -> tuple[list[tuple[str | None, Path]], dict]:+ """``(repos, scope)`` for the resolved command target."""+ repos = _targets(target)+ if target.is_workspace and target.repo_filter is None:+ return repos, {"kind": "workspace", "name": target.ws_root.name}+ return repos, {"kind": "repo", "name": repos[0][1].name}+++def _emit(text: str, fmt: str, out_path: str | None, document: dict) -> None:+ """Write or print the rendered report, then warn about any failed section."""+ if out_path:+ Path(out_path).write_text(text, encoding="utf-8", newline="\n")+ err_console.print(f"Wrote {fmt} report to {out_path}")+ else:+ click.echo(text, nl=False)+ failed = [+ f"{s['id']} ({s['repo']})" if s.get("repo") else s["id"]+ for s in document["sections"]+ if s.get("failed")+ ]+ if failed:+ from rich.markup import escape++ err_console.print(+ f"[yellow]warning[/yellow] {len(failed)} section(s) failed and are reported as "+ f"inconclusive: {escape(', '.join(failed))}"+ )++[email protected]("assessment")[email protected]("path", required=False, type=click.Path(exists=True, file_okay=False))[email protected]("--sections", "wanted", default=None, help="Comma-separated section ids.")+ "--format",+ "fmt",+ default="markdown",+ show_default=True,+ help="Renderer: json, markdown or html (or one a plugin registers).",+)[email protected]("--out", "out_path", type=click.Path(dir_okay=False), help="Write to this file.")[email protected]("--workspace", "workspace_flag", is_flag=True, help="Cover every workspace repo.")[email protected]("--no-workspace", is_flag=True, help="Force single-repo mode.")[email protected]("--repo", "repo_alias", default=None, help="Workspace repo alias to cover.")+def assessment_command(+ path: str | None,+ wanted: str | None,+ fmt: str,+ out_path: str | None,+ workspace_flag: bool,+ no_workspace: bool,+ repo_alias: str | None,+) -> None:+ """Assessment pack: components, hotspots, bus factor, dead code, test reach,+ contracts, decisions, provenance and the quarter's moves, each with its basis."""+ from repowise.core.report.render import report_renderers++ if not out_path:+ silence_logs_for_machine_output_until_close() # stdout carries only the report+ sections = _pick_sections(wanted)+ if fmt not in report_renderers.names:+ raise click.BadParameter(+ f"unknown format {fmt!r}; available: {', '.join(report_renderers.names)}",+ param_hint="--format",+ )+ target = resolve_command_target(+ path=path,+ workspace_flag=workspace_flag,+ no_workspace_flag=no_workspace,+ repo_alias=repo_alias,+ )+ target.notice(err_console, command="report assessment")+ repos, scope = _scope(target)+ document = run_async(_build(repos, sections, scope))+ _emit(report_renderers.get(fmt)(document), fmt, out_path, document)diff --git a/packages/cli/src/repowise/cli/commands/report_cmd.py b/packages/cli/src/repowise/cli/commands/report_cmd.pynew file mode 100644index 000000000..0e72a8d63--- /dev/null+++ b/packages/cli/src/repowise/cli/commands/report_cmd.py@@ -0,0 +1,25 @@+"""``repowise report`` - evidence reports a team hands to someone else.++Each subcommand lives in its own module and is listed in :data:`_SUBCOMMANDS`;+adding one is adding one line there.+"""++from __future__ import annotations++import click++from repowise.core.registry import LazyCommand++#: ``"module:attr"`` of each ``repowise report`` subcommand.+_SUBCOMMANDS: tuple[str, ...] = (+ "repowise.cli.commands.report_assessment_cmd:assessment_command",+)++[email protected]("report")+def report_group() -> None:+ """Evidence reports built from the index: assessment."""+++for _target in _SUBCOMMANDS:+ report_group.add_command(LazyCommand("", _target).load())diff --git a/packages/cli/src/repowise/cli/main.py b/packages/cli/src/repowise/cli/main.pyindex 7139efc20..aba555d1a 100644--- a/packages/cli/src/repowise/cli/main.py+++ b/packages/cli/src/repowise/cli/main.py@@ -75,6 +75,7 @@ _OSS_COMMANDS: tuple[tuple[str, str], ...] = (("changes", "changes_cmd:changes_group"),("check", "check_cmd:check_command"),("events", "events_cmd:events_command"),+ ("report", "report_cmd:report_group"),("impacted-tests", "impacted_tests_cmd:impacted_tests_command"),("search", "search_cmd:search_command"),("ask", "ask_cmd:ask_command"),diff --git a/packages/core/src/repowise/core/events/snapshot.py b/packages/core/src/repowise/core/events/snapshot.pyindex 85ab5489a..486613c45 100644--- a/packages/core/src/repowise/core/events/snapshot.py+++ b/packages/core/src/repowise/core/events/snapshot.py@@ -112,8 +112,8 @@ async def collect_facts(capped = len(recent) >= MAX_RECENT_ROWSkey = owner_key(repo_root)key_id = _digest(key.hex()) if key else None- governing, stale = await _decisions(session, repository_id)- contracts = _provided_contracts(repo_root, head_commit)+ governing, stale = await governing_decisions(session, repository_id)+ contracts = provided_contracts(repo_root, head_commit)from repowise.core.analysis.owners import people_resolverfrom repowise.core.components.catalog import owner_group_name@@ -207,9 +207,10 @@ async def _recent_commit_files(session: Any, repository_id: str) -> list[dict[streturn [dict(r._mapping) for r in rows]-async def _decisions(+async def governing_decisions(session: Any, repository_id: str) -> tuple[dict[str, list[tuple[str, str]]], set[str]]:+ """Governing ``(id, title)`` pairs per file, and the ids at or past :data:`STALE_THRESHOLD`."""from repowise.core.persistence.crud.authority import governing_decisions_by_filefrom repowise.core.persistence.models import DecisionRecord@@ -227,7 +228,7 @@ async def _decisions(return governing, set(stale)-def _provided_contracts(repo_root: Path, head_commit: str | None) -> dict[str, dict[str, int]] | None:+def provided_contracts(repo_root: Path, head_commit: str | None) -> dict[str, dict[str, int]] | None:"""``{file: {contract_id: consumer links}}`` for this repo's provided contracts.``None`` outside a workspace, or when the workspace's contracts were notdiff --git a/packages/core/src/repowise/core/events/store.py b/packages/core/src/repowise/core/events/store.pyindex 90f1dbd7a..f7c24d02e 100644--- a/packages/core/src/repowise/core/events/store.py+++ b/packages/core/src/repowise/core/events/store.py@@ -180,7 +180,7 @@ async def record_snapshot(events: list[EngineEvent] = []# A gap marker's stamp never equals a real one, so a run after it is a baseline.if previous is not None and previous.stamp == stamp:- before = await _run_facts(session, previous.id)+ before = await run_facts(session, previous.id)events = await _store_events(session, repo, run, previous, before, facts, settings, taken_at)@@ -222,7 +222,8 @@ async def record_gap(await session.flush()-async def _run_facts(session: Any, run_id: str) -> dict[str, dict[str, Any]]:+async def run_facts(session: Any, run_id: str) -> dict[str, dict[str, Any]]:+ """The component facts one snapshot run stored, by component name."""from repowise.core.persistence.models import ComponentSnapshotrows = await session.execute(diff --git a/packages/core/src/repowise/core/report/__init__.py b/packages/core/src/repowise/core/report/__init__.pynew file mode 100644index 000000000..47cb2ff99--- /dev/null+++ b/packages/core/src/repowise/core/report/__init__.py@@ -0,0 +1,30 @@+"""Evidence reports built from the index: ``repowise report assessment``.++A report is one versioned JSON document (:mod:`.build`) of sections, each a+provider on the ``report-section`` seam (:mod:`.model`, :mod:`.sections`),+whose items keep the OpenSSF Scorecard check-record keys plus ``method`` and+``basis``. Renderers on the ``report-renderer`` seam (:mod:`.render`) turn+the document into JSON, Markdown or self-contained HTML.+"""++from __future__ import annotations++from repowise.core.report.model import (+ BASES,+ INCONCLUSIVE,+ SCHEMA_VERSION,+ ReportContext,+ Section,+ check,+ report_sections,+)++__all__ = [+ "BASES",+ "INCONCLUSIVE",+ "SCHEMA_VERSION",+ "ReportContext",+ "Section",+ "check",+ "report_sections",+]diff --git a/packages/core/src/repowise/core/report/build.py b/packages/core/src/repowise/core/report/build.pynew file mode 100644index 000000000..715eb21f3--- /dev/null+++ b/packages/core/src/repowise/core/report/build.py@@ -0,0 +1,166 @@+"""Build the assessment document from the registered sections.++The caller opens each repository's index (the CLI does it per repo, single+or workspace) and passes a :class:`ReportContext`; this runs the sections+and assembles one versioned document. Paths in the document are relative to+each repository; no local absolute path is written.+"""++from __future__ import annotations++import logging+import re+from datetime import UTC, datetime+from pathlib import Path+from typing import Any++from repowise.core.report.model import (+ DOCS_URL,+ SCHEMA_VERSION,+ ReportContext,+ Section,+ check,+ report_sections,+)++logger = logging.getLogger(__name__)++NOTICE = (+ "This report is evidence about code and components, gathered from the index. "+ "It is not a score of people: owners are counted, never ranked or named."+)+++def available_sections() -> list[tuple[str, Section]]:+ """Every registered section, local ones and plugins', in report order."""+ import repowise.core.report.sections # noqa: F401 (registers the local sections)+ from repowise.core.registry.plugins import load_plugins++ load_plugins()+ pairs = [(name, report_sections.get(name)) for name in report_sections.names]+ return sorted(pairs, key=lambda p: (p[1].order, p[0]))+++async def _index_entry(ctx: ReportContext) -> dict[str, Any]:+ from sqlalchemy import select++ from repowise.core.persistence.models import Repository, SnapshotRun++ repo = await ctx.session.get(Repository, ctx.repository_id)+ snap = await ctx.session.scalar(+ select(SnapshotRun)+ .where(SnapshotRun.repository_id == ctx.repository_id)+ .order_by(SnapshotRun.taken_at.desc(), SnapshotRun.id.desc())+ .limit(1)+ )+ return {+ "alias": ctx.alias,+ "name": repo.name if repo else ctx.repo_root.name,+ "head_commit": ctx.head_commit,+ "last_snapshot": (+ {"taken_at": snap.taken_at.isoformat(), "stamp": snap.stamp} if snap else None+ ),+ }+++async def collect_repo(+ ctx: ReportContext, sections: list[tuple[str, Section]]+) -> tuple[dict[str, Any], list[dict[str, Any]]]:+ """``(repos entry, sections)`` for one repository."""+ out: list[dict[str, Any]] = []+ for name, section in sections:+ try:+ checks = await section.collect(ctx)+ except Exception as exc: # one broken section must not lose the rest+ logger.warning("report section %s failed: %s", name, exc)+ await ctx.session.rollback() # a failed read leaves the session unusable+ checks = [+ check(+ name,+ reason=f"the section failed to collect ({type(exc).__name__})",+ details=[str(exc)],+ method=section.summary,+ basis="unresolved",+ )+ ]+ failed = True+ else:+ failed = False+ if checks is None:+ continue+ doc = {"url": DOCS_URL, "short": section.summary}+ for item in checks:+ item.setdefault("documentation", doc)+ entry = {+ "id": name,+ "title": section.title,+ "summary": section.summary,+ "repo": ctx.alias,+ "checks": checks,+ }+ if failed:+ entry["failed"] = True+ out.append(scrub(entry, ctx.repo_root))+ return await _index_entry(ctx), out+++#: Absolute paths that are not the repository's own: a drive path, a UNC+#: share, or a POSIX path under a top-level directory a machine path starts in.+#: Ceiling: a POSIX path under another top-level directory is kept; contract ids+#: such as ``http::GET::/users`` must survive, so a bare ``/x`` cannot be matched.+_ABSOLUTE = re.compile(+ r"(?<!\w)(?:[A-Za-z]:[\\/]|\\\\)[^\s'\"<>|]*"+ r"|(?<![\w:/.])/(?:home|Users|tmp|var|private|mnt|opt|root|srv|etc|usr|Volumes)/"+ r"[^\s'\"<>|]*"+)+++def _scrub_text(text: str, roots: tuple[str, ...]) -> str:+ for root in roots:+ text = text.replace(root + "/", "").replace(root + "\\", "").replace(root, ".")+ return _ABSOLUTE.sub("<path>", text)+++def scrub(value: Any, repo_root: Path) -> Any:+ """*value* with the repository root made relative and any other absolute+ path replaced, in every string it holds, so a report handed on never+ carries a local path (a catalog read error quotes one, for instance)."""+ resolved = Path(repo_root).resolve()+ forms = {str(repo_root), str(resolved), resolved.as_posix(), Path(repo_root).as_posix()}+ roots = tuple(sorted((f for f in forms if f and f != "."), key=len, reverse=True))++ def walk(v: Any) -> Any:+ if isinstance(v, str):+ return _scrub_text(v, roots)+ if isinstance(v, dict):+ return {walk(k): walk(x) for k, x in v.items()}+ if isinstance(v, list | tuple):+ return [walk(x) for x in v]+ return v++ return walk(value)+++def assemble(+ scope: dict[str, Any],+ parts: list[tuple[dict[str, Any], list[dict[str, Any]]]],+ *,+ generated_at: datetime | None = None,+) -> dict[str, Any]:+ """The canonical document. *scope* is ``{"kind": "repo"|"workspace", "name": ...}``."""+ from repowise.core import __version__+ from repowise.core.events.snapshot import current_stamp++ return {+ "schema_version": SCHEMA_VERSION,+ "kind": "assessment",+ "generated_at": (generated_at or datetime.now(UTC)).replace(microsecond=0).isoformat(),+ "generator": {"name": "repowise", "version": __version__, "stamp": current_stamp()},+ "scope": scope,+ "notice": NOTICE,+ "repos": [entry for entry, _ in parts],+ "sections": [s for _, sections in parts for s in sections],+ }+++__all__ = ["NOTICE", "assemble", "available_sections", "collect_repo", "scrub"]diff --git a/packages/core/src/repowise/core/report/model.py b/packages/core/src/repowise/core/report/model.pynew file mode 100644index 000000000..ac5c05aa6--- /dev/null+++ b/packages/core/src/repowise/core/report/model.py@@ -0,0 +1,179 @@+"""The report document, its evidence items and the ``report-section`` seam.++Each evidence item ("check") keeps the keys of an OpenSSF Scorecard v2 check+result (``name``, ``score``, ``reason``, ``details``, ``documentation`` with+``url`` and ``short``) and adds ``method`` and ``basis``. As in Scorecard,+``score`` is 0 to 10 and -1 means inconclusive. Unlike Scorecard it may be a+one-decimal float, and it is ``None`` on a descriptive item (counts and lists+with no scale): evidence is never turned into a score it does not carry.++A section is registered under ``SeamRegistry("report-section")`` by name; a+plugin adds its own the same way, building its items with :func:`check`.+"""++from __future__ import annotations++from collections.abc import Awaitable, Callable, Iterable+from dataclasses import dataclass, field+from pathlib import Path+from typing import Any++from repowise.core.registry.plugins import SeamRegistry++SCHEMA_VERSION = 1+INCONCLUSIVE = -1+#: ``measured`` (counted from the index), ``inferred`` (derived by a static+#: rule), ``declared`` (read from what the repository says about itself),+#: ``unresolved`` (the evidence is missing) and ``gated`` (held back on a+#: language the finding layer is not verified for).+BASES = ("measured", "inferred", "declared", "unresolved", "gated")+DOCS_URL = (+ "https://github.com/repowise-dev/repowise/blob/main/docs/reference/CLI_REFERENCE.md"+ "#repowise-report-assessment-path"+)+++def check(+ name: str,+ *,+ reason: str,+ basis: str,+ method: str,+ score: float | None = None,+ details: Iterable[str] = (),+ data: dict[str, Any] | None = None,+) -> dict[str, Any]:+ """One evidence item. Missing or held-back evidence is always inconclusive."""+ if basis not in BASES:+ raise ValueError(f"unknown basis {basis!r}; expected one of {BASES}")+ if basis in ("unresolved", "gated"):+ score = INCONCLUSIVE+ elif score is not None:+ score = round(min(max(float(score), 0.0), 10.0), 1)+ item: dict[str, Any] = {+ "name": name,+ "score": score,+ "reason": reason,+ "details": list(details),+ "method": method,+ "basis": basis,+ }+ if data is not None:+ item["data"] = data+ return item+++#: Detail lines one item lists before it says how many more there are.+MAX_DETAILS = 20+++def capped(lines: list[str], limit: int = MAX_DETAILS) -> list[str]:+ """*lines*, cut at *limit* with a closing count of the rest."""+ if len(lines) <= limit:+ return lines+ return [*lines[:limit], f"and {len(lines) - limit} more"]+++#: Component names one summary line lists before it says how many more there are.+MAX_NAMES = 30+++def capped_names(names: list[str]) -> str:+ """*names* joined, cut at :data:`MAX_NAMES` with a count of the rest."""+ shown = ", ".join(names[:MAX_NAMES])+ return shown + (f" and {len(names) - MAX_NAMES} more" if len(names) > MAX_NAMES else "")+++def component_summary(+ name: str,+ *,+ outcomes: dict[str, int],+ quiet: list[str],+ method: str,+ basis: str,+ data: dict[str, Any],+ named: dict[str, list[str]] | None = None,+) -> dict[str, Any]:+ """The one summary row a per-component section opens with.++ Components get an item of their own only when there is something to say;+ the rest are named here, under a label in *named* or as *quiet*, and *data*+ keeps every component's figures, so the JSON loses nothing the shorter+ text leaves out.+ """+ counted = ", ".join(f"{label}: {n}" for label, n in outcomes.items() if n)+ details = [+ f"{label}: {capped_names(names)}" for label, names in (named or {}).items() if names+ ]+ if quiet:+ details.append(f"nothing to note: {capped_names(quiet)}")+ return check(+ name,+ reason=f"{sum(outcomes.values())} component(s); {counted or 'none'}",+ details=details,+ method=method,+ basis=basis,+ data=data,+ )+++@dataclass+class ReportContext:+ """One indexed repository, open for reading, with shared reads cached."""++ session: Any+ repository_id: str+ repo_root: Path+ alias: str | None = None+ head_commit: str | None = None+ _cache: dict[str, Any] = field(default_factory=dict)++ async def components(self) -> Any:+ """Declared and derived components (:class:`RepoComponents`)."""+ if "components" not in self._cache:+ from repowise.core.components.store import load_repo_components, workspace_services++ self._cache["components"] = await load_repo_components(+ self.session,+ self.repository_id,+ self.repo_root,+ services=workspace_services(self.repo_root),+ )+ return self._cache["components"]++ async def rollups(self) -> dict[str, dict[str, Any]]:+ """Component rollups by name, plus the whole repository under ``None``."""+ if "rollups" not in self._cache:+ from repowise.core.components.store import component_rollups++ found = await self.components()+ files = {n: p for n, p in found.resolved.files.items() if p}+ everything = sorted(+ {f for paths in files.values() for f in paths} | set(found.resolved.unassigned)+ )+ rolled: dict[Any, dict[str, Any]] = await component_rollups(+ self.session, self.repository_id, files, found.test_files+ )+ if everything:+ whole = await component_rollups(+ self.session, self.repository_id, {"": everything}, found.test_files+ )+ rolled[None] = whole[""]+ self._cache["rollups"] = rolled+ return self._cache["rollups"]+++@dataclass(frozen=True)+class Section:+ """A report section: *collect* returns its checks, or ``None`` when the+ section does not apply to this repository (it is then left out)."""++ title: str+ #: One line saying what the section measures; the documentation ``short``.+ summary: str+ collect: Callable[[ReportContext], Awaitable[list[dict[str, Any]] | None]]+ #: Sections are listed by this, then by name.+ order: int = 100+++report_sections: SeamRegistry[Section] = SeamRegistry("report-section")diff --git a/packages/core/src/repowise/core/report/render.py b/packages/core/src/repowise/core/report/render.pynew file mode 100644index 000000000..748c3eb6e--- /dev/null+++ b/packages/core/src/repowise/core/report/render.py@@ -0,0 +1,183 @@+"""Renderers for a report document: the ``report-renderer`` seam.++A renderer takes only the document and returns text. ``json`` is the+canonical form; ``markdown`` and ``html`` present the same items. The HTML+is one self-contained file: inline CSS, no scripts, and a content security+policy that forbids every fetch, so it opens offline and prints as is.+"""++from __future__ import annotations++import html+import json+from collections.abc import Callable+from typing import Any++from repowise.core.registry.plugins import SeamRegistry++Renderer = Callable[[dict[str, Any]], str]+++def render_json(document: dict[str, Any]) -> str:+ return json.dumps(document, indent=2, ensure_ascii=False) + "\n"+++def _score(value: Any) -> str:+ if value is None:+ return ""+ return "?" if value == -1 else f"{value:g}"+++def _heading(section: dict[str, Any]) -> str:+ return f"{section['title']} ({section['repo']})" if section.get("repo") else section["title"]+++def _index_line(repo: dict[str, Any]) -> tuple[str, str, str]:+ snap = repo.get("last_snapshot") or {}+ name = repo.get("alias") or repo.get("name") or ""+ if repo.get("indexed") is False:+ return name, "not indexed", "none"+ commit = (repo.get("head_commit") or "")[:12]+ taken = f"{snap['taken_at'][:10]} ({snap['stamp']})" if snap else "none"+ return name, commit, taken+++def _line(text: Any) -> str:+ """*text* on one line, with backticks escaped so it cannot open code."""+ return " ".join(str(text).split()).replace("`", "\\`")+++def _cell(text: Any) -> str:+ return _line(text).replace("|", "\\|")+++def _code(text: Any) -> str:+ """*text* as an inline code span; a backtick cannot be escaped inside one."""+ return "`" + " ".join(str(text).split()).replace("`", "'") + "`"+++def render_markdown(document: dict[str, Any]) -> str:+ gen = document["generator"]+ lines = [+ f"# Assessment: {_line(document['scope'].get('name') or document['scope']['kind'])}",+ "",+ document["notice"],+ "",+ f"Generated {document['generated_at']} by {gen['name']} {gen['version']} "+ f"(stamp {gen['stamp']}), schema version {document['schema_version']}. "+ "Score is 0 to 10, `?` is inconclusive, blank is a descriptive item.",+ "",+ "| Repository | Indexed commit | Last snapshot |",+ "|---|---|---|",+ *(f"| {' | '.join(_cell(v) for v in _index_line(r))} |" for r in document["repos"]),+ ]+ for section in document["sections"]:+ lines += [+ "",+ f"## {_line(_heading(section))}",+ "",+ _line(section["summary"]),+ "",+ "| Check | Score | Basis | Reason |",+ "|---|---|---|---|",+ ]+ for c in section["checks"]:+ name = _code(c["name"]).replace("|", "\\|")+ cells = (name, _score(c["score"]), c["basis"], _cell(c["reason"]))+ lines.append(f"| {' | '.join(cells)} |")+ for method in dict.fromkeys(c["method"] for c in section["checks"]):+ lines += ["", f"Method: {_line(method)}."]+ detailed = [c for c in section["checks"] if c["details"]]+ if detailed:+ lines.append("")+ for c in detailed:+ lines.append(f"- {_code(c['name'])}")+ lines += [f" - {_line(d)}" for d in c["details"]]+ return "\n".join(lines) + "\n"+++_CSS = """+:root { color-scheme: light; --ink: #1d232a; --muted: #5b6672; --line: #d7dde3;+ --band: #f3f5f7; --measured: #1f6f43; --inferred: #6a4d00; --declared: #23527c;+ --unresolved: #6b6b6b; --gated: #8a2f2f; }+body { margin: 0 auto; max-width: 64rem; padding: 2rem 1rem; color: var(--ink);+ background: #fff; font: 14px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif; }+h1 { font-size: 1.6rem; margin: 0 0 .5rem; }+h2 { font-size: 1.15rem; margin: 2rem 0 .25rem; border-bottom: 1px solid var(--line); }+p.muted, .method { color: var(--muted); }+table { width: 100%; border-collapse: collapse; margin: .5rem 0; table-layout: fixed; }+th, td { text-align: left; vertical-align: top; padding: .3rem .5rem;+ border-bottom: 1px solid var(--line); overflow-wrap: anywhere; }+th { background: var(--band); font-weight: 600; }+td.score { width: 4rem; font-variant-numeric: tabular-nums; }+col.name { width: 28%; } col.score { width: 4.5rem; } col.basis { width: 6.5rem; }+code { font: 12px ui-monospace, SFMono-Regular, Consolas, monospace; }+.basis { font-weight: 600; }+.b-measured { color: var(--measured); } .b-inferred { color: var(--inferred); }+.b-declared { color: var(--declared); } .b-unresolved { color: var(--unresolved); }+.b-gated { color: var(--gated); }+ul.details { margin: .25rem 0 0; padding-left: 1.1rem; color: var(--muted); }+.notice { background: var(--band); padding: .6rem .8rem; border-left: 3px solid var(--declared); }+@media print { body { padding: 0; max-width: none; font-size: 11px; }+ h2 { break-after: avoid; } tr { break-inside: avoid; } a { color: inherit; } }+"""+++def render_html(document: dict[str, Any]) -> str:+ e = html.escape+ gen = document["generator"]+ title = f"Assessment: {document['scope'].get('name') or document['scope']['kind']}"+ out = [+ "<!doctype html>",+ '<html lang="en"><head><meta charset="utf-8">',+ '<meta name="viewport" content="width=device-width, initial-scale=1">',+ "<meta http-equiv=\"Content-Security-Policy\" "+ "content=\"default-src 'none'; style-src 'unsafe-inline'\">",+ f"<title>{e(title)}</title><style>{_CSS}</style></head><body>",+ f"<h1>{e(title)}</h1>",+ f'<p class="notice">{e(document["notice"])}</p>',+ f'<p class="muted">Generated {e(document["generated_at"])} by {e(gen["name"])} '+ f"{e(gen['version'])} (stamp {e(gen['stamp'])}), schema version "+ f"{document['schema_version']}. Score is 0 to 10, ? is inconclusive, blank is a "+ "descriptive item.</p>",+ "<table><thead><tr><th>Repository</th><th>Indexed commit</th><th>Last snapshot</th>"+ "</tr></thead><tbody>",+ *(+ "<tr>" + "".join(f"<td>{e(v)}</td>" for v in _index_line(r)) + "</tr>"+ for r in document["repos"]+ ),+ "</tbody></table>",+ ]+ for section in document["sections"]:+ out += [+ f'<section id="{e(section["id"])}"><h2>{e(_heading(section))}</h2>',+ f'<p class="muted">{e(section["summary"])}</p>',+ '<table><colgroup><col class="name"><col class="score"><col class="basis"><col>'+ "</colgroup><thead><tr><th>Check</th><th>Score</th><th>Basis</th><th>Reason</th>"+ "</tr></thead><tbody>",+ ]+ for c in section["checks"]:+ details = "".join(f"<li>{e(d)}</li>" for d in c["details"])+ out.append(+ f"<tr><td><code>{e(c['name'])}</code></td>"+ f'<td class="score">{e(_score(c["score"]))}</td>'+ f'<td class="basis b-{e(c["basis"])}">{e(c["basis"])}</td>'+ f"<td>{e(c['reason'])}"+ + (f'<ul class="details">{details}</ul>' if details else "")+ + "</td></tr>"+ )+ out.append("</tbody></table>")+ for method in dict.fromkeys(c["method"] for c in section["checks"]):+ out.append(f'<p class="method">Method: {e(method)}.</p>')+ out.append("</section>")+ out.append("</body></html>")+ return "\n".join(out) + "\n"+++report_renderers: SeamRegistry[Renderer] = SeamRegistry("report-renderer")+report_renderers.register("json", render_json, default=True)+report_renderers.register("markdown", render_markdown)+report_renderers.register("html", render_html)+++__all__ = ["Renderer", "render_html", "render_json", "render_markdown", "report_renderers"]diff --git a/packages/core/src/repowise/core/report/sections/__init__.py b/packages/core/src/repowise/core/report/sections/__init__.pynew file mode 100644index 000000000..387f8581c--- /dev/null+++ b/packages/core/src/repowise/core/report/sections/__init__.py@@ -0,0 +1,21 @@+"""The local report sections, one module each.++Every module in this package is imported here, and each registers itself on+``report_sections``, so adding a section is adding one file. A section that+needs data some indexes lack (outcomes, for one) returns ``None`` from+``collect`` when the data is absent and is then left out of the report.+"""++from __future__ import annotations++import importlib+import logging+import pkgutil++_log = logging.getLogger("repowise.plugins")++for _module in pkgutil.iter_modules(__path__):+ try: # one broken section must not take the others down, as with plugins+ importlib.import_module(f"{__name__}.{_module.name}")+ except Exception as exc:+ _log.warning("report section module %s failed to load: %s", _module.name, exc)diff --git a/packages/core/src/repowise/core/report/sections/bus_factor.py b/packages/core/src/repowise/core/report/sections/bus_factor.pynew file mode 100644index 000000000..0b5117268--- /dev/null+++ b/packages/core/src/repowise/core/report/sections/bus_factor.py@@ -0,0 +1,94 @@+"""Bus-factor exposure per component. Owners are counted, never named."""++from __future__ import annotations++from typing import Any++from repowise.core.report.model import (+ ReportContext,+ Section,+ check,+ component_summary,+ report_sections,+)++_METHOD = "fewest primary owners who together own over half the owned files"+#: A bus factor at or below this is counted and named in the summary row.+_LOW = 2+++def _details(bus: dict[str, Any], comp: Any) -> list[str]:+ return [+ f"{bus['owned_files']} of {bus['file_count']} file(s) have a known primary owner",+ f"{bus['single_owner_files']} file(s) have a single owner",+ *([f"criticality: {comp.criticality}"] if comp.criticality else []),+ *([f"tags: {', '.join(comp.tags)}"] if comp.tags else []),+ *([bus["note"]] if bus.get("note") else []),+ ]+++async def collect(ctx: ReportContext) -> list[dict[str, Any]]:+ found = await ctx.components()+ rollups = await ctx.rollups()+ declared = {c.name: c for c in found.resolved.components}+ out: list[dict[str, Any]] = []+ figures: dict[str, dict[str, Any]] = {}+ outcomes = {"bus factor 1": 0, "bus factor 2": 0, "3 or more": 0, "unresolved": 0}+ quiet: list[str] = []+ low: dict[str, list[str]] = {"bus factor 1": [], "bus factor 2": []}+ for name, rolled in sorted((n, r) for n, r in rollups.items() if n is not None):+ bus = figures[name] = rolled["bus_factor"]+ if bus["basis"] == "unavailable":+ outcomes["unresolved"] += 1+ out.append(+ check(+ f"bus-factor:{name}", reason=bus["reason"], method=_METHOD, basis="unresolved"+ )+ )+ continue+ if bus["value"] > _LOW:+ outcomes["3 or more"] += 1+ quiet.append(name)+ continue+ label = f"bus factor {bus['value']}"+ outcomes[label] += 1+ comp = declared.get(name)+ # Only a component the catalog marks (criticality or tags) gets its own+ # item; every other low one is counted and named in the summary row.+ if comp is None or not (comp.criticality or comp.tags):+ low[label].append(name)+ continue+ out.append(+ check(+ f"bus-factor:{name}",+ reason=f"bus factor {bus['value']}",+ details=_details(bus, comp),+ method=bus["method"],+ basis=bus["basis"],+ data=bus,+ )+ )+ out.insert(+ 0,+ component_summary(+ "bus-factor",+ outcomes=outcomes,+ quiet=quiet,+ named=low,+ method=_METHOD,+ basis="measured",+ data={"components": figures},+ ),+ )+ return out+++report_sections.register(+ "bus-factor",+ Section(+ title="Bus-factor exposure",+ summary="How few people hold most of each component's files; counted, never named.",+ collect=collect,+ order=30,+ ),+)diff --git a/packages/core/src/repowise/core/report/sections/components.py b/packages/core/src/repowise/core/report/sections/components.pynew file mode 100644index 000000000..d999e374d--- /dev/null+++ b/packages/core/src/repowise/core/report/sections/components.py@@ -0,0 +1,244 @@+"""Component map and posture: each component's health, catalog facts and+ownership findings, from the component rollups and ownership checks."""++from __future__ import annotations++from typing import Any++from repowise.core.report.model import (+ ReportContext,+ Section,+ capped_names,+ check,+ component_summary,+ report_sections,+)++_OWNERSHIP_METHOD = (+ "declared owners (catalog spec.owner, CODEOWNERS, teams.yaml) against indexed "+ "commits in the 90 days before the newest one"+)++#: Summary buckets, most pressing first; a component is counted in one.+_BUCKETS = (+ "ownership findings",+ "owner activity unknown",+ "health gated",+ "no health score",+ "no declared owner",+ "nothing to note",+)+++def _map_item(found: Any, comps: list, directory_issues: list[str]) -> dict[str, Any]:+ """The component map: how many components, where they came from, catalog problems."""+ declared = sum(1 for c, _ in comps if c.declared)+ catalog = found.catalog+ return check(+ "component-map",+ score=None,+ reason=(+ f"{len(comps)} component(s): {declared} declared, {len(comps) - declared} "+ f"derived; {len(found.resolved.unassigned)} file(s) belong to none"+ ),+ details=[+ *(f"catalog file: {s}" for s in catalog.sources),+ *(f"catalog {i.severity}: {i.message}" for i in catalog.issues),+ *(f"team directory: {issue}" for issue in directory_issues),+ ],+ method=(+ "components declared in .repowise/components.yaml or catalog-info.yaml, "+ "else derived from workspace services, module pages or top-level directories"+ ),+ basis="declared" if catalog.sources else "inferred",+ data={+ "declared": declared,+ "derived": len(comps) - declared,+ "unassigned_files": len(found.resolved.unassigned),+ },+ )+++def _gated_item(rollups: dict) -> dict[str, Any] | None:+ gated = ((rollups.get(None) or {}).get("health") or {}).get("gated_files")+ if not gated:+ return None+ return check(+ "health:gated",+ reason=f"{gated} file(s) in languages health is held back on carry no score here",+ method="the language gates every health surface applies",+ basis="gated",+ data={"gated_files": gated},+ )+++def _posture(health: dict[str, Any]) -> tuple[str, float | None, str]:+ """``(basis, score, posture text)`` of one component's health rollup."""+ if health.get("basis") == "measured":+ posture = f"health {health['average']} over {health['scored_files']} scored file(s)"+ return "measured", health["average"], posture+ basis = "gated" if health.get("gated_files") else "unresolved"+ return basis, None, health.get("reason", "no health score")+++def _unknown_owners(ownership: dict[str, Any]) -> int:+ """How many declared owners of a component have activity nobody can check:+ an identity history never shows, a bare handle, or no history at all."""+ return (+ sum(1 for t in ownership.get("declared_teams", []) if t.get("activity") == "unknown")+ + ownership.get("declared_individuals", {}).get("unknown", 0)+ + ownership.get("declared_unresolved", 0)+ )+++def _outcome(ownership: dict[str, Any], basis: str) -> str:+ """The one summary bucket a component is counted in, most pressing first."""+ if ownership.get("findings"):+ return "ownership findings"+ if _unknown_owners(ownership):+ return "owner activity unknown"+ if basis in ("gated", "unresolved"):+ return {"gated": "health gated", "unresolved": "no health score"}[basis]+ if not ownership.get("files_with_declared_owner"):+ return "no declared owner"+ return "nothing to note"+++def _unknown_reason(ownership: dict[str, Any]) -> str:+ """Why a component's owner activity is unknown; equal text means the same owners+ (teams by name, individuals and bare handles by count, never by name)."""+ teams = sorted(+ t["team"] for t in ownership.get("declared_teams", []) if t.get("activity") == "unknown"+ )+ who = f" (teams: {', '.join(teams)})" if teams else ""+ return (+ f"activity of {_unknown_owners(ownership)} declared owner(s){who} is unknown: no "+ "indexed commit matches them, so whether they still change this code cannot be checked"+ )+++def _ownership_items(unknown: dict[str, dict[str, Any]]) -> list[dict[str, Any]]:+ """Unresolved ownership items: one per distinct reason, naming every component+ that shares it, so a repo-wide CODEOWNERS line is one row, not one per component."""+ groups: dict[str, list[str]] = {}+ for name, ownership in unknown.items():+ groups.setdefault(_unknown_reason(ownership), []).append(name)+ out = []+ for i, (reason, names) in enumerate(groups.items(), 1):+ if len(names) == 1:+ label, details = f"ownership:{names[0]}", []+ data: dict[str, Any] = unknown[names[0]]+ else:+ label = "ownership:unknown" if len(groups) == 1 else f"ownership:unknown:{i}"+ details = [f"{len(names)} component(s): {capped_names(names)}"]+ data = {"components": names}+ out.append(+ check(+ label,+ reason=reason,+ details=details,+ method=_OWNERSHIP_METHOD,+ basis="unresolved",+ data=data,+ )+ )+ return out+++def _component_item(+ comp: Any, paths: list[str], figures: dict[str, Any], posture: tuple+) -> dict[str, Any]:+ basis, score, text = posture+ findings = figures["ownership"].get("findings", [])+ group = figures["owning_team"]+ source = f"declared in {comp.declared_in}" if comp.declared else f"derived ({comp.source})"+ details = [+ source,+ *([f"criticality: {comp.criticality}"] if comp.criticality else []),+ *([f"tags: {', '.join(comp.tags)}"] if comp.tags else []),+ *([f"owning team: {group}"] if group else []),+ *(f"{f['kind']}: {f['message']}" for f in findings),+ ]+ method = figures["health"].get("method", "file health scores")+ return check(+ f"component:{comp.name}",+ score=score,+ reason=f"{len(paths)} file(s); {text}; {len(findings)} ownership finding(s)",+ details=details,+ method=f"{method}; ownership: {_OWNERSHIP_METHOD}",+ basis=basis,+ data=figures,+ )+++async def collect(ctx: ReportContext) -> list[dict[str, Any]]:+ from repowise.core.components.catalog import owner_group_name+ from repowise.core.components.store import component_ownership++ found = await ctx.components()+ rollups = await ctx.rollups()+ comps = [(c, found.resolved.files[c.name]) for c in found.resolved.components]+ blocks, directory_issues = await component_ownership(+ ctx.session,+ ctx.repository_id,+ ctx.repo_root,+ comps,+ {n: r["bus_factor"] for n, r in rollups.items() if n is not None},+ )+ out = [_map_item(found, comps, directory_issues)]+ gated = _gated_item(rollups)+ if gated:+ out.append(gated)++ figures: dict[str, dict[str, Any]] = {}+ outcomes = dict.fromkeys(_BUCKETS, 0)+ quiet: list[str] = []+ undeclared: list[str] = []+ items: list[dict[str, Any]] = []+ unknown: dict[str, dict[str, Any]] = {}+ for comp, paths in comps:+ health = rollups.get(comp.name, {}).get("health") or {"basis": "unavailable"}+ figures[comp.name] = {+ "source": comp.source,+ "criticality": comp.criticality,+ "tags": list(comp.tags),+ "owning_team": owner_group_name(comp.owner),+ "file_count": len(paths),+ "health": health,+ "ownership": blocks.get(comp.name, {}),+ }+ ownership = figures[comp.name]["ownership"]+ posture = _posture(health)+ outcome = _outcome(ownership, posture[0])+ outcomes[outcome] += 1+ if outcome == "nothing to note":+ quiet.append(comp.name)+ elif outcome == "no declared owner":+ undeclared.append(comp.name)+ if ownership.get("findings") or posture[0] != "measured":+ items.append(_component_item(comp, paths, figures[comp.name], posture))+ if _unknown_owners(ownership):+ unknown[comp.name] = ownership+ out.append(+ component_summary(+ "components",+ outcomes=outcomes,+ quiet=quiet,+ named={"no declared owner": undeclared},+ method=f"file health scores per component; ownership: {_OWNERSHIP_METHOD}",+ basis="measured",+ data={"components": figures},+ )+ )+ return out + items + _ownership_items(unknown)+++report_sections.register(+ "components",+ Section(+ title="Component map and posture",+ summary="Each component's health, catalog facts and ownership findings.",+ collect=collect,+ order=10,+ ),+)diff --git a/packages/core/src/repowise/core/report/sections/contracts.py b/packages/core/src/repowise/core/report/sections/contracts.pynew file mode 100644index 000000000..98269bc7a--- /dev/null+++ b/packages/core/src/repowise/core/report/sections/contracts.py@@ -0,0 +1,79 @@+"""Contracts each component provides, with consumer links in other repos."""++from __future__ import annotations++from typing import Any++from repowise.core.report.model import ReportContext, Section, capped, check, report_sections++_METHOD = "provider contracts from the workspace contract store and their cross-repo consumer links"+++async def collect(ctx: ReportContext) -> list[dict[str, Any]]:+ from repowise.core.events.snapshot import provided_contracts++ contracts = provided_contracts(ctx.repo_root, ctx.head_commit)+ if contracts is None:+ return [+ check(+ "contracts",+ reason=(+ "contracts are read from a workspace's contract store extracted at this "+ "repository's indexed commit, and none is available"+ ),+ method=_METHOD,+ basis="unresolved",+ )+ ]+ found = await ctx.components()+ out = []+ total = 0+ quiet: list[str] = []+ for comp in found.resolved.components:+ provided: dict[str, int] = {}+ for path in found.resolved.files.get(comp.name, ()):+ for cid, consumers in contracts.get(path, {}).items():+ provided[cid] = provided.get(cid, 0) + consumers+ if not provided:+ quiet.append(comp.name)+ continue+ total += len(provided)+ consumed = sum(1 for n in provided.values() if n)+ out.append(+ check(+ f"contracts:{comp.name}",+ reason=f"{len(provided)} provided contract(s), {consumed} with consumers elsewhere",+ details=capped(+ [f"{cid}: {n} consumer link(s)" for cid, n in sorted(provided.items())]+ ),+ method=_METHOD,+ basis="measured",+ data={"provided": dict(sorted(provided.items()))},+ )+ )+ out.insert(+ 0,+ check(+ "contracts",+ reason=(+ f"{total} provided contract(s) detected across {len(out)} component(s)"+ + ("; zero may mean none were detected, not that none exist" if not total else "")+ ),+ details=[f"none detected: {', '.join(quiet)}"] if quiet else [],+ method=_METHOD,+ basis="measured",+ data={"provided": total},+ ),+ )+ return out+++report_sections.register(+ "contracts",+ Section(+ title="Contracts",+ summary="Contracts each component provides and how many other repos consume them.",+ collect=collect,+ order=60,+ ),+)diff --git a/packages/core/src/repowise/core/report/sections/dead_code.py b/packages/core/src/repowise/core/report/sections/dead_code.pynew file mode 100644index 000000000..7dca2b326--- /dev/null+++ b/packages/core/src/repowise/core/report/sections/dead_code.py@@ -0,0 +1,77 @@+"""Dead code by confidence tier, with the findings gated languages hold back.++Counts come from the stored summary every dead-code surface serves; the+stored ``safe_to_delete`` flag is never read.+"""++from __future__ import annotations++from typing import Any++from repowise.core.report.model import ReportContext, Section, check, report_sections++_METHOD = "static reachability findings, open status, tiered by confidence"+++async def collect(ctx: ReportContext) -> list[dict[str, Any]]:+ from repowise.core.analysis.dead_code.serving import TIER_DESCRIPTIONS+ from repowise.core.components.store import dead_code_ran+ from repowise.core.persistence.crud.analysis.dead_code import get_dead_code_summary++ if not await dead_code_ran(ctx.session, ctx.repository_id):+ return [+ check(+ "dead-code",+ reason="dead-code analysis has not run for this repository",+ method=_METHOD,+ basis="unresolved",+ )+ ]+ summary = await get_dead_code_summary(ctx.session, ctx.repository_id)+ tiers = summary["confidence_summary"]+ out = [+ check(+ "dead-code",+ reason=(+ f"{summary['total_findings']} open finding(s), {summary['total_lines']} line(s) "+ "where counted"+ ),+ details=[f"{kind}: {n}" for kind, n in sorted(summary["by_kind"].items())],+ method=_METHOD,+ basis="inferred",+ data={"by_kind": summary["by_kind"], "lines": summary["total_lines"]},+ )+ ]+ for tier in ("high", "medium", "low"):+ out.append(+ check(+ f"dead-code:{tier}",+ reason=f"{tiers[tier]} finding(s) at {tier} confidence",+ details=[TIER_DESCRIPTIONS[tier]],+ method=_METHOD,+ basis="inferred",+ data={"count": tiers[tier]},+ )+ )+ for language, held in sorted(summary["gated"].items()):+ out.append(+ check(+ f"dead-code:gated:{language}",+ reason=f"{held['count']} finding(s) held back: {held['reason']}",+ method=_METHOD,+ basis="gated",+ data={"count": held["count"]},+ )+ )+ return out+++report_sections.register(+ "dead-code",+ Section(+ title="Dead code",+ summary="Unreachable files and unused exports by confidence tier.",+ collect=collect,+ order=40,+ ),+)diff --git a/packages/core/src/repowise/core/report/sections/decisions.py b/packages/core/src/repowise/core/report/sections/decisions.pynew file mode 100644index 000000000..61f3bde3b--- /dev/null+++ b/packages/core/src/repowise/core/report/sections/decisions.py@@ -0,0 +1,104 @@+"""Governing decisions per component, with the ones gone stale."""++from __future__ import annotations++from typing import Any++from repowise.core.report.model import (+ ReportContext,+ Section,+ capped,+ check,+ component_summary,+ report_sections,+)++_METHOD = (+ "accepted decisions at a governing currency whose recorded files fall in the component; "+ "stale at staleness 0.5 or above"+)+++async def collect(ctx: ReportContext) -> list[dict[str, Any]]:+ from sqlalchemy import func, select++ from repowise.core.events.snapshot import governing_decisions+ from repowise.core.persistence.models import DecisionRecord++ recorded = await ctx.session.scalar(+ select(func.count()).where(DecisionRecord.repository_id == ctx.repository_id)+ )+ if not recorded:+ return [+ check(+ "decisions",+ reason="no decision is recorded for this repository",+ method=_METHOD,+ basis="unresolved",+ )+ ]+ governing, stale = await governing_decisions(ctx.session, ctx.repository_id)+ titles = {d: t for pairs in governing.values() for d, t in pairs}+ out = [+ check(+ "decisions",+ reason=(+ f"{len(titles)} governing decision(s) of {recorded} recorded, {len(stale)} stale"+ + ("; zero may mean none were recorded for these files" if not titles else "")+ ),+ details=capped([f"stale: {d} {titles[d]}" for d in sorted(stale)]),+ method=_METHOD,+ basis="declared",+ data={"governing": len(titles), "recorded": recorded, "stale": sorted(stale)},+ )+ ]+ found = await ctx.components()+ figures: dict[str, dict[str, Any]] = {}+ outcomes = {"with stale decisions": 0, "governed, none stale": 0, "no governing decision": 0}+ quiet: list[str] = []+ noted: list[dict[str, Any]] = []+ for comp in found.resolved.components:+ paths = found.resolved.files.get(comp.name, ())+ ids = sorted({d for p in paths for d, _ in governing.get(p, ())})+ gone = [d for d in ids if d in stale]+ figures[comp.name] = {"governing": ids, "stale": gone}+ if not gone:+ outcomes["governed, none stale" if ids else "no governing decision"] += 1+ if ids:+ quiet.append(comp.name)+ continue+ outcomes["with stale decisions"] += 1+ noted.append(+ check(+ f"decisions:{comp.name}",+ reason=f"{len(ids)} governing decision(s), {len(gone)} stale",+ details=capped(+ [f"{d}{' (stale)' if d in stale else ''}: {titles[d]}" for d in ids]+ ),+ method=_METHOD,+ basis="declared",+ data=figures[comp.name],+ )+ )+ out.append(+ component_summary(+ "decisions:components",+ outcomes=outcomes,+ quiet=quiet,+ method=_METHOD,+ basis="declared",+ data={"components": figures},+ )+ )+ return out + noted+++report_sections.register(+ "decisions",+ Section(+ title="Governing decisions",+ summary="Recorded decisions that bind each component's files, and which are stale.",+ collect=collect,+ order=70,+ ),+)diff --git a/packages/core/src/repowise/core/report/sections/hotspots.py b/packages/core/src/repowise/core/report/sections/hotspots.pynew file mode 100644index 000000000..b1010b511--- /dev/null+++ b/packages/core/src/repowise/core/report/sections/hotspots.py@@ -0,0 +1,88 @@+"""Hotspots: files git history flags for high recent churn, per component."""++from __future__ import annotations++from typing import Any++from repowise.core.report.model import (+ ReportContext,+ Section,+ capped,+ check,+ component_summary,+ report_sections,+)++_METHOD = "files git history flags as hotspots (high recent churn), from the component rollups"+++async def collect(ctx: ReportContext) -> list[dict[str, Any]]:+ rollups = await ctx.rollups()+ whole = (rollups.get(None) or {}).get("hotspots") or {"basis": "unavailable"}+ if whole["basis"] != "measured":+ return [+ check(+ "hotspots",+ reason=whole.get("reason", "no git history indexed"),+ method=_METHOD,+ basis="unresolved",+ )+ ]+ components = sorted((n, r["hotspots"]) for n, r in rollups.items() if n is not None)+ hot = sorted(+ ((n, h) for n, h in components if h["basis"] == "measured" and h["count"]),+ key=lambda kv: (-kv[1]["count"], kv[0]),+ )+ unresolved = [(n, h) for n, h in components if h["basis"] != "measured"]+ quiet = [n for n, h in components if h["basis"] == "measured" and not h["count"]]+ out = [+ check(+ "hotspots",+ reason=f"{whole['count']} hotspot file(s) across {len(hot)} component(s)",+ details=capped([f"{name}: {h['count']}" for name, h in hot]),+ method=_METHOD,+ basis="measured",+ data={"count": whole["count"], "top": whole["top"]},+ ),+ component_summary(+ "hotspots:components",+ outcomes={+ "with hotspots": len(hot),+ "no git history": len(unresolved),+ "no hotspots": len(quiet),+ },+ quiet=quiet,+ method=_METHOD,+ basis="measured",+ data={"components": dict(components)},+ ),+ ]+ for name, h in hot:+ rest = h["count"] - len(h["top"])+ out.append(+ check(+ f"hotspots:{name}",+ reason=f"{h['count']} hotspot file(s)",+ # The rollup keeps the top files by hotspot score; the rest are counted.+ details=[*h["top"], *([f"and {rest} more"] if rest > 0 else [])],+ method=_METHOD,+ basis="measured",+ data=h,+ )+ )+ for name, h in unresolved:+ out.append(+ check(f"hotspots:{name}", reason=h["reason"], method=_METHOD, basis="unresolved")+ )+ return out+++report_sections.register(+ "hotspots",+ Section(+ title="Hotspots",+ summary="Files with high recent churn, counted per component.",+ collect=collect,+ order=20,+ ),+)diff --git a/packages/core/src/repowise/core/report/sections/provenance.py b/packages/core/src/repowise/core/report/sections/provenance.pynew file mode 100644index 000000000..97b1eccaa--- /dev/null+++ b/packages/core/src/repowise/core/report/sections/provenance.py@@ -0,0 +1,117 @@+"""Provenance: how many recent commits carry a known source, and which agents+and models the agent-marked ones name.++Accountability only: agents and models are named, not counted, so no share of+agent work and no comparison with people can be read off the report. Unknown+commits are never counted as human. Nothing is shown when the repository+switches attribution off.+"""++from __future__ import annotations++from datetime import timedelta+from typing import Any++from sqlalchemy import func, select++from repowise.core.report.model import ReportContext, Section, check, report_sections++_METHOD = (+ "public git markers (bot authors, trailers, footers, git-ai notes, Agent Trace files) "+ "and opted-in capture, over commits in the {days} days before the newest indexed one"+)+++def _tally(rows: Any) -> tuple[int, int, set[str], set[str]]:+ """``(commits, known, agents, models)`` from ``(attribution, agent, model, n)`` rows."""+ from repowise.core.attribution import AGENT, UNKNOWN, commit_label++ total = known = 0+ agents: set[str] = set()+ models: set[str] = set()+ for attribution, agent, model, n in rows:+ label = commit_label(attribution, agent)+ total += n+ if label != UNKNOWN:+ known += n+ if label == AGENT:+ agents.add(agent or "unnamed agent")+ if model:+ models.add(model)+ return total, known, agents, models+++async def collect(ctx: ReportContext) -> list[dict[str, Any]]:+ from repowise.core.attribution import attribution_enabled+ from repowise.core.events.snapshot import RECENT_DAYS+ from repowise.core.persistence.models import GitCommit++ method = _METHOD.format(days=RECENT_DAYS)+ if not attribution_enabled(ctx.repo_root):+ return [+ check(+ "provenance",+ reason="attribution is switched off for this repository",+ method=method,+ basis="unresolved",+ )+ ]+ repo = GitCommit.repository_id == ctx.repository_id+ newest = await ctx.session.scalar(select(func.max(GitCommit.committed_at)).where(repo))+ if newest is None:+ return [+ check("provenance", reason="no commits are indexed", method=method, basis="unresolved")+ ]+ rows = await ctx.session.execute(+ select(GitCommit.attribution, GitCommit.agent_name, GitCommit.agent_model_id, func.count())+ .where(repo, GitCommit.committed_at >= newest - timedelta(days=RECENT_DAYS))+ .group_by(GitCommit.attribution, GitCommit.agent_name, GitCommit.agent_model_id)+ )+ total, known, agents, models = _tally(rows.all())+ as_of = newest.date().isoformat()+ return [+ check(+ "provenance:coverage",+ reason=f"{known} of {total} commit(s) up to {as_of} carry a known source",+ details=[f"{total - known} commit(s) carry no marker; their source is unknown"],+ method=method,+ # Coverage is how much is known, not a grade: no markers is unknown.+ basis="measured" if known else "unresolved",+ data={"commits": total, "known": known, "window_days": RECENT_DAYS, "as_of": as_of},+ ),+ check(+ "provenance:agents",+ reason=(+ f"{len(agents)} agent(s) named on agent-marked commits"+ if agents+ else "no commit in the window names an agent"+ ),+ details=sorted(agents),+ method=method,+ basis="declared",+ data={"agents": sorted(agents)},+ ),+ check(+ "provenance:models",+ reason=(+ f"{len(models)} model(s) named by Agent Trace records"+ if models+ else "no Agent Trace record in the window names a model"+ ),+ details=sorted(models),+ method="the model an Agent Trace record names for its commit",+ basis="declared",+ data={"models": sorted(models)},+ ),+ ]+++report_sections.register(+ "provenance",+ Section(+ title="Provenance",+ summary="Coverage of known provenance, and which agents and models produced changes.",+ collect=collect,+ order=80,+ ),+)diff --git a/packages/core/src/repowise/core/report/sections/reach.py b/packages/core/src/repowise/core/report/sections/reach.pynew file mode 100644index 000000000..afae4dcb0--- /dev/null+++ b/packages/core/src/repowise/core/report/sections/reach.py@@ -0,0 +1,108 @@+"""Test reach: line coverage where a report was ingested (measured), and+which production files a test reaches statically (inferred), kept apart."""++from __future__ import annotations++from typing import Any++from repowise.core.report.model import (+ ReportContext,+ Section,+ check,+ component_summary,+ report_sections,+)+++def _items(component: str | None, reach: dict[str, Any]) -> list[dict[str, Any]]:+ """The items for one component, or the whole repository when *component* is ``None``."""+ suffix = f":{component}" if component is not None else ""+ if reach["basis"] == "unavailable":+ return [+ check(+ f"test-reach{suffix}",+ reason=reach["reason"],+ method="test pairing from health analysis",+ basis="unresolved",+ )+ ]+ out = [+ check(+ f"test-reach{suffix}",+ score=reach["share"] * 10,+ reason=(+ f"{reach['reached_files']} of {reach['production_files']} production file(s) "+ "reached by a test"+ ),+ method=reach["method"],+ basis="inferred",+ data={k: v for k, v in reach.items() if k != "line_coverage"},+ )+ ]+ measured = reach.get("line_coverage")+ if measured:+ out.append(+ check(+ f"line-coverage{suffix}",+ score=measured["pct"] / 10,+ reason=(+ f"{measured['pct']}% line coverage over {measured['measured_files']} file(s)"+ ),+ method=measured["method"],+ basis="measured",+ data=measured,+ )+ )+ return out+++async def collect(ctx: ReportContext) -> list[dict[str, Any]]:+ rollups = await ctx.rollups()+ whole = rollups.get(None)+ if whole is None:+ return []+ out = _items(None, whole["test_reach"])+ if whole["test_reach"]["basis"] != "unavailable" and "line_coverage" not in whole["test_reach"]:+ out.append(+ check(+ "line-coverage",+ reason="no coverage report is ingested; `repowise coverage add` ingests one",+ method="NLOC-weighted line coverage from ingested coverage reports",+ basis="unresolved",+ )+ )+ figures: dict[str, dict[str, Any]] = {}+ outcomes = {"under half reached": 0, "half or more reached": 0, "unresolved": 0}+ quiet: list[str] = []+ noted: list[dict[str, Any]] = []+ for name, rolled in sorted((n, r) for n, r in rollups.items() if n is not None):+ reach = figures[name] = rolled["test_reach"]+ if reach["basis"] == "unavailable":+ outcomes["unresolved"] += 1+ noted.extend(_items(name, reach))+ continue+ outcomes["under half reached" if reach["share"] < 0.5 else "half or more reached"] += 1+ quiet.append(name)+ out.append(+ component_summary(+ "test-reach:components",+ outcomes=outcomes,+ quiet=quiet,+ method="per-component test reach and line coverage; figures in data",+ basis="inferred",+ data={"components": figures},+ )+ )+ out.extend(noted)+ return out+++report_sections.register(+ "test-reach",+ Section(+ title="Test reach",+ summary="Measured line coverage and inferred test reach, reported separately.",+ collect=collect,+ order=50,+ ),+)diff --git a/packages/core/src/repowise/core/report/sections/trend.py b/packages/core/src/repowise/core/report/sections/trend.pynew file mode 100644index 000000000..bef0ea42f--- /dev/null+++ b/packages/core/src/repowise/core/report/sections/trend.py@@ -0,0 +1,107 @@+"""Compared with a quarter ago: what moved between the newest component+snapshot and the newest one at least 90 days older under the same stamp.++Reuses the event diff rules, so a move counts here exactly when it would+count as an event. Snapshots under different analyzer or parser stamps are+never compared. Agent-share moves are left out: the report shows no share.+"""++from __future__ import annotations++from collections import defaultdict+from datetime import timedelta+from typing import Any++from sqlalchemy import select++from repowise.core.report.model import ReportContext, Section, capped, check, report_sections++QUARTER_DAYS = 90+_LEFT_OUT = frozenset({"attribution_jump"})+_METHOD = (+ "the event diff rules, for the event kinds the repository has on, applied to two "+ f"stored component snapshots with the same analyzer and parser stamp, at least "+ f"{QUARTER_DAYS} days apart"+)+++async def collect(ctx: ReportContext) -> list[dict[str, Any]]:+ from repowise.core.events.diff import diff_snapshots+ from repowise.core.events.model import KINDS+ from repowise.core.events.store import GAP_STAMP, load_event_settings, run_facts+ from repowise.core.persistence.models import SnapshotRun++ runs = select(SnapshotRun).where(+ SnapshotRun.repository_id == ctx.repository_id,+ SnapshotRun.stamp.not_like(f"{GAP_STAMP}%"),+ )+ newest = await ctx.session.scalar(+ runs.order_by(SnapshotRun.taken_at.desc(), SnapshotRun.id.desc()).limit(1)+ )+ baseline = None+ if newest is not None:+ baseline = await ctx.session.scalar(+ runs.where(+ SnapshotRun.stamp == newest.stamp,+ SnapshotRun.taken_at <= newest.taken_at - timedelta(days=QUARTER_DAYS),+ )+ .order_by(SnapshotRun.taken_at.desc(), SnapshotRun.id.desc())+ .limit(1)+ )+ if baseline is None:+ return [+ check(+ "trend",+ reason=(+ f"no stored snapshot from {QUARTER_DAYS} or more days before the newest "+ "one under the same stamp"+ ),+ method=_METHOD,+ basis="unresolved",+ )+ ]+ before = await run_facts(ctx.session, baseline.id)+ after = await run_facts(ctx.session, newest.id)+ # The kinds this repository's events config turns on, so a move counts here+ # exactly when it would fire as an event (new_hotspot is off by default).+ kinds = load_event_settings(ctx.repo_root).kinds - _LEFT_OUT+ moved: dict[str, list[str]] = defaultdict(list)+ for kind, component, subject, _evidence in diff_snapshots(before, after):+ if kind in kinds:+ moved[kind].append(f"{component}: {subject}" if subject else component)+ span = f"{baseline.taken_at.date().isoformat()} to {newest.taken_at.date().isoformat()}"+ out = [+ check(+ "trend",+ reason=f"{sum(len(v) for v in moved.values())} move(s) from {span}",+ method=_METHOD,+ basis="measured",+ data={+ "from": baseline.taken_at.isoformat(),+ "to": newest.taken_at.isoformat(),+ "stamp": newest.stamp,+ },+ )+ ]+ for kind in sorted(moved):+ out.append(+ check(+ f"trend:{kind}",+ reason=f"{KINDS[kind].summary}: {len(moved[kind])}",+ details=capped(moved[kind]),+ method=_METHOD,+ basis="measured",+ )+ )+ return out+++report_sections.register(+ "trend",+ Section(+ title="Compared with a quarter ago",+ summary="What moved per component since a snapshot at least 90 days older.",+ collect=collect,+ order=90,+ ),+)diff --git a/tests/unit/cli/test_lazy_commands.py b/tests/unit/cli/test_lazy_commands.pyindex 1b2e2477b..34d684696 100644--- a/tests/unit/cli/test_lazy_commands.py+++ b/tests/unit/cli/test_lazy_commands.py@@ -39,7 +39,7 @@ _EXPECTED_NAMES = frozenset("events", "expand","export", "generate", "generate-claude-md", "health", "hook","impacted-tests", "init", "login", "logout", "mcp", "next", "overlap", "plugins",- "publish", "reindex",+ "publish", "reindex", "report","restyle","risk", "saved", "savings", "search", "security", "serve", "status", "symbol","telemetry", "uninstall", "update", "watch", "whats-new", "whoami", "why",diff --git a/tests/unit/core/test_report.py b/tests/unit/core/test_report.pynew file mode 100644index 000000000..72f74a533--- /dev/null+++ b/tests/unit/core/test_report.py@@ -0,0 +1,629 @@+"""`repowise report assessment`: sections over a fixture index, the section+seam, the renderers, and the CLI."""++from __future__ import annotations++import json+import sys+from datetime import UTC, datetime, timedelta+from pathlib import Path++import pytest+from click.testing import CliRunner++from repowise.core.report.model import ReportContext, Section, check, report_sections++_NOW = datetime(2026, 10, 1, tzinfo=UTC)+++async def _seed(root: Path) -> None:+ """A two-component index: ``api`` (Python) and ``web`` (Java, a gated language)."""+ from repowise.core.persistence import (+ create_engine,+ create_session_factory,+ get_session,+ init_db,+ upsert_repository,+ )+ from repowise.core.persistence.models import (+ DeadCodeFinding,+ GitCommit,+ GitMetadata,+ GraphNode,+ HealthFileMetric,+ )++ (root / ".repowise").mkdir(parents=True, exist_ok=True)+ engine = create_engine(f"sqlite+aiosqlite:///{(root / '.repowise' / 'wiki.db').as_posix()}")+ try:+ await init_db(engine)+ async with get_session(create_session_factory(engine)) as session:+ repo = await upsert_repository(session, name="shop", local_path=str(root))+ repo.head_commit = "c" * 40+ rid = repo.id+ files = {"api/a.py": False, "api/b.py": False, "api/test_a.py": True, "web/W.java": False}+ session.add_all(+ GraphNode(repository_id=rid, node_id=p, node_type="file", is_test=t)+ for p, t in files.items()+ )+ owners = {"api/a.py": "Alice", "api/b.py": "Bob", "web/W.java": "Alice"}+ session.add_all(+ GitMetadata(+ repository_id=rid,+ file_path=p,+ primary_owner_name=o,+ primary_owner_email=f"{o.lower()}@example.com",+ is_hotspot=p == "api/a.py",+ )+ for p, o in owners.items()+ )+ session.add_all(+ [+ HealthFileMetric(+ repository_id=rid, file_path="api/a.py", score=6.0, nloc=100,+ has_test_file=True, line_coverage_pct=80.0,+ ),+ HealthFileMetric(+ repository_id=rid, file_path="api/b.py", score=9.0, nloc=100,+ has_test_file=False,+ ),+ HealthFileMetric(+ repository_id=rid, file_path="web/W.java", score=3.0, nloc=50,+ has_test_file=False,+ ),+ ]+ )+ session.add_all(+ [+ DeadCodeFinding(+ repository_id=rid, kind="unused_export", file_path="api/b.py",+ symbol_name="old", confidence=0.9, lines=10, status="open",+ safe_to_delete=True,+ ),+ DeadCodeFinding(+ repository_id=rid, kind="unreachable_file", file_path="web/W.java",+ confidence=1.0, lines=50, status="open",+ ),+ ]+ )+ labels = [+ ("agent", "claude", "anthropic/claude-x"),+ ("agent", "codex", None),+ ("human_attested", None, None),+ ("unknown", None, None),+ ]+ session.add_all(+ GitCommit(+ repository_id=rid,+ sha=f"{i:040d}",+ author_name="Alice",+ author_email="[email protected]",+ committed_at=_NOW - timedelta(days=i),+ attribution=label,+ agent_name=agent,+ agent_model_id=model,+ )+ for i, (label, agent, model) in enumerate(labels)+ )+ finally:+ await engine.dispose()+++async def ctx(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):+ from repowise.core.persistence import create_engine, create_session_factory, get_session+ from repowise.core.persistence.models import Repository++ monkeypatch.delenv("REPOWISE_DB_URL", raising=False)+ root = (tmp_path / "shop").resolve()+ await _seed(root)+ engine = create_engine(f"sqlite+aiosqlite:///{(root / '.repowise' / 'wiki.db').as_posix()}")+ async with get_session(create_session_factory(engine)) as session:+ repo = (await session.execute(Repository.__table__.select())).first()+ yield ReportContext(session, repo.id, root, head_commit=repo.head_commit)+ await engine.dispose()+++def _by_name(items: list[dict]) -> dict[str, dict]:+ return {c["name"]: c for c in items}+++async def _section(name: str, ctx: ReportContext) -> dict[str, dict]:+ import repowise.core.report.sections # noqa: F401++ return _by_name(await report_sections.get(name).collect(ctx))+++# ---------------------------------------------------------------------------+# Evidence items+# ---------------------------------------------------------------------------+++def test_check_keeps_scorecard_keys_and_forces_inconclusive_without_evidence():+ item = check("x", reason="r", basis="measured", method="m", score=12.34, details=["d"])+ assert list(item) == ["name", "score", "reason", "details", "method", "basis"]+ assert item["score"] == 10.0+ assert check("x", reason="r", basis="gated", method="m", score=7)["score"] == -1+ assert check("x", reason="r", basis="unresolved", method="m")["score"] == -1+ assert check("x", reason="r", basis="declared", method="m")["score"] is None+ with pytest.raises(ValueError):+ check("x", reason="r", basis="guessed", method="m")+++# ---------------------------------------------------------------------------+# Sections+# ---------------------------------------------------------------------------+++async def test_components_section_scores_health_and_marks_gated_languages(ctx):+ items = await _section("components", ctx)+ assert items["component-map"]["data"]["derived"] == 2+ summary = items["components"]+ # api has nothing to note, so it is named in the summary; its figures stay in data.+ assert "component:api" not in items+ assert summary["details"] == ["no declared owner: api"]+ assert summary["data"]["components"]["api"]["health"]["average"] == 7.5+ web = items["component:web"] # gated evidence always keeps its own item+ assert (web["basis"], web["score"]) == ("gated", -1)+ assert items["health:gated"]["data"]["gated_files"] == 1+++async def test_unknown_owner_activity_is_unresolved_never_quiet(ctx):+ (ctx.repo_root / ".github").mkdir()+ (ctx.repo_root / ".github" / "CODEOWNERS").write_text("api/ @org/ghosts\n", encoding="utf-8")+ items = await _section("components", ctx)+ owners = items["ownership:api"] # a reason only one component has keeps its own item+ assert (owners["basis"], owners["score"]) == ("unresolved", -1)+ assert "(teams: ghosts)" in owners["reason"]+ assert "owner activity unknown: 1" in items["components"]["reason"]+ assert all("nothing to note" not in d for d in items["components"]["details"])+++async def test_components_sharing_unknown_owners_fold_into_one_row(ctx):+ (ctx.repo_root / ".github").mkdir()+ (ctx.repo_root / ".github" / "CODEOWNERS").write_text("* @org/ghosts\n", encoding="utf-8")+ items = await _section("components", ctx)+ row = items["ownership:unknown"]+ assert (row["basis"], row["data"]) == ("unresolved", {"components": ["api", "web"]})+ assert row["details"] == ["2 component(s): api, web"]+ assert not any(n.startswith("ownership:") and n != "ownership:unknown" for n in items)+ assert "owner activity unknown: 2" in items["components"]["reason"]+++async def test_hotspots_counted_per_component(ctx):+ items = await _section("hotspots", ctx)+ assert items["hotspots"]["data"]["count"] == 1+ assert items["hotspots:api"]["details"] == ["api/a.py"]+ assert "hotspots:web" not in items+++async def test_bus_factor_is_per_component_and_names_nobody(ctx):+ items = await _section("bus-factor", ctx)+ # No catalog marks either component, so both are counted and named in the summary.+ assert set(items) == {"bus-factor"}+ summary = items["bus-factor"]+ assert summary["reason"] == "2 component(s); bus factor 1: 1, bus factor 2: 1"+ assert summary["details"] == ["bus factor 1: web", "bus factor 2: api"]+ api = summary["data"]["components"]["api"]+ assert (api["value"], api["basis"]) == (2, "inferred") # under five owned files+ text = json.dumps(items)+ assert "Alice" not in text and "Bob" not in text and "example.com" not in text+++async def test_bus_factor_item_for_a_component_the_catalog_marks(ctx):+ (ctx.repo_root / ".repowise" / "components.yaml").write_text(+ "apiVersion: backstage.io/v1alpha1\nkind: Component\nmetadata:\n name: api\n"+ " annotations:\n repowise.dev/paths: api/**\n repowise.dev/criticality: critical\n"+ "spec: {type: service, lifecycle: production, owner: group:default/core}\n",+ encoding="utf-8",+ )+ fresh = ReportContext(ctx.session, ctx.repository_id, ctx.repo_root)+ items = await _section("bus-factor", fresh)+ assert set(items) == {"bus-factor", "bus-factor:api"}+ assert "criticality: critical" in items["bus-factor:api"]["details"]+ assert items["bus-factor"]["details"] == ["bus factor 1: web"]+++async def test_dead_code_tiers_and_gated_findings(ctx):+ items = await _section("dead-code", ctx)+ assert items["dead-code:high"]["data"]["count"] == 1+ assert items["dead-code:medium"]["data"]["count"] == 0+ gated = items["dead-code:gated:java"]+ assert (gated["basis"], gated["score"], gated["data"]["count"]) == ("gated", -1, 1)+ assert "safe" not in json.dumps(items).lower()+++async def test_dead_code_not_run_is_inconclusive(ctx):+ from sqlalchemy import delete++ from repowise.core.persistence.models import DeadCodeFinding++ await ctx.session.execute(delete(DeadCodeFinding))+ items = await _section("dead-code", ctx)+ assert items["dead-code"]["basis"] == "unresolved"+++async def test_test_reach_keeps_measured_and_inferred_apart(ctx):+ items = await _section("test-reach", ctx)+ assert (items["test-reach"]["basis"], items["test-reach"]["score"]) == ("inferred", 3.3)+ assert (items["line-coverage"]["basis"], items["line-coverage"]["score"]) == ("measured", 8.0)+ per = items["test-reach:components"]+ assert per["data"]["components"]["api"]["share"] == 0.5+ assert per["details"] == ["nothing to note: api, web"]+ assert "test-reach:api" not in items+++async def test_unavailable_test_reach_is_said_once(ctx):+ from sqlalchemy import delete++ from repowise.core.persistence.models import HealthFileMetric++ await ctx.session.execute(delete(HealthFileMetric))+ items = await _section("test-reach", ctx)+ assert items["test-reach"]["basis"] == "unresolved"+ assert "line-coverage" not in items+ assert items["test-reach:api"]["basis"] == "unresolved" # never dropped+++async def test_contracts_unavailable_outside_a_workspace_then_measured(ctx, monkeypatch):+ from repowise.core.events import snapshot++ items = await _section("contracts", ctx)+ assert items["contracts"]["basis"] == "unresolved"+ monkeypatch.setattr(snapshot, "provided_contracts", lambda *_a: {})+ none = (await _section("contracts", ctx))["contracts"]+ assert "zero may mean none were detected" in none["reason"]+ monkeypatch.setattr(+ snapshot, "provided_contracts", lambda *_a: {"api/a.py": {"http::GET::/x": 2}}+ )+ items = await _section("contracts", ctx)+ assert items["contracts:api"]["data"]["provided"] == {"http::GET::/x": 2}+ assert items["contracts"]["data"]["provided"] == 1+++async def test_decisions_per_component_with_stale(ctx, monkeypatch):+ from repowise.core.events import snapshot++ async def governing(*_a):+ return {"api/a.py": [("d1", "Use JWT")], "api/b.py": [("d2", "One DB")]}, {"d2"}++ from repowise.core.persistence.models import DecisionRecord++ monkeypatch.setattr(snapshot, "governing_decisions", governing)+ empty = await _section("decisions", ctx)+ assert list(empty) == ["decisions"] and empty["decisions"]["basis"] == "unresolved"+ ctx.session.add(DecisionRecord(repository_id=ctx.repository_id, title="Use JWT"))+ await ctx.session.flush()+ items = await _section("decisions", ctx)+ assert items["decisions"]["data"] == {"governing": 2, "recorded": 1, "stale": ["d2"]}+ assert items["decisions:api"]["details"] == ["d1: Use JWT", "d2 (stale): One DB"]+ assert "decisions:web" not in items+ assert items["decisions:components"]["data"]["components"]["web"] == {+ "governing": [],+ "stale": [],+ }+++async def test_provenance_names_agents_without_counting_them(ctx):+ items = await _section("provenance", ctx)+ cov = items["provenance:coverage"]+ assert cov["data"]["known"] == 3 and cov["data"]["commits"] == 4+ assert (cov["basis"], cov["score"]) == ("measured", None) # coverage is not a grade+ assert items["provenance:agents"]["details"] == ["claude", "codex"]+ assert items["provenance:models"]["details"] == ["anthropic/claude-x"]+ text = json.dumps(items)+ assert "share" not in text and "human" not in text+++async def test_provenance_without_markers_is_unresolved(ctx):+ from sqlalchemy import update++ from repowise.core.persistence.models import GitCommit++ await ctx.session.execute(update(GitCommit).values(attribution="unknown", agent_name=None))+ cov = (await _section("provenance", ctx))["provenance:coverage"]+ assert (cov["basis"], cov["score"]) == ("unresolved", -1)+++async def test_provenance_shows_nothing_when_attribution_is_off(ctx):+ (ctx.repo_root / ".repowise" / "config.yaml").write_text(+ "attribution:\n enabled: false\n", encoding="utf-8"+ )+ items = await _section("provenance", ctx)+ assert list(items) == ["provenance"] and items["provenance"]["basis"] == "unresolved"+++async def test_trend_needs_a_same_stamp_snapshot_a_quarter_older(ctx):+ from repowise.core.persistence.models import ComponentSnapshot, SnapshotRun++ async def run(days_ago: int, stamp: str, hotspots: list[str]) -> None:+ r = SnapshotRun(+ repository_id=ctx.repository_id, taken_at=_NOW - timedelta(days=days_ago), stamp=stamp+ )+ ctx.session.add(r)+ await ctx.session.flush()+ facts = {"definition": "d", "hotspots": hotspots}+ ctx.session.add(ComponentSnapshot(run_id=r.id, component="api", facts_json=json.dumps(facts)))+ await ctx.session.flush()++ await run(0, "s1", ["a.py", "b.py"])+ await run(100, "s0", ["a.py"])+ assert (await _section("trend", ctx))["trend"]["basis"] == "unresolved"+ await run(120, "s1", ["a.py"])+ items = await _section("trend", ctx)+ assert items["trend"]["basis"] == "measured"+ # new_hotspot is off by default in the events config, so it does not count here.+ assert "trend:new_hotspot" not in items+ (ctx.repo_root / ".repowise" / "config.yaml").write_text(+ "events:\n kinds: {new_hotspot: true}\n", encoding="utf-8"+ )+ items = await _section("trend", ctx)+ assert items["trend:new_hotspot"]["details"] == ["api: b.py"]+++def test_long_detail_lists_are_capped():+ from repowise.core.report.model import capped++ assert capped([str(i) for i in range(25)], 20)[-1] == "and 5 more"+ assert capped(["a"], 20) == ["a"]+++# ---------------------------------------------------------------------------+# Seam: a third-party section+# ---------------------------------------------------------------------------+++async def test_a_plugin_section_registers_and_appears(ctx, tmp_path, monkeypatch):+ from repowise.core.registry import plugins+ from repowise.core.report.build import assemble, available_sections, collect_repo++ (tmp_path / "rw_report_plugin.py").write_text(+ "from repowise.core.report import Section, check, report_sections\n"+ "async def collect(ctx):\n"+ " return [check('licence', reason='MIT', basis='declared', method='LICENSE file')]\n"+ "report_sections.register('licence', Section('Licence', 'The declared licence.', collect, 5))\n",+ encoding="utf-8",+ )+ monkeypatch.syspath_prepend(str(tmp_path))+ monkeypatch.setenv("REPOWISE_PLUGINS", "rw_report_plugin")+ plugins.reset()+ try:+ sections = available_sections()+ assert sections[0][0] == "licence"+ doc = assemble({"kind": "repo", "name": "shop"}, [await collect_repo(ctx, sections[:1])])+ (section,) = doc["sections"]+ assert section["checks"][0]["documentation"]["short"] == "The declared licence."+ finally:+ report_sections._impls.pop("licence", None)+ sys.modules.pop("rw_report_plugin", None)+ plugins.reset()+++async def test_a_failing_section_is_inconclusive_not_fatal(ctx):+ from repowise.core.report.build import collect_repo++ async def boom(_ctx):+ raise RuntimeError("nope")++ async def leak(ctx_):+ raise OSError(f"cannot open {ctx_.repo_root / 'x.yaml'}")++ _entry, sections = await collect_repo(+ ctx, [("broken", Section("Broken", "b", boom)), ("leak", Section("Leak", "l", leak))]+ )+ assert sections[0]["checks"][0]["score"] == -1 and sections[0]["failed"] is True+ assert sections[0]["checks"][0]["details"] == ["nope"]+ assert sections[1]["checks"][0]["details"] == ["cannot open x.yaml"]+++def test_scrub_removes_local_paths_and_keeps_contract_ids(tmp_path):+ from repowise.core.report.build import scrub++ root = tmp_path / "shop"+ out = scrub(+ {+ "a": f"cannot read: {root}/.repowise/components.yaml",+ "b": ["at /home/someone/x.py", r"in C:\Users\me\y.py", "http::GET::/users/{id}"],+ "c": str(root),+ },+ root,+ )+ assert out == {+ "a": "cannot read: .repowise/components.yaml",+ "b": ["at <path>", "in <path>", "http::GET::/users/{id}"],+ "c": ".",+ }+++async def test_a_catalog_read_error_does_not_leak_the_repo_path(ctx, monkeypatch):+ from repowise.core.report.build import collect_repo++ catalog = ctx.repo_root / ".repowise" / "components.yaml"+ catalog.write_text("kind: Component\n", encoding="utf-8")+ real = Path.read_text++ def unreadable(self, *a, **k): # the OSError quotes the absolute path, as a real one does+ if self == catalog:+ raise PermissionError(13, "Permission denied", str(self))+ return real(self, *a, **k)++ monkeypatch.setattr(Path, "read_text", unreadable)+ _entry, sections = await collect_repo(ctx, [("components", report_sections.get("components"))])+ details = [d for s in sections for c in s["checks"] for d in c["details"]]+ assert any("cannot read" in d for d in details)+ for d in details:+ assert str(ctx.repo_root) not in d and ctx.repo_root.as_posix() not in d+ assert ":\\" not in d+++# ---------------------------------------------------------------------------+# Renderers+# ---------------------------------------------------------------------------+++def _doc() -> dict:+ from repowise.core.report.build import assemble++ items = [+ check("a|b", reason="<b>bold</b>", basis="measured", method="m", score=7.3),+ check("c", reason="none", basis="unresolved", method="m", details=["one"]),+ ]+ section = {"id": "s", "title": "S", "summary": "sum", "repo": None, "checks": items}+ entry = {"alias": None, "name": "shop", "head_commit": "c" * 40, "last_snapshot": None}+ return assemble({"kind": "repo", "name": "shop"}, [(entry, [section])], generated_at=_NOW)+++def test_json_is_the_canonical_document():+ from repowise.core.report.render import report_renderers++ doc = _doc()+ assert json.loads(report_renderers.get("json")(doc)) == doc+ assert doc["schema_version"] == 1 and doc["scope"] == {"kind": "repo", "name": "shop"}+++def test_markdown_is_stable_and_escapes_table_cells():+ from repowise.core.report.render import render_markdown++ text = render_markdown(_doc())+ assert text == render_markdown(_doc())+ assert r"| `a\|b` | 7.3 | measured | <b>bold</b> |" in text+ assert "| `c` | ? | unresolved | none |" in text+ assert " - one" in text+++def test_markdown_keeps_one_line_and_closes_code_spans():+ from repowise.core.report.render import render_markdown++ doc = _doc()+ item = doc["sections"][0]["checks"][1]+ item["name"], item["details"] = "c`d", ["two\nlines `x`"]+ doc["sections"][0]["summary"] = "multi\nline"+ text = render_markdown(doc)+ assert " - two lines \\`x\\`" in text+ assert "- `c'd`" in text and "\nmulti line\n" in text+++def test_html_is_self_contained_and_escaped():+ from repowise.core.report.render import render_html++ page = render_html(_doc())+ assert page.startswith("<!doctype html>")+ assert "default-src 'none'" in page+ for forbidden in ("<script", "<link", "src=", "http://", "https://", "@import"):+ assert forbidden not in page+ assert "<b>bold</b>" in page and "<b>bold</b>" not in page+ assert "@media print" in page+++# ---------------------------------------------------------------------------+# CLI+# ---------------------------------------------------------------------------+++def indexed(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:+ from repowise.cli.helpers import run_async++ monkeypatch.delenv("REPOWISE_DB_URL", raising=False)+ monkeypatch.delenv("REPOWISE_DATABASE_URL", raising=False)+ root = (tmp_path / "shop").resolve()+ run_async(_seed(root))+ return root+++def test_cli_writes_json_and_filters_sections(indexed: Path, tmp_path: Path) -> None:+ from repowise.cli.main import cli++ out = tmp_path / "report.json"+ result = CliRunner().invoke(+ cli,+ ["report", "assessment", str(indexed), "--no-workspace", "--sections",+ "hotspots,dead-code", "--format", "json", "--out", str(out)],+ )+ assert result.exit_code == 0, result.output+ doc = json.loads(out.read_text(encoding="utf-8"))+ assert [s["id"] for s in doc["sections"]] == ["hotspots", "dead-code"]+ assert doc["repos"][0]["name"] == "shop"+ assert str(indexed) not in out.read_text(encoding="utf-8")+++def test_cli_prints_markdown_and_rejects_unknown_names(indexed: Path) -> None:+ from repowise.cli.main import cli++ ok = CliRunner().invoke(cli, ["report", "assessment", str(indexed), "--no-workspace"])+ assert ok.exit_code == 0, ok.output+ assert ok.output.startswith("# Assessment: shop")+ bad = CliRunner().invoke(cli, ["report", "assessment", str(indexed), "--sections", "nope"])+ assert bad.exit_code == 2 and "available:" in bad.output+ fmt = CliRunner().invoke(cli, ["report", "assessment", str(indexed), "--format", "pdf"])+ assert fmt.exit_code == 2+++def test_cli_without_an_index_says_so(tmp_path: Path) -> None:+ from repowise.cli.main import cli++ result = CliRunner().invoke(cli, ["report", "assessment", str(tmp_path), "--no-workspace"])+ assert result.exit_code == 1 and "repowise init" in result.output+++def test_cli_workspace_scope_covers_every_repo(tmp_path: Path, monkeypatch) -> None:+ from repowise.cli.helpers import run_async+ from repowise.cli.main import cli++ monkeypatch.delenv("REPOWISE_DB_URL", raising=False)+ ws = (tmp_path / "ws").resolve()+ run_async(_seed(ws / "shop"))+ (ws / "docs").mkdir()+ (ws / ".repowise-workspace.yaml").write_text(+ "version: 1\nrepos:\n - path: shop\n alias: shop\n is_primary: true\n"+ " - path: docs\n alias: docs\n",+ encoding="utf-8",+ )+ result = CliRunner().invoke(+ cli, ["report", "assessment", str(ws), "--sections", "hotspots", "--format", "json"]+ )+ assert result.exit_code == 0, result.output+ doc = json.loads(result.output[result.output.index("{") :])+ assert doc["scope"] == {"kind": "workspace", "name": "ws"}+ assert [(r["alias"], r.get("indexed", True)) for r in doc["repos"]] == [+ ("shop", True),+ ("docs", False),+ ]+ assert [s["repo"] for s in doc["sections"]] == ["shop"]+++def test_cli_warns_when_a_section_failed(indexed: Path) -> None:+ import repowise.core.report.sections # noqa: F401+ from repowise.cli.main import cli++ async def boom(_ctx):+ raise RuntimeError("nope")++ report_sections.register("zz-broken", Section("Broken", "b", boom, 999))+ try:+ result = CliRunner().invoke(+ cli, ["report", "assessment", str(indexed), "--sections", "zz-broken"]+ )+ finally:+ report_sections._impls.pop("zz-broken", None)+ assert result.exit_code == 0, result.output+ assert "1 section(s) failed" in result.output and "zz-broken" in result.output+++def test_generated_at_is_whole_seconds():+ from repowise.core.report.build import assemble++ doc = assemble({"kind": "repo", "name": "x"}, [], generated_at=_NOW.replace(microsecond=123456))+ assert doc["generated_at"] == "2026-10-01T00:00:00+00:00"+++async def test_component_hotspots_list_the_top_files_then_count_the_rest(ctx):+ from sqlalchemy import update++ from repowise.core.persistence.models import GitMetadata++ await ctx.session.execute(update(GitMetadata).values(is_hotspot=True))+ found = await ctx.rollups()+ found["api"]["hotspots"]["top"] = found["api"]["hotspots"]["top"][:1] # as if capped at 1+ items = await _section("hotspots", ctx)+ assert items["hotspots:api"]["details"][-1] == "and 1 more"