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): report estate, workspace-scope sections read once from the stored workspace artifacts (#4554)
Raghav Chamadiyadc6d4e5800ba
diff --git a/docs/architecture/workspace.md b/docs/architecture/workspace.mdindex 4f2e88ba8..77ac4b1d3 100644--- a/docs/architecture/workspace.md+++ b/docs/architecture/workspace.md@@ -169,6 +169,7 @@ both ways).| `breaking_change` | `contract_links`, previous and new stores | Provider breaks with the consumer files they reach || `test_impact.analyze_workspace_test_impact` | `contract_links`, each consumer repo's test reachability from the link's `consumer_symbol_id` | Tests to run, unresolved rows with reasons || `diagnostics.build_diagnostics` | Contracts, `contract_links`, extraction stats | Counts, unmatched reasons, weak links, coverage |+| `report estate` (`report/sections/estate_*.py`) | `system_graph.json`, `contracts.json`, `graph_evidence`, the architecture metrics | Estate summary, system map and architecture, contracts and dangling calls |Service links reach the graph views (cycles, metrics, conformance, blast radius).Breaking changes, test impact and diagnostics read `contract_links` only, since adiff --git a/docs/layers/REPORTS.md b/docs/layers/REPORTS.mdindex 86bfa8612..83fe25850 100644--- a/docs/layers/REPORTS.md+++ b/docs/layers/REPORTS.md@@ -10,6 +10,7 @@ opens offline.| `report assessment` | Component posture, hotspots, bus factor, dead code by tier, test reach, contracts, governing decisions, provenance coverage and what moved in the last quarter | Acquirer, board, platform lead, migration committee || `report changes` | Every change merged in a period: components and owning teams, review record, reaching tests, policy verdict, provenance and later outcome, with a period summary | Auditor reviewing change management (SOC 2 CC8.1, ISO 27001 A.8.32, PCI DSS 6.5) || `report inventory` | Components with owner teams, languages, entry points and the packages they import | Software inventory review (PCI DSS 6.3.2) |+| `report estate` | A workspace's repos and services, the system map and architecture with the evidence behind them, contracts and the calls that reached no provider | Platform lead, acquirer, team taking over an estate |```bashrepowise report assessment --format html --out assessment.html@@ -18,6 +19,8 @@ repowise report inventory --format csv --out inventory.csv```In a workspace, `report assessment` and `report inventory` cover every repository.+`report estate` covers the workspace as one system, from what `repowise update --workspace`+stored.## How to read themdiff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.mdindex b42bd14e1..955928791 100644--- a/docs/reference/CLI_REFERENCE.md+++ b/docs/reference/CLI_REFERENCE.md@@ -33,7 +33,7 @@ Grouped by task; `PATH` and flags are in each command's section.[`impacted-tests`](#repowise-impacted-tests-revspec), [`coverage`](#repowise-coverage),[`components`](#repowise-components), [`packages`](#repowise-packages), [`changes`](#repowise-changes),[`suspects`](#repowise-suspects), [`events`](#repowise-events), [`report- assessment`](#repowise-report-assessment-path)+ assessment`](#repowise-report-assessment-path), [`report estate`](#repowise-report-estate-path)- **Decisions:** [`decision`](#repowise-decision)- **Agent wiring:** [`agents`](#repowise-agents), [`generate-claude-md`](#repowise-generate-claude-md-path), [`AGENTS.md`](#agentsmd), [`attribution`](#repowise-attribution)- **Hooks and distill:** [`distill`](#repowise-distill-command), [`expand`](#repowise-expand-ref),@@ -1536,6 +1536,29 @@ lists components with no owner team.---+### `repowise report estate [PATH]`++One document for a whole workspace, read from what `repowise update --workspace` stored; nothing is extracted again.++```bash+repowise report estate --format html --out estate.html+```++| Flag | What it does | Default |+|------|--------------|---------|+| `--sections`, `--format`, `--out` | As `assessment`. | all, `markdown`, stdout |++| Section | Holds | Basis |+|---|---|---|+| `estate-summary` | Repos configured, indexed, read and in the graph; contracts read at an older commit than the index; services; the graph's evidence state with its reasons | `measured`; services `inferred`; `unresolved` when evidence is insufficient |+| `estate-map` | Service dependency edges by kind with strategy and confidence; architecture score, propagation cost, core, cycles, roles | `inferred`; score `unresolved` when evidence is insufficient, and named partial beside it when partial |+| `estate-contracts` | Providers, consumers and links by type and repo pair; HTTP calls read, located but unresolved, and files calling out through code no extractor reads; each consumer that matched no provider in another service (consumer, file, target, contract id), capped with a count of the rest; calls to public hosts counted apart | `measured` |++Outside a workspace it exits 1. A section is a `Section(scope="workspace", report="estate")` in+`repowise/core/report/sections/`; it runs once with a `WorkspaceReportContext`.++---+### `repowise distill <command>`Run a command and print a compact, reversible rendering of its output. Guide: [DISTILL.md](../agent/DISTILL.md).diff --git a/packages/cli/src/repowise/cli/commands/report_assessment_cmd.py b/packages/cli/src/repowise/cli/commands/report_assessment_cmd.pyindex ae08fbed1..e413906b3 100644--- a/packages/cli/src/repowise/cli/commands/report_assessment_cmd.py+++ b/packages/cli/src/repowise/cli/commands/report_assessment_cmd.py@@ -42,10 +42,11 @@ async def _build("""The document over *repos*; *options* go to each :class:`ReportContext`.Members of the workspace at *ws_root* read dead code with its cross-repo cut.+ Over a whole workspace, its workspace-scope sections run once after the repos."""from repowise.core.persistence.models import Repository- from repowise.core.report.build import assemble, collect_repo- from repowise.core.report.model import ReportContext+ from repowise.core.report.build import assemble, collect_repo, collect_workspace+ from repowise.core.report.model import ReportContext, WorkspaceReportContextparts = []for alias, root in repos:@@ -70,14 +71,18 @@ async def _build(**options,)parts.append(await collect_repo(ctx, sections))- return assemble(scope, parts)+ workspace = []+ if ws_root is not None and scope["kind"] == "workspace":+ ws_ctx = WorkspaceReportContext(ws_root, repos=[entry for entry, _ in parts])+ workspace = await collect_workspace(ws_ctx, sections)+ return assemble(scope, parts, workspace=workspace)-def _pick_sections(wanted: str | None) -> list:- """The registered sections, narrowed to *wanted* (comma-separated ids)."""+def _pick_sections(wanted: str | None, report: str = "assessment") -> list:+ """The registered *report* sections, narrowed to *wanted* (comma-separated ids)."""from repowise.core.report.build import available_sections- sections = available_sections()+ sections = available_sections(report)if not wanted:return sectionsnames = [n.strip() for n in wanted.split(",") if n.strip()]diff --git a/packages/cli/src/repowise/cli/commands/report_cmd.py b/packages/cli/src/repowise/cli/commands/report_cmd.pyindex 3924d717f..80d20ac62 100644--- a/packages/cli/src/repowise/cli/commands/report_cmd.py+++ b/packages/cli/src/repowise/cli/commands/report_cmd.py@@ -15,12 +15,13 @@ _SUBCOMMANDS: tuple[str, ...] = ("repowise.cli.commands.report_assessment_cmd:assessment_command","repowise.cli.commands.report_inventory_cmd:inventory_command","repowise.cli.commands.report_changes_cmd:changes_command",+ "repowise.cli.commands.report_estate_cmd:estate_command",)@click.group("report")def report_group() -> None:- """Evidence reports built from the index: assessment, inventory, changes."""+ """Evidence reports built from the index: assessment, inventory, changes, estate."""for _target in _SUBCOMMANDS:diff --git a/packages/cli/src/repowise/cli/commands/report_estate_cmd.py b/packages/cli/src/repowise/cli/commands/report_estate_cmd.pynew file mode 100644index 000000000..5fea58905--- /dev/null+++ b/packages/cli/src/repowise/cli/commands/report_estate_cmd.py@@ -0,0 +1,59 @@+"""``repowise report estate`` - the estate report for a workspace.++The ``estate`` report sections, which read the workspace's stored cross-repo+artifacts (system graph, contracts, diagnostics) once, with every member+repository's indexed commit listed. Built and rendered the way+``report assessment`` builds its document.+"""++from __future__ import annotations++import click++from repowise.cli.helpers import (+ err_console,+ resolve_command_target,+ run_async,+ silence_logs_for_machine_output_until_close,+)++[email protected]("estate")[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, html or csv (or one a plugin registers).",+)[email protected]("--out", "out_path", type=click.Path(dir_okay=False), help="Write to this file.")+def estate_command(path: str | None, wanted: str | None, fmt: str, out_path: str | None) -> None:+ """Estate report: repositories and services, the system map and architecture with+ the evidence behind them, contracts and the calls that reached no provider."""+ from repowise.cli._helpers.target import WorkspaceNotFound+ from repowise.cli.commands.report_assessment_cmd import (+ _build,+ _emit,+ _pick_sections,+ _renderer,+ _targets,+ )++ if not out_path:+ silence_logs_for_machine_output_until_close() # stdout carries only the report+ sections = _pick_sections(wanted, "estate")+ render = _renderer(fmt)+ try:+ target = resolve_command_target(path=path, workspace_flag=True)+ except WorkspaceNotFound as exc:+ raise click.ClickException(+ "report estate covers a workspace, and no .repowise-workspace.yaml was found "+ "at or above this directory. Run 'repowise init <workspace-dir>' first."+ ) from exc+ target.notice(err_console, command="report estate")+ scope = {"kind": "workspace", "name": target.ws_root.name}+ document = run_async(_build(_targets(target), sections, scope, ws_root=target.ws_root))+ document["kind"] = "estate"+ _emit(render(document), fmt, out_path, document)diff --git a/packages/core/src/repowise/core/report/__init__.py b/packages/core/src/repowise/core/report/__init__.pyindex 47cb2ff99..6218c5b33 100644--- a/packages/core/src/repowise/core/report/__init__.py+++ b/packages/core/src/repowise/core/report/__init__.py@@ -15,6 +15,7 @@ from repowise.core.report.model import (SCHEMA_VERSION,ReportContext,Section,+ WorkspaceReportContext,check,report_sections,)@@ -25,6 +26,7 @@ __all__ = ["SCHEMA_VERSION","ReportContext","Section",+ "WorkspaceReportContext","check","report_sections",]diff --git a/packages/core/src/repowise/core/report/build.py b/packages/core/src/repowise/core/report/build.pyindex b1ba05306..c1d22a1b0 100644--- a/packages/core/src/repowise/core/report/build.py+++ b/packages/core/src/repowise/core/report/build.py@@ -2,14 +2,17 @@The caller opens each repository's index (the CLI does it per repo, singleor 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.+and assembles one versioned document. Over a whole workspace, its+workspace-scope sections then run once on a :class:`WorkspaceReportContext`.+Paths are relative to each repository (or the workspace root); no local+absolute path is written."""from __future__ import annotationsimport loggingimport re+from collections.abc import Sequencefrom datetime import UTC, datetimefrom pathlib import Pathfrom typing import Any@@ -19,6 +22,7 @@ from repowise.core.report.model import (SCHEMA_VERSION,ReportContext,Section,+ WorkspaceReportContext,check,report_sections,)@@ -65,47 +69,85 @@ async def _index_entry(ctx: ReportContext) -> dict[str, Any]:}+async def _collect(+ ctx: ReportContext | WorkspaceReportContext,+ name: str,+ section: Section,+ *,+ repo: str | None,+ root: Path,+ url: str,+) -> dict[str, Any] | None:+ """One section's entry, ``None`` when it does not apply; a failure is inconclusive."""+ 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)+ if isinstance(ctx, ReportContext):+ 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:+ return None+ doc = {"url": url, "short": section.summary}+ for item in checks:+ item.setdefault("documentation", doc)+ entry = {+ "id": name,+ "title": section.title,+ "summary": section.summary,+ "repo": repo,+ "checks": checks,+ }+ if failed:+ entry["failed"] = True+ return scrub(entry, root)++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."""+ """``(repos entry, sections)`` for one repository; workspace sections are skipped."""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:+ if section.scope != "repo":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))+ entry = await _collect(+ ctx, name, section, repo=ctx.alias, root=ctx.repo_root, url=DOCS_URL+ )+ if entry is not None:+ out.append(entry)return await _index_entry(ctx), out+async def collect_workspace(+ ctx: WorkspaceReportContext, sections: list[tuple[str, Section]]+) -> list[dict[str, Any]]:+ """The workspace-scope sections of *sections*, each run once over the workspace.++ Their entries carry ``repo: None`` and paths relative to the workspace root.+ """+ out: list[dict[str, Any]] = []+ for name, section in sections:+ if section.scope != "workspace":+ continue+ url = f"{DOCS_URL.split('#')[0]}#repowise-report-{section.report}-path"+ entry = await _collect(ctx, name, section, repo=None, root=ctx.ws_root, url=url)+ if entry is not None:+ out.append(entry)+ return 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@@ -147,9 +189,14 @@ def assemble(scope: dict[str, Any],parts: list[tuple[dict[str, Any], list[dict[str, Any]]]],*,+ workspace: Sequence[dict[str, Any]] = (),generated_at: datetime | None = None,) -> dict[str, Any]:- """The canonical document. *scope* is ``{"kind": "repo"|"workspace", "name": ...}``."""+ """The canonical document. *scope* is ``{"kind": "repo"|"workspace", "name": ...}``.++ *workspace* holds the entries of :func:`collect_workspace`, appended once+ after every repository's own sections.+ """from repowise.core import __version__from repowise.core.events.snapshot import current_stamp@@ -161,8 +208,15 @@ def assemble("scope": scope,"notice": NOTICE,"repos": [entry for entry, _ in parts],- "sections": [s for _, sections in parts for s in sections],+ "sections": [*(s for _, sections in parts for s in sections), *workspace],}-__all__ = ["NOTICE", "assemble", "available_sections", "collect_repo", "scrub"]+__all__ = [+ "NOTICE",+ "assemble",+ "available_sections",+ "collect_repo",+ "collect_workspace",+ "scrub",+]diff --git a/packages/core/src/repowise/core/report/model.py b/packages/core/src/repowise/core/report/model.pyindex 028e2ac62..410139c7b 100644--- a/packages/core/src/repowise/core/report/model.py+++ b/packages/core/src/repowise/core/report/model.py@@ -175,19 +175,79 @@ class ReportContext:return self._cache["rollups"]+@dataclass+class WorkspaceReportContext:+ """A workspace's stored cross-repo artifacts, loaded once and shared by its sections.++ Reads only what ``repowise update --workspace`` wrote under+ ``.repowise-workspace/``; nothing is extracted or matched again here.+ """++ ws_root: Path+ #: The document's ``repos`` entries, one per configured repository+ #: (``head_commit`` when indexed, ``indexed: False`` otherwise).+ repos: list[dict[str, Any]] = field(default_factory=list)+ _cache: dict[str, Any] = field(default_factory=dict)++ def _load(self, key: str, loader: Callable[[], Any]) -> Any:+ if key not in self._cache:+ self._cache[key] = loader()+ return self._cache[key]++ def config(self) -> Any:+ """The workspace config (:class:`~repowise.core.workspace.config.WorkspaceConfig`)."""+ from repowise.core.workspace.config import WorkspaceConfig++ return self._load("config", lambda: WorkspaceConfig.load(self.ws_root))++ def system_graph(self) -> Any:+ """The stored system graph, or ``None`` when none was built."""+ from repowise.core.workspace.system_graph import load_system_graph++ return self._load("graph", lambda: load_system_graph(self.ws_root))++ def contract_store(self) -> Any:+ """The stored contract store, or ``None`` when none was extracted."""+ from repowise.core.workspace.contracts import load_contract_store++ return self._load("contracts", lambda: load_contract_store(self.ws_root))++ def evidence(self) -> Any:+ """The graph's evidence state (:class:`GraphEvidence`), ``None`` without a graph."""+ from repowise.core.workspace.graph_evidence import graph_evidence++ graph = self.system_graph()+ return self._load("evidence", lambda: graph_evidence(graph) if graph else None)+++#: Where a section runs: once per repository, or once per workspace.+SCOPES = ("repo", "workspace")++@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)."""+ section does not apply (it is then left out).++ A ``repo`` section gets a :class:`ReportContext` per repository. A+ ``workspace`` section gets one :class:`WorkspaceReportContext` and runs+ once, only when the report covers a whole workspace.+ """title: str#: One line saying what the section measures; the documentation ``short``.summary: str- collect: Callable[[ReportContext], Awaitable[list[dict[str, Any]] | None]]+ collect: Callable[[Any], Awaitable[list[dict[str, Any]] | None]]#: Sections are listed by this, then by name.order: int = 100- #: The report kind the section belongs to (``assessment``, ``changes``).+ #: The report kind the section belongs to (``assessment``, ``changes``, ``estate``).report: str = "assessment"+ #: One of :data:`SCOPES`.+ scope: str = "repo"++ def __post_init__(self) -> None:+ if self.scope not in SCOPES:+ raise ValueError(f"unknown section scope {self.scope!r}; expected one of {SCOPES}")report_sections: SeamRegistry[Section] = SeamRegistry("report-section")diff --git a/packages/core/src/repowise/core/report/sections/_estate.py b/packages/core/src/repowise/core/report/sections/_estate.pynew file mode 100644index 000000000..7287266cd--- /dev/null+++ b/packages/core/src/repowise/core/report/sections/_estate.py@@ -0,0 +1,33 @@+"""What the estate sections share: the missing-artifact item and the evidence wording."""++from __future__ import annotations++from typing import Any++from repowise.core.report.model import check+++def missing_graph(name: str, method: str) -> list[dict[str, Any]]:+ """The one item a section gives when the workspace has no stored system graph."""+ return [+ check(+ name,+ reason=(+ "no system graph is stored for this workspace; 'repowise update --workspace' "+ "builds it once two or more member repos are indexed"+ ),+ method=method,+ basis="unresolved",+ )+ ]+++def evidence_note(evidence: Any) -> str:+ """``""`` when the graph's evidence is measured, else ``"; <state> evidence (<codes>)"``.++ The reasons are spelled out once, in the estate summary's ``evidence`` item.+ """+ if evidence is None or evidence.state == "measured":+ return ""+ codes = ", ".join(r.code.replace("_", " ") for r in evidence.reasons)+ return f"; {evidence.state} evidence ({codes})"diff --git a/packages/core/src/repowise/core/report/sections/estate_contracts.py b/packages/core/src/repowise/core/report/sections/estate_contracts.pynew file mode 100644index 000000000..b1e255ce5--- /dev/null+++ b/packages/core/src/repowise/core/report/sections/estate_contracts.py@@ -0,0 +1,213 @@+"""Contracts across the estate, and the calls that reached no provider in it."""++from __future__ import annotations++from collections import Counter+from typing import Any++from repowise.core.report.model import (+ Section,+ WorkspaceReportContext,+ capped,+ check,+ report_sections,+)+from repowise.core.report.sections._estate import missing_graph++_METHOD = (+ "the contract store and extraction diagnostics 'repowise update --workspace' stored: "+ "contracts read per repo, the links matched between repos, and the consumers left unmatched"+)+_REASONS = {+ "no_provider": "no provider in the workspace",+ "unlinked": "a provider exists, no link formed",+}+++def dangling_calls(graph: Any, store: Any) -> list[dict[str, Any]]:+ """Consumers (calls, subscriptions, table reads) that matched no provider in+ another service, one row per repo, file and contract id.++ The one place the diagnostics' unmatched consumers are read, so a change to+ their shape is one edit here. A consumer served inside its own service is+ not dangling, whichever list the diagnostics keep it in. The target comes+ from the consumer's stored contract: the workspace repo its host resolved+ to, else the host or base it names; a call to a public host outside the+ workspace is marked ``external``.+ """+ contracts: dict[tuple[str, str, str], Any] = {}+ for c in store.contracts if store is not None else ():+ if c.role == "consumer": # the first one read gives the row its line+ contracts.setdefault((c.repo, c.file_path, c.contract_id), c)+ rows = []+ seen: set[tuple[str, str, str]] = set()+ for u in graph.diagnostics.unmatched_consumers:+ key = (u.repo, u.file_path, u.contract_id)+ if u.reason == "internal_only" or key in seen:+ continue+ seen.add(key)+ contract = contracts.get(key)+ meta = contract.meta if contract is not None else {}+ rows.append(+ {+ "consumer": u.repo,+ "file": u.file_path,+ "line": contract.line if contract is not None else None,+ "contract_id": u.contract_id,+ "type": u.contract_type,+ "reason": u.reason,+ "target": meta.get("target_repo") or meta.get("host") or meta.get("base_token"),+ "external": bool(meta.get("external")) or u.reason == "external_host",+ }+ )+ return sorted(+ rows,+ key=lambda r: (r["consumer"], r["file"], r["line"] is None, r["line"] or 0, r["contract_id"]),+ )+++def _contracts(graph: Any, store: Any) -> dict[str, Any]:+ diag = graph.diagnostics+ providers: Counter[str] = Counter()+ consumers: Counter[str] = Counter()+ for r in diag.repo_breakdown:+ providers.update(r.providers_by_type)+ consumers.update(r.consumers_by_type)+ links = store.contract_links if store is not None else []+ service_links = store.service_links if store is not None else []+ match_types = Counter(link.match_type for link in links)+ linked: Counter[str] = Counter(link.contract_type for link in links)+ pairs = Counter((link.consumer_repo, link.provider_repo, link.contract_type) for link in links)+ details = [+ f"{t}: {providers[t]} provider(s), {consumers[t]} consumer(s), {linked[t]} link(s)"+ for t in sorted(set(providers) | set(consumers))+ ]+ details += capped(+ [f"{c} -> {p}: {n} {t} link(s)" for (c, p, t), n in sorted(pairs.items())]+ )+ if service_links:+ details.append(+ f"{len(service_links)} service-level link(s): the host names a workspace repo "+ "but no route there serves the path"+ )+ details.append(+ f"{len(diag.orphan_providers)} provider(s) no consumer in the workspace reaches "+ "(may be called from outside it)"+ )+ kinds = ", ".join(f"{k} {n}" for k, n in sorted(match_types.items()))+ return check(+ "contracts",+ reason=(+ f"{diag.total_providers} provider(s) and {diag.total_consumers} consumer(s) read; "+ f"{len(links)} cross-repo link(s)" + (f" ({kinds})" if kinds else "")+ + f", {diag.weak_link_count} weak"+ ),+ details=details,+ method=_METHOD,+ basis="measured",+ data={+ "providers_by_type": dict(sorted(providers.items())),+ "consumers_by_type": dict(sorted(consumers.items())),+ "links_by_type": dict(sorted(linked.items())),+ "links_by_match_type": dict(sorted(match_types.items())),+ "service_links": len(service_links),+ "orphan_providers": len(diag.orphan_providers),+ },+ )+++def _http_coverage(graph: Any) -> dict[str, Any]:+ diag = graph.diagnostics+ read = sum(r.consumers_by_type.get("http", 0) for r in diag.repo_breakdown)+ unresolved = diag.http_consumers_unresolved+ missed = diag.unrecognised_call_file_count+ data = {"read": read, "unresolved": unresolved, "unrecognised_call_files": missed}+ method = (+ "HTTP calls read as contracts, over those plus calls located but not resolvable and "+ "files that call out through code no extractor reads (one per file)"+ )+ if missed is None:+ return check(+ "http-calls",+ reason=(+ f"{read} read, {unresolved} located but not resolvable; calls no extractor "+ "recognises were not counted, since this artifact predates that count"+ ),+ method=method,+ basis="unresolved",+ data=data,+ )+ seen = read + unresolved + missed+ by_repo = [+ f"{repo}: {n} file(s)"+ for repo, n in sorted((diag.unrecognised_call_files or {}).items())+ if n+ ]+ return check(+ "http-calls",+ reason=(+ f"{read} HTTP call(s) read as contracts, {unresolved} located but not resolvable, "+ f"{missed} file(s) calling out through code no extractor reads"+ if seen+ else "no HTTP call located, and no file makes a recognisable network call"+ ),+ details=capped(by_repo),+ method=method,+ basis="measured",+ data=data,+ )+++def _dangling(graph: Any, store: Any) -> dict[str, Any]:+ rows = dangling_calls(graph, store)+ external = [r for r in rows if r["external"]]+ dangling = [r for r in rows if not r["external"]]+ by_reason = Counter(r["reason"] for r in dangling)+ by_type = Counter(r["type"] for r in dangling)+ lines = [+ f"{r['consumer']} {r['file']}" + (f":{r['line']}" if r["line"] else "")+ + f" -> {r['target'] or 'target not resolved'}: {r['contract_id']} "+ f"({_REASONS.get(r['reason'], r['reason'])})"+ for r in dangling+ ]+ details = capped(lines)+ if external:+ details.append(f"{len(external)} call(s) to public hosts outside the workspace not counted")+ types = ", ".join(f"{t} {n}" for t, n in sorted(by_type.items()))+ return check(+ "dangling-calls",+ reason=(+ f"{len(dangling)} consumer(s) matched no provider in another service"+ + (f" ({types})" if types else "")+ + (+ ": " + ", ".join(f"{_REASONS.get(k, k)} {n}" for k, n in sorted(by_reason.items()))+ if by_reason+ else ""+ )+ ),+ details=details,+ method=_METHOD + "; one row per consumer file and contract id",+ basis="measured",+ data={"dangling": dangling, "external": len(external)},+ )+++async def collect(ctx: WorkspaceReportContext) -> list[dict[str, Any]]:+ graph = ctx.system_graph()+ if graph is None:+ return missing_graph("contracts", _METHOD)+ store = ctx.contract_store()+ return [_contracts(graph, store), _http_coverage(graph), _dangling(graph, store)]+++report_sections.register(+ "estate-contracts",+ Section(+ title="Contracts and dangling calls",+ summary="Contracts read and linked across repos, and each call that reached no provider.",+ collect=collect,+ order=30,+ report="estate",+ scope="workspace",+ ),+)diff --git a/packages/core/src/repowise/core/report/sections/estate_map.py b/packages/core/src/repowise/core/report/sections/estate_map.pynew file mode 100644index 000000000..f78a09301--- /dev/null+++ b/packages/core/src/repowise/core/report/sections/estate_map.py@@ -0,0 +1,125 @@+"""The system map and its architecture figures, each with the evidence it rests on."""++from __future__ import annotations++from collections import Counter+from typing import Any++from repowise.core.report.model import (+ Section,+ WorkspaceReportContext,+ capped,+ check,+ report_sections,+)+from repowise.core.report.sections._estate import evidence_note, missing_graph++_EDGES = (+ "the stored system graph: contract links folded into service-to-service edges, with "+ "package dependencies and co-change; an edge keeps the strategy and confidence of its "+ "strongest link"+)+_ARCHITECTURE = (+ "architecture metrics over the system graph's structural edges (propagation cost, cyclic "+ "core, cycles, declared-rule violations), as 'repowise workspace metrics' computes them; "+ "the 1-10 score is a fixed formula, not a calibrated grade"+)+++def _dependencies(ctx: WorkspaceReportContext, graph: Any) -> dict[str, Any]:+ structural = [e for e in graph.edges if e.structural]+ co_change = len(graph.edges) - len(structural)+ by_kind = Counter(e.kind for e in structural)+ kinds = ", ".join(f"{kind} {n}" for kind, n in sorted(by_kind.items())) or "none"+ ranked = sorted(structural, key=lambda e: (-e.weight, e.source, e.target, e.kind))+ return check(+ "dependencies",+ reason=(+ f"{len(structural)} service dependency edge(s) ({kinds}), plus {co_change} "+ f"co-change edge(s) that record history, not a dependency"+ + evidence_note(ctx.evidence())+ ),+ details=capped(+ [+ f"{e.source} -> {e.target}: {e.kind}, {e.weight} link(s), "+ f"{e.strategy or e.match_type}, confidence {e.confidence:.2f}"+ for e in ranked+ ]+ ),+ method=_EDGES,+ basis="inferred",+ data={"edges": [e.to_dict() for e in graph.edges]},+ )+++def _architecture(ctx: WorkspaceReportContext, graph: Any) -> dict[str, Any]:+ from repowise.core.workspace.architecture_metrics import compute_architecture_metrics+ from repowise.core.workspace.conformance import check_conformance, tags_by_repo_from_config+ from repowise.core.workspace.cycles import detect_cycles++ config = ctx.config()+ violations = check_conformance(+ graph, config.conformance.rules, tags_by_repo_from_config(config)+ )+ metrics = compute_architecture_metrics(+ graph, conformance_violations=len(violations), generated_at=graph.generated_at+ )+ data = metrics.to_dict()+ if metrics.score is None:+ return check(+ "architecture",+ reason=f"not determined: {ctx.evidence().summary}",+ method=_ARCHITECTURE,+ basis="unresolved",+ data=data,+ )+ cycles, _total = detect_cycles(graph)+ roles = metrics.role_breakdown()+ details = [+ f"propagation cost {metrics.propagation_cost_pct:.1f}%: the average share of other "+ "services one service can reach",+ f"cyclic core: {', '.join(metrics.core_members)}" if metrics.core_members+ else "cyclic core: none",+ f"{metrics.cycle_count} dependency cycle(s)",+ *capped(+ [+ " -> ".join([*c.nodes, c.nodes[0]])+ + (f" ({c.async_legs} event leg(s))" if c.async_legs else "")+ for c in cycles+ ],+ limit=10,+ ),+ "service roles: " + ", ".join(f"{role} {n}" for role, n in sorted(roles.items())),+ ]+ if metrics.conformance_violations:+ details.append(f"{metrics.conformance_violations} declared-rule violation(s)")+ return check(+ "architecture",+ reason=f"{metrics.architecture_type}, scored {metrics.score:g} of 10"+ + evidence_note(ctx.evidence()),+ score=metrics.score,+ details=details,+ method=_ARCHITECTURE,+ basis="inferred",+ data=data,+ )+++async def collect(ctx: WorkspaceReportContext) -> list[dict[str, Any]]:+ graph = ctx.system_graph()+ if graph is None:+ return missing_graph("system-map", _EDGES)+ return [_dependencies(ctx, graph), _architecture(ctx, graph)]+++report_sections.register(+ "estate-map",+ Section(+ title="System map and architecture",+ summary="How the services depend on each other, and what that structure scores.",+ collect=collect,+ order=20,+ report="estate",+ scope="workspace",+ ),+)diff --git a/packages/core/src/repowise/core/report/sections/estate_summary.py b/packages/core/src/repowise/core/report/sections/estate_summary.pynew file mode 100644index 000000000..45bb2f4c2--- /dev/null+++ b/packages/core/src/repowise/core/report/sections/estate_summary.py@@ -0,0 +1,154 @@+"""The estate at a glance: its repositories, its services and the evidence behind them."""++from __future__ import annotations++from typing import Any++from repowise.core.report.model import (+ Section,+ WorkspaceReportContext,+ capped,+ capped_names,+ check,+ report_sections,+)+from repowise.core.report.sections._estate import missing_graph++_METHOD = (+ "the workspace config, each member's index, and the system graph and contract "+ "extraction 'repowise update --workspace' stored"+)+++def _repositories(ctx: WorkspaceReportContext, graph: Any) -> dict[str, Any]:+ walked = graph.repo_provenance+ services: dict[str, list[str]] = {}+ for node in graph.nodes:+ services.setdefault(node.repo, []).append(node.name)+ rows = []+ for entry in ctx.repos:+ alias = entry.get("alias") or entry.get("name")+ indexed = entry.get("indexed", True)+ extracted = (walked.get(alias) or {}).get("head")+ head = entry.get("head_commit")+ rows.append(+ {+ "alias": alias,+ "indexed": indexed,+ "indexed_commit": head,+ "contracts_commit": extracted,+ "services": sorted(services.get(alias, [])),+ }+ )+ not_indexed = [r["alias"] for r in rows if not r["indexed"]]+ unread = [r["alias"] for r in rows if r["indexed"] and r["alias"] not in walked]+ empty = [r["alias"] for r in rows if r["alias"] in walked and not r["services"]]+ behind = [+ r+ for r in rows+ if r["indexed"] and r["contracts_commit"] and r["indexed_commit"]+ and r["contracts_commit"] != r["indexed_commit"]+ ]+ details = []+ if not_indexed:+ details.append(f"not indexed, so nothing about them is known: {capped_names(not_indexed)}")+ if unread:+ details.append(f"indexed but not read by the last workspace update: {capped_names(unread)}")+ if empty:+ details.append(f"read but yielded no contracts, so not in the graph: {capped_names(empty)}")+ details += capped(+ [+ f"{r['alias']}: contracts read at {r['contracts_commit'][:12]}, index at "+ f"{r['indexed_commit'][:12]}"+ for r in behind+ ]+ )+ in_graph = sum(1 for r in rows if r["services"])+ return check(+ "repositories",+ reason=(+ f"{len(rows)} configured: {len(rows) - len(not_indexed)} indexed, "+ f"{sum(1 for r in rows if r['alias'] in walked)} read "+ f"by contract extraction, {in_graph} with a service in the system graph"+ + (f"; {len(behind)} with contracts read at another commit than the index" if behind else "")+ ),+ details=details,+ method=_METHOD,+ basis="measured",+ data={"repositories": rows},+ )+++def _services(graph: Any) -> dict[str, Any]:+ by_repo: dict[str, list[str]] = {}+ for node in graph.nodes:+ by_repo.setdefault(node.repo, []).append(f"{node.name} ({node.kind})")+ isolated = sorted(n.id for n in graph.nodes if n.is_isolated)+ providing = sum(1 for n in graph.nodes if n.provider_count)+ consuming = sum(1 for n in graph.nodes if n.consumer_count)+ details = capped([f"{repo}: {', '.join(sorted(names))}" for repo, names in sorted(by_repo.items())])+ if isolated:+ details.append(f"no detected dependency either way: {capped_names(isolated)}")+ return check(+ "services",+ reason=(+ f"{len(graph.nodes)} service(s) across {len(by_repo)} repositories: {providing} "+ f"provide a contract, {consuming} consume one, {len(isolated)} isolated"+ ),+ details=details,+ method=(+ "service boundaries from build manifests (a repo without one is one service), "+ "kept when a contract was read from them"+ ),+ basis="inferred",+ data={"services": [n.to_dict() for n in graph.nodes]},+ )+++def _evidence(ctx: WorkspaceReportContext, graph: Any) -> dict[str, Any]:+ evidence = ctx.evidence()+ counts = (+ f"{evidence.runtime_edges} runtime and {evidence.build_edges} build edge(s) across "+ f"{evidence.services} service(s)"+ )+ if evidence.state == "measured":+ reason = f"measured: every service takes part in a runtime dependency ({counts})"+ elif evidence.state == "partial":+ reason = f"partial: figures are computed, with part of the estate out of sight ({counts})"+ else:+ reason = (+ f"insufficient: architecture figures, cycle verdicts and impact sets are not "+ f"determined ({counts})"+ )+ return check(+ "evidence",+ reason=reason,+ details=[+ *(r.message for r in evidence.reasons),+ f"system graph written {graph.generated_at or 'at an unknown time'}",+ ],+ method="the system graph's evidence rules: services, cross-service edges, isolated "+ "services and repos that yielded no contracts",+ basis="unresolved" if evidence.state == "insufficient" else "measured",+ data=evidence.to_dict(),+ )+++async def collect(ctx: WorkspaceReportContext) -> list[dict[str, Any]]:+ graph = ctx.system_graph()+ if graph is None:+ return missing_graph("estate", _METHOD)+ return [_repositories(ctx, graph), _services(graph), _evidence(ctx, graph)]+++report_sections.register(+ "estate-summary",+ Section(+ title="Estate summary",+ summary="Repositories, services and how much evidence the system graph rests on.",+ collect=collect,+ order=10,+ report="estate",+ scope="workspace",+ ),+)diff --git a/tests/unit/core/test_report_estate.py b/tests/unit/core/test_report_estate.pynew file mode 100644index 000000000..60423afd4--- /dev/null+++ b/tests/unit/core/test_report_estate.py@@ -0,0 +1,290 @@+"""`repowise report estate`: the workspace-scope section seam and the estate sections,+read from stored workspace artifacts."""++from __future__ import annotations++import json+from pathlib import Path++import pytest+from click.testing import CliRunner++from repowise.core.report.build import assemble, available_sections, collect_workspace+from repowise.core.report.model import (+ SCOPES,+ Section,+ WorkspaceReportContext,+ report_sections,+)+from repowise.core.workspace.contracts import (+ Contract,+ ContractLink,+ ContractStore,+ save_contract_store,+)+from repowise.core.workspace.diagnostics import (+ ExtractionDiagnostics,+ RepoDiagnostics,+ UnmatchedConsumer,+)+from repowise.core.workspace.system_graph import (+ SystemEdge,+ SystemGraph,+ SystemNode,+ save_system_graph,+)++_PROV = {"head": "a" * 40, "extracted_at": "2026-10-01T00:00:00+00:00"}+++def _node(repo: str, **kw) -> SystemNode:+ return SystemNode(id=repo, repo=repo, service_path=None, name=repo, **kw)+++def _edge(src: str, dst: str, kind: str = "http") -> SystemEdge:+ return SystemEdge(+ id=f"{src}->{dst}:{kind}",+ source=src,+ target=dst,+ kind=kind,+ match_type="exact",+ confidence=0.9,+ weight=2,+ structural=True,+ strategy="exact_id",+ )+++def _unmatched(repo: str, cid: str, reason: str = "no_provider", path: str = "client.py"):+ return UnmatchedConsumer(repo, path, cid, cid.split("::")[0], reason)+++def _consumer(repo: str, cid: str, path: str = "client.py", line: int = 3, **meta) -> Contract:+ return Contract(repo, cid, cid.split("::")[0], "consumer", path, "call", 0.9, line=line, meta=meta)+++def _workspace(root: Path, *, edges: bool = True, dangling: int = 1) -> Path:+ """A three-repo workspace: web calls api; worker is isolated."""+ unmatched = [_unmatched("web", f"http::GET::/missing/{i}") for i in range(dangling)]+ unmatched += [+ _unmatched("web", "http::GET::/self", "internal_only"),+ _unmatched("web", "http::GET::/v1/charges", path="pay.py"),+ ]+ graph = SystemGraph(+ generated_at="2026-10-01T00:00:00+00:00",+ nodes=[+ _node("web", consumer_count=3),+ _node("api", provider_count=2),+ _node("worker", provider_count=1, is_isolated=True),+ ],+ edges=[_edge("web", "api")] if edges else [],+ diagnostics=ExtractionDiagnostics(+ total_providers=3,+ total_consumers=4,+ total_links=1,+ repo_breakdown=[+ RepoDiagnostics("web", consumers_by_type={"http": 4}, consumer_count=4),+ RepoDiagnostics("api", providers_by_type={"http": 2}, provider_count=2),+ ],+ unmatched_consumers=unmatched,+ unrecognised_call_files={"web": 1},+ ),+ repo_provenance={"web": _PROV, "api": _PROV, "worker": _PROV, "docs": _PROV},+ )+ save_system_graph(graph, root)+ store = ContractStore(+ contracts=[+ _consumer("web", "http::GET::/missing/0", line=12, target_repo="billing"),+ _consumer("web", "http::GET::/v1/charges", path="pay.py", external=True, host="api.stripe.com"),+ ],+ contract_links=[+ ContractLink(+ "http::GET::/users", "http", "exact", 0.9,+ "api", "routes.py", "users", None, "web", "client.py", "call", None,+ )+ ],+ )+ save_contract_store(store, root)+ (root / ".repowise-workspace.yaml").write_text(+ "version: 1\nrepos:\n"+ + "".join(f" - path: {r}\n alias: {r}\n" for r in ("web", "api", "worker", "docs")),+ encoding="utf-8",+ )+ return root+++def _ctx(root: Path) -> WorkspaceReportContext:+ return WorkspaceReportContext(+ root,+ repos=[+ {"alias": "web", "head_commit": "a" * 40},+ {"alias": "api", "head_commit": "b" * 40},+ {"alias": "worker", "head_commit": "a" * 40},+ {"alias": "docs", "name": "docs", "indexed": False},+ ],+ )+++async def _estate(ctx: WorkspaceReportContext) -> dict[str, dict]:+ sections = await collect_workspace(ctx, available_sections("estate"))+ return {s["id"]: {c["name"]: c for c in s["checks"]} for s in sections}+++# ---------------------------------------------------------------------------+# The seam+# ---------------------------------------------------------------------------+++def test_every_registered_section_declares_a_known_scope():+ available_sections() # imports the local sections+ for name in report_sections.names:+ assert report_sections.get(name).scope in SCOPES, name+ estate = available_sections("estate")+ assert estate and all(s.scope == "workspace" for _, s in estate)+ with pytest.raises(ValueError, match="scope"):+ Section("Bad", "b", None, scope="estate")+++async def test_workspace_sections_run_once_and_repo_sections_skip_them(tmp_path, monkeypatch):+ from repowise.core.report import build++ calls = []++ async def ws(ctx):+ calls.append(ctx)+ raise OSError(f"cannot read {ctx.ws_root / 'x.json'}")++ async def entry(_ctx):+ return {}++ sections = [("ws", Section("Ws", "w", ws, scope="workspace"))]+ monkeypatch.setattr(build, "_index_entry", entry)+ assert await build.collect_repo(None, sections) == ({}, [])+ (section,) = await collect_workspace(WorkspaceReportContext(tmp_path), sections)+ assert len(calls) == 1+ assert section["repo"] is None and section["failed"] is True+ assert section["checks"][0]["details"] == ["cannot read x.json"]+ assert section["checks"][0]["documentation"]["url"].endswith("#repowise-report-assessment-path")+++def test_assemble_appends_workspace_sections_after_the_repos():+ repo = {"id": "hotspots", "repo": "shop", "checks": []}+ ws = {"id": "estate-summary", "repo": None, "checks": []}+ doc = assemble({"kind": "workspace", "name": "w"}, [({"alias": "shop"}, [repo])], workspace=[ws])+ assert doc["sections"] == [repo, ws]+++# ---------------------------------------------------------------------------+# The estate sections+# ---------------------------------------------------------------------------+++async def test_without_a_system_graph_every_estate_section_is_unresolved(tmp_path):+ found = await _estate(WorkspaceReportContext(tmp_path))+ items = [c for checks in found.values() for c in checks.values()]+ assert len(found) == 3 and all(c["basis"] == "unresolved" for c in items)+ assert "repowise update --workspace" in items[0]["reason"]+++async def test_summary_names_unindexed_unread_and_stale_repos(tmp_path):+ found = await _estate(_ctx(_workspace(tmp_path)))+ summary = found["estate-summary"]+ repos = summary["repositories"]+ assert repos["reason"].startswith("4 configured: 3 indexed, 4 read by contract extraction")+ assert "not indexed, so nothing about them is known: docs" in repos["details"]+ assert any(d.startswith("api: contracts read at aaaaaaaaaaaa") for d in repos["details"])+ assert summary["services"]["reason"].endswith("1 isolated")+ evidence = summary["evidence"]+ assert evidence["reason"].startswith("partial") and evidence["basis"] == "measured"+ assert any("worker" in d for d in evidence["details"])+++async def test_architecture_is_not_determined_without_cross_service_edges(tmp_path):+ found = await _estate(_ctx(_workspace(tmp_path, edges=False)))+ arch = found["estate-map"]["architecture"]+ assert arch["score"] == -1 and arch["basis"] == "unresolved"+ assert arch["reason"].startswith("not determined:")+ assert found["estate-summary"]["evidence"]["reason"].startswith("insufficient")+++async def test_a_partial_score_says_so_beside_it(tmp_path):+ found = await _estate(_ctx(_workspace(tmp_path)))+ arch = found["estate-map"]["architecture"]+ assert arch["score"] is not None and arch["score"] >= 0 and arch["basis"] == "inferred"+ assert "partial evidence (isolated services" in arch["reason"]+ deps = found["estate-map"]["dependencies"]+ assert deps["details"] == ["web -> api: http, 2 link(s), exact_id, confidence 0.90"]+++async def test_dangling_calls_are_named_capped_and_counted(tmp_path):+ found = await _estate(_ctx(_workspace(tmp_path, dangling=25)))+ dangling = found["estate-contracts"]["dangling-calls"]+ assert dangling["reason"] == (+ "25 consumer(s) matched no provider in another service (http 25): "+ "no provider in the workspace 25"+ )+ assert dangling["details"][0] == (+ "web client.py:12 -> billing: http::GET::/missing/0 (no provider in the workspace)"+ )+ assert dangling["details"][1].startswith("web client.py -> target not resolved: http::GET::")+ assert "and 5 more" in dangling["details"]+ assert dangling["details"][-1] == "1 call(s) to public hosts outside the workspace not counted"+ assert len(dangling["data"]["dangling"]) == 25 # the JSON keeps every row+ assert all("self" not in r["contract_id"] for r in dangling["data"]["dangling"])+ contracts = found["estate-contracts"]["contracts"]+ assert "1 cross-repo link(s) (exact 1)" in contracts["reason"]+ assert "web -> api: 1 http link(s)" in contracts["details"]+ calls = found["estate-contracts"]["http-calls"]+ assert calls["reason"] == (+ "4 HTTP call(s) read as contracts, 0 located but not resolvable, "+ "1 file(s) calling out through code no extractor reads"+ )+++def test_dangling_calls_read_the_in_service_split_either_way():+ from repowise.core.report.sections.estate_contracts import dangling_calls++ graph = SystemGraph(+ diagnostics=ExtractionDiagnostics(+ unmatched_consumers=[+ _unmatched("a", "grpc::X/*"),+ _unmatched("a", "grpc::X/*"),+ _unmatched("a", "grpc::Y/*", "internal_only"),+ _unmatched("a", "http::GET::/v1/charges", "external_host"),+ ]+ )+ )+ rows = dangling_calls(graph, None) # no contract store: the diagnostics alone decide+ assert [(r["contract_id"], r["target"], r["external"]) for r in rows] == [+ ("grpc::X/*", None, False),+ ("http::GET::/v1/charges", None, True),+ ]+++# ---------------------------------------------------------------------------+# CLI+# ---------------------------------------------------------------------------+++def test_cli_estate_outside_a_workspace_says_so(tmp_path: Path) -> None:+ from repowise.cli.main import cli++ result = CliRunner().invoke(cli, ["report", "estate", str(tmp_path)])+ assert result.exit_code == 1 and "covers a workspace" in result.output+++def test_cli_estate_reads_the_stored_artifacts(tmp_path: Path, monkeypatch) -> None:+ from repowise.cli.main import cli++ monkeypatch.delenv("REPOWISE_DB_URL", raising=False)+ ws = _workspace((tmp_path / "ws").resolve())+ out = tmp_path / "estate.json"+ result = CliRunner().invoke(cli, ["report", "estate", str(ws), "--format", "json", "--out", str(out)])+ assert result.exit_code == 0, result.output+ doc = json.loads(out.read_text(encoding="utf-8"))+ assert doc["kind"] == "estate" and doc["scope"] == {"kind": "workspace", "name": "ws"}+ assert [s["id"] for s in doc["sections"]] == ["estate-summary", "estate-map", "estate-contracts"]+ assert all(s["repo"] is None for s in doc["sections"])+ assert [r.get("indexed", True) for r in doc["repos"]] == [False] * 4 # no member is indexed+ md = CliRunner().invoke(cli, ["report", "estate", str(ws), "--sections", "estate-map"])+ assert md.exit_code == 0 and "# Estate: ws" in md.output and "## Estate summary" not in md.output