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.

perf(workspace): lean system-graph view for the map (#4599)

Raghav Chamadiya3779fb6d7622
diff --git a/packages/api-client/src/types/workspace.ts b/packages/api-client/src/types/workspace.ts
index 0a1eb98bf..13713be27 100644
--- a/packages/api-client/src/types/workspace.ts
+++ b/packages/api-client/src/types/workspace.ts
@@ -283,7 +283,7 @@ import type {
ArchitectureMetrics,
} from "@repowise-dev/types";
-/** `GET /api/workspace/system-graph` — the full service-granular system graph. */
+/** `GET /api/workspace/system-graph` — the service-granular system graph (`?view=map`: its lean view). */
export type WorkspaceSystemGraphResponse = SystemGraph;
/** `GET /api/workspace/blast-radius` — cross-repo downstream impact set. */
diff --git a/packages/api-client/src/workspace.ts b/packages/api-client/src/workspace.ts
index 7848f5e54..89f1f651f 100644
--- a/packages/api-client/src/workspace.ts
+++ b/packages/api-client/src/workspace.ts
@@ -115,13 +115,19 @@ export async function getWorkspaceDiagnostics(
* The service-granular system graph (nodes = services, typed directed edges)
* that the Live System Map renders. Thin pass-through over the persisted
* `system_graph.json` artifact.
+ *
+ * `view: "map"` asks for the map's lean view: no `diagnostics` (read them from
+ * `getWorkspaceDiagnostics`), no `contract_refs` on structural edges, and a
+ * `ref_count` on every edge. A server without the view returns the full graph,
+ * which has the same shape with those fields filled.
*/
export async function getWorkspaceSystemGraph(
fetchOptions?: RequestInit,
+ opts?: { view?: "map" },
): Promise<WorkspaceSystemGraphResponse> {
return apiGet<WorkspaceSystemGraphResponse>(
"/api/workspace/system-graph",
- undefined,
+ opts?.view ? { view: opts.view } : undefined,
fetchOptions,
);
}
diff --git a/packages/core/src/repowise/core/workspace/system_map_view.py b/packages/core/src/repowise/core/workspace/system_map_view.py
new file mode 100644
index 000000000..f0f37ed43
--- /dev/null
+++ b/packages/core/src/repowise/core/workspace/system_map_view.py
@@ -0,0 +1,54 @@
+"""The System Map's lean view of ``system_graph.json``.
+
+The map draws nodes and edges. The stored graph also carries the extraction
+diagnostics (most of its bytes on a real estate) and up to
+:data:`~repowise.core.workspace.system_graph.MAX_EDGE_REFS` evidence refs on
+every edge, which only a drawer showing one edge reads. This projection drops
+both so the map's first request carries only what it draws; the diagnostics
+are served on their own by the diagnostics route.
+
+Pure: one parsed ``system_graph.json`` dict in, the wire dict out, so any
+server holding the artifact serves the same view.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from repowise.core.workspace.system_graph import SystemEdge, SystemNode
+
+__all__ = ["lean_system_graph"]
+
+#: Top-level keys the map never reads. Every other key passes through, so a
+#: field added to the graph reaches the map without a change here.
+_DROPPED_KEYS = frozenset({"diagnostics", "repo_provenance"})
+
+
+def _lean_edge(raw: dict[str, Any]) -> dict[str, Any]:
+ edge = {**raw, **SystemEdge.from_dict(raw).to_dict()}
+ refs = edge.pop("contract_refs") or []
+ edge["ref_count"] = len(set(refs))
+ # A co-change edge's refs are its file pairs, which nothing else serves
+ # per service pair, so the drawer keeps them (bounded by MAX_EDGE_REFS). A
+ # structural edge's evidence is its contract links, read from the
+ # contracts routes when the edge is opened.
+ if not edge["structural"]:
+ edge["contract_refs"] = refs
+ return edge
+
+
+def lean_system_graph(graph: dict[str, Any]) -> dict[str, Any]:
+ """The graph without diagnostics or structural edge refs, plus ``ref_count``.
+
+ Nodes and edges are normalized the way the stored-graph reader does, so
+ an artifact written before a field existed reads with its default; keys the
+ dataclasses do not know (a node's ``group``, say) pass through untouched.
+ ``ref_count`` is the number of distinct refs the full edge keeps, so the
+ drawer can state how much evidence there is before fetching it.
+ """
+ lean = {k: v for k, v in graph.items() if k not in _DROPPED_KEYS}
+ lean.setdefault("version", 1)
+ lean.setdefault("generated_at", "")
+ lean["nodes"] = [{**n, **SystemNode.from_dict(n).to_dict()} for n in graph.get("nodes", [])]
+ lean["edges"] = [_lean_edge(e) for e in graph.get("edges", [])]
+ return lean
diff --git a/packages/server/src/repowise/server/routers/workspace.py b/packages/server/src/repowise/server/routers/workspace.py
index 73b952070..81b77c2f3 100644
--- a/packages/server/src/repowise/server/routers/workspace.py
+++ b/packages/server/src/repowise/server/routers/workspace.py
@@ -10,6 +10,7 @@ from __future__ import annotations
import logging
import sqlite3
from pathlib import Path
+from typing import Literal
from fastapi import APIRouter, Depends, HTTPException, Query, Request
@@ -43,6 +44,7 @@ from repowise.server.schemas import (
WorkspaceRepoRemovedResponse,
WorkspaceResponse,
WorkspaceSyncResponse,
+ WorkspaceSystemGraphMapResponse,
WorkspaceSystemGraphResponse,
WorkspaceTestImpactResponse,
)
@@ -514,20 +516,35 @@ async def get_workspace_graph(
# ---------------------------------------------------------------------------
[email protected]("/system-graph", response_model=WorkspaceSystemGraphResponse)
+ "/system-graph",
+ response_model=WorkspaceSystemGraphResponse | WorkspaceSystemGraphMapResponse,
+)
async def get_system_graph(
ws_config=Depends(get_workspace_config),
enricher=Depends(get_cross_repo_enricher),
+ view: Literal["map"] | None = Query(
+ None,
+ description=(
+ "`map`: the map's lean view, without diagnostics or structural edge "
+ "refs and with `ref_count` on every edge"
+ ),
+ ),
):
"""Service-granular system graph: typed service nodes + directed edges.
Read straight from the ``system_graph.json`` artifact built during workspace
update. Edge direction is uniform — ``source`` depends on / calls ``target``.
Returns an empty graph (not 404) when no graph has been built yet.
+ ``view=map`` returns :func:`lean_system_graph` of it instead.
"""
_require_workspace(ws_config)
graph = enricher.get_system_graph() if enricher is not None else None
+ if view == "map":
+ from repowise.core.workspace.system_map_view import lean_system_graph
+
+ return WorkspaceSystemGraphMapResponse(**lean_system_graph(graph or {}))
if not graph:
return WorkspaceSystemGraphResponse()
return WorkspaceSystemGraphResponse(**graph)
diff --git a/packages/server/src/repowise/server/schemas/__init__.py b/packages/server/src/repowise/server/schemas/__init__.py
index 2e4ff28a5..db6b3a178 100644
--- a/packages/server/src/repowise/server/schemas/__init__.py
+++ b/packages/server/src/repowise/server/schemas/__init__.py
@@ -331,7 +331,9 @@ if TYPE_CHECKING:
WorkspaceSyncResponse,
WorkspaceSyncResult,
WorkspaceSystemEdge,
+ WorkspaceSystemGraphMapResponse,
WorkspaceSystemGraphResponse,
+ WorkspaceSystemMapEdge,
WorkspaceSystemNode,
WorkspaceTestImpactFile,
WorkspaceTestImpactResponse,
@@ -638,7 +640,9 @@ _EXPORTS: dict[str, tuple[str, ...]] = {
"WorkspaceSyncResponse",
"WorkspaceSyncResult",
"WorkspaceSystemEdge",
+ "WorkspaceSystemGraphMapResponse",
"WorkspaceSystemGraphResponse",
+ "WorkspaceSystemMapEdge",
"WorkspaceSystemNode",
"WorkspaceTestImpactFile",
"WorkspaceTestImpactResponse",
@@ -943,7 +947,9 @@ __all__ = [
"WorkspaceSyncResponse",
"WorkspaceSyncResult",
"WorkspaceSystemEdge",
+ "WorkspaceSystemGraphMapResponse",
"WorkspaceSystemGraphResponse",
+ "WorkspaceSystemMapEdge",
"WorkspaceSystemNode",
"WorkspaceTestImpactFile",
"WorkspaceTestImpactResponse",
diff --git a/packages/server/src/repowise/server/schemas/workspace.py b/packages/server/src/repowise/server/schemas/workspace.py
index 803008c5d..b30dfc86b 100644
--- a/packages/server/src/repowise/server/schemas/workspace.py
+++ b/packages/server/src/repowise/server/schemas/workspace.py
@@ -421,6 +421,25 @@ class WorkspaceSystemGraphResponse(BaseModel):
diagnostics: WorkspaceExtractionDiagnostics = WorkspaceExtractionDiagnostics()
+class WorkspaceSystemMapEdge(WorkspaceSystemEdge):
+ """An edge of the map's lean view. Mirrors ``core.workspace.system_map_view``."""
+
+ #: A co-change edge's file pairs; None on a structural edge, whose evidence
+ #: the contracts routes serve.
+ contract_refs: list[str] | None = None
+ #: Distinct refs the full edge keeps.
+ ref_count: int = 0
+
+
+class WorkspaceSystemGraphMapResponse(BaseModel):
+ """``GET /api/workspace/system-graph?view=map``: the graph without diagnostics."""
+
+ version: int = 1
+ generated_at: str = ""
+ nodes: list[WorkspaceSystemNode] = []
+ edges: list[WorkspaceSystemMapEdge] = []
+
+
# ---------------------------------------------------------------------------
# Cross-repo blast radius (reachability over the system graph)
# Mirrors repowise.core.workspace.blast_radius.
diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.ts
index 97c5d00ed..858ec52fc 100644
--- a/packages/types/src/generated/http.ts
+++ b/packages/types/src/generated/http.ts
@@ -4949,6 +4949,14 @@ export interface WorkspaceSystemEdge {
strategy?: string | null;
}
+/** ``GET /api/workspace/system-graph?view=map``: the graph without diagnostics. */
+export interface WorkspaceSystemGraphMapResponse {
+ version?: number;
+ generated_at?: string;
+ nodes?: WorkspaceSystemNode[];
+ edges?: WorkspaceSystemMapEdge[];
+}
+
export interface WorkspaceSystemGraphResponse {
version?: number;
generated_at?: string;
@@ -4957,6 +4965,21 @@ export interface WorkspaceSystemGraphResponse {
diagnostics?: WorkspaceExtractionDiagnostics;
}
+/** An edge of the map's lean view. Mirrors ``core.workspace.system_map_view``. */
+export interface WorkspaceSystemMapEdge {
+ id: string;
+ source: string;
+ target: string;
+ kind: string;
+ match_type: string;
+ confidence?: number;
+ weight?: number;
+ structural?: boolean;
+ contract_refs?: string[] | null;
+ strategy?: string | null;
+ ref_count?: number;
+}
+
export interface WorkspaceSystemNode {
id: string;
repo: string;
diff --git a/packages/types/src/workspace.ts b/packages/types/src/workspace.ts
index 4e10e2df7..f55c136bd 100644
--- a/packages/types/src/workspace.ts
+++ b/packages/types/src/workspace.ts
@@ -188,8 +188,13 @@ export interface SystemEdge {
weight: number;
/** True for contract/package edges, false for behavioral co-change edges. */
structural: boolean;
- /** Back-pointers to the underlying evidence, for drill-down (bounded). */
- contract_refs: string[];
+ /**
+ * Back-pointers to the underlying evidence, for drill-down (bounded). The
+ * map's lean view (`?view=map`) sends null on structural edges.
+ */
+ contract_refs?: string[] | null;
+ /** Distinct refs the full edge keeps; set by the lean view in place of the list. */
+ ref_count?: number;
/** Strategy of the link that gave the edge its confidence; null on a co-change edge. */
strategy?: LinkStrategyWire | null;
}
@@ -199,7 +204,8 @@ export interface SystemGraph {
generated_at: string;
nodes: SystemNode[];
edges: SystemEdge[];
- diagnostics: ExtractionDiagnostics;
+ /** Absent from the map's lean view, which reads `/api/workspace/diagnostics`. */
+ diagnostics?: ExtractionDiagnostics;
}
// ---------------------------------------------------------------------------
diff --git a/packages/ui/__tests__/workspace/system-map-ai-prompt.test.ts b/packages/ui/__tests__/workspace/system-map-ai-prompt.test.ts
index 5ab7ddeff..63d401867 100644
--- a/packages/ui/__tests__/workspace/system-map-ai-prompt.test.ts
+++ b/packages/ui/__tests__/workspace/system-map-ai-prompt.test.ts
@@ -203,6 +203,21 @@ describe("system map AI prompts", () => {
expect(text).not.toContain("get_blast_radius");
});
+ it("edge prompt for a lean edge states the kept count instead of no evidence", () => {
+ const text = buildEdgeAiPrompt({
+ edge: { id: "web->api:http", kind: "http", match_type: "exact", confidence: 0.9, weight: 4, structural: true },
+ source: { id: "web", name: "web" },
+ target: { id: "api", name: "api" },
+ sentence: "web calls api over HTTP.",
+ weightLabel: "4 endpoints called",
+ evidence: [],
+ refs: [],
+ refCount: 3,
+ });
+ expect(text).toContain("The graph kept 3 contract ids for this edge");
+ expect(text).not.toContain("No evidence rows were returned");
+ });
+
it("edge prompt for co-change asks about a hidden dependency", () => {
const text = buildEdgeAiPrompt({
edge: { id: "a->b:co_change", kind: "co_change", match_type: "inferred", confidence: 0.7, weight: 2, structural: false },
diff --git a/packages/ui/__tests__/workspace/system-map-logic.test.ts b/packages/ui/__tests__/workspace/system-map-logic.test.ts
index 476d1521e..4c143a669 100644
--- a/packages/ui/__tests__/workspace/system-map-logic.test.ts
+++ b/packages/ui/__tests__/workspace/system-map-logic.test.ts
@@ -106,6 +106,16 @@ describe("collapseToRepos", () => {
expect(e.match_type).toBe("exact"); // strongest
});
+ it("merges the lean map view's counts where it has no refs to merge", () => {
+ const { contract_refs: _a, ...a } = edge("web", "api::a", { ref_count: 2 });
+ const { contract_refs: _b, ...b } = edge("web", "api::b", { ref_count: 3 });
+ const { diagnostics: _d, ...lean } = graph([node("api::a", "api"), node("api::b", "api"), node("web", "web")], [a, b]);
+ const collapsed = collapseToRepos(lean);
+ expect(collapsed.edges[0]!.ref_count).toBe(5);
+ expect(collapsed.edges[0]!.contract_refs).toBeUndefined();
+ expect(collapsed.diagnostics).toBeUndefined();
+ });
+
it("keeps different edge kinds between the same repos distinct", () => {
const g = graph(
[node("web", "web"), node("api", "api")],
diff --git a/packages/ui/__tests__/workspace/system-map.test.tsx b/packages/ui/__tests__/workspace/system-map.test.tsx
index d36ad5db2..b6da4c6e6 100644
--- a/packages/ui/__tests__/workspace/system-map.test.tsx
+++ b/packages/ui/__tests__/workspace/system-map.test.tsx
@@ -415,6 +415,36 @@ describe("SystemMapDrawer", () => {
expect(screen.queryByRole("link", { name: /overview\.py/ })).not.toBeInTheDocument();
});
+ it("states a lean edge's evidence count without claiming it kept none", () => {
+ const { contract_refs: _refs, ...lean } = edge("web", "api", { weight: 2, ref_count: 2 });
+ const g2 = graph([node("web"), node("api")], [lean]);
+ render(
+ <SystemMapDrawer graph={g2} rawGraph={g2} collapsed={false} onClose={() => {}} onSelect={() => {}} selection={{ type: "edge", id: "web->api" }} />,
+ );
+ expect(screen.getByText("2 references")).toBeInTheDocument();
+ expect(screen.getByText(/The graph kept 2 contract ids for this edge/)).toBeInTheDocument();
+ expect(screen.queryByText(/kept no evidence/)).not.toBeInTheDocument();
+ });
+
+ it("reads a service's diagnostics from the host when the graph has none", () => {
+ const { diagnostics: _d, ...lean } = g;
+ render(
+ <SystemMapDrawer
+ {...base}
+ graph={lean}
+ rawGraph={lean}
+ selection={{ type: "node", id: "web" }}
+ onSelect={() => {}}
+ diagnostics={{
+ unmatched_consumers: [
+ { repo: "web", file_path: "client.ts", contract_id: "http::GET::/x", contract_type: "http", reason: "no_provider" },
+ ],
+ } as never}
+ />,
+ );
+ expect(screen.getByText(/1 call from here match/)).toBeInTheDocument();
+ });
+
it("renders nothing when there is no selection", () => {
render(<SystemMapDrawer {...base} selection={null} onSelect={() => {}} />);
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
diff --git a/packages/ui/src/workspace/system-map/collapse.ts b/packages/ui/src/workspace/system-map/collapse.ts
index 3e20d0aad..c8419ad09 100644
--- a/packages/ui/src/workspace/system-map/collapse.ts
+++ b/packages/ui/src/workspace/system-map/collapse.ts
@@ -83,7 +83,7 @@ export function collapseToRepos(graph: SystemGraph): SystemGraph {
id: key,
source,
target,
- contract_refs: edge.contract_refs.slice(0, MAX_REFS),
+ ...(edge.contract_refs ? { contract_refs: edge.contract_refs.slice(0, MAX_REFS) } : {}),
});
continue;
}
@@ -92,8 +92,13 @@ export function collapseToRepos(graph: SystemGraph): SystemGraph {
if (edge.confidence > existing.confidence) existing.strategy = edge.strategy ?? null;
existing.confidence = Math.max(existing.confidence, edge.confidence);
existing.match_type = strongerMatch(existing.match_type, edge.match_type);
- if (existing.contract_refs.length < MAX_REFS) {
- existing.contract_refs = [...existing.contract_refs, ...edge.contract_refs].slice(0, MAX_REFS);
+ if (existing.contract_refs && existing.contract_refs.length < MAX_REFS) {
+ existing.contract_refs = [...existing.contract_refs, ...(edge.contract_refs ?? [])].slice(0, MAX_REFS);
+ }
+ // A lean edge carries only its count; the sum can repeat an id two
+ // services share, as the merged ref list above can.
+ if (existing.ref_count != null) {
+ existing.ref_count = Math.min(existing.ref_count + (edge.ref_count ?? 0), MAX_REFS);
}
}
@@ -110,6 +115,6 @@ export function collapseToRepos(graph: SystemGraph): SystemGraph {
generated_at: graph.generated_at,
nodes,
edges,
- diagnostics: graph.diagnostics,
+ ...(graph.diagnostics ? { diagnostics: graph.diagnostics } : {}),
};
}
diff --git a/packages/ui/src/workspace/system-map/system-map-ai-prompt.ts b/packages/ui/src/workspace/system-map/system-map-ai-prompt.ts
index 223552c75..5ac04d47a 100644
--- a/packages/ui/src/workspace/system-map/system-map-ai-prompt.ts
+++ b/packages/ui/src/workspace/system-map/system-map-ai-prompt.ts
@@ -186,6 +186,8 @@ export interface BuildEdgePromptOptions {
evidence: PromptEdgeEvidence[];
/** Contract ids from the edge itself, used when no links were resolved. */
refs: string[];
+ /** Distinct contract ids the graph kept, when `refs` came without them (the lean map view). */
+ refCount?: number;
/** Co-change file pairs, for behavioral edges. */
pairs?: [string, string | null][];
/** Cycles this edge sits on, as service names. */
@@ -212,7 +214,9 @@ export function buildEdgeAiPrompt(o: BuildEdgePromptOptions): string {
)
: o.refs.length > 0
? capped(o.refs, (r) => `- \`${r}\``, "contract ids")
- : "No evidence rows were returned for this edge."
+ : (o.refCount ?? 0) > 0
+ ? `The graph kept ${o.refCount} contract ids for this edge; list them from the contracts between \`${o.source.name}\` and \`${o.target.name}\` before you start.`
+ : "No evidence rows were returned for this edge."
: (o.pairs ?? []).length > 0
? capped(o.pairs ?? [], ([a, b]) => `- \`${a}\`${b ? ` with \`${b}\`` : ""}`, "file pairs")
: "No file pairs were returned for this edge.";
diff --git a/packages/ui/src/workspace/system-map/system-map-drawer.tsx b/packages/ui/src/workspace/system-map/system-map-drawer.tsx
index c0ad4ecdf..8dab9c7f4 100644
--- a/packages/ui/src/workspace/system-map/system-map-drawer.tsx
+++ b/packages/ui/src/workspace/system-map/system-map-drawer.tsx
@@ -16,6 +16,7 @@
import { useMemo, useState, type ElementType, type ReactNode } from "react";
import type {
DependencyCycle,
+ ExtractionDiagnostics,
NodeArchitectureRole,
SystemEdge,
SystemGraph,
@@ -84,6 +85,8 @@ export interface SystemMapDrawerData {
coChangesHref?: string | undefined;
LinkComponent?: ElementType | undefined;
onShowBlastRadius?: ((nodeId: string) => void) | undefined;
+ /** Extraction diagnostics, when the graph came without them (the lean map view). */
+ diagnostics?: ExtractionDiagnostics | null | undefined;
}
export interface SystemMapDrawerProps extends SystemMapDrawerData {
@@ -259,6 +262,7 @@ function NodeBody({
repoHref,
LinkComponent,
onShowBlastRadius,
+ diagnostics,
onSelect,
resolve,
onPrompt,
@@ -275,7 +279,7 @@ function NodeBody({
const out = neighbourGroups(graph, node.id, "out");
const incoming = neighbourGroups(graph, node.id, "in");
const myCycles = collapsed ? [] : cyclesThrough(cycles, node.id);
- const diag = serviceDiagnostics(rawGraph.diagnostics, node.id, resolve);
+ const diag = serviceDiagnostics(diagnostics ?? rawGraph.diagnostics, node.id, resolve);
const summary = useMemo(
() => (repoContracts ? summarizeServiceContracts(repoContracts, node.id, resolve) : null),
[repoContracts, node.id, resolve],
@@ -604,6 +608,8 @@ function EdgeBody({
);
const refs = uniqueRefs(edge);
const pairs = edge.structural ? [] : coChangePairs(edge);
+ // The lean map view sends a structural edge's count, not its refs.
+ const keptRefs = edge.contract_refs ? refs.length : (edge.ref_count ?? 0);
const myCycles = collapsed ? [] : cyclesWithEdge(cycles, edge.id);
const name = (id: string) => nodeOf(id)?.name ?? id;
@@ -622,6 +628,7 @@ function EdgeBody({
weightLabel: weightLabel(edge),
evidence: links ?? [],
refs,
+ refCount: keptRefs,
pairs,
cycles: myCycles.map((c) => c.nodes.map(name)),
flavor,
@@ -676,7 +683,7 @@ function EdgeBody({
label: "Evidence kept",
value: (
<span className="tabular-nums">
- {plural(edge.structural ? refs.length : pairs.length, "reference", "references")}
+ {plural(edge.structural ? keptRefs : pairs.length, "reference", "references")}
</span>
),
},
@@ -778,6 +785,10 @@ function EdgeBody({
{`Showing ${Math.min(refs.length, DRAWER_EVIDENCE_ROWS)} of ${refs.length} contract ids the graph kept for this edge; it aggregates ${weightLabel(edge)}.`}
</p>
</>
+ ) : keptRefs > 0 ? (
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ {`The graph kept ${plural(keptRefs, "contract id", "contract ids")} for this edge; it aggregates ${weightLabel(edge)}.`}
+ </p>
) : (
<p className="text-xs text-[var(--color-text-tertiary)]">The graph kept no evidence for this edge.</p>
)}
diff --git a/packages/ui/src/workspace/system-map/system-map-model.ts b/packages/ui/src/workspace/system-map/system-map-model.ts
index ca16377df..8b24939ef 100644
--- a/packages/ui/src/workspace/system-map/system-map-model.ts
+++ b/packages/ui/src/workspace/system-map/system-map-model.ts
@@ -179,7 +179,7 @@ export function edgeLinks(
): WorkspaceContractLinkEntry[] {
if (!edge.structural) return [];
const type = KIND_CONTRACT_TYPE[edge.kind];
- const refs = new Set(edge.contract_refs);
+ const refs = new Set(edge.contract_refs ?? []);
const seen = new Set<string>();
const out: WorkspaceContractLinkEntry[] = [];
for (const lk of links) {
@@ -197,7 +197,7 @@ export function edgeLinks(
/** Co-change refs are `source_file~target_file`. */
export function coChangePairs(edge: SystemEdge): [string, string | null][] {
- return edge.contract_refs.map((ref) => {
+ return (edge.contract_refs ?? []).map((ref) => {
const split = ref.indexOf("~");
return split === -1 ? [ref, null] : [ref.slice(0, split), ref.slice(split + 1)];
});
@@ -205,7 +205,7 @@ export function coChangePairs(edge: SystemEdge): [string, string | null][] {
/** Structural refs repeat when two files use one contract; the list shows it once. */
export function uniqueRefs(edge: SystemEdge): string[] {
- return [...new Set(edge.contract_refs)];
+ return [...new Set(edge.contract_refs ?? [])];
}
// ---------------------------------------------------------------------------
diff --git a/packages/web/src/app/workspace/system-map/page.tsx b/packages/web/src/app/workspace/system-map/page.tsx
index c81153c66..d371148a0 100644
--- a/packages/web/src/app/workspace/system-map/page.tsx
+++ b/packages/web/src/app/workspace/system-map/page.tsx
@@ -30,9 +30,15 @@ import { OverviewSection } from "@repowise-dev/ui/overview/section";
import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
import { formatNumber } from "@repowise-dev/ui/lib/format";
import { unmatchedOutsideService } from "@repowise-dev/ui/workspace/contract-facts";
-import type { NodeArchitectureRole, SystemGraph, ConformanceReport } from "@/lib/api/types";
+import type {
+ ConformanceReport,
+ ExtractionDiagnostics,
+ NodeArchitectureRole,
+ SystemGraph,
+} from "@/lib/api/types";
import {
useWorkspaceSystemGraph,
+ useWorkspaceDiagnostics,
useWorkspaceGraph,
useWorkspaceBlastRadius,
useWorkspaceBreakingChanges,
@@ -64,10 +70,13 @@ export default function SystemMapPage() {
const router = useRouter();
const searchParams = useSearchParams();
- // One wave above the fold: the graph, repo health, and the three small
- // reports the lede, the lens counts and "Needs attention" all read. Blast
- // radius and per-repo contracts are fetched only when asked for.
- const { data: graph, isLoading, error } = useWorkspaceSystemGraph();
+ // One wave above the fold: the map's lean graph, repo health, and the three
+ // small reports the lede, the lens counts and "Needs attention" all read.
+ // Diagnostics follow the graph; a server without the lean view sends them
+ // inside it. Blast radius and per-repo contracts are fetched only when asked for.
+ const { data: graph, isLoading, error } = useWorkspaceSystemGraph("map");
+ const { data: fetchedDiagnostics } = useWorkspaceDiagnostics(Boolean(graph && !graph.diagnostics));
+ const diagnostics = graph?.diagnostics ?? fetchedDiagnostics;
const { data: repoGraph } = useWorkspaceGraph();
const { data: architecture, error: architectureError } = useWorkspaceArchitecture();
const { data: conformance, error: conformanceError } = useWorkspaceConformance();
@@ -196,8 +205,9 @@ export default function SystemMapPage() {
coChangesHref: "/workspace/co-changes",
LinkComponent: Link,
onShowBlastRadius: (id: string) => setLens("blast", id),
+ diagnostics,
}),
- [repoContracts, repoContractsLoading, conformance, repoIdByAlias, setLens],
+ [repoContracts, repoContractsLoading, conformance, repoIdByAlias, setLens, diagnostics],
);
return (
@@ -210,7 +220,7 @@ export default function SystemMapPage() {
{graph && (
<Lede graph={graph} architecture={architecture} conformance={conformance} t={t} />
)}
- {graph && <StatRibbon stats={ribbon(t, tLinks, graph, architecture)} LinkComponent={Link} />}
+ {graph && <StatRibbon stats={ribbon(t, tLinks, graph, architecture, diagnostics)} LinkComponent={Link} />}
<OverviewSection title={t("section.title")} description={t("section.description")}>
{/* Said once, beside the map it qualifies; the score above reads "–" when not determined. */}
@@ -278,7 +288,7 @@ export default function SystemMapPage() {
graph={graph}
conformance={conformance}
breaking={breaking}
- diagnostics={graph.diagnostics}
+ diagnostics={diagnostics}
conformanceError={Boolean(conformanceError)}
breakingError={Boolean(breakingError)}
onSelect={onSelectionChange}
@@ -429,8 +439,8 @@ function ribbon(
tLinks: Translator,
graph: SystemGraph,
architecture: ReturnType<typeof useWorkspaceArchitecture>["data"],
+ diag: ExtractionDiagnostics | null | undefined,
): RibbonStat[] {
- const diag = graph.diagnostics;
const repos = new Set(graph.nodes.map((n) => n.repo)).size;
const structural = graph.edges.filter((e) => e.structural).length;
return [
diff --git a/packages/web/src/lib/hooks/use-workspace.ts b/packages/web/src/lib/hooks/use-workspace.ts
index 9b4064ea6..a680077ec 100644
--- a/packages/web/src/lib/hooks/use-workspace.ts
+++ b/packages/web/src/lib/hooks/use-workspace.ts
@@ -3,6 +3,7 @@
import useSWR from "swr";
import {
getWorkspaceSystemGraph,
+ getWorkspaceDiagnostics,
getWorkspaceGraph,
getWorkspaceBlastRadius,
getWorkspaceBreakingChanges,
@@ -10,6 +11,7 @@ import {
getWorkspaceArchitecture,
} from "@/lib/api/workspace";
import type {
+ ExtractionDiagnostics,
WorkspaceSystemGraphResponse,
WorkspaceGraphResponse,
WorkspaceBlastRadiusResponse,
@@ -18,10 +20,25 @@ import type {
WorkspaceArchitectureResponse,
} from "@/lib/api/types";
-export function useWorkspaceSystemGraph() {
+/**
+ * The system graph. ``view="map"`` asks for the map's lean view, which leaves
+ * the diagnostics to ``useWorkspaceDiagnostics``; a server without that view
+ * answers with the full graph, diagnostics included.
+ */
+export function useWorkspaceSystemGraph(view?: "map") {
const { data, error, isLoading } = useSWR<WorkspaceSystemGraphResponse>(
- "workspace:system-graph",
- () => getWorkspaceSystemGraph(),
+ view ? `workspace:system-graph:${view}` : "workspace:system-graph",
+ () => getWorkspaceSystemGraph(undefined, view ? { view } : undefined),
+ { revalidateOnFocus: false },
+ );
+ return { data: data ?? null, isLoading, error };
+}
+
+/** Extraction diagnostics. Pass ``enabled=false`` to defer the request. */
+export function useWorkspaceDiagnostics(enabled = true) {
+ const { data, error, isLoading } = useSWR<ExtractionDiagnostics>(
+ enabled ? "workspace:diagnostics" : null,
+ () => getWorkspaceDiagnostics(),
{ revalidateOnFocus: false },
);
return { data: data ?? null, isLoading, error };
diff --git a/tests/unit/server/test_workspace_router.py b/tests/unit/server/test_workspace_router.py
index 5a90b9a3c..8a87bc596 100644
--- a/tests/unit/server/test_workspace_router.py
+++ b/tests/unit/server/test_workspace_router.py
@@ -1202,6 +1202,36 @@ class TestGetSystemGraph:
kinds = {(e["source"], e["target"], e["kind"]) for e in data["edges"]}
assert ("frontend", "backend", "http") in kinds # consumer -> provider
assert ("frontend", "backend", "package") in kinds # dependent -> dependency
+ assert "diagnostics" in data
+ assert all("contract_refs" in e and "ref_count" not in e for e in data["edges"])
+
+ @pytest.mark.asyncio
+ async def test_map_view_is_lean(self, tmp_path: Path) -> None:
+ enricher = _make_system_graph_enricher(tmp_path)
+ app = _make_workspace_app(ws_config=_make_ws_config(), enricher=enricher)
+ transport = ASGITransport(app=app)
+ async with AsyncClient(transport=transport, base_url="http://test") as c:
+ full = (await c.get("/api/workspace/system-graph")).json()
+ resp = await c.get("/api/workspace/system-graph", params={"view": "map"})
+ assert resp.status_code == 200
+ lean = resp.json()
+ assert "diagnostics" not in lean
+ assert [n["id"] for n in lean["nodes"]] == [n["id"] for n in full["nodes"]]
+ assert [e["id"] for e in lean["edges"]] == [e["id"] for e in full["edges"]]
+ http = next(e for e in lean["edges"] if e["kind"] == "http")
+ assert http["contract_refs"] is None
+ assert http["ref_count"] == 1
+
+ @pytest.mark.asyncio
+ async def test_map_view_empty_when_no_graph(self) -> None:
+ app = _make_workspace_app(ws_config=_make_ws_config(), enricher=None)
+ transport = ASGITransport(app=app)
+ async with AsyncClient(transport=transport, base_url="http://test") as c:
+ resp = await c.get("/api/workspace/system-graph", params={"view": "map"})
+ bad = await c.get("/api/workspace/system-graph", params={"view": "nope"})
+ assert resp.status_code == 200
+ assert resp.json() == {"version": 1, "generated_at": "", "nodes": [], "edges": []}
+ assert bad.status_code == 422
class TestGetBlastRadius:
diff --git a/tests/unit/workspace/test_system_map_view.py b/tests/unit/workspace/test_system_map_view.py
new file mode 100644
index 000000000..3caa352b9
--- /dev/null
+++ b/tests/unit/workspace/test_system_map_view.py
@@ -0,0 +1,97 @@
+"""The System Map's lean view of the stored system graph."""
+
+from __future__ import annotations
+
+from repowise.core.workspace.system_map_view import lean_system_graph
+
+
+def _graph() -> dict:
+ return {
+ "version": 2,
+ "generated_at": "t",
+ "repo_provenance": {"backend": {"commit": "abc"}},
+ "nodes": [
+ {"id": "backend", "repo": "backend", "service_path": None, "name": "backend", "group": "core"},
+ # Written before the orphan / isolated flags existed.
+ {"id": "frontend", "repo": "frontend", "name": "frontend"},
+ ],
+ "edges": [
+ {
+ "id": "frontend->backend:http",
+ "source": "frontend",
+ "target": "backend",
+ "kind": "http",
+ "match_type": "exact",
+ "confidence": 0.9,
+ "weight": 3,
+ "structural": True,
+ # One contract used from two files repeats its id.
+ "contract_refs": ["http::GET::/a", "http::GET::/a", "http::GET::/b"],
+ "strategy": "exact_path",
+ },
+ {
+ "id": "backend->frontend:co_change",
+ "source": "backend",
+ "target": "frontend",
+ "kind": "co_change",
+ "match_type": "inferred",
+ "confidence": 0.4,
+ "weight": 2,
+ "structural": False,
+ "contract_refs": ["a.py~b.ts", "c.py~d.ts"],
+ "strategy": None,
+ },
+ ],
+ "diagnostics": {"total_links": 1, "orphan_providers": [{"repo": "backend"}]},
+ }
+
+
+def test_drops_diagnostics_and_provenance() -> None:
+ lean = lean_system_graph(_graph())
+ assert "diagnostics" not in lean
+ assert "repo_provenance" not in lean
+ assert (lean["version"], lean["generated_at"]) == (2, "t")
+
+
+def test_structural_edge_carries_a_count_not_its_refs() -> None:
+ http = lean_system_graph(_graph())["edges"][0]
+ assert "contract_refs" not in http
+ assert http["ref_count"] == 2 # distinct ids, as the drawer lists them
+ assert (http["weight"], http["strategy"], http["structural"]) == (3, "exact_path", True)
+
+
+def test_co_change_edge_keeps_its_file_pairs() -> None:
+ co = lean_system_graph(_graph())["edges"][1]
+ assert co["contract_refs"] == ["a.py~b.ts", "c.py~d.ts"]
+ assert co["ref_count"] == 2
+
+
+def test_nodes_keep_unknown_keys_and_gain_defaults() -> None:
+ backend, frontend = lean_system_graph(_graph())["nodes"]
+ assert backend["group"] == "core"
+ assert frontend["is_isolated"] is False
+ assert frontend["service_path"] is None
+ assert "group" not in frontend
+
+
+def test_input_is_not_mutated() -> None:
+ graph = _graph()
+ lean_system_graph(graph)
+ assert graph == _graph()
+
+
+def test_old_artifact_edges_read_with_defaults() -> None:
+ graph = {
+ "nodes": [],
+ "edges": [
+ {"id": "a->b:package", "source": "a", "target": "b", "kind": "package", "contract_refs": None},
+ ],
+ }
+ (edge,) = lean_system_graph(graph)["edges"]
+ assert edge["ref_count"] == 0
+ assert edge["strategy"] == "manifest" # as the stored-graph reader backfills it
+ assert edge["structural"] is True
+
+
+def test_empty_graph() -> None:
+ assert lean_system_graph({}) == {"version": 1, "generated_at": "", "nodes": [], "edges": []}