Skip to content

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

feat(web): estate report page and GET /api/workspace/estate, built by the function the CLI calls (#4592)

Raghav Chamadiyaa48b6a577d42
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.md
index 10b6a1c8d..ca29c2705 100644
--- a/docs/reference/CLI_REFERENCE.md
+++ b/docs/reference/CLI_REFERENCE.md
@@ -1557,9 +1557,14 @@ repowise report estate --format html --out estate.html
| `estate-seams` | Service pairs joined by an edge, ranked by link confidence x reach x (1 + co-change no contract explains), every input shown per pair; a fixed heuristic, not a calibrated risk | `inferred`; `unresolved` when evidence is insufficient |
| `estate-start` | Services ranked by how many others a change to them reaches; per repo, the most central production files with the least written documentation | `inferred` |
-Outside a workspace it exits 1. A section is a `Section(scope="workspace", report="estate")` in
+Outside a workspace it exits 1. A member with no index is listed as not indexed; one whose index was
+written by an older repowise is listed as behind (run `repowise update` there), and one whose index
+cannot be opened as unreadable. A section is a `Section(scope="workspace", report="estate")` in
`repowise/core/report/sections/`; it runs once with a `WorkspaceReportContext`.
+The local server returns the same document as JSON at `GET /api/workspace/estate`, and the web UI
+shows it on the workspace **Estate report** page. Both call `report/estate.py::build_estate_document`.
+
---
### `repowise distill <command>`
diff --git a/packages/api-client/src/types/workspace.ts b/packages/api-client/src/types/workspace.ts
index 17d77abdb..0a1eb98bf 100644
--- a/packages/api-client/src/types/workspace.ts
+++ b/packages/api-client/src/types/workspace.ts
@@ -297,3 +297,6 @@ export type WorkspaceConformanceResponse = ConformanceReport;
/** `GET /api/workspace/architecture` — architecture-complexity metrics + roles. */
export type WorkspaceArchitectureResponse = ArchitectureMetrics;
+
+/** `GET /api/workspace/estate` — the estate report `repowise report estate` prints. */
+export type { EstateReport as WorkspaceEstateResponse } from "@repowise-dev/types";
diff --git a/packages/api-client/src/workspace.ts b/packages/api-client/src/workspace.ts
index cd0cf66c2..7848f5e54 100644
--- a/packages/api-client/src/workspace.ts
+++ b/packages/api-client/src/workspace.ts
@@ -13,6 +13,7 @@ import type {
WorkspaceBreakingChangesResponse,
WorkspaceConformanceResponse,
WorkspaceArchitectureResponse,
+ WorkspaceEstateResponse,
WorkspaceTestImpactResponse,
ExtractionDiagnostics,
} from "./types";
@@ -173,6 +174,18 @@ export async function getWorkspaceArchitecture(): Promise<WorkspaceArchitectureR
return apiGet<WorkspaceArchitectureResponse>("/api/workspace/architecture");
}
+/**
+ * The estate report: repositories and services, the system map and its
+ * evidence, contracts and dangling calls, health and churn per repo, the
+ * riskiest seams and where to start. Built on request from the stored
+ * workspace artifacts and every member index, so it takes about a second.
+ */
+export async function getWorkspaceEstate(
+ fetchOptions?: RequestInit,
+): Promise<WorkspaceEstateResponse> {
+ return apiGet<WorkspaceEstateResponse>("/api/workspace/estate", undefined, fetchOptions);
+}
+
/**
* Trigger a re-sync (re-index) of the workspace. Pass ``repoAlias`` to
* scope to one repo; otherwise the server fans out across every loaded
diff --git a/packages/cli/src/repowise/cli/commands/report_estate_cmd.py b/packages/cli/src/repowise/cli/commands/report_estate_cmd.py
index 202d1d1f0..a90a4cdcc 100644
--- a/packages/cli/src/repowise/cli/commands/report_estate_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/report_estate_cmd.py
@@ -2,8 +2,8 @@
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.
+repository's indexed commit listed. Built by the same function the web
+server's estate route calls, and rendered the way ``report assessment`` renders.
"""
from __future__ import annotations
@@ -34,13 +34,8 @@ def estate_command(path: str | None, wanted: str | None, fmt: str, out_path: str
the evidence behind them, contracts and the calls that reached no provider, health
and churn per repo, the riskiest seams and where to start."""
from repowise.cli._helpers.target import WorkspaceNotFound
- from repowise.cli.commands.report_assessment_cmd import (
- _build,
- _emit,
- _pick_sections,
- _renderer,
- _targets,
- )
+ from repowise.cli.commands.report_assessment_cmd import _emit, _pick_sections, _renderer
+ from repowise.core.report.estate import build_estate_document
if not out_path:
silence_logs_for_machine_output_until_close() # stdout carries only the report
@@ -54,7 +49,5 @@ def estate_command(path: str | None, wanted: str | None, fmt: str, out_path: str
"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"
+ document = run_async(build_estate_document(target.ws_root, sections))
_emit(render(document), fmt, out_path, document)
diff --git a/packages/core/src/repowise/core/report/estate.py b/packages/core/src/repowise/core/report/estate.py
new file mode 100644
index 000000000..0a4897189
--- /dev/null
+++ b/packages/core/src/repowise/core/report/estate.py
@@ -0,0 +1,81 @@
+"""The estate report document for a workspace, built once for every surface.
+
+``repowise report estate`` and ``GET /api/workspace/estate`` both call
+:func:`build_estate_document`, so the CLI and the web page read one document.
+It opens each member's index the way the estate sections do
+(:meth:`WorkspaceReportContext.each_index`), runs any repo-scope section, then
+the workspace-scope sections once over the stored workspace artifacts.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Sequence
+from pathlib import Path
+from typing import Any
+
+from repowise.core.report.build import assemble, available_sections, collect_repo, collect_workspace
+from repowise.core.report.model import ReportContext, Section, WorkspaceReportContext
+
+#: A member whose index exists but was not read: ``behind`` when the store
+#: lacks a table or column this version reads even after the reconcile
+#: ``init_db`` runs, ``unreadable`` when opening it raised a storage error or
+#: it holds no repository row. ``indexed: False`` is kept for no index at all.
+INDEX_STATES = ("behind", "unreadable")
+
+
+async def _member(
+ alias: str, root: Path, sections: Sequence[tuple[str, Section]]
+) -> tuple[dict[str, Any], list[dict[str, Any]]]:
+ """``(repos entry, repo-scope sections)`` for one member.
+
+ Storage errors become the member's ``index_state``; any other error
+ propagates, so a defect is never reported as a missing index.
+ """
+ from sqlalchemy.exc import SQLAlchemyError
+
+ from repowise.core.persistence.database import schema_behind
+ from repowise.core.workspace.registry import open_repo_db, repo_db_path
+ from repowise.core.workspace.repo_index import checkout_repository
+
+ entry: dict[str, Any] = {"alias": alias, "name": root.name}
+ if not repo_db_path(root).is_file():
+ return {**entry, "indexed": False}, []
+ unreadable = ({**entry, "index_state": "unreadable"}, [])
+ try:
+ engine, sessions = await open_repo_db(root)
+ except (SQLAlchemyError, OSError):
+ return unreadable
+ try:
+ if await schema_behind(engine):
+ return {**entry, "index_state": "behind"}, []
+ async with sessions() as session:
+ repo = await checkout_repository(session, root)
+ if repo is None:
+ return unreadable
+ ctx = ReportContext(session, repo.id, root, alias=alias, head_commit=repo.head_commit)
+ return await collect_repo(ctx, list(sections))
+ except (SQLAlchemyError, OSError):
+ return unreadable
+ finally:
+ await engine.dispose()
+
+
+async def build_estate_document(
+ ws_root: Path, sections: Sequence[tuple[str, Section]] | None = None
+) -> dict[str, Any]:
+ """The ``estate`` report over the workspace at *ws_root*; *sections* defaults
+ to every registered estate section."""
+ picked = list(sections) if sections is not None else available_sections("estate")
+ ctx = WorkspaceReportContext(ws_root)
+ parts = [
+ await _member(entry.alias, (ws_root / entry.path).resolve(), picked)
+ for entry in ctx.config().repos
+ ]
+ ctx.repos = [entry for entry, _ in parts]
+ workspace = await collect_workspace(ctx, picked)
+ document = assemble({"kind": "workspace", "name": ws_root.name}, parts, workspace=workspace)
+ document["kind"] = "estate"
+ return document
+
+
+__all__ = ["INDEX_STATES", "build_estate_document"]
diff --git a/packages/core/src/repowise/core/report/render.py b/packages/core/src/repowise/core/report/render.py
index 0d1567ec7..82de135e3 100644
--- a/packages/core/src/repowise/core/report/render.py
+++ b/packages/core/src/repowise/core/report/render.py
@@ -37,6 +37,10 @@ def _index_line(repo: dict[str, Any]) -> tuple[str, str, str]:
name = repo.get("alias") or repo.get("name") or ""
if repo.get("indexed") is False:
return name, "not indexed", "none"
+ if repo.get("index_state") == "behind":
+ return name, "index behind this version, run repowise update", "none"
+ if repo.get("index_state") == "unreadable":
+ return name, "index could not be read", "none"
commit = (repo.get("head_commit") or "")[:12]
taken = f"{snap['taken_at'][:10]} ({snap['stamp']})" if snap else "none"
return name, commit, taken
diff --git a/packages/core/src/repowise/core/report/sections/estate_summary.py b/packages/core/src/repowise/core/report/sections/estate_summary.py
index 45bb2f4c2..23143d200 100644
--- a/packages/core/src/repowise/core/report/sections/estate_summary.py
+++ b/packages/core/src/repowise/core/report/sections/estate_summary.py
@@ -38,10 +38,16 @@ def _repositories(ctx: WorkspaceReportContext, graph: Any) -> dict[str, Any]:
"indexed_commit": head,
"contracts_commit": extracted,
"services": sorted(services.get(alias, [])),
+ "index_state": entry.get("index_state"),
}
)
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]
+ behind_index = [r["alias"] for r in rows if r["index_state"] == "behind"]
+ unopened = [r["alias"] for r in rows if r["index_state"] == "unreadable"]
+ unread = [
+ r["alias"] for r in rows
+ if r["indexed"] and not r["index_state"] and r["alias"] not in walked
+ ]
empty = [r["alias"] for r in rows if r["alias"] in walked and not r["services"]]
behind = [
r
@@ -52,6 +58,13 @@ def _repositories(ctx: WorkspaceReportContext, graph: Any) -> dict[str, Any]:
details = []
if not_indexed:
details.append(f"not indexed, so nothing about them is known: {capped_names(not_indexed)}")
+ if behind_index:
+ details.append(
+ "index written by an older repowise, so its commit was not read; run "
+ f"'repowise update' there: {capped_names(behind_index)}"
+ )
+ if unopened:
+ details.append(f"index could not be opened or holds no repository: {capped_names(unopened)}")
if unread:
details.append(f"indexed but not read by the last workspace update: {capped_names(unread)}")
if empty:
diff --git a/packages/server/src/repowise/server/routers/workspace.py b/packages/server/src/repowise/server/routers/workspace.py
index bbbb2cdbe..73b952070 100644
--- a/packages/server/src/repowise/server/routers/workspace.py
+++ b/packages/server/src/repowise/server/routers/workspace.py
@@ -34,6 +34,7 @@ from repowise.server.schemas import (
WorkspaceContractsResponse,
WorkspaceContractSummary,
WorkspaceCrossRepoSummary,
+ WorkspaceEstateResponse,
WorkspaceExtractionDiagnostics,
WorkspaceGraphEdge,
WorkspaceGraphNode,
@@ -840,6 +841,33 @@ async def get_architecture(
return WorkspaceArchitectureResponse(**metrics.to_dict())
+# ---------------------------------------------------------------------------
+# GET /api/workspace/estate
+# ---------------------------------------------------------------------------
+
+
[email protected]("/estate", response_model=WorkspaceEstateResponse)
+async def get_estate(
+ request: Request,
+ ws_config=Depends(get_workspace_config),
+) -> WorkspaceEstateResponse:
+ """The estate report ``repowise report estate --format json`` prints.
+
+ Built on request by the same core function the CLI calls, from the stored
+ workspace artifacts and each member's index; nothing is extracted again.
+ Opens every member index, so it costs about 0.1 to 0.3 s per repo once the
+ server is warm. Without a stored system graph the graph sections come back
+ inconclusive and say which command builds it.
+ """
+ _require_workspace(ws_config)
+
+ from repowise.core.report.estate import build_estate_document
+
+ ws_root = getattr(request.app.state, "workspace_root", None)
+ _require_workspace(ws_root)
+ return WorkspaceEstateResponse(**await build_estate_document(Path(ws_root)))
+
+
# ---------------------------------------------------------------------------
# POST /api/workspace/sync
# ---------------------------------------------------------------------------
diff --git a/packages/server/src/repowise/server/schemas/__init__.py b/packages/server/src/repowise/server/schemas/__init__.py
index c688ed850..2e4ff28a5 100644
--- a/packages/server/src/repowise/server/schemas/__init__.py
+++ b/packages/server/src/repowise/server/schemas/__init__.py
@@ -314,6 +314,9 @@ if TYPE_CHECKING:
WorkspaceContractSummary,
WorkspaceCrossRepoSummary,
WorkspaceDependencyCycle,
+ WorkspaceEstateCheck,
+ WorkspaceEstateResponse,
+ WorkspaceEstateSection,
WorkspaceExtractionDiagnostics,
WorkspaceGraphEdge,
WorkspaceGraphNode,
@@ -618,6 +621,9 @@ _EXPORTS: dict[str, tuple[str, ...]] = {
"WorkspaceContractSummary",
"WorkspaceCrossRepoSummary",
"WorkspaceDependencyCycle",
+ "WorkspaceEstateCheck",
+ "WorkspaceEstateResponse",
+ "WorkspaceEstateSection",
"WorkspaceExtractionDiagnostics",
"WorkspaceGraphEdge",
"WorkspaceGraphNode",
@@ -920,6 +926,9 @@ __all__ = [
"WorkspaceContractsResponse",
"WorkspaceCrossRepoSummary",
"WorkspaceDependencyCycle",
+ "WorkspaceEstateCheck",
+ "WorkspaceEstateResponse",
+ "WorkspaceEstateSection",
"WorkspaceExtractionDiagnostics",
"WorkspaceGraphEdge",
"WorkspaceGraphNode",
diff --git a/packages/server/src/repowise/server/schemas/workspace.py b/packages/server/src/repowise/server/schemas/workspace.py
index e7bd7fac2..803008c5d 100644
--- a/packages/server/src/repowise/server/schemas/workspace.py
+++ b/packages/server/src/repowise/server/schemas/workspace.py
@@ -2,7 +2,7 @@
from __future__ import annotations
-from typing import Literal
+from typing import Any, Literal
from pydantic import BaseModel, ConfigDict, Field
@@ -665,3 +665,83 @@ class WorkspaceTestImpactResponse(BaseModel):
#: Free-form counters and the state that produced an empty answer, so an
#: empty response always names its reason.
summary: dict = Field(default_factory=dict)
+
+
+# ---------------------------------------------------------------------------
+# Estate report: the ``repowise report estate`` document, as
+# repowise.core.report.estate.build_estate_document returns it.
+# ---------------------------------------------------------------------------
+
+
+class WorkspaceEstateCheckDocs(BaseModel):
+ url: str
+ short: str
+
+
+class WorkspaceEstateCheck(BaseModel):
+ """One evidence item: OpenSSF Scorecard check keys plus ``method`` and ``basis``.
+
+ ``score`` is 0-10, -1 when inconclusive, ``None`` on a descriptive item.
+ ``data`` holds the item's full figures; its keys depend on ``name``.
+ """
+
+ name: str
+ score: float | None = None
+ reason: str
+ details: list[str] = []
+ method: str
+ basis: Literal["measured", "inferred", "declared", "unresolved", "gated"]
+ data: dict[str, Any] | None = None
+ documentation: WorkspaceEstateCheckDocs | None = None
+
+
+class WorkspaceEstateSection(BaseModel):
+ id: str
+ title: str
+ summary: str
+ #: ``None`` for a workspace-scope section, else the member's alias.
+ repo: str | None = None
+ checks: list[WorkspaceEstateCheck] = []
+ #: The section raised; its one check says why and is inconclusive.
+ failed: bool = False
+
+
+class WorkspaceEstateSnapshot(BaseModel):
+ taken_at: str
+ stamp: str | None = None
+
+
+class WorkspaceEstateRepo(BaseModel):
+ alias: str | None = None
+ name: str
+ head_commit: str | None = None
+ last_snapshot: WorkspaceEstateSnapshot | None = None
+ #: ``False`` when the member has no index at all.
+ indexed: bool = True
+ #: Set when an index exists but was not read: ``behind`` (written by an
+ #: older repowise; run ``repowise update``) or ``unreadable``.
+ index_state: Literal["behind", "unreadable"] | None = None
+
+
+class WorkspaceEstateGenerator(BaseModel):
+ name: str
+ version: str
+ stamp: str
+
+
+class WorkspaceEstateScope(BaseModel):
+ kind: Literal["workspace"]
+ name: str
+
+
+class WorkspaceEstateResponse(BaseModel):
+ """``GET /api/workspace/estate``: the estate report document."""
+
+ schema_version: int
+ kind: Literal["estate"]
+ generated_at: str
+ generator: WorkspaceEstateGenerator
+ scope: WorkspaceEstateScope
+ notice: str
+ repos: list[WorkspaceEstateRepo] = []
+ sections: list[WorkspaceEstateSection] = []
diff --git a/packages/types/package.json b/packages/types/package.json
index 449727f4c..621550c65 100644
--- a/packages/types/package.json
+++ b/packages/types/package.json
@@ -24,6 +24,7 @@
"./events": "./src/events.ts",
"./views": "./src/views.ts",
"./workspace": "./src/workspace.ts",
+ "./estate": "./src/estate.ts",
"./blast-radius": "./src/blast-radius.ts",
"./risk-semantics": "./src/risk-semantics.ts",
"./jobs": "./src/jobs.ts",
diff --git a/packages/types/src/estate.ts b/packages/types/src/estate.ts
new file mode 100644
index 000000000..920652655
--- /dev/null
+++ b/packages/types/src/estate.ts
@@ -0,0 +1,102 @@
+/**
+ * The estate report for a workspace: `GET /api/workspace/estate`, the same
+ * document `repowise report estate --format json` prints.
+ *
+ * The envelope is generated from the server's response models
+ * (`packages/server/src/repowise/server/schemas/workspace.py`). Each check's
+ * `data` is free-form on the wire; the interfaces below name the keys the
+ * estate sections write (`packages/core/src/repowise/core/report/sections/estate_*.py`)
+ * for the checks a page reads as tables.
+ */
+export type {
+ WorkspaceEstateCheck as EstateCheck,
+ WorkspaceEstateRepo as EstateRepo,
+ WorkspaceEstateResponse as EstateReport,
+ WorkspaceEstateSection as EstateSection,
+} from "./generated/http.js";
+
+/** `estate-summary` / `repositories`: `data.repositories`. */
+export interface EstateRepositoryRow {
+ alias: string;
+ indexed: boolean;
+ indexed_commit: string | null;
+ /** The commit contracts were last read at; differs from `indexed_commit` when stale. */
+ contracts_commit: string | null;
+ services: string[];
+ /** Set when an index exists but was not read: written by an older repowise, or unreadable. */
+ index_state?: "behind" | "unreadable" | null;
+}
+
+/** `estate-health` / `health`: `data.repositories`, lowest health first. */
+export interface EstateHealthRow {
+ repo: string;
+ /** Average file health, 1-10. */
+ average_health: number;
+ maintainability_average: number | null;
+ hotspot_health: number | null;
+ taken_at: string | null;
+ store_commit: string | null;
+ index_commit: string | null;
+}
+
+/** `estate-health` / `churn-hotspots` and `bug-magnets`: `data.repositories[alias]`. */
+export interface EstateHistoryRow {
+ commits: number;
+ newest_commit: string | null;
+ files: number;
+ hotspots?: number;
+ top_hotspots?: string[];
+ bug_magnets?: number;
+ top_bug_magnets?: { file: string; fixes: number; last_fix: string | null }[];
+ files_with_fixes?: number;
+}
+
+/** `estate-map` / `dependencies`: `data.edges`, a system-graph edge. */
+export interface EstateEdge {
+ source: string;
+ target: string;
+ kind: string;
+ weight: number;
+ confidence: number;
+ match_type: string;
+ structural: boolean;
+ strategy?: string | null;
+}
+
+/** `estate-contracts` / `dangling-calls`: `data.dangling`. */
+export interface EstateDanglingCall {
+ consumer: string;
+ file: string;
+ line: number | null;
+ contract_id: string;
+ type: string;
+ /** `no_provider` or `unlinked`. */
+ reason: string;
+ target: string | null;
+ external: boolean;
+}
+
+/** `estate-seams` / `seams`: `data.seams`, highest score first. */
+export interface EstateSeam {
+ services: [string, string];
+ /** `->` (first depends on second), `<->` (both ways) or `~` (co-change only). */
+ direction: string;
+ kinds: string[];
+ confidence: number | null;
+ reach: number;
+ co_change: number | null;
+ declared: boolean;
+ undeclared_co_change: number | null;
+ score: number | null;
+ /** The score left out co-change that could only raise it. */
+ score_is_floor: boolean;
+ missing: string[];
+}
+
+/** `estate-start` / `start-files`: `data.repositories[alias]`. */
+export interface EstateStartFile {
+ path: string;
+ pagerank: number;
+ /** Words on the file's written page; 0 when only a page rendered from code exists. */
+ doc_words: number;
+}
diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.ts
index 23db72b7b..97c5d00ed 100644
--- a/packages/types/src/generated/http.ts
+++ b/packages/types/src/generated/http.ts
@@ -4653,6 +4653,74 @@ export interface WorkspaceDependencyCycle {
async_legs?: number;
}
+/**
+ * One evidence item: OpenSSF Scorecard check keys plus ``method`` and ``basis``.
+ *
+ * ``score`` is 0-10, -1 when inconclusive, ``None`` on a descriptive item.
+ * ``data`` holds the item's full figures; its keys depend on ``name``.
+ */
+export interface WorkspaceEstateCheck {
+ name: string;
+ score?: number | null;
+ reason: string;
+ details?: string[];
+ method: string;
+ basis: "measured" | "inferred" | "declared" | "unresolved" | "gated";
+ data?: Record<string, unknown> | null;
+ documentation?: WorkspaceEstateCheckDocs | null;
+}
+
+export interface WorkspaceEstateCheckDocs {
+ url: string;
+ short: string;
+}
+
+export interface WorkspaceEstateGenerator {
+ name: string;
+ version: string;
+ stamp: string;
+}
+
+export interface WorkspaceEstateRepo {
+ alias?: string | null;
+ name: string;
+ head_commit?: string | null;
+ last_snapshot?: WorkspaceEstateSnapshot | null;
+ indexed?: boolean;
+ index_state?: "behind" | "unreadable" | null;
+}
+
+/** ``GET /api/workspace/estate``: the estate report document. */
+export interface WorkspaceEstateResponse {
+ schema_version: number;
+ kind: "estate";
+ generated_at: string;
+ generator: WorkspaceEstateGenerator;
+ scope: WorkspaceEstateScope;
+ notice: string;
+ repos?: WorkspaceEstateRepo[];
+ sections?: WorkspaceEstateSection[];
+}
+
+export interface WorkspaceEstateScope {
+ kind: "workspace";
+ name: string;
+}
+
+export interface WorkspaceEstateSection {
+ id: string;
+ title: string;
+ summary: string;
+ repo?: string | null;
+ checks?: WorkspaceEstateCheck[];
+ failed?: boolean;
+}
+
+export interface WorkspaceEstateSnapshot {
+ taken_at: string;
+ stamp?: string | null;
+}
+
/** One reason a graph's evidence is short of measured. */
export interface WorkspaceEvidenceReason {
code: string;
diff --git a/packages/types/src/index.ts b/packages/types/src/index.ts
index 878b3e0a1..c1ae2b0dc 100644
--- a/packages/types/src/index.ts
+++ b/packages/types/src/index.ts
@@ -24,6 +24,7 @@ export * from "./history.js";
export * from "./events.js";
export * from "./views.js";
export * from "./workspace.js";
+export * from "./estate.js";
export * from "./blast-radius.js";
export * from "./risk-semantics.js";
export * from "./jobs.js";
diff --git a/packages/ui/vitest.config.ts b/packages/ui/vitest.config.ts
index 5afa8d5c7..7d82613c7 100644
--- a/packages/ui/vitest.config.ts
+++ b/packages/ui/vitest.config.ts
@@ -37,6 +37,7 @@ export default defineConfig({
"@repowise-dev/types/events": path.resolve(__dirname, "../types/src/events.ts"),
"@repowise-dev/types/views": path.resolve(__dirname, "../types/src/views.ts"),
"@repowise-dev/types/workspace": path.resolve(__dirname, "../types/src/workspace.ts"),
+ "@repowise-dev/types/estate": path.resolve(__dirname, "../types/src/estate.ts"),
"@repowise-dev/types/blast-radius": path.resolve(__dirname, "../types/src/blast-radius.ts"),
"@repowise-dev/types/jobs": path.resolve(__dirname, "../types/src/jobs.ts"),
"@repowise-dev/types/settings": path.resolve(__dirname, "../types/src/settings.ts"),
diff --git a/packages/web/messages/en.json b/packages/web/messages/en.json
index d0bc7e20e..3661cd1ee 100644
--- a/packages/web/messages/en.json
+++ b/packages/web/messages/en.json
@@ -150,6 +150,7 @@
"conformance": "Conformance",
"contracts": "Contracts",
"coChanges": "Co-Changes",
+ "estateReport": "Estate report",
"groupPeopleAndHistory": "People & History",
"groupSettings": "Settings",
"groupUnderstand": "Understand",
@@ -1611,6 +1612,153 @@
"description": "A ready-to-paste prompt that has your AI agent resolve these architecture rule violations by removing the disallowed dependencies."
}
},
+ "estate": {
+ "indexBehind": "index behind, run repowise update",
+ "indexUnreadable": "index could not be read",
+ "indexBehindLabel": "Index behind",
+ "indexBehindSentence": "{count, plural, one {# repo has an index written by an older repowise, so it was not read} other {# repos have an index written by an older repowise, so they were not read}}. Run repowise update in each to bring it up to date.",
+ "title": "Estate report",
+ "description": "One read across every repository in the workspace: the system map and the evidence behind it, contracts and the calls that reached no provider, health and churn per repo, the riskiest seams and where to start.",
+ "unavailableTitle": "Estate report unavailable",
+ "unavailableDescription": "The server could not build the report ({error}). A server older than this page does not serve it; upgrade repowise and restart repowise serve.",
+ "noGraphLabel": "No system graph",
+ "noGraphSentence": "No system graph is stored for this workspace yet, so the map, contracts, seams and service reach are not determined. Run repowise update --workspace once two or more member repos are indexed. Health, churn and the files to start with still read from each index.",
+ "evidencePartial": "Partial evidence",
+ "evidencePartialSentence": "The figures below are computed with part of the estate out of sight: {reason}.",
+ "evidenceInsufficient": "Not determined",
+ "evidenceInsufficientSentence": "The architecture score, cycle verdicts, seams and service reach are not determined: {reason}.",
+ "staleLabel": "Stale",
+ "staleSentence": "{count, plural, one {# repo has its contracts read at another commit than its index} other {# repos have their contracts read at another commit than their index}}. Run repowise update --workspace to read them again.",
+ "failedLabel": "Failed",
+ "failedSentence": "This section failed to build, so the report marks it inconclusive.",
+ "generated": "Built {when} by repowise {version} from the stored workspace artifacts and each member's index.",
+ "shownOf": "Showing {shown} of {total}. repowise report estate --format json lists every one.",
+ "notIndexed": "not indexed",
+ "notRead": "not read",
+ "noSnapshot": "no snapshot",
+ "notMeasured": "not measured",
+ "notMeasuredNote": "A dash means not measured: no health snapshot, too little indexed history, or the repo is not indexed. The sentences below name which.",
+ "none": "none",
+ "contractsBehind": "behind the index",
+ "snapshotBehind": "older than the index",
+ "dependsOn": "depends on",
+ "targetUnresolved": "target not resolved",
+ "undocumented": "undocumented",
+ "docWords": "{count, plural, one {# doc word} other {# doc words}}",
+ "behindContract": "behind a contract",
+ "coChangeOnly": "co-change only",
+ "coChangeUnexplained": "{value}, no contract",
+ "scoreFloor": "at least {score}",
+ "serviceLinksNote": "{count, plural, one {# service-level link names a workspace repo whose routes do not serve the path.} other {# service-level links name a workspace repo whose routes do not serve the path.}}",
+ "orphanNote": "{count, plural, one {# provider is reached by no consumer in the workspace; it may be called from outside it.} other {# providers are reached by no consumer in the workspace; they may be called from outside it.}}",
+ "externalNote": "{count, plural, one {# call to a public host outside the workspace is not counted.} other {# calls to public hosts outside the workspace are not counted.}}",
+ "ribbon": {
+ "repos": "Repositories",
+ "reposSub": "{indexed} of {total} indexed",
+ "services": "Services",
+ "servicesSub": "in the system graph",
+ "links": "Cross-repo links",
+ "linksSub": "contracts matched between repos",
+ "dangling": "Dangling calls",
+ "danglingSub": "matched no provider in another service",
+ "architecture": "Architecture score",
+ "architectureSub": "out of 10, a fixed formula",
+ "notDetermined": "not determined"
+ },
+ "section": {
+ "summary": {
+ "title": "Estate summary",
+ "description": "Repositories, services and how much evidence the system graph rests on."
+ },
+ "map": {
+ "title": "System map and architecture",
+ "description": "How the services depend on each other, and what that structure scores."
+ },
+ "contracts": {
+ "title": "Contracts and dangling calls",
+ "description": "Contracts read and linked across repos, and each call that reached no provider."
+ },
+ "health": {
+ "title": "Health, churn and bug magnets by repository",
+ "description": "Each repo reads on its own; repos are never averaged together. Lowest health first."
+ },
+ "seams": {
+ "title": "Riskiest seams",
+ "description": "Service pairs ranked by link confidence, reach and co-change no contract explains. A fixed heuristic, not a calibrated risk."
+ },
+ "start": {
+ "title": "Where to start",
+ "description": "The services most others depend on, then each repo's central, least documented files."
+ }
+ },
+ "check": {
+ "estate": "System graph",
+ "repositories": "Repositories",
+ "services": "Services",
+ "evidence": "Evidence",
+ "dependencies": "Dependencies",
+ "architecture": "Architecture",
+ "contracts": "Contracts",
+ "http-calls": "HTTP calls",
+ "dangling-calls": "Dangling calls",
+ "health": "Health",
+ "churn-hotspots": "Churn hotspots",
+ "bug-magnets": "Bug magnets",
+ "seams": "Seams",
+ "start-services": "Services to read first",
+ "start-files": "Files to read first",
+ "system-map": "System map"
+ },
+ "basis": {
+ "measured": "Measured",
+ "inferred": "Inferred",
+ "declared": "Declared",
+ "unresolved": "Not determined",
+ "gated": "Held back"
+ },
+ "band": {
+ "healthy": "Healthy",
+ "warning": "Warning",
+ "alert": "Alert"
+ },
+ "danglingReason": {
+ "no_provider": "no provider in the workspace",
+ "unlinked": "a provider exists, no link formed"
+ },
+ "col": {
+ "repo": "Repository",
+ "indexedAt": "Index at",
+ "contractsAt": "Contracts read at",
+ "services": "Services",
+ "dependency": "Dependency",
+ "kind": "Kind",
+ "links": "Links",
+ "strategy": "How linked",
+ "confidence": "Confidence",
+ "type": "Type",
+ "providers": "Providers",
+ "consumers": "Consumers",
+ "consumer": "Consumer",
+ "file": "File",
+ "target": "Target",
+ "contract": "Contract",
+ "why": "Why",
+ "health": "Health",
+ "maintainability": "Maintainability",
+ "hotspotHealth": "Over hotspots",
+ "churnHotspots": "Churn hotspots",
+ "bugMagnets": "Bug magnets",
+ "snapshot": "Snapshot",
+ "pair": "Services",
+ "edge": "Edge",
+ "reach": "Reach",
+ "coChange": "Co-change",
+ "seamScore": "Seam score",
+ "service": "Service",
+ "reaches": "Services a change reaches",
+ "docs": "Documentation"
+ }
+ },
"contracts": {
"links": {
"title": "Matched links",
diff --git a/packages/web/messages/zh-CN.json b/packages/web/messages/zh-CN.json
index 9896a0704..183ee67b4 100644
--- a/packages/web/messages/zh-CN.json
+++ b/packages/web/messages/zh-CN.json
@@ -150,6 +150,7 @@
"conformance": "一致性",
"contracts": "契约",
"coChanges": "共变分析",
+ "estateReport": "全局报告",
"groupPeopleAndHistory": "人员与历史",
"groupSettings": "设置",
"groupUnderstand": "理解",
@@ -1611,6 +1612,153 @@
"description": "一段可直接粘贴的提示词,让你的 AI 代理通过移除不被允许的依赖来解决这些架构规则违规。"
}
},
+ "estate": {
+ "indexBehind": "索引已过旧,请运行 repowise update",
+ "indexUnreadable": "索引无法读取",
+ "indexBehindLabel": "索引过旧",
+ "indexBehindSentence": "{count, plural, other {# 个仓库的索引由旧版 repowise 生成,因此未被读取}}。请在每个仓库中运行 repowise update 进行更新。",
+ "title": "全局报告",
+ "description": "一次读完工作区内的每个仓库:系统地图及其依据、契约与未找到提供方的调用、各仓库的健康度与变更热度、风险最高的服务接缝,以及从哪里入手。",
+ "unavailableTitle": "全局报告不可用",
+ "unavailableDescription": "服务器无法生成该报告({error})。比此页面旧的服务器不提供该报告;请升级 repowise 并重启 repowise serve。",
+ "noGraphLabel": "无系统图",
+ "noGraphSentence": "此工作区尚未保存系统图,因此系统地图、契约、服务接缝和服务影响范围均无法确定。至少两个成员仓库建立索引后,运行 repowise update --workspace。健康度、变更热度和建议优先阅读的文件仍从各仓库索引读取。",
+ "evidencePartial": "部分依据",
+ "evidencePartialSentence": "以下数据是在部分系统不可见的情况下计算的:{reason}。",
+ "evidenceInsufficient": "无法确定",
+ "evidenceInsufficientSentence": "架构评分、循环判断、服务接缝和服务影响范围无法确定:{reason}。",
+ "staleLabel": "已过期",
+ "staleSentence": "{count, plural, other {# 个仓库的契约读取提交与其索引提交不一致}}。运行 repowise update --workspace 重新读取。",
+ "failedLabel": "失败",
+ "failedSentence": "此部分生成失败,报告将其标记为无法得出结论。",
+ "generated": "由 repowise {version} 于 {when} 根据已保存的工作区产物和各成员索引生成。",
+ "shownOf": "显示 {shown} / {total}。repowise report estate --format json 会列出全部。",
+ "notIndexed": "未索引",
+ "notRead": "未读取",
+ "noSnapshot": "无快照",
+ "notMeasured": "未测量",
+ "notMeasuredNote": "短横线表示未测量:没有健康度快照、已索引的历史过短,或仓库未索引。下方的说明会指出具体原因。",
+ "none": "无",
+ "contractsBehind": "落后于索引",
+ "snapshotBehind": "早于索引",
+ "dependsOn": "依赖",
+ "targetUnresolved": "目标未解析",
+ "undocumented": "无文档",
+ "docWords": "{count, plural, other {# 个文档词}}",
+ "behindContract": "有契约约束",
+ "coChangeOnly": "仅共同变更",
+ "coChangeUnexplained": "{value},无契约",
+ "scoreFloor": "至少 {score}",
+ "serviceLinksNote": "{count, plural, other {# 条服务级链接指向某个工作区仓库,但该仓库的路由不提供对应路径。}}",
+ "orphanNote": "{count, plural, other {# 个提供方没有被工作区内任何消费方调用;可能由工作区外部调用。}}",
+ "externalNote": "{count, plural, other {# 次对工作区外公共主机的调用未计入。}}",
+ "ribbon": {
+ "repos": "仓库",
+ "reposSub": "{total} 个中 {indexed} 个已索引",
+ "services": "服务",
+ "servicesSub": "位于系统图中",
+ "links": "跨仓库链接",
+ "linksSub": "仓库之间匹配的契约",
+ "dangling": "悬空调用",
+ "danglingSub": "未匹配到其他服务的提供方",
+ "architecture": "架构评分",
+ "architectureSub": "满分 10,按固定公式计算",
+ "notDetermined": "无法确定"
+ },
+ "section": {
+ "summary": {
+ "title": "全局概览",
+ "description": "仓库、服务,以及系统图所依据的证据有多少。"
+ },
+ "map": {
+ "title": "系统地图与架构",
+ "description": "服务之间如何相互依赖,以及该结构的评分。"
+ },
+ "contracts": {
+ "title": "契约与悬空调用",
+ "description": "跨仓库读取和链接的契约,以及每个未找到提供方的调用。"
+ },
+ "health": {
+ "title": "各仓库的健康度、变更热点与缺陷磁铁",
+ "description": "每个仓库单独评估,从不合并平均。健康度最低的排在最前。"
+ },
+ "seams": {
+ "title": "风险最高的服务接缝",
+ "description": "按链接置信度、影响范围以及无契约解释的共同变更对服务对排序。这是固定的启发式规则,不是经过校准的风险值。"
+ },
+ "start": {
+ "title": "从哪里入手",
+ "description": "被最多其他服务依赖的服务,以及每个仓库中最核心、文档最少的文件。"
+ }
+ },
+ "check": {
+ "estate": "系统图",
+ "repositories": "仓库",
+ "services": "服务",
+ "evidence": "依据",
+ "dependencies": "依赖",
+ "architecture": "架构",
+ "contracts": "契约",
+ "http-calls": "HTTP 调用",
+ "dangling-calls": "悬空调用",
+ "health": "健康度",
+ "churn-hotspots": "变更热点",
+ "bug-magnets": "缺陷磁铁",
+ "seams": "服务接缝",
+ "start-services": "优先阅读的服务",
+ "start-files": "优先阅读的文件",
+ "system-map": "系统地图"
+ },
+ "basis": {
+ "measured": "实测",
+ "inferred": "推断",
+ "declared": "声明",
+ "unresolved": "无法确定",
+ "gated": "暂不提供"
+ },
+ "band": {
+ "healthy": "健康",
+ "warning": "警告",
+ "alert": "告警"
+ },
+ "danglingReason": {
+ "no_provider": "工作区内没有提供方",
+ "unlinked": "存在提供方,但未形成链接"
+ },
+ "col": {
+ "repo": "仓库",
+ "indexedAt": "索引提交",
+ "contractsAt": "契约读取提交",
+ "services": "服务",
+ "dependency": "依赖",
+ "kind": "类型",
+ "links": "链接",
+ "strategy": "链接方式",
+ "confidence": "置信度",
+ "type": "类型",
+ "providers": "提供方",
+ "consumers": "消费方",
+ "consumer": "消费方",
+ "file": "文件",
+ "target": "目标",
+ "contract": "契约",
+ "why": "原因",
+ "health": "健康度",
+ "maintainability": "可维护性",
+ "hotspotHealth": "热点健康度",
+ "churnHotspots": "变更热点",
+ "bugMagnets": "缺陷磁铁",
+ "snapshot": "快照",
+ "pair": "服务",
+ "edge": "边",
+ "reach": "影响范围",
+ "coChange": "共同变更",
+ "seamScore": "接缝评分",
+ "service": "服务",
+ "reaches": "变更可波及的服务数",
+ "docs": "文档"
+ }
+ },
"contracts": {
"links": {
"title": "匹配链接",
diff --git a/packages/web/src/app/workspace/estate/estate-model.test.ts b/packages/web/src/app/workspace/estate/estate-model.test.ts
new file mode 100644
index 000000000..5bd3832d2
--- /dev/null
+++ b/packages/web/src/app/workspace/estate/estate-model.test.ts
@@ -0,0 +1,68 @@
+import { describe, expect, it } from "vitest";
+import type { EstateCheck, EstateReport } from "@repowise-dev/types/estate";
+import { graphEvidence, missingGraph, repoRows } from "./estate-model";
+
+function check(name: string, data?: Record<string, unknown>): EstateCheck {
+ return { name, score: null, reason: "", details: [], method: "", basis: "measured", data: data ?? null };
+}
+
+function report(sections: { id: string; checks: EstateCheck[] }[], repos: EstateReport["repos"]): EstateReport {
+ return {
+ schema_version: 1,
+ kind: "estate",
+ generated_at: "2026-10-24T00:00:00+00:00",
+ generator: { name: "repowise", version: "0", stamp: "s" },
+ scope: { kind: "workspace", name: "ws" },
+ notice: "",
+ repos,
+ sections: sections.map((s) => ({ ...s, title: s.id, summary: "", repo: null })),
+ };
+}
+
+describe("repoRows", () => {
+ it("joins health, churn and magnets per configured repo, lowest health first", () => {
+ const rows = repoRows(
+ report(
+ [
+ {
+ id: "estate-health",
+ checks: [
+ check("health", {
+ repositories: [
+ { repo: "api", average_health: 5.2 },
+ { repo: "web", average_health: 8.4 },
+ ],
+ }),
+ check("churn-hotspots", { repositories: { web: { commits: 9, hotspots: 2 } } }),
+ check("bug-magnets", { repositories: { api: { commits: 9, bug_magnets: 1 } } }),
+ ],
+ },
+ ],
+ [
+ { alias: "docs", name: "docs", indexed: false },
+ { alias: "web", name: "web" },
+ { alias: "api", name: "api" },
+ ],
+ ),
+ );
+ expect(rows.map((r) => r.repo)).toEqual(["api", "web", "docs"]);
+ expect(rows[0]).toMatchObject({ indexed: true, churn: null, magnets: { bug_magnets: 1 } });
+ expect(rows[1]).toMatchObject({ churn: { hotspots: 2 }, magnets: null });
+ expect(rows[2]).toMatchObject({ indexed: false, health: null });
+ });
+});
+
+describe("graph state", () => {
+ it("reads the missing-graph item and the evidence block from the summary", () => {
+ const none = report([{ id: "estate-summary", checks: [check("estate")] }], []);
+ expect(missingGraph(none)?.name).toBe("estate");
+ expect(graphEvidence(none)).toBeNull();
+
+ const partial = report(
+ [{ id: "estate-summary", checks: [check("evidence", { state: "partial", summary: "x" })] }],
+ [],
+ );
+ expect(missingGraph(partial)).toBeNull();
+ expect(graphEvidence(partial)?.state).toBe("partial");
+ });
+});
diff --git a/packages/web/src/app/workspace/estate/estate-model.ts b/packages/web/src/app/workspace/estate/estate-model.ts
new file mode 100644
index 000000000..03a3995cd
--- /dev/null
+++ b/packages/web/src/app/workspace/estate/estate-model.ts
@@ -0,0 +1,97 @@
+/**
+ * Reads the estate report document for the page. Every figure comes from a
+ * check the engine wrote (`report/sections/estate_*.py`); nothing here
+ * recomputes a section, it only picks checks and joins their per-repo rows.
+ */
+import type {
+ EstateCheck,
+ EstateHealthRow,
+ EstateHistoryRow,
+ EstateReport,
+} from "@repowise-dev/types/estate";
+import type { GraphEvidence } from "@repowise-dev/types/workspace";
+
+/** The check *name* in section *sectionId*, if the report carries it. */
+export function findCheck(
+ report: EstateReport,
+ sectionId: string,
+ name: string,
+): EstateCheck | undefined {
+ const section = (report.sections ?? []).find((s) => s.id === sectionId);
+ return (section?.checks ?? []).find((c) => c.name === name);
+}
+
+/** A check's `data[key]` as the shape the engine writes there, or `fallback`. */
+export function checkData<T>(check: EstateCheck | undefined, key: string, fallback: T): T {
+ const value = check?.data?.[key];
+ return value === undefined || value === null ? fallback : (value as T);
+}
+
+/**
+ * The item every graph section gives when no system graph is stored: the
+ * summary then holds one inconclusive `estate` check saying which command
+ * builds it.
+ */
+export function missingGraph(report: EstateReport): EstateCheck | null {
+ return findCheck(report, "estate-summary", "estate") ?? null;
+}
+
+/** The graph's evidence state, as the summary's `evidence` check carries it. */
+export function graphEvidence(report: EstateReport): GraphEvidence | null {
+ const check = findCheck(report, "estate-summary", "evidence");
+ return (check?.data as GraphEvidence | null | undefined) ?? null;
+}
+
+export interface EstateRepoRow {
+ repo: string;
+ indexed: boolean;
+ indexState: "behind" | "unreadable" | null;
+ health: EstateHealthRow | null;
+ /** Null when the repo's history was not measured (too short, unread, not indexed). */
+ churn: EstateHistoryRow | null;
+ magnets: EstateHistoryRow | null;
+}
+
+/**
+ * One row per configured repository, joining the health, churn-hotspot and
+ * bug-magnet checks. Repos keep the health check's order (lowest health
+ * first), then the rest in report order, so the weakest repo leads.
+ */
+export function repoRows(report: EstateReport): EstateRepoRow[] {
+ const health = checkData<EstateHealthRow[]>(
+ findCheck(report, "estate-health", "health"),
+ "repositories",
+ [],
+ );
+ const churn = checkData<Record<string, EstateHistoryRow>>(
+ findCheck(report, "estate-health", "churn-hotspots"),
+ "repositories",
+ {},
+ );
+ const magnets = checkData<Record<string, EstateHistoryRow>>(
+ findCheck(report, "estate-health", "bug-magnets"),
+ "repositories",
+ {},
+ );
+ const byRepo = new Map(health.map((h) => [h.repo, h]));
+ const aliases = (report.repos ?? []).map((r) => ({
+ repo: r.alias ?? r.name,
+ indexed: r.indexed ?? true,
+ indexState: r.index_state ?? null,
+ }));
+ const rank = (repo: string) => {
+ const i = health.findIndex((h) => h.repo === repo);
+ return i < 0 ? health.length : i;
+ };
+ return aliases
+ .map((a, order) => ({ ...a, order }))
+ .sort((a, b) => rank(a.repo) - rank(b.repo) || a.order - b.order)
+ .map(({ repo, indexed, indexState }) => ({
+ repo,
+ indexed,
+ indexState,
+ health: byRepo.get(repo) ?? null,
+ churn: churn[repo] ?? null,
+ magnets: magnets[repo] ?? null,
+ }));
+}
diff --git a/packages/web/src/app/workspace/estate/estate-table.tsx b/packages/web/src/app/workspace/estate/estate-table.tsx
new file mode 100644
index 000000000..cf1b0438c
--- /dev/null
+++ b/packages/web/src/app/workspace/estate/estate-table.tsx
@@ -0,0 +1,68 @@
+import type { ReactNode } from "react";
+
+export interface EstateColumn {
+ label: string;
+ /** Figures align right so their digits line up. */
+ numeric?: boolean;
+}
+
+/**
+ * A plain, server-rendered table in the hotspot-table style: mono micro-label
+ * headers, hairline rows, tabular figures, and its own horizontal scroll so
+ * the page never scrolls sideways at phone width.
+ */
+export function EstateTable({
+ caption,
+ columns,
+ rows,
+ note,
+}: {
+ caption: string;
+ columns: EstateColumn[];
+ rows: { key: string; cells: ReactNode[] }[];
+ /** Under the table, e.g. how many rows were left out. */
+ note?: string | undefined;
+}) {
+ return (
+ <div className="flex flex-col gap-2">
+ <div className="-mx-[var(--page-pad)] overflow-x-auto px-[var(--page-pad)] sm:mx-0 sm:px-0">
+ <table className="w-full min-w-[560px] border-collapse text-xs">
+ <caption className="sr-only">{caption}</caption>
+ <thead>
+ <tr className="border-b border-[var(--color-border-default)] text-left font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ {columns.map((c) => (
+ <th
+ key={c.label}
+ scope="col"
+ className={`pb-2 pr-4 font-medium last:pr-0 ${c.numeric ? "text-right" : ""}`}
+ >
+ {c.label}
+ </th>
+ ))}
+ </tr>
+ </thead>
+ <tbody>
+ {rows.map((row) => (
+ <tr
+ key={row.key}
+ className="border-b border-[var(--color-border-default)] align-top last:border-b-0"
+ >
+ {row.cells.map((cell, i) => (
+ <td
+ key={columns[i]?.label ?? i}
+ className={`py-2.5 pr-4 text-[var(--color-text-secondary)] last:pr-0 ${
+ columns[i]?.numeric ? "text-right font-mono tabular-nums" : ""
+ }`}
+ >
+ {cell}
+ </td>
+ ))}
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ {note ? <p className="text-xs text-[var(--color-text-tertiary)]">{note}</p> : null}
+ </div>
+ );
+}
diff --git a/packages/web/src/app/workspace/estate/page.tsx b/packages/web/src/app/workspace/estate/page.tsx
new file mode 100644
index 000000000..b10f1327b
--- /dev/null
+++ b/packages/web/src/app/workspace/estate/page.tsx
@@ -0,0 +1,608 @@
+import type { Metadata } from "next";
+import type { ReactNode } from "react";
+import { getTranslations } from "next-intl/server";
+import { FileText } from "lucide-react";
+import type {
+ EstateCheck,
+ EstateDanglingCall,
+ EstateEdge,
+ EstateReport,
+ EstateRepositoryRow,
+ EstateSeam,
+ EstateSection,
+ EstateStartFile,
+} from "@repowise-dev/types/estate";
+import { PageShell } from "@repowise-dev/ui/shared/page-shell";
+import { EmptyState } from "@repowise-dev/ui/shared/empty-state";
+import { Callout } from "@repowise-dev/ui/shared/callout";
+import { OverviewSection } from "@repowise-dev/ui/overview/section";
+import { StatRibbon, type RibbonStat } from "@repowise-dev/ui/stats/stat-ribbon";
+import { healthMark } from "@repowise-dev/ui/health/tokens";
+import { formatDate, formatNumber } from "@repowise-dev/ui/lib/format";
+import { getWorkspaceEstate } from "@/lib/api/workspace";
+import { EstateTable } from "./estate-table";
+import {
+ checkData,
+ findCheck,
+ graphEvidence,
+ missingGraph,
+ repoRows,
+ type EstateRepoRow,
+} from "./estate-model";
+
+export async function generateMetadata(): Promise<Metadata> {
+ const t = await getTranslations("estate");
+ return { title: t("title") };
+}
+
+export const revalidate = 30;
+
+/** The minimal translator shape the helpers below need; next-intl's `t` fits. */
+type Translator = ((key: string, values?: Record<string, string | number>) => string) & {
+ has: (key: string) => boolean;
+};
+
+/** Rows a table shows before it says how many it left out; the JSON keeps every one. */
+const DEPENDENCY_ROWS = 20;
+const DANGLING_ROWS = 25;
+const SEAM_ROWS = 10;
+const START_SERVICE_ROWS = 10;
+
+const SECTION_KEYS: Record<string, string> = {
+ "estate-summary": "summary",
+ "estate-map": "map",
+ "estate-contracts": "contracts",
+ "estate-health": "health",
+ "estate-seams": "seams",
+ "estate-start": "start",
+};
+
+/** Checks the health table below already shows row by row. */
+const IN_HEALTH_TABLE = new Set(["health", "churn-hotspots", "bug-magnets"]);
+
+const mono = "font-mono text-[11px] text-[var(--color-text-primary)] [overflow-wrap:anywhere]";
+const quiet = "text-[var(--color-text-tertiary)]";
+
+function short(sha: string | null | undefined): string {
+ return sha ? sha.slice(0, 12) : "";
+}
+
+function indexStateLabel(t: Translator, state: "behind" | "unreadable"): string {
+ return state === "behind" ? t("indexBehind") : t("indexUnreadable");
+}
+
+function shownOf(t: Translator, shown: number, total: number): string | undefined {
+ return total > shown ? t("shownOf", { shown, total }) : undefined;
+}
+
+/**
+ * The estate report for the workspace: the same document
+ * `repowise report estate` prints, one section per report section.
+ *
+ * Sentences from the engine (each check's reason and notes) are shown as
+ * written, in English; the page's own labels are translated.
+ */
+export default async function EstatePage() {
+ const t = (await getTranslations("estate")) as unknown as Translator;
+
+ let report: EstateReport | null = null;
+ let error = "";
+ try {
+ report = await getWorkspaceEstate();
+ } catch (err) {
+ error = err instanceof Error ? err.message : String(err);
+ }
+
+ if (!report) {
+ return (
+ <PageShell title={t("title")} icon={<FileText />} description={t("description")}>
+ <EmptyState
+ tone="error"
+ title={t("unavailableTitle")}
+ description={t("unavailableDescription", { error })}
+ />
+ </PageShell>
+ );
+ }
+
+ const noGraph = missingGraph(report);
+ const evidence = graphEvidence(report);
+ const repos = report.repos ?? [];
+ const indexed = repos.filter((r) => (r.indexed ?? true) && !r.index_state).length;
+ const behindIndex = repos.filter((r) => r.index_state === "behind").length;
+ const repositories = checkData<EstateRepositoryRow[]>(
+ findCheck(report, "estate-summary", "repositories"),
+ "repositories",
+ [],
+ );
+ const stale = repositories.filter(
+ (r) => r.indexed && r.contracts_commit && r.indexed_commit && r.contracts_commit !== r.indexed_commit,
+ ).length;
+ const services = checkData<unknown[] | null>(
+ findCheck(report, "estate-summary", "services"),
+ "services",
+ null,
+ );
+ const contracts = findCheck(report, "estate-contracts", "contracts");
+ const links = Object.values(checkData<Record<string, number>>(contracts, "links_by_match_type", {}))
+ .reduce((a, b) => a + b, 0);
+ const dangling = findCheck(report, "estate-contracts", "dangling-calls");
+ const architecture = findCheck(report, "estate-map", "architecture");
+
+ const ribbon: RibbonStat[] = [
+ {
+ label: t("ribbon.repos"),
+ value: formatNumber(repos.length),
+ sub: t("ribbon.reposSub", { indexed, total: repos.length }),
+ },
+ {
+ label: t("ribbon.services"),
+ value: services ? formatNumber(services.length) : "",
+ sub: t("ribbon.servicesSub"),
+ },
+ {
+ label: t("ribbon.links"),
+ value: contracts?.data ? formatNumber(links) : "",
+ sub: t("ribbon.linksSub"),
+ },
+ {
+ label: t("ribbon.dangling"),
+ value: dangling
+ ? formatNumber(checkData<EstateDanglingCall[]>(dangling, "dangling", []).length)
+ : "",
+ sub: t("ribbon.danglingSub"),
+ },
+ {
+ label: t("ribbon.architecture"),
+ value: !architecture
+ ? ""
+ : architecture.basis === "unresolved" || architecture.score == null
+ ? t("ribbon.notDetermined")
+ : architecture.score.toFixed(1),
+ sub: t("ribbon.architectureSub"),
+ },
+ ];
+
+ return (
+ <PageShell title={t("title")} icon={<FileText />} description={t("description")}>
+ {noGraph ? (
+ <Callout tone="warning" label={t("noGraphLabel")}>
+ {t("noGraphSentence")}
+ </Callout>
+ ) : evidence && evidence.state !== "measured" ? (
+ <Callout
+ tone="warning"
+ label={evidence.state === "partial" ? t("evidencePartial") : t("evidenceInsufficient")}
+ >
+ {t(evidence.state === "partial" ? "evidencePartialSentence" : "evidenceInsufficientSentence", {
+ reason: evidence.summary,
+ })}
+ </Callout>
+ ) : null}
+ {behindIndex > 0 ? (
+ <Callout tone="warning" label={t("indexBehindLabel")}>
+ {t("indexBehindSentence", { count: behindIndex })}
+ </Callout>
+ ) : null}
+ {stale > 0 ? (
+ <Callout tone="info" label={t("staleLabel")}>
+ {t("staleSentence", { count: stale })}
+ </Callout>
+ ) : null}
+
+ <StatRibbon stats={ribbon} />
+
+ {(report.sections ?? []).map((section, i) => (
+ <ReportSection key={`${section.id}:${section.repo ?? ""}`} section={section} report={report} t={t} flush={i === 0} />
+ ))}
+
+ <p className={`text-xs ${quiet}`}>
+ {t("generated", {
+ when: formatDate(report.generated_at),
+ version: report.generator.version,
+ })}{" "}
+ <span lang="en">{report.notice}</span>
+ </p>
+ </PageShell>
+ );
+}
+
+function ReportSection({
+ section,
+ report,
+ t,
+ flush,
+}: {
+ section: EstateSection;
+ report: EstateReport;
+ t: Translator;
+ flush: boolean;
+}) {
+ const key = SECTION_KEYS[section.id];
+ const title = key ? t(`section.${key}.title`) : section.title;
+ const description = key ? t(`section.${key}.description`) : section.summary;
+ const checks = section.checks ?? [];
+ return (
+ <OverviewSection id={section.id} title={title} description={description} flush={flush}>
+ {section.failed ? (
+ <Callout tone="error" label={t("failedLabel")}>
+ {t("failedSentence")}
+ </Callout>
+ ) : null}
+ {section.id === "estate-health" && !section.failed ? (
+ <HealthTable rows={repoRows(report)} t={t} />
+ ) : null}
+ <div className="flex flex-col gap-6">
+ {checks.map((check) => (
+ <CheckBlock
+ key={check.name}
+ check={check}
+ t={t}
+ body={section.id === "estate-health" && IN_HEALTH_TABLE.has(check.name) ? null : checkBody(check, t)}
+ showDetails={!(section.id === "estate-health" && IN_HEALTH_TABLE.has(check.name))}
+ />
+ ))}
+ </div>
+ </OverviewSection>
+ );
+}
+
+/** One evidence item: its name and basis, the engine's sentence, then a table or its notes. */
+function CheckBlock({
+ check,
+ t,
+ body,
+ showDetails,
+}: {
+ check: EstateCheck;
+ t: Translator;
+ body: ReactNode | null;
+ showDetails: boolean;
+}) {
+ const label = t.has(`check.${check.name}`) ? t(`check.${check.name}`) : check.name;
+ const details = check.details ?? [];
+ return (
+ <div className="flex min-w-0 flex-col gap-2">
+ <p className="flex flex-wrap items-baseline gap-x-2 font-mono text-[10px] uppercase tracking-[0.12em]">
+ <span className="text-[var(--color-text-secondary)]">{label}</span>
+ <span className={quiet}>{t(`basis.${check.basis}`)}</span>
+ </p>
+ <p lang="en" className="max-w-[80ch] text-[15px] leading-relaxed text-[var(--color-text-primary)] [text-wrap:pretty]">
+ {check.reason}
+ </p>
+ {body ??
+ (showDetails && details.length > 0 ? (
+ <ul lang="en" className="m-0 flex list-none flex-col gap-1 p-0 text-xs text-[var(--color-text-secondary)]">
+ {details.map((line, i) => (
+ <li key={i} className="[overflow-wrap:anywhere]">
+ {line}
+ </li>
+ ))}
+ </ul>
+ ) : null)}
+ </div>
+ );
+}
+
+/** The table a check reads as, or null to list its notes instead. */
+function checkBody(check: EstateCheck, t: Translator): ReactNode | null {
+ switch (check.name) {
+ case "repositories":
+ return <RepositoriesTable rows={checkData<EstateRepositoryRow[]>(check, "repositories", [])} t={t} />;
+ case "dependencies":
+ return <DependenciesTable edges={checkData<EstateEdge[]>(check, "edges", [])} t={t} />;
+ case "contracts":
+ return <ContractsTable check={check} t={t} />;
+ case "dangling-calls":
+ return <DanglingTable check={check} t={t} />;
+ case "seams":
+ return check.data ? <SeamsTable seams={checkData<EstateSeam[]>(check, "seams", [])} t={t} /> : null;
+ case "start-services":
+ return check.data ? <StartServicesTable reach={checkData<Record<string, number>>(check, "reach", {})} t={t} /> : null;
+ case "start-files":
+ return check.data ? (
+ <StartFilesTable repos={checkData<Record<string, EstateStartFile[]>>(check, "repositories", {})} t={t} />
+ ) : null;
+ default:
+ return null;
+ }
+}
+
+function RepositoriesTable({ rows, t }: { rows: EstateRepositoryRow[]; t: Translator }) {
+ if (rows.length === 0) return null;
+ return (
+ <EstateTable
+ caption={t("check.repositories")}
+ columns={[
+ { label: t("col.repo") },
+ { label: t("col.indexedAt") },
+ { label: t("col.contractsAt") },
+ { label: t("col.services") },
+ ]}
+ rows={rows.map((r) => {
+ const behind = r.contracts_commit && r.indexed_commit && r.contracts_commit !== r.indexed_commit;
+ return {
+ key: r.alias,
+ cells: [
+ <span key="r" className="font-medium text-[var(--color-text-primary)]">{r.alias}</span>,
+ r.index_state ? (
+ <span key="i" className="text-[var(--color-warning)]">{indexStateLabel(t, r.index_state)}</span>
+ ) : r.indexed ? (
+ <span key="i" className={mono}>{short(r.indexed_commit)}</span>
+ ) : (
+ <span key="i" className={quiet}>{t("notIndexed")}</span>
+ ),
+ r.contracts_commit ? (
+ <span key="c" className={mono}>
+ {short(r.contracts_commit)}
+ {behind ? <span className="ml-1.5 font-sans text-[10px] text-[var(--color-warning)]">{t("contractsBehind")}</span> : null}
+ </span>
+ ) : (
+ <span key="c" className={quiet}>{t("notRead")}</span>
+ ),
+ r.services.length > 0 ? r.services.join(", ") : <span key="s" className={quiet}>{t("none")}</span>,
+ ],
+ };
+ })}
+ />
+ );
+}
+
+function DependenciesTable({ edges, t }: { edges: EstateEdge[]; t: Translator }) {
+ const structural = edges
+ .filter((e) => e.structural)
+ .sort((a, b) => b.weight - a.weight || a.source.localeCompare(b.source) || a.target.localeCompare(b.target));
+ if (structural.length === 0) return null;
+ const shown = structural.slice(0, DEPENDENCY_ROWS);
+ return (
+ <EstateTable
+ caption={t("check.dependencies")}
+ columns={[
+ { label: t("col.dependency") },
+ { label: t("col.kind") },
+ { label: t("col.links"), numeric: true },
+ { label: t("col.strategy") },
+ { label: t("col.confidence"), numeric: true },
+ ]}
+ rows={shown.map((e) => ({
+ key: `${e.source}->${e.target}:${e.kind}`,
+ cells: [
+ <span key="d" className="text-[var(--color-text-primary)]">
+ {e.source} <span aria-hidden className={quiet}>→</span>
+ <span className="sr-only">{t("dependsOn")}</span> {e.target}
+ </span>,
+ <span key="k" className="font-mono text-[11px]">{e.kind}</span>,
+ formatNumber(e.weight),
+ <span key="s" className="font-mono text-[11px]">{e.strategy ?? e.match_type}</span>,
+ e.confidence.toFixed(2),
+ ],
+ }))}
+ note={shownOf(t, shown.length, structural.length)}
+ />
+ );
+}
+
+function ContractsTable({ check, t }: { check: EstateCheck; t: Translator }) {
+ const providers = checkData<Record<string, number>>(check, "providers_by_type", {});
+ const consumers = checkData<Record<string, number>>(check, "consumers_by_type", {});
+ const linked = checkData<Record<string, number>>(check, "links_by_type", {});
+ const types = [...new Set([...Object.keys(providers), ...Object.keys(consumers)])].sort();
+ if (types.length === 0) return null;
+ const orphans = checkData<number>(check, "orphan_providers", 0);
+ const serviceLinks = checkData<number>(check, "service_links", 0);
+ const notes = [
+ serviceLinks > 0 ? t("serviceLinksNote", { count: serviceLinks }) : "",
+ orphans > 0 ? t("orphanNote", { count: orphans }) : "",
+ ].filter(Boolean);
+ return (
+ <EstateTable
+ caption={t("check.contracts")}
+ columns={[
+ { label: t("col.type") },
+ { label: t("col.providers"), numeric: true },
+ { label: t("col.consumers"), numeric: true },
+ { label: t("col.links"), numeric: true },
+ ]}
+ rows={types.map((type) => ({
+ key: type,
+ cells: [
+ <span key="t" className="font-mono text-[11px] text-[var(--color-text-primary)]">{type}</span>,
+ formatNumber(providers[type] ?? 0),
+ formatNumber(consumers[type] ?? 0),
+ formatNumber(linked[type] ?? 0),
+ ],
+ }))}
+ note={notes.join(" ") || undefined}
+ />
+ );
+}
+
+function DanglingTable({ check, t }: { check: EstateCheck; t: Translator }) {
+ const rows = checkData<EstateDanglingCall[]>(check, "dangling", []);
+ const external = checkData<number>(check, "external", 0);
+ const externalNote = external > 0 ? t("externalNote", { count: external }) : undefined;
+ if (rows.length === 0) {
+ return externalNote ? <p className={`text-xs ${quiet}`}>{externalNote}</p> : null;
+ }
+ const shown = rows.slice(0, DANGLING_ROWS);
+ return (
+ <EstateTable
+ caption={t("check.dangling-calls")}
+ columns={[
+ { label: t("col.consumer") },
+ { label: t("col.file") },
+ { label: t("col.target") },
+ { label: t("col.contract") },
+ { label: t("col.why") },
+ ]}
+ rows={shown.map((r) => ({
+ key: `${r.consumer}:${r.file}:${r.contract_id}`,
+ cells: [
+ <span key="c" className="font-medium text-[var(--color-text-primary)]">{r.consumer}</span>,
+ <span key="f" className={mono}>{r.line ? `${r.file}:${r.line}` : r.file}</span>,
+ r.target ?? <span key="t" className={quiet}>{t("targetUnresolved")}</span>,
+ <span key="i" className={mono}>{r.contract_id}</span>,
+ t.has(`danglingReason.${r.reason}`) ? t(`danglingReason.${r.reason}`) : r.reason,
+ ],
+ }))}
+ note={[shownOf(t, shown.length, rows.length), externalNote].filter(Boolean).join(" ") || undefined}
+ />
+ );
+}
+
+/** The three-band mark beside each repo's health, as every health mark draws it. */
+function HealthMark({ score, t }: { score: number; t: Translator }) {
+ const mark = healthMark(score);
+ return (
+ <span className="inline-flex items-center gap-1.5">
+ <span aria-hidden className="h-1.5 w-1.5 rounded-full" style={{ background: mark.color }} />
+ <span className="font-mono font-semibold tabular-nums text-[var(--color-text-primary)]">{mark.value}</span>
+ <span className="text-xs text-[var(--color-text-secondary)]">{t(`band.${mark.band}`)}</span>
+ </span>
+ );
+}
+
+function HealthTable({ rows, t }: { rows: EstateRepoRow[]; t: Translator }) {
+ if (rows.length === 0) return null;
+ const dash = <span className={quiet} title={t("notMeasured")}>—</span>;
+ const fixed = (n: number | null | undefined) => (n == null ? dash : n.toFixed(1));
+ return (
+ <EstateTable
+ caption={t("section.health.title")}
+ columns={[
+ { label: t("col.repo") },
+ { label: t("col.health") },
+ { label: t("col.maintainability"), numeric: true },
+ { label: t("col.hotspotHealth"), numeric: true },
+ { label: t("col.churnHotspots"), numeric: true },
+ { label: t("col.bugMagnets"), numeric: true },
+ { label: t("col.snapshot") },
+ ]}
+ rows={rows.map((r) => {
+ const h = r.health;
+ const staleSnapshot = h && h.store_commit && h.index_commit && h.store_commit !== h.index_commit;
+ return {
+ key: r.repo,
+ cells: [
+ <span key="r" className="font-medium text-[var(--color-text-primary)]">{r.repo}</span>,
+ h ? (
+ <HealthMark key="h" score={h.average_health} t={t} />
+ ) : (
+ <span key="h" className={quiet}>
+ {r.indexState ? indexStateLabel(t, r.indexState) : r.indexed ? t("noSnapshot") : t("notIndexed")}
+ </span>
+ ),
+ fixed(h?.maintainability_average),
+ fixed(h?.hotspot_health),
+ r.churn ? formatNumber(r.churn.hotspots ?? 0) : dash,
+ r.magnets ? (
+ <span key="m">
+ {formatNumber(r.magnets.bug_magnets ?? 0)}
+ {(r.magnets.top_bug_magnets ?? []).slice(0, 3).map((m) => (
+ <span key={m.file} className="mt-0.5 block text-right font-mono text-[10px] text-[var(--color-text-tertiary)] [overflow-wrap:anywhere]">
+ {m.file}
+ </span>
+ ))}
+ </span>
+ ) : (
+ dash
+ ),
+ h?.taken_at ? (
+ <span key="s">
+ {formatDate(h.taken_at)}
+ {staleSnapshot ? (
+ <span className="mt-0.5 block text-[10px] text-[var(--color-warning)]">{t("snapshotBehind")}</span>
+ ) : null}
+ </span>
+ ) : (
+ dash
+ ),
+ ],
+ };
+ })}
+ note={t("notMeasuredNote")}
+ />
+ );
+}
+
+function SeamsTable({ seams, t }: { seams: EstateSeam[]; t: Translator }) {
+ if (seams.length === 0) return null;
+ const shown = seams.slice(0, SEAM_ROWS);
+ return (
+ <EstateTable
+ caption={t("check.seams")}
+ columns={[
+ { label: t("col.pair") },
+ { label: t("col.edge") },
+ { label: t("col.confidence"), numeric: true },
+ { label: t("col.reach"), numeric: true },
+ { label: t("col.coChange") },
+ { label: t("col.seamScore"), numeric: true },
+ ]}
+ rows={shown.map((s) => ({
+ key: `${s.services[0]}${s.direction}${s.services[1]}`,
+ cells: [
+ <span key="p" className="text-[var(--color-text-primary)]">
+ {s.services[0]} <span className={`font-mono ${quiet}`}>{s.direction}</span> {s.services[1]}
+ </span>,
+ s.kinds.length > 0 ? <span key="k" className="font-mono text-[11px]">{s.kinds.join("+")}</span> : <span key="k" className={quiet}>{t("coChangeOnly")}</span>,
+ s.confidence == null ? "—" : s.confidence.toFixed(2),
+ formatNumber(s.reach),
+ s.declared
+ ? t("behindContract")
+ : s.co_change == null
+ ? <span key="c" className={quiet}>{t("notMeasured")}</span>
+ : s.co_change > 0
+ ? t("coChangeUnexplained", { value: s.co_change.toFixed(2) })
+ : t("none"),
+ s.score == null ? "—" : s.score_is_floor ? t("scoreFloor", { score: s.score }) : String(s.score),
+ ],
+ }))}
+ note={shownOf(t, shown.length, seams.length)}
+ />
+ );
+}
+
+function StartServicesTable({ reach, t }: { reach: Record<string, number>; t: Translator }) {
+ const ranked = Object.entries(reach)
+ .filter(([, n]) => n > 0)
+ .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
+ if (ranked.length === 0) return null;
+ const shown = ranked.slice(0, START_SERVICE_ROWS);
+ return (
+ <EstateTable
+ caption={t("check.start-services")}
+ columns={[{ label: t("col.service") }, { label: t("col.reaches"), numeric: true }]}
+ rows={shown.map(([service, n]) => ({
+ key: service,
+ cells: [
+ <span key="s" className="font-medium text-[var(--color-text-primary)]">{service}</span>,
+ formatNumber(n),
+ ],
+ }))}
+ note={shownOf(t, shown.length, ranked.length)}
+ />
+ );
+}
+
+function StartFilesTable({ repos, t }: { repos: Record<string, EstateStartFile[]>; t: Translator }) {
+ // Repos keep the engine's order: widest reach first. Three files each, as the CLI lists them.
+ const rows = Object.entries(repos).flatMap(([repo, files]) =>
+ files.slice(0, 3).map((f, i) => ({ repo, file: f, first: i === 0 })),
+ );
+ if (rows.length === 0) return null;
+ return (
+ <EstateTable
+ caption={t("check.start-files")}
+ columns={[{ label: t("col.repo") }, { label: t("col.file") }, { label: t("col.docs") }]}
+ rows={rows.map(({ repo, file, first }) => ({
+ key: `${repo}:${file.path}`,
+ cells: [
+ first ? <span key="r" className="font-medium text-[var(--color-text-primary)]">{repo}</span> : "",
+ <span key="f" className={mono}>{file.path}</span>,
+ file.doc_words > 0 ? t("docWords", { count: file.doc_words }) : <span key="d" className={quiet}>{t("undocumented")}</span>,
+ ],
+ }))}
+ />
+ );
+}
diff --git a/packages/web/src/components/layout/nav-items.ts b/packages/web/src/components/layout/nav-items.ts
index b2cacace6..b7aeb4cae 100644
--- a/packages/web/src/components/layout/nav-items.ts
+++ b/packages/web/src/components/layout/nav-items.ts
@@ -17,6 +17,7 @@ import {
BookOpen,
Boxes,
DollarSign,
+ FileText,
FlaskConical,
FolderTree,
GitCommitHorizontal,
@@ -71,6 +72,7 @@ export const WORKSPACE_NAV: NavItem[] = [
{ label: "Conformance", labelKey: "conformance", href: "/workspace/conformance", icon: ShieldCheck },
{ label: "Contracts", labelKey: "contracts", href: "/workspace/contracts", icon: Link2 },
{ label: "Co-Changes", labelKey: "coChanges", href: "/workspace/co-changes", icon: GitMerge },
+ { label: "Estate report", labelKey: "estateReport", href: "/workspace/estate", icon: FileText },
];
export function repoNavGroups(repoId: string): NavGroup[] {
diff --git a/tests/unit/server/test_workspace_estate_route.py b/tests/unit/server/test_workspace_estate_route.py
new file mode 100644
index 000000000..b2a88e7a1
--- /dev/null
+++ b/tests/unit/server/test_workspace_estate_route.py
@@ -0,0 +1,179 @@
+"""GET /api/workspace/estate: the estate report document, as the CLI builds it."""
+
+from __future__ import annotations
+
+from contextlib import asynccontextmanager
+from pathlib import Path
+
+import pytest
+from fastapi import FastAPI
+from httpx import ASGITransport, AsyncClient
+
+from repowise.core.persistence.models import Repository
+from repowise.core.report.estate import build_estate_document
+from repowise.core.workspace.config import WorkspaceConfig
+from repowise.core.workspace.registry import open_repo_db
+from repowise.core.workspace.system_graph import (
+ SystemEdge,
+ SystemGraph,
+ SystemNode,
+ save_system_graph,
+)
+from repowise.server.routers import workspace
+from repowise.server.schemas.workspace import WorkspaceEstateResponse
+
+_SECTIONS = [
+ "estate-summary",
+ "estate-map",
+ "estate-contracts",
+ "estate-health",
+ "estate-seams",
+ "estate-start",
+]
+
+
+def _app(root: Path | None) -> FastAPI:
+ @asynccontextmanager
+ async def lifespan(app: FastAPI):
+ yield
+
+ app = FastAPI(lifespan=lifespan)
+ app.state.workspace_config = WorkspaceConfig.load(root) if root else None
+ app.state.cross_repo_enricher = None
+ app.state.workspace_root = str(root) if root else None
+ app.include_router(workspace.router)
+ return app
+
+
+async def _get(app: FastAPI):
+ async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as c:
+ return await c.get("/api/workspace/estate")
+
+
+async def _workspace(root: Path, *, graph: bool = True) -> Path:
+ """web (indexed) calls api (not indexed)."""
+ (root / ".repowise-workspace.yaml").write_text(
+ "version: 1\nrepos:\n - path: web\n alias: web\n - path: api\n alias: api\n",
+ encoding="utf-8",
+ )
+ (root / "api").mkdir()
+ web = root / "web"
+ (web / ".repowise").mkdir(parents=True)
+ engine, factory = await open_repo_db(web)
+ async with factory() as session:
+ session.add(
+ Repository(id="r-web", name="web", url="", local_path=str(web), head_commit="a" * 40)
+ )
+ await session.commit()
+ await engine.dispose()
+ if graph:
+ save_system_graph(
+ SystemGraph(
+ generated_at="2026-10-01T00:00:00+00:00",
+ nodes=[
+ SystemNode(id="web", repo="web", service_path=None, name="web"),
+ SystemNode(id="api", repo="api", service_path=None, name="api"),
+ ],
+ edges=[
+ SystemEdge(
+ id="web->api", source="web", target="api", kind="http", weight=2,
+ confidence=0.9, match_type="exact", structural=True,
+ )
+ ],
+ ),
+ root,
+ )
+ return root
+
+
+async def test_estate_route_serves_the_document_the_cli_builds(tmp_path, monkeypatch):
+ monkeypatch.delenv("REPOWISE_DB_URL", raising=False)
+ root = await _workspace(tmp_path.resolve())
+ resp = await _get(_app(root))
+ assert resp.status_code == 200, resp.text
+ served = resp.json()
+ built = WorkspaceEstateResponse(**await build_estate_document(root)).model_dump(mode="json")
+ assert served["kind"] == "estate" and served["scope"] == {"kind": "workspace", "name": root.name}
+ assert [s["id"] for s in served["sections"]] == _SECTIONS
+ assert served["sections"] == built["sections"] and served["repos"] == built["repos"]
+ web, api = served["repos"]
+ assert web["alias"] == "web" and web["head_commit"] == "a" * 40 and web["indexed"] is True
+ assert api == {
+ "alias": "api",
+ "name": "api",
+ "head_commit": None,
+ "last_snapshot": None,
+ "indexed": False,
+ "index_state": None,
+ }
+ summary = {c["name"]: c for c in served["sections"][0]["checks"]}
+ rows = {r["alias"]: r for r in summary["repositories"]["data"]["repositories"]}
+ assert rows["web"]["indexed"] and not rows["api"]["indexed"]
+
+
+async def test_without_a_system_graph_the_graph_sections_are_inconclusive(tmp_path, monkeypatch):
+ monkeypatch.delenv("REPOWISE_DB_URL", raising=False)
+ root = await _workspace(tmp_path.resolve(), graph=False)
+ resp = await _get(_app(root))
+ assert resp.status_code == 200, resp.text
+ sections = {s["id"]: s for s in resp.json()["sections"]}
+ (missing,) = sections["estate-summary"]["checks"]
+ assert missing["basis"] == "unresolved" and missing["score"] == -1
+ assert "repowise update --workspace" in missing["reason"]
+
+
+async def test_estate_route_outside_a_workspace_is_404():
+ resp = await _get(_app(None))
+ assert resp.status_code == 404
+
+
+async def test_a_member_index_behind_this_version_is_named_not_called_unindexed(
+ tmp_path, monkeypatch
+):
+ import repowise.core.persistence.database as database
+ from repowise.core.report.render import report_renderers
+
+ monkeypatch.delenv("REPOWISE_DB_URL", raising=False)
+ root = await _workspace(tmp_path.resolve())
+
+ async def behind(engine):
+ return True
+
+ monkeypatch.setattr(database, "schema_behind", behind)
+ resp = await _get(_app(root))
+ assert resp.status_code == 200, resp.text
+ doc = resp.json()
+ web, api = doc["repos"]
+ assert web["indexed"] is True and web["index_state"] == "behind" and web["head_commit"] is None
+ assert api["indexed"] is False and api["index_state"] is None
+ summary = {c["name"]: c for c in doc["sections"][0]["checks"]}["repositories"]
+ assert any("older repowise" in d and "web" in d for d in summary["details"])
+ assert not any("not indexed" in d and "web" in d for d in summary["details"])
+ assert "index behind this version" in report_renderers.get("markdown")(doc)
+
+
+async def test_an_unreadable_member_index_is_named_and_other_errors_propagate(
+ tmp_path, monkeypatch
+):
+ import repowise.core.workspace.repo_index as repo_index
+
+ monkeypatch.delenv("REPOWISE_DB_URL", raising=False)
+ root = await _workspace(tmp_path.resolve())
+ (root / "api" / ".repowise").mkdir()
+ (root / "api" / ".repowise" / "wiki.db").write_bytes(b"not a sqlite database" * 64)
+ doc = await build_estate_document(root)
+ web, api = doc["repos"]
+ assert web["head_commit"] == "a" * 40
+ assert api == {"alias": "api", "name": "api", "index_state": "unreadable"}
+
+ async def broken(session, path):
+ raise RuntimeError("a defect, not a missing index")
+
+ monkeypatch.setattr(repo_index, "checkout_repository", broken)
+ with pytest.raises(RuntimeError):
+ await build_estate_document(root)