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(workspace): live system map for cross-repo services (#512)

Raghav Chamadiya6345929e8852
diff --git a/README.md b/README.md
index 9bec3ba96..6f0e5f8b1 100644
--- a/README.md
+++ b/README.md
@@ -317,9 +317,15 @@ repowise serve # starts MCP server + local dashboard
```bash
cd my-workspace/ # parent dir containing backend/, frontend/, shared-libs/
repowise init . # scans for git repos, indexes each, runs cross-repo analysis
-repowise serve # workspace dashboard + per-repo pages
+repowise serve # workspace dashboard, Live System Map + per-repo pages
```
+The workspace **Live System Map** renders your services and their typed
+relationships (HTTP / gRPC / events / package deps / co-change) as a
+code-derived, always-current diagram — health-colored, filterable, with
+drill-down to the underlying contracts. See
+[Workspaces](docs/WORKSPACES.md#live-system-map).
+
`repowise init` automatically registers the MCP server, installs a PostToolUse
hook in `~/.claude/settings.json`, generates `.mcp.json` at the project root, and
offers a post-commit hook that keeps everything in sync. If the Codex CLI is
diff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.md
index cff0a9323..88d2c9a45 100644
--- a/docs/USER_GUIDE.md
+++ b/docs/USER_GUIDE.md
@@ -806,6 +806,9 @@ Configure API connection, default provider/model, embedder, and view webhook/MCP
**Workspace Dashboard** (`/workspace`) *(workspace mode only)*
Aggregate stats across all repos, repo cards with file/symbol/coverage counts, and cross-repo intelligence summary.
+**Workspace System Map** (`/workspace/system-map`) *(workspace mode only)*
+A code-derived diagram of your services and their typed relationships (HTTP, gRPC, events, package deps, co-change), health-colored, with edge-kind filters, a service-to-repo collapse toggle, and click-through drill-down to the underlying contracts.
+
**Workspace Contracts** (`/workspace/contracts`) *(workspace mode only)*
All detected API contracts (HTTP, gRPC, message topics) with provider/consumer matching, filterable by type and repo.
diff --git a/docs/WORKSPACES.md b/docs/WORKSPACES.md
index 3da418238..958815288 100644
--- a/docs/WORKSPACES.md
+++ b/docs/WORKSPACES.md
@@ -227,7 +227,7 @@ The contracts, package dependencies, and co-changes above are each a flat list.
Edge direction is uniform: **`source` depends on / calls `target`.** A consumer points to the provider it calls; a dependent repo points to the repo it imports. Structural edges (contracts, package deps) are flagged distinctly from behavioral co-change edges — repowise never conflates "these change together" with "these call each other".
-Fetch it over REST with `GET /api/workspace/system-graph`.
+Fetch it over REST with `GET /api/workspace/system-graph`, or explore it visually in the [Live System Map](#live-system-map).
## Extraction Diagnostics
@@ -264,11 +264,24 @@ repowise serve
In workspace mode, the web UI adds:
- **Workspace Dashboard** (`/workspace`) — aggregate stats across all repos, repo cards with file/symbol/coverage counts, and cross-repo intelligence summary
+- **System Map** (`/workspace/system-map`) — the [Live System Map](#live-system-map): a code-derived diagram of services and their typed relationships
- **Contracts View** (`/workspace/contracts`) — all detected API contracts with provider/consumer matching, filterable by type and repo
- **Co-Changes View** (`/workspace/co-changes`) — cross-repo file pairs ranked by co-change strength
The sidebar shows all workspace repos under **Repositories**. Click any repo to access its full per-repo pages (overview, docs, graph, search, hotspots, etc.).
+### Live System Map
+
+The System Map renders the [system graph](#system-graph) as an always-current diagram. It is the visual counterpart to the REST endpoint — the same nodes and edges, laid out and explorable, never a hand-drawn picture.
+
+- **Service nodes**, coloured by category (service, frontend, worker, library, external), with a health ring rolled up from the owning repo and small flags for orphan or isolated services.
+- **Typed edges** distinguished by `kind` (colour + glyph) and by `match_type` (solid for exact/manual, dashed for candidate, dotted for inferred co-change). Behavioral co-change edges read differently from structural contract/dependency edges.
+- **Filters** to toggle each edge kind on or off, and a **service ↔ repo** switch that collapses a monorepo's services into one node per repository.
+- **Drill-down**: click a service to inspect its providers/consumers and connected services; click an edge to see its match type, confidence, weight, and the underlying contract evidence, with a jump to the Contracts view.
+- A **legend** explaining the edge colours, dash patterns, and the health scale.
+
+The map appears once the workspace has at least two indexed repositories with detected relationships; it shows honest empty states otherwise.
+
---
## MCP Integration
diff --git a/packages/ui/__tests__/workspace/system-map-logic.test.ts b/packages/ui/__tests__/workspace/system-map-logic.test.ts
new file mode 100644
index 000000000..161b02291
--- /dev/null
+++ b/packages/ui/__tests__/workspace/system-map-logic.test.ts
@@ -0,0 +1,203 @@
+import { describe, it, expect } from "vitest";
+import type { SystemEdge, SystemGraph, SystemNode } from "@repowise-dev/types";
+import { collapseToRepos } from "../../src/workspace/system-map/collapse";
+import { applyView } from "../../src/workspace/system-map/layout";
+import {
+ edgeKindStyle,
+ matchTypeDash,
+ matchTypeLabel,
+ EDGE_KIND_ORDER,
+} from "../../src/workspace/system-map/edge-kinds";
+import { nodeKindStyle, NODE_KIND_ORDER } from "../../src/workspace/system-map/node-kinds";
+import { resolveEdgeOverlay, resolveNodeOverlay } from "../../src/workspace/system-map/types";
+
+function node(id: string, repo: string, over: Partial<SystemNode> = {}): SystemNode {
+ return {
+ id,
+ repo,
+ service_path: id.includes("::") ? id.split("::")[1]! : null,
+ name: id.split("/").pop() ?? id,
+ kind: "service",
+ provider_count: 0,
+ consumer_count: 0,
+ contract_types: [],
+ is_orphan_provider: false,
+ is_orphan_consumer: false,
+ is_isolated: false,
+ ...over,
+ };
+}
+
+function edge(source: string, target: string, over: Partial<SystemEdge> = {}): SystemEdge {
+ return {
+ id: `${source}->${target}`,
+ source,
+ target,
+ kind: "http",
+ match_type: "exact",
+ confidence: 1,
+ weight: 1,
+ structural: true,
+ contract_refs: [],
+ ...over,
+ };
+}
+
+function graph(nodes: SystemNode[], edges: SystemEdge[]): SystemGraph {
+ return { version: 1, generated_at: "2026-06-19T00:00:00Z", nodes, edges, diagnostics: {} as never };
+}
+
+describe("collapseToRepos", () => {
+ it("merges services of a repo into one node and sums their counts", () => {
+ const g = graph(
+ [
+ node("api::svc/a", "api", { provider_count: 2, contract_types: ["http"] }),
+ node("api::svc/b", "api", { consumer_count: 3, contract_types: ["grpc"] }),
+ node("web", "web", { kind: "frontend" }),
+ ],
+ [edge("web", "api::svc/a")],
+ );
+ const collapsed = collapseToRepos(g);
+ expect(collapsed.nodes.map((n) => n.id).sort()).toEqual(["api", "web"]);
+ const api = collapsed.nodes.find((n) => n.id === "api")!;
+ expect(api.provider_count).toBe(2);
+ expect(api.consumer_count).toBe(3);
+ expect(api.contract_types).toEqual(["grpc", "http"]);
+ expect(api.service_path).toBeNull();
+ });
+
+ it("drops intra-repo edges and merges parallel cross-repo edges", () => {
+ const g = graph(
+ [node("api::a", "api"), node("api::b", "api"), node("web", "web")],
+ [
+ edge("api::a", "api::b"), // intra-repo → dropped
+ edge("web", "api::a", { weight: 1, confidence: 0.6, match_type: "candidate" }),
+ edge("web", "api::b", { weight: 2, confidence: 0.9, match_type: "exact" }),
+ ],
+ );
+ const collapsed = collapseToRepos(g);
+ expect(collapsed.edges).toHaveLength(1);
+ const e = collapsed.edges[0]!;
+ expect(e.source).toBe("web");
+ expect(e.target).toBe("api");
+ expect(e.weight).toBe(3); // 1 + 2
+ expect(e.confidence).toBe(0.9); // max
+ expect(e.match_type).toBe("exact"); // strongest
+ });
+
+ it("keeps different edge kinds between the same repos distinct", () => {
+ const g = graph(
+ [node("web", "web"), node("api", "api")],
+ [edge("web", "api", { kind: "http" }), edge("web", "api", { kind: "co_change", structural: false })],
+ );
+ const collapsed = collapseToRepos(g);
+ expect(collapsed.edges).toHaveLength(2);
+ expect(new Set(collapsed.edges.map((e) => e.kind))).toEqual(new Set(["http", "co_change"]));
+ });
+
+ it("flags a repo with no surviving edges as isolated", () => {
+ const g = graph([node("api::a", "api"), node("api::b", "api"), node("lonely", "lonely")], [edge("api::a", "api::b")]);
+ const collapsed = collapseToRepos(g);
+ expect(collapsed.nodes.find((n) => n.id === "lonely")!.is_isolated).toBe(true);
+ // api had only an intra-repo edge → also isolated after collapse
+ expect(collapsed.nodes.find((n) => n.id === "api")!.is_isolated).toBe(true);
+ });
+
+ it("preserves a single-kind repo's kind, neutralizes a mixed one", () => {
+ const g = graph(
+ [node("libs::x", "libs", { kind: "library" }), node("libs::y", "libs", { kind: "library" })],
+ [],
+ );
+ expect(collapseToRepos(g).nodes[0]!.kind).toBe("library");
+ const mixed = graph(
+ [node("app::x", "app", { kind: "frontend" }), node("app::y", "app", { kind: "worker" })],
+ [],
+ );
+ expect(collapseToRepos(mixed).nodes[0]!.kind).toBe("service");
+ });
+});
+
+describe("applyView", () => {
+ const g = graph(
+ [node("a", "a"), node("b", "b")],
+ [edge("a", "b", { kind: "http" }), edge("a", "b", { id: "cc", kind: "co_change", structural: false })],
+ );
+
+ it("filters edges to the visible kinds, keeping all nodes", () => {
+ const view = { visibleKinds: new Set(["http"] as const), collapsed: false };
+ const out = applyView(g, view);
+ expect(out.edges).toHaveLength(1);
+ expect(out.edges[0]!.kind).toBe("http");
+ expect(out.nodes).toHaveLength(2);
+ });
+
+ it("hides everything when no kinds are visible", () => {
+ const out = applyView(g, { visibleKinds: new Set(), collapsed: false });
+ expect(out.edges).toHaveLength(0);
+ });
+
+ it("collapses before filtering", () => {
+ const multi = graph(
+ [node("api::a", "api"), node("web", "web")],
+ [edge("web", "api::a", { kind: "http" })],
+ );
+ const out = applyView(multi, { visibleKinds: new Set(["http"] as const), collapsed: true });
+ expect(out.nodes.map((n) => n.id).sort()).toEqual(["api", "web"]);
+ expect(out.edges[0]!.target).toBe("api");
+ });
+});
+
+describe("edge-kind registry", () => {
+ it("covers every kind in the union and display order", () => {
+ expect(EDGE_KIND_ORDER).toHaveLength(6);
+ for (const kind of EDGE_KIND_ORDER) {
+ const s = edgeKindStyle(kind);
+ expect(s.label).toBeTruthy();
+ expect(s.color).toMatch(/^var\(--/);
+ }
+ });
+
+ it("marks co-change as the only behavioral kind", () => {
+ expect(edgeKindStyle("co_change").category).toBe("behavioral");
+ expect(edgeKindStyle("http").category).toBe("structural");
+ });
+
+ it("falls back gracefully for an unknown kind", () => {
+ expect(edgeKindStyle("quantum").label).toBe("Link");
+ });
+
+ it("maps match type to a distinct dash and label", () => {
+ expect(matchTypeDash("exact")).toBe("none");
+ expect(matchTypeDash("manual")).toBe("none");
+ expect(matchTypeDash("candidate")).toBe("6 4");
+ expect(matchTypeDash("inferred")).toBe("2 4");
+ expect(matchTypeLabel("candidate")).toBe("Candidate");
+ });
+});
+
+describe("node-kind registry", () => {
+ it("maps each kind to a tone and label", () => {
+ expect(NODE_KIND_ORDER).toHaveLength(5);
+ expect(nodeKindStyle("frontend").tone).toBe("container");
+ expect(nodeKindStyle("service").label).toBe("Service");
+ });
+});
+
+describe("overlay resolution", () => {
+ it("returns null when no overlay touches the element", () => {
+ expect(resolveNodeOverlay(undefined, "x")).toBeNull();
+ expect(resolveNodeOverlay({ highlightNodeIds: new Set(["other"]) }, "x")).toBeNull();
+ });
+
+ it("resolves highlight, dim, and badge for a node", () => {
+ const state = resolveNodeOverlay(
+ { highlightNodeIds: new Set(["x"]), nodeBadges: { x: { label: "3", tone: "danger" } } },
+ "x",
+ );
+ expect(state).toEqual({ highlighted: true, dimmed: false, badge: { label: "3", tone: "danger" } });
+ });
+
+ it("resolves edge overlay independently", () => {
+ expect(resolveEdgeOverlay({ dimEdgeIds: new Set(["e"]) }, "e")).toEqual({ highlighted: false, dimmed: true });
+ });
+});
diff --git a/packages/ui/__tests__/workspace/system-map.test.tsx b/packages/ui/__tests__/workspace/system-map.test.tsx
new file mode 100644
index 000000000..f06d899ba
--- /dev/null
+++ b/packages/ui/__tests__/workspace/system-map.test.tsx
@@ -0,0 +1,169 @@
+import { describe, it, expect, vi, beforeAll } from "vitest";
+import { render, screen, fireEvent } from "@testing-library/react";
+import type { SystemEdge, SystemGraph, SystemNode } from "@repowise-dev/types";
+import { SystemMap } from "../../src/workspace/system-map/system-map";
+import { SystemMapFilters } from "../../src/workspace/system-map/system-map-filters";
+import { SystemMapLegend } from "../../src/workspace/system-map/system-map-legend";
+import { SystemMapInspector } from "../../src/workspace/system-map/system-map-inspector";
+
+// jsdom has no layout engine → stub ResizeObserver so React Flow can mount.
+beforeAll(() => {
+ class RO {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ }
+ vi.stubGlobal("ResizeObserver", RO);
+});
+
+function node(id: string, over: Partial<SystemNode> = {}): SystemNode {
+ return {
+ id,
+ repo: id.split("::")[0] ?? id,
+ service_path: null,
+ name: id,
+ kind: "service",
+ provider_count: 0,
+ consumer_count: 0,
+ contract_types: [],
+ is_orphan_provider: false,
+ is_orphan_consumer: false,
+ is_isolated: false,
+ ...over,
+ };
+}
+
+function edge(source: string, target: string, over: Partial<SystemEdge> = {}): SystemEdge {
+ return {
+ id: `${source}->${target}`,
+ source,
+ target,
+ kind: "http",
+ match_type: "exact",
+ confidence: 0.9,
+ weight: 1,
+ structural: true,
+ contract_refs: [],
+ ...over,
+ };
+}
+
+function graph(nodes: SystemNode[], edges: SystemEdge[]): SystemGraph {
+ return { version: 1, generated_at: "2026-06-19T00:00:00Z", nodes, edges, diagnostics: {} as never };
+}
+
+describe("SystemMap empty states", () => {
+ it("shows the no-services state for an empty graph", () => {
+ render(<SystemMap graph={graph([], [])} />);
+ expect(screen.getByText(/no services to map/i)).toBeInTheDocument();
+ });
+
+ it("shows the no-relationships state when nodes exist but no edges", async () => {
+ render(<SystemMap graph={graph([node("a"), node("b")], [])} />);
+ // Layout runs async (ELK) before the empty-state resolves.
+ expect(await screen.findByText(/no cross-repo relationships detected/i)).toBeInTheDocument();
+ });
+
+ it("surfaces an error", () => {
+ render(<SystemMap graph={null} error={new Error("boom")} />);
+ expect(screen.getByText(/couldn't load the system map/i)).toBeInTheDocument();
+ expect(screen.getByText(/boom/i)).toBeInTheDocument();
+ });
+});
+
+describe("SystemMapFilters", () => {
+ it("only offers edge kinds present in the graph and toggles them", () => {
+ const onToggleKind = vi.fn();
+ render(
+ <SystemMapFilters
+ availableKinds={new Set(["http", "co_change"])}
+ visibleKinds={new Set(["http", "co_change"])}
+ onToggleKind={onToggleKind}
+ collapsed={false}
+ onToggleCollapsed={() => {}}
+ />,
+ );
+ expect(screen.getByRole("button", { name: "HTTP" })).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Co-change" })).toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "gRPC" })).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "HTTP" }));
+ expect(onToggleKind).toHaveBeenCalledWith("http");
+ });
+
+ it("toggles the collapse view", () => {
+ const onToggleCollapsed = vi.fn();
+ render(
+ <SystemMapFilters
+ availableKinds={new Set(["http"])}
+ visibleKinds={new Set(["http"])}
+ onToggleKind={() => {}}
+ collapsed={false}
+ onToggleCollapsed={onToggleCollapsed}
+ />,
+ );
+ fireEvent.click(screen.getByRole("button", { name: /service view/i }));
+ expect(onToggleCollapsed).toHaveBeenCalled();
+ });
+});
+
+describe("SystemMapLegend", () => {
+ it("explains every edge kind, the match-type dashes, and the health scale", () => {
+ render(<SystemMapLegend />);
+ expect(screen.getByText("HTTP")).toBeInTheDocument();
+ expect(screen.getByText("Co-change")).toBeInTheDocument();
+ expect(screen.getByText(/exact \/ manual/i)).toBeInTheDocument();
+ expect(screen.getByText(/at risk/i)).toBeInTheDocument();
+ });
+});
+
+describe("SystemMapInspector", () => {
+ const g = graph(
+ [
+ node("web", { kind: "frontend", consumer_count: 2, contract_types: ["http"] }),
+ node("api", { provider_count: 2, contract_types: ["http"], is_orphan_provider: true }),
+ ],
+ [edge("web", "api", { contract_refs: ["http:GET /v1/users"] })],
+ );
+
+ it("renders a selected service with its counts and connections", () => {
+ const onSelectNode = vi.fn();
+ render(
+ <SystemMapInspector
+ selection={{ type: "node", id: "api" }}
+ graph={g}
+ onClose={() => {}}
+ onSelectNode={onSelectNode}
+ />,
+ );
+ expect(screen.getByText("api")).toBeInTheDocument();
+ expect(screen.getByText("2 contracts")).toBeInTheDocument();
+ expect(screen.getByText(/orphan provider/i)).toBeInTheDocument();
+ // "Depended on by" lists web → clicking selects it
+ fireEvent.click(screen.getByText("web"));
+ expect(onSelectNode).toHaveBeenCalledWith("web");
+ });
+
+ it("renders a selected edge and opens its contract evidence", () => {
+ const onOpenContract = vi.fn();
+ render(
+ <SystemMapInspector
+ selection={{ type: "edge", id: "web->api" }}
+ graph={g}
+ onClose={() => {}}
+ onSelectNode={() => {}}
+ onOpenContract={onOpenContract}
+ />,
+ );
+ expect(screen.getByText(/http relationship/i)).toBeInTheDocument();
+ expect(screen.getByText("90%")).toBeInTheDocument(); // confidence
+ fireEvent.click(screen.getByText("http:GET /v1/users"));
+ expect(onOpenContract).toHaveBeenCalledWith("http:GET /v1/users");
+ });
+
+ it("renders nothing when there is no selection", () => {
+ const { container } = render(
+ <SystemMapInspector selection={null} graph={g} onClose={() => {}} onSelectNode={() => {}} />,
+ );
+ expect(container).toBeEmptyDOMElement();
+ });
+});
diff --git a/packages/ui/package.json b/packages/ui/package.json
index ef5b8c761..0d5a424dd 100644
--- a/packages/ui/package.json
+++ b/packages/ui/package.json
@@ -60,6 +60,7 @@
"./dashboard": "./src/dashboard/index.ts",
"./dashboard/*": "./src/dashboard/*.tsx",
"./workspace": "./src/workspace/index.ts",
+ "./workspace/system-map": "./src/workspace/system-map/index.ts",
"./workspace/*": "./src/workspace/*.tsx",
"./jobs": "./src/jobs/index.ts",
"./jobs/*": "./src/jobs/*.tsx",
diff --git a/packages/ui/src/workspace/system-map/collapse.ts b/packages/ui/src/workspace/system-map/collapse.ts
new file mode 100644
index 000000000..f202176ad
--- /dev/null
+++ b/packages/ui/src/workspace/system-map/collapse.ts
@@ -0,0 +1,113 @@
+/**
+ * Pure transform: collapse the service-granular system graph into a
+ * repo-granular one. Services in the same repo merge into a single repo node;
+ * intra-repo edges drop out; cross-repo edges sharing a (source, target, kind)
+ * merge with summed weight and the strongest match type. Used by the map's
+ * "collapse to repos" toggle. Side-effect free and cheap to test.
+ */
+
+import type { SystemEdge, SystemEdgeMatchType, SystemGraph, SystemNode } from "@repowise-dev/types";
+
+/** Confidence ordering for picking the strongest match type when merging. */
+const MATCH_RANK: Record<SystemEdgeMatchType, number> = {
+ exact: 3,
+ manual: 2,
+ candidate: 1,
+ inferred: 0,
+};
+
+/** Cap on retained drill-down refs per merged edge (mirrors the core bound). */
+const MAX_REFS = 50;
+
+function strongerMatch(a: SystemEdgeMatchType, b: SystemEdgeMatchType): SystemEdgeMatchType {
+ return MATCH_RANK[a] >= MATCH_RANK[b] ? a : b;
+}
+
+function repoNode(repo: string, members: SystemNode[]): SystemNode {
+ const contractTypes = new Set<string>();
+ let providerCount = 0;
+ let consumerCount = 0;
+ let orphanProvider = false;
+ let orphanConsumer = false;
+ for (const m of members) {
+ providerCount += m.provider_count;
+ consumerCount += m.consumer_count;
+ m.contract_types.forEach((t) => contractTypes.add(t));
+ orphanProvider = orphanProvider || m.is_orphan_provider;
+ orphanConsumer = orphanConsumer || m.is_orphan_consumer;
+ }
+ // A repo node's kind: keep a single service kind unless every member is a
+ // library or external (then surface that), so the collapsed view stays honest.
+ const kinds = new Set(members.map((m) => m.kind));
+ const kind: SystemNode["kind"] =
+ kinds.size === 1 ? (members[0]?.kind ?? "service") : "service";
+ return {
+ id: repo,
+ repo,
+ service_path: null,
+ name: repo,
+ kind,
+ provider_count: providerCount,
+ consumer_count: consumerCount,
+ contract_types: [...contractTypes].sort(),
+ is_orphan_provider: orphanProvider,
+ is_orphan_consumer: orphanConsumer,
+ is_isolated: false, // recomputed below from the collapsed edge set
+ };
+}
+
+export function collapseToRepos(graph: SystemGraph): SystemGraph {
+ const repoOf = new Map<string, string>();
+ const membersByRepo = new Map<string, SystemNode[]>();
+ for (const node of graph.nodes) {
+ repoOf.set(node.id, node.repo);
+ const list = membersByRepo.get(node.repo) ?? [];
+ list.push(node);
+ membersByRepo.set(node.repo, list);
+ }
+
+ const nodes = [...membersByRepo.entries()]
+ .map(([repo, members]) => repoNode(repo, members))
+ .sort((a, b) => a.id.localeCompare(b.id));
+
+ const merged = new Map<string, SystemEdge>();
+ for (const edge of graph.edges) {
+ const source = repoOf.get(edge.source) ?? edge.source;
+ const target = repoOf.get(edge.target) ?? edge.target;
+ if (source === target) continue; // intra-repo edge disappears on collapse
+ const key = `${source}->${target}::${edge.kind}`;
+ const existing = merged.get(key);
+ if (!existing) {
+ merged.set(key, {
+ ...edge,
+ id: key,
+ source,
+ target,
+ contract_refs: edge.contract_refs.slice(0, MAX_REFS),
+ });
+ continue;
+ }
+ existing.weight += edge.weight;
+ 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);
+ }
+ }
+
+ const edges = [...merged.values()].sort((a, b) => a.id.localeCompare(b.id));
+ const connected = new Set<string>();
+ for (const e of edges) {
+ connected.add(e.source);
+ connected.add(e.target);
+ }
+ for (const n of nodes) n.is_isolated = !connected.has(n.id);
+
+ return {
+ version: graph.version,
+ generated_at: graph.generated_at,
+ nodes,
+ edges,
+ diagnostics: graph.diagnostics,
+ };
+}
diff --git a/packages/ui/src/workspace/system-map/edge-kinds.ts b/packages/ui/src/workspace/system-map/edge-kinds.ts
new file mode 100644
index 000000000..3892e37ed
--- /dev/null
+++ b/packages/ui/src/workspace/system-map/edge-kinds.ts
@@ -0,0 +1,94 @@
+/**
+ * Edge-kind registry — the single source of truth for how each
+ * `SystemEdgeKind` is labelled, coloured, and iconified on the Live System Map.
+ *
+ * Adding a new transport (the plan's growing dimension) is a new entry here
+ * plus the matching `SystemEdgeKind` union member in
+ * `@repowise-dev/types/workspace` — never an edit to a rendering `if/else`.
+ *
+ * Two orthogonal axes drive an edge's appearance:
+ * - `kind` → colour + glyph + structural/behavioral category (this file)
+ * - `match_type` → stroke dash pattern (exact solid, candidate dashed,
+ * inferred dotted) — see `matchTypeDash`.
+ */
+
+import { ArrowRight, Boxes, Database, Link2, Radio, Zap, type LucideIcon } from "lucide-react";
+import type { SystemEdgeKind, SystemEdgeMatchType } from "@repowise-dev/types";
+
+/** Whether an edge reflects a structural contract/dependency or behavioral co-change. */
+export type EdgeCategory = "structural" | "behavioral";
+
+export interface SystemEdgeKindStyle {
+ kind: SystemEdgeKind;
+ /** Short human label for the legend and inspector. */
+ label: string;
+ /** Semantic tint (a theme CSS var) — carried by the chip glyph. */
+ color: string;
+ icon: LucideIcon;
+ category: EdgeCategory;
+}
+
+/**
+ * Canonical edge-kind styles. Co-change is the only behavioral kind; every
+ * contract / dependency transport is structural. Colours reference existing
+ * theme vars so the map stays consistent with the C4 / knowledge-graph views.
+ */
+export const SYSTEM_EDGE_KINDS: Record<SystemEdgeKind, SystemEdgeKindStyle> = {
+ http: { kind: "http", label: "HTTP", color: "var(--color-accent-secondary)", icon: ArrowRight, category: "structural" },
+ grpc: { kind: "grpc", label: "gRPC", color: "var(--color-accent-fill)", icon: Zap, category: "structural" },
+ event: { kind: "event", label: "Event", color: "var(--color-warning)", icon: Radio, category: "structural" },
+ package: { kind: "package", label: "Package", color: "var(--color-accent-primary)", icon: Boxes, category: "structural" },
+ db: { kind: "db", label: "Database", color: "var(--color-text-tertiary)", icon: Database, category: "structural" },
+ co_change: { kind: "co_change", label: "Co-change", color: "var(--color-edge-co-change)", icon: Link2, category: "behavioral" },
+};
+
+const FALLBACK_KIND: SystemEdgeKindStyle = {
+ kind: "http",
+ label: "Link",
+ color: "var(--color-text-tertiary)",
+ icon: ArrowRight,
+ category: "structural",
+};
+
+/** Resolve the style for an edge kind, tolerant of an unknown future kind. */
+export function edgeKindStyle(kind: string): SystemEdgeKindStyle {
+ return SYSTEM_EDGE_KINDS[kind as SystemEdgeKind] ?? FALLBACK_KIND;
+}
+
+/** Every edge kind, in legend/display order (structural first, behavioral last). */
+export const EDGE_KIND_ORDER: SystemEdgeKind[] = ["http", "grpc", "event", "package", "db", "co_change"];
+
+/**
+ * Stroke dash by match confidence: exact / manual links are solid (we trust
+ * them), candidate links are dashed (heuristic), inferred (co-change) is dotted
+ * (behavioral, never a guaranteed call). One place, so the map and the legend
+ * never disagree.
+ */
+export function matchTypeDash(matchType: SystemEdgeMatchType): string {
+ switch (matchType) {
+ case "candidate":
+ return "6 4";
+ case "inferred":
+ return "2 4";
+ case "exact":
+ case "manual":
+ default:
+ return "none";
+ }
+}
+
+/** Human label for a match type (legend + inspector). */
+export function matchTypeLabel(matchType: SystemEdgeMatchType): string {
+ switch (matchType) {
+ case "exact":
+ return "Exact";
+ case "candidate":
+ return "Candidate";
+ case "manual":
+ return "Manual";
+ case "inferred":
+ return "Inferred";
+ default:
+ return matchType;
+ }
+}
diff --git a/packages/ui/src/workspace/system-map/index.ts b/packages/ui/src/workspace/system-map/index.ts
new file mode 100644
index 000000000..cc3cbf4fe
--- /dev/null
+++ b/packages/ui/src/workspace/system-map/index.ts
@@ -0,0 +1,33 @@
+/**
+ * Live System Map — public surface. The host renders `<SystemMap>` with a
+ * `SystemGraph`; everything else (registries, layout, overlay types) is
+ * exported for downstream consumers (hosted frontend) and later phases.
+ */
+
+export { SystemMap, type SystemMapProps } from "./system-map";
+export { SystemMapLegend } from "./system-map-legend";
+export { SystemMapFilters, type SystemMapFiltersProps } from "./system-map-filters";
+export { SystemMapInspector, type SystemMapInspectorProps } from "./system-map-inspector";
+export { useSystemMapLayout, type SystemMapLayout, type UseSystemMapLayoutArgs } from "./use-system-map-layout";
+export { applyView, computeSystemMapPositions, SYSTEM_MAP_NODE_SIZE, type SystemMapView } from "./layout";
+export { collapseToRepos } from "./collapse";
+export {
+ SYSTEM_EDGE_KINDS,
+ EDGE_KIND_ORDER,
+ edgeKindStyle,
+ matchTypeDash,
+ matchTypeLabel,
+ type SystemEdgeKindStyle,
+ type EdgeCategory,
+} from "./edge-kinds";
+export { SYSTEM_NODE_KINDS, NODE_KIND_ORDER, nodeKindStyle, type SystemNodeKindStyle } from "./node-kinds";
+export {
+ resolveNodeOverlay,
+ resolveEdgeOverlay,
+ type RepoHealth,
+ type SystemMapOverlay,
+ type SystemMapBadge,
+ type SystemMapSelection,
+ type NodeOverlayState,
+ type EdgeOverlayState,
+} from "./types";
diff --git a/packages/ui/src/workspace/system-map/layout.ts b/packages/ui/src/workspace/system-map/layout.ts
new file mode 100644
index 000000000..0bd0e2828
--- /dev/null
+++ b/packages/ui/src/workspace/system-map/layout.ts
@@ -0,0 +1,46 @@
+/**
+ * Pure layout + filtering for the Live System Map. Filters the system graph to
+ * the visible edge kinds, optionally collapses to repos, then positions the
+ * nodes with the shared ELK helper (reused from the C4 view — one layout
+ * engine, no bespoke positioning). Returns plain data; the hook turns it into
+ * React Flow nodes/edges.
+ */
+
+import { computeC4Layout, type C4LayoutPosition } from "../../c4/layout/elk-c4-layout";
+import type { SystemEdgeKind, SystemGraph } from "@repowise-dev/types";
+import { collapseToRepos } from "./collapse";
+
+/** Uniform service-node footprint on the map. */
+export const SYSTEM_MAP_NODE_SIZE = { width: 200, height: 84 } as const;
+
+export interface SystemMapView {
+ /** Edge kinds to keep; an edge survives only if its kind is in the set. */
+ visibleKinds: ReadonlySet<SystemEdgeKind>;
+ /** Collapse services into one node per repo. */
+ collapsed: boolean;
+}
+
+/**
+ * Apply the view's filters to a raw system graph. Pure: returns a new graph;
+ * nodes are retained even when filtering leaves them edgeless (honest — an
+ * isolated service is real signal, not noise to hide).
+ */
+export function applyView(graph: SystemGraph, view: SystemMapView): SystemGraph {
+ const base = view.collapsed ? collapseToRepos(graph) : graph;
+ const edges = base.edges.filter((e) => view.visibleKinds.has(e.kind));
+ return { ...base, edges };
+}
+
+/** Position every node via the shared ELK layered layout. */
+export async function computeSystemMapPositions(
+ graph: SystemGraph,
+): Promise<Map<string, C4LayoutPosition>> {
+ return computeC4Layout(
+ graph.nodes.map((n) => ({
+ id: n.id,
+ width: SYSTEM_MAP_NODE_SIZE.width,
+ height: SYSTEM_MAP_NODE_SIZE.height,
+ })),
+ graph.edges.map((e) => ({ id: e.id, source: e.source, target: e.target })),
+ );
+}
diff --git a/packages/ui/src/workspace/system-map/node-kinds.ts b/packages/ui/src/workspace/system-map/node-kinds.ts
new file mode 100644
index 000000000..7e9f11fdb
--- /dev/null
+++ b/packages/ui/src/workspace/system-map/node-kinds.ts
@@ -0,0 +1,39 @@
+/**
+ * Node-kind registry — maps each `SystemNode.kind` to a categorical tone (from
+ * the shared graph-primitives palette) and a display label. The single source
+ * of truth for how a service node looks; adding a kind is one entry here plus
+ * the union member in `@repowise-dev/types/workspace`.
+ */
+
+import type { SystemNode } from "@repowise-dev/types";
+
+type SystemNodeKind = SystemNode["kind"];
+
+export interface SystemNodeKindStyle {
+ kind: SystemNodeKind;
+ /** Display label shown in the node's kind band. */
+ label: string;
+ /** Tone key into the shared `TONE_STYLES` palette (graph-primitives). */
+ tone: string;
+}
+
+export const SYSTEM_NODE_KINDS: Record<SystemNodeKind, SystemNodeKindStyle> = {
+ service: { kind: "service", label: "Service", tone: "service" },
+ frontend: { kind: "frontend", label: "Frontend", tone: "container" },
+ worker: { kind: "worker", label: "Worker", tone: "pipeline" },
+ library: { kind: "library", label: "Library", tone: "module" },
+ external: { kind: "external", label: "External", tone: "external" },
+};
+
+const FALLBACK_KIND: SystemNodeKindStyle = {
+ kind: "service",
+ label: "Service",
+ tone: "service",
+};
+
+export function nodeKindStyle(kind: string): SystemNodeKindStyle {
+ return SYSTEM_NODE_KINDS[kind as SystemNodeKind] ?? FALLBACK_KIND;
+}
+
+/** Every node kind, in legend/display order. */
+export const NODE_KIND_ORDER: SystemNodeKind[] = ["service", "frontend", "worker", "library", "external"];
diff --git a/packages/ui/src/workspace/system-map/system-map-edge.tsx b/packages/ui/src/workspace/system-map/system-map-edge.tsx
new file mode 100644
index 000000000..89095d021
--- /dev/null
+++ b/packages/ui/src/workspace/system-map/system-map-edge.tsx
@@ -0,0 +1,98 @@
+"use client";
+
+/**
+ * A typed system-map edge. Colour + glyph come from the edge-kind registry;
+ * the dash pattern encodes match confidence (exact solid, candidate dashed,
+ * inferred dotted). Co-change edges read as behavioral, contract/dep edges as
+ * structural. Selection and overlay state (highlight / dim / badge) reuse the
+ * same calm-vs-emphasised treatment as the knowledge-graph edges.
+ */
+
+import { memo } from "react";
+import { BaseEdge, EdgeLabelRenderer, getSmoothStepPath, type EdgeProps } from "@xyflow/react";
+import { edgeKindStyle, matchTypeDash } from "./edge-kinds";
+import type { SystemMapEdgeData } from "./types";
+
+function strokeWidth(weight: number): number {
+ return Math.min(1 + Math.log2(weight + 1) * 0.5, 3);
+}
+
+function SystemMapEdgeInner(props: EdgeProps) {
+ const { id, sourceX, sourceY, targetX, targetY, sourcePosition, targetPosition, markerEnd, data, selected } = props;
+ const { edge, overlay } = data as unknown as SystemMapEdgeData;
+ const style = edgeKindStyle(edge.kind);
+
+ const [edgePath, labelX, labelY] = getSmoothStepPath({
+ sourceX,
+ sourceY,
+ sourcePosition,
+ targetX,
+ targetY,
+ targetPosition,
+ borderRadius: 8,
+ });
+
+ const emphasized = selected || overlay?.highlighted;
+ const dimmed = overlay?.dimmed ?? false;
+ const stroke = emphasized ? "var(--color-viz-selection)" : style.color;
+ const dash = emphasized ? "none" : matchTypeDash(edge.match_type);
+ const opacity = dimmed ? 0.08 : emphasized ? 1 : 0.85;
+
+ const Icon = style.icon;
+ const label = edge.weight > 1 ? `${style.label} ×${edge.weight}` : style.label;
+
+ return (
+ <>
+ <BaseEdge
+ id={id}
+ path={edgePath}
+ {...(markerEnd ? { markerEnd } : {})}
+ style={{
+ stroke,
+ strokeWidth: emphasized ? 2.5 : strokeWidth(edge.weight),
+ strokeDasharray: dash,
+ opacity,
+ animation: emphasized ? "edgeFlow 1.5s linear infinite" : "none",
+ }}
+ />
+ {!dimmed && (
+ <EdgeLabelRenderer>
+ <div
+ className="nodrag nopan"
+ style={{
+ position: "absolute",
+ transform: `translate(-50%, -50%) translate(${labelX}px, ${labelY}px)`,
+ display: "inline-flex",
+ alignItems: "center",
+ gap: 4,
+ background: "var(--color-bg-surface)",
+ color: "var(--color-text-secondary)",
+ padding: "2px 7px",
+ borderRadius: 6,
+ fontFamily: "var(--font-mono, ui-monospace, monospace)",
+ fontSize: 9.5,
+ fontWeight: 500,
+ letterSpacing: 0.3,
+ pointerEvents: "none",
+ border: emphasized
+ ? "1px solid var(--color-viz-selection)"
+ : "1px solid var(--color-border-default)",
+ whiteSpace: "nowrap",
+ opacity: emphasized ? 1 : 0.92,
+ }}
+ >
+ <Icon size={10} aria-hidden style={{ color: style.color, flexShrink: 0 }} />
+ {label}
+ {overlay?.badge && (
+ <span style={{ color: "var(--color-risk-high)", fontWeight: 700 }}>· {overlay.badge.label}</span>
+ )}
+ </div>
+ </EdgeLabelRenderer>
+ )}
+ </>
+ );
+}
+
+export const SystemMapEdge = memo(SystemMapEdgeInner);
+
+export const systemMapEdgeTypes = { systemEdge: SystemMapEdge };
diff --git a/packages/ui/src/workspace/system-map/system-map-filters.tsx b/packages/ui/src/workspace/system-map/system-map-filters.tsx
new file mode 100644
index 000000000..07a6acd1f
--- /dev/null
+++ b/packages/ui/src/workspace/system-map/system-map-filters.tsx
@@ -0,0 +1,85 @@
+"use client";
+
+/**
+ * Map controls: per-edge-kind visibility toggles and the collapse-to-repos
+ * switch. Only edge kinds actually present in the graph are offered, so the
+ * toolbar never shows a dead toggle. Pure controlled component — state lives in
+ * the parent map.
+ */
+
+import type { SystemEdgeKind } from "@repowise-dev/types";
+import { EDGE_KIND_ORDER, SYSTEM_EDGE_KINDS } from "./edge-kinds";
+
+export interface SystemMapFiltersProps {
+ /** Edge kinds present in the (uncollapsed) graph; only these are shown. */
+ availableKinds: ReadonlySet<SystemEdgeKind>;
+ visibleKinds: ReadonlySet<SystemEdgeKind>;
+ onToggleKind: (kind: SystemEdgeKind) => void;
+ collapsed: boolean;
+ onToggleCollapsed: () => void;
+}
+
+export function SystemMapFilters({
+ availableKinds,
+ visibleKinds,
+ onToggleKind,
+ collapsed,
+ onToggleCollapsed,
+}: SystemMapFiltersProps) {
+ const kinds = EDGE_KIND_ORDER.filter((k) => availableKinds.has(k));
+
+ return (
+ <div style={{ display: "flex", flexWrap: "wrap", alignItems: "center", gap: 8 }}>
+ {kinds.map((kind) => {
+ const s = SYSTEM_EDGE_KINDS[kind];
+ const Icon = s.icon;
+ const active = visibleKinds.has(kind);
+ return (
+ <button
+ key={kind}
+ type="button"
+ onClick={() => onToggleKind(kind)}
+ aria-pressed={active}
+ title={`Toggle ${s.label} edges`}
+ style={{
+ display: "inline-flex",
+ alignItems: "center",
+ gap: 5,
+ padding: "3px 9px",
+ borderRadius: 999,
+ fontSize: 11,
+ fontWeight: 500,
+ cursor: "pointer",
+ color: active ? "var(--color-text-primary)" : "var(--color-text-tertiary)",
+ background: active ? "var(--color-bg-elevated)" : "transparent",
+ border: `1px solid ${active ? "var(--color-border-default)" : "var(--color-border-subtle)"}`,
+ opacity: active ? 1 : 0.6,
+ }}
+ >
+ <Icon size={11} style={{ color: s.color }} aria-hidden />
+ {s.label}
+ </button>
+ );
+ })}
+ <div style={{ width: 1, height: 18, background: "var(--color-border-default)" }} />
+ <button
+ type="button"
+ onClick={onToggleCollapsed}
+ aria-pressed={collapsed}
+ title="Group services into one node per repository"
+ style={{
+ padding: "3px 9px",
+ borderRadius: 999,
+ fontSize: 11,
+ fontWeight: 500,
+ cursor: "pointer",
+ color: collapsed ? "var(--color-text-primary)" : "var(--color-text-tertiary)",
+ background: collapsed ? "var(--color-bg-elevated)" : "transparent",
+ border: `1px solid ${collapsed ? "var(--color-border-default)" : "var(--color-border-subtle)"}`,
+ }}
+ >
+ {collapsed ? "Repo view" : "Service view"}
+ </button>
+ </div>
+ );
+}
diff --git a/packages/ui/src/workspace/system-map/system-map-inspector.tsx b/packages/ui/src/workspace/system-map/system-map-inspector.tsx
new file mode 100644
index 000000000..d4f8c75c5
--- /dev/null
+++ b/packages/ui/src/workspace/system-map/system-map-inspector.tsx
@@ -0,0 +1,248 @@
+"use client";
+
+/**
+ * Right-rail inspector for the Live System Map. Mirrors the C4 node inspector
+ * idiom (absolute panel, top-right, close button) but is driven by the current
+ * selection: a service node (health, provider/consumer counts, contract types,
+ * connected services) or an edge (kind, match type, confidence, weight, and the
+ * underlying contract refs with a hook to open them on the Contracts surface).
+ */
+
+import { X } from "lucide-react";
+import type { SystemEdge, SystemGraph, SystemNode } from "@repowise-dev/types";
+import { HealthRing } from "../workspace-graph-node";
+import { edgeKindStyle, matchTypeLabel } from "./edge-kinds";
+import { nodeKindStyle } from "./node-kinds";
+import type { RepoHealth, SystemMapSelection } from "./types";
+
+export interface SystemMapInspectorProps {
+ selection: SystemMapSelection;
+ graph: SystemGraph;
+ healthByRepo?: ReadonlyMap<string, RepoHealth>;
+ onClose: () => void;
+ /** Select another node (e.g. clicking a connected service). */
+ onSelectNode: (nodeId: string) => void;
+ /** Open a contract on the Contracts surface (drill to both code sides). */
+ onOpenContract?: (contractId: string) => void;
+}
+
+const panelStyle: React.CSSProperties = {
+ position: "absolute",
+ top: 12,
+ right: 12,
+ width: 300,
+ maxHeight: "calc(100% - 24px)",
+ overflowY: "auto",
+ background: "var(--color-bg-elevated)",
+ border: "1px solid var(--color-border-default)",
+ borderRadius: 10,
+ boxShadow: "0 8px 24px rgba(0,0,0,0.28)",
+ zIndex: 4,
+ fontSize: 12,
+ color: "var(--color-text-secondary)",
+};
+
+function Header({ kind, onClose }: { kind: string; onClose: () => void }) {
+ return (
+ <div
+ style={{
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "space-between",
+ padding: "10px 12px",
+ borderBottom: "1px solid var(--color-border-default)",
+ }}
+ >
+ <span style={{ fontSize: 10, fontWeight: 700, letterSpacing: 0.6, textTransform: "uppercase", color: "var(--color-text-tertiary)" }}>
+ {kind}
+ </span>
+ <button type="button" onClick={onClose} aria-label="Close inspector" style={{ cursor: "pointer", color: "var(--color-text-tertiary)", display: "inline-flex" }}>
+ <X size={14} />
+ </button>
+ </div>
+ );
+}
+
+function Field({ label, value }: { label: string; value: React.ReactNode }) {
+ return (
+ <div style={{ display: "flex", justifyContent: "space-between", gap: 12, padding: "3px 0" }}>
+ <span style={{ color: "var(--color-text-tertiary)" }}>{label}</span>
+ <span style={{ color: "var(--color-text-primary)", textAlign: "right", wordBreak: "break-word" }}>{value}</span>
+ </div>
+ );
+}
+
+function NodeBody({
+ node,
+ graph,
+ health,
+ onSelectNode,
+}: {
+ node: SystemNode;
+ graph: SystemGraph;
+ health: RepoHealth | null;
+ onSelectNode: (id: string) => void;
+}) {
+ const kind = nodeKindStyle(node.kind);
+ const outgoing = graph.edges.filter((e) => e.source === node.id);
+ const incoming = graph.edges.filter((e) => e.target === node.id);
+ const neighbour = (id: string) => graph.nodes.find((n) => n.id === id)?.name ?? id;
+
+ return (
+ <div style={{ padding: "10px 12px", display: "flex", flexDirection: "column", gap: 8 }}>
+ <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
+ {health && <HealthRing score={health.score} source={health.source} size={36} />}
+ <div>
+ <div style={{ fontSize: 14, fontWeight: 600, color: "var(--color-text-primary)" }}>{node.name}</div>
+ <div style={{ fontSize: 11, color: "var(--color-text-tertiary)" }}>{kind.label} · {node.repo}</div>
+ </div>
+ </div>
+ <div>
+ {node.service_path && <Field label="Path" value={<span style={{ fontFamily: "var(--font-mono, monospace)", fontSize: 11 }}>{node.service_path}</span>} />}
+ <Field label="Provides" value={`${node.provider_count} contracts`} />
+ <Field label="Consumes" value={`${node.consumer_count} contracts`} />
+ <Field label="Types" value={node.contract_types.length ? node.contract_types.join(", ") : "none"} />
+ {node.is_orphan_provider && <Field label="Status" value={<span style={{ color: "var(--color-warning)" }}>Orphan provider</span>} />}
+ {node.is_orphan_consumer && <Field label="Status" value={<span style={{ color: "var(--color-warning)" }}>Orphan consumer</span>} />}
+ {node.is_isolated && <Field label="Status" value={<span style={{ color: "var(--color-text-tertiary)" }}>Isolated</span>} />}
+ </div>
+ <NeighbourList title={`Depends on (${outgoing.length})`} edges={outgoing} resolve={(e) => e.target} neighbour={neighbour} onSelectNode={onSelectNode} />
+ <NeighbourList title={`Depended on by (${incoming.length})`} edges={incoming} resolve={(e) => e.source} neighbour={neighbour} onSelectNode={onSelectNode} />
+ </div>
+ );
+}
+
+function NeighbourList({
+ title,
+ edges,
+ resolve,
+ neighbour,
+ onSelectNode,
+}: {
+ title: string;
+ edges: SystemEdge[];
+ resolve: (e: SystemEdge) => string;
+ neighbour: (id: string) => string;
+ onSelectNode: (id: string) => void;
+}) {
+ if (edges.length === 0) return null;
+ return (
+ <div>
+ <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: 0.4, textTransform: "uppercase", color: "var(--color-text-tertiary)", marginBottom: 3 }}>
+ {title}
+ </div>
+ <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
+ {edges.map((e) => {
+ const id = resolve(e);
+ const s = edgeKindStyle(e.kind);
+ return (
+ <button
+ key={e.id}
+ type="button"
+ onClick={() => onSelectNode(id)}
+ style={{ display: "flex", alignItems: "center", gap: 6, padding: "2px 4px", borderRadius: 4, cursor: "pointer", textAlign: "left", color: "var(--color-text-secondary)" }}
+ >
+ <span style={{ width: 7, height: 7, borderRadius: "50%", background: s.color, flexShrink: 0 }} />
+ <span style={{ flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{neighbour(id)}</span>
+ <span style={{ fontSize: 10, color: "var(--color-text-tertiary)" }}>{s.label}</span>
+ </button>
+ );
+ })}
+ </div>
+ </div>
+ );
+}
+
+function EdgeBody({
+ edge,
+ graph,
+ onSelectNode,
+ onOpenContract,
+}: {
+ edge: SystemEdge;
+ graph: SystemGraph;
+ onSelectNode: (id: string) => void;
+ onOpenContract?: (contractId: string) => void;
+}) {
+ const s = edgeKindStyle(edge.kind);
+ const name = (id: string) => graph.nodes.find((n) => n.id === id)?.name ?? id;
+ const Icon = s.icon;
+ return (
+ <div style={{ padding: "10px 12px", display: "flex", flexDirection: "column", gap: 8 }}>
+ <div style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 13, color: "var(--color-text-primary)" }}>
+ <Icon size={13} style={{ color: s.color }} aria-hidden />
+ {s.label} relationship
+ </div>
+ <div>
+ <Field label="From" value={<LinkText label={name(edge.source)} onClick={() => onSelectNode(edge.source)} />} />
+ <Field label="To" value={<LinkText label={name(edge.target)} onClick={() => onSelectNode(edge.target)} />} />
+ <Field label="Match" value={matchTypeLabel(edge.match_type)} />
+ <Field label="Confidence" value={`${Math.round(edge.confidence * 100)}%`} />
+ <Field label="Weight" value={String(edge.weight)} />
+ <Field label="Nature" value={edge.structural ? "Structural" : "Behavioral"} />
+ </div>
+ {edge.contract_refs.length > 0 && (
+ <div>
+ <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: 0.4, textTransform: "uppercase", color: "var(--color-text-tertiary)", marginBottom: 3 }}>
+ Evidence ({edge.contract_refs.length})
+ </div>
+ <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
+ {edge.contract_refs.map((ref) => (
+ <button
+ key={ref}
+ type="button"
+ onClick={onOpenContract ? () => onOpenContract(ref) : undefined}
+ disabled={!onOpenContract}
+ title={onOpenContract ? "Open on the Contracts page" : ref}
+ style={{
+ fontFamily: "var(--font-mono, monospace)",
+ fontSize: 10.5,
+ textAlign: "left",
+ color: onOpenContract ? "var(--color-accent-primary)" : "var(--color-text-tertiary)",
+ cursor: onOpenContract ? "pointer" : "default",
+ overflow: "hidden",
+ textOverflow: "ellipsis",
+ whiteSpace: "nowrap",
+ }}
+ >
+ {ref}
+ </button>
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
+
+function LinkText({ label, onClick }: { label: string; onClick: () => void }) {
+ return (
+ <button type="button" onClick={onClick} style={{ color: "var(--color-accent-primary)", cursor: "pointer" }}>
+ {label}
+ </button>
+ );
+}
+
+export function SystemMapInspector({ selection, graph, healthByRepo, onClose, onSelectNode, onOpenContract }: SystemMapInspectorProps) {
+ if (!selection) return null;
+
+ if (selection.type === "node") {
+ const node = graph.nodes.find((n) => n.id === selection.id);
+ if (!node) return null;
+ return (
+ <div style={panelStyle}>
+ <Header kind="Service" onClose={onClose} />
+ <NodeBody node={node} graph={graph} health={healthByRepo?.get(node.repo) ?? null} onSelectNode={onSelectNode} />
+ </div>
+ );
+ }
+
+ const edge = graph.edges.find((e) => e.id === selection.id);
+ if (!edge) return null;
+ return (
+ <div style={panelStyle}>
+ <Header kind="Relationship" onClose={onClose} />
+ <EdgeBody edge={edge} graph={graph} onSelectNode={onSelectNode} {...(onOpenContract ? { onOpenContract } : {})} />
+ </div>
+ );
+}
diff --git a/packages/ui/src/workspace/system-map/system-map-legend.tsx b/packages/ui/src/workspace/system-map/system-map-legend.tsx
new file mode 100644
index 000000000..ce679bae6
--- /dev/null
+++ b/packages/ui/src/workspace/system-map/system-map-legend.tsx
@@ -0,0 +1,77 @@
+"use client";
+
+/**
+ * Static legend for the Live System Map: what the edge colours/glyphs mean
+ * (by kind), what the dash patterns mean (by match confidence), and the node
+ * health scale. Reads the same registries the map renders from, so the two can
+ * never drift.
+ */
+
+import { EDGE_KIND_ORDER, SYSTEM_EDGE_KINDS } from "./edge-kinds";
+
+function Row({ children }: { children: React.ReactNode }) {
+ return <div style={{ display: "flex", flexWrap: "wrap", gap: 10, alignItems: "center" }}>{children}</div>;
+}
+
+function Item({ swatch, label }: { swatch: React.ReactNode; label: string }) {
+ return (
+ <span style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 10.5, color: "var(--color-text-secondary)" }}>
+ {swatch}
+ {label}
+ </span>
+ );
+}
+
+function dashLine(dash: string, label: string) {
+ return (
+ <Item
+ key={label}
+ label={label}
+ swatch={
+ <svg width={22} height={6} aria-hidden>
+ <line x1={0} y1={3} x2={22} y2={3} stroke="var(--color-text-secondary)" strokeWidth={1.5} strokeDasharray={dash} />
+ </svg>
+ }
+ />
+ );
+}
+
+export function SystemMapLegend() {
+ return (
+ <div
+ style={{
+ display: "flex",
+ flexDirection: "column",
+ gap: 6,
+ padding: "8px 10px",
+ background: "var(--color-bg-surface)",
+ border: "1px solid var(--color-border-default)",
+ borderRadius: 8,
+ maxWidth: 460,
+ }}
+ >
+ <Row>
+ {EDGE_KIND_ORDER.map((kind) => {
+ const s = SYSTEM_EDGE_KINDS[kind];
+ const Icon = s.icon;
+ return <Item key={kind} label={s.label} swatch={<Icon size={11} style={{ color: s.color }} aria-hidden />} />;
+ })}
+ </Row>
+ <Row>
+ {dashLine("none", "Exact / manual")}
+ {dashLine("6 4", "Candidate")}
+ {dashLine("2 4", "Inferred (co-change)")}
+ </Row>
+ <Row>
+ <span style={{ fontSize: 10.5, color: "var(--color-text-tertiary)" }}>Node ring = repo health:</span>
+ <Item swatch={<Dot color="var(--color-risk-low)" />} label="healthy" />
+ <Item swatch={<Dot color="var(--color-risk-medium)" />} label="moderate" />
+ <Item swatch={<Dot color="var(--color-risk-high)" />} label="at risk" />
+ </Row>
+ </div>
+ );
+}
+
+function Dot({ color }: { color: string }) {
+ return <span style={{ width: 10, height: 10, borderRadius: "50%", background: color, display: "inline-block" }} />;
+}
diff --git a/packages/ui/src/workspace/system-map/system-map-node.tsx b/packages/ui/src/workspace/system-map/system-map-node.tsx
new file mode 100644
index 000000000..3781092ad
--- /dev/null
+++ b/packages/ui/src/workspace/system-map/system-map-node.tsx
@@ -0,0 +1,96 @@
+"use client";
+
+/**
+ * A service node on the Live System Map. Built on the shared `NodeShell`
+ * (categorical tone by kind) with the reused workspace `HealthRing` for the
+ * repo health rollup and small flags for orphan / isolated services. Overlay
+ * state (Phase 3+ highlight / dim / badge) is applied via NodeShell's existing
+ * selection/diff vocabulary so later phases need no new node component.
+ */
+
+import { memo } from "react";
+import type { NodeProps } from "@xyflow/react";
+import { HealthRing } from "../workspace-graph-node";
+import { NodeShell } from "../../graph-primitives/node-shell";
+import { nodeKindStyle } from "./node-kinds";
+import type { SystemMapNodeData } from "./types";
+
+/** Tone → a single theme colour used for the flag's text, border, and tint. */
+function flagColor(tone: "danger" | "warning" | "info"): string {
+ switch (tone) {
+ case "danger":
+ return "var(--color-risk-high)";
+ case "warning":
+ return "var(--color-warning)";
+ default:
+ return "var(--color-accent-fill)";
+ }
+}
+
+function Flag({ label, title, tone }: { label: string; title: string; tone: "danger" | "warning" | "info" }) {
+ const color = flagColor(tone);
+ return (
+ <span
+ title={title}
+ style={{
+ background: `color-mix(in srgb, ${color} 18%, transparent)`,
+ color,
+ border: `1px solid color-mix(in srgb, ${color} 45%, transparent)`,
+ borderRadius: 4,
+ padding: "0 4px",
+ fontSize: 8,
+ fontWeight: 700,
+ letterSpacing: 0.3,
+ }}
+ >
+ {label}
+ </span>
+ );
+}
+
+function SystemMapNodeInner({ data, selected }: NodeProps) {
+ const { node, health, overlay } = data as unknown as SystemMapNodeData;
+ const kind = nodeKindStyle(node.kind);
+
+ const counts = `${node.provider_count} prov · ${node.consumer_count} cons`;
+ const types = node.contract_types.length > 0 ? node.contract_types.join(", ") : "no contracts";
+
+ const badges = (
+ <>
+ {overlay?.badge && (
+ <Flag label={overlay.badge.label} title={overlay.badge.label} tone={overlay.badge.tone} />
+ )}
+ {node.is_orphan_provider && <Flag label="ORPHAN" title="Exposes contracts no consumer calls" tone="warning" />}
+ {node.is_isolated && <Flag label="ISOLATED" title="Participates in no cross-repo edges" tone="info" />}
+ </>
+ );
+
+ const footer = (
+ <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
+ {health && <HealthRing score={health.score} source={health.source} size={28} />}
+ <div style={{ display: "flex", flexDirection: "column", gap: 1 }}>
+ <span>{counts}</span>
+ <span style={{ opacity: 0.7 }}>{types}</span>
+ </div>
+ </div>
+ );
+
+ return (
+ <NodeShell
+ tone={kind.tone}
+ kindLabel={node.service_path ? `${kind.label} · ${node.repo}` : kind.label}
+ title={node.name}
+ footer={footer}
+ badges={badges}
+ selected={selected || overlay?.highlighted}
+ {...(overlay?.dimmed ? { diffState: "faded" as const } : {})}
+ width={200}
+ height={84}
+ titleFontSize={13}
+ />
+ );
+}
+
+export const SystemMapNode = memo(SystemMapNodeInner);
+
+export const systemMapNodeTypes = { systemService: SystemMapNode };
diff --git a/packages/ui/src/workspace/system-map/system-map.tsx b/packages/ui/src/workspace/system-map/system-map.tsx
new file mode 100644
index 000000000..94c75651e
--- /dev/null
+++ b/packages/ui/src/workspace/system-map/system-map.tsx
@@ -0,0 +1,198 @@
+"use client";
+
+/**
+ * The Live System Map — a code-derived, always-current diagram of the
+ * workspace's services (nodes) and their typed relationships (edges). Pure
+ * presentation over the Phase 1 `SystemGraph`: no computation, no fetching.
+ * The host passes the graph (and an optional repo-health join); this renders
+ * it with the shared ELK + React Flow stack, edge-kind filters, a legend, and
+ * a node/edge inspector. Phases 3-5 decorate it via the additive `overlay`
+ * prop without forking this component.
+ */
+
+import { useCallback, useMemo, useState } from "react";
+import {
+ Background,
+ BackgroundVariant,
+ Controls,
+ MiniMap,
+ ReactFlow,
+ ReactFlowProvider,
+ type EdgeMouseHandler,
+ type NodeMouseHandler,
+} from "@xyflow/react";
+import "@xyflow/react/dist/style.css";
+import type { SystemEdgeKind, SystemGraph } from "@repowise-dev/types";
+import { EmptyState } from "../../shared/empty-state";
+import { systemMapNodeTypes } from "./system-map-node";
+import { systemMapEdgeTypes } from "./system-map-edge";
+import { SystemMapLegend } from "./system-map-legend";
+import { SystemMapFilters } from "./system-map-filters";
+import { SystemMapInspector } from "./system-map-inspector";
+import { useSystemMapLayout } from "./use-system-map-layout";
+import type { SystemMapView } from "./layout";
+import type { RepoHealth, SystemMapOverlay, SystemMapSelection } from "./types";
+
+export interface SystemMapProps {
+ graph: SystemGraph | null;
+ loading?: boolean;
+ error?: Error | null;
+ /** Repo health by repo alias, joined onto service nodes (optional). */
+ healthByRepo?: ReadonlyMap<string, RepoHealth>;
+ /** Additive decoration from a later phase (ripple, badges, violations). */
+ overlay?: SystemMapOverlay;
+ /** Open a contract on the Contracts surface (edge drill-down). */
+ onOpenContract?: (contractId: string) => void;
+}
+
+export function SystemMap(props: SystemMapProps) {
+ return (
+ <ReactFlowProvider>
+ <SystemMapInner {...props} />
+ </ReactFlowProvider>
+ );
+}
+
+function SystemMapInner({ graph, loading, error, healthByRepo, overlay, onOpenContract }: SystemMapProps) {
+ const availableKinds = useMemo<Set<SystemEdgeKind>>(
+ () => new Set((graph?.edges ?? []).map((e) => e.kind)),
+ [graph],
+ );
+
+ const [hiddenKinds, setHiddenKinds] = useState<Set<SystemEdgeKind>>(() => new Set());
+ const [collapsed, setCollapsed] = useState(false);
+ const [selection, setSelection] = useState<SystemMapSelection>(null);
+
+ const visibleKinds = useMemo<Set<SystemEdgeKind>>(
+ () => new Set([...availableKinds].filter((k) => !hiddenKinds.has(k))),
+ [availableKinds, hiddenKinds],
+ );
+
+ const view = useMemo<SystemMapView>(() => ({ visibleKinds, collapsed }), [visibleKinds, collapsed]);
+
+ const { nodes, edges, loading: layoutLoading } = useSystemMapLayout({
+ graph,
+ view,
+ ...(healthByRepo ? { healthByRepo } : {}),
+ ...(overlay ? { overlay } : {}),
+ });
+
+ const toggleKind = useCallback((kind: SystemEdgeKind) => {
+ setHiddenKinds((prev) => {
+ const next = new Set(prev);
+ if (next.has(kind)) next.delete(kind);
+ else next.add(kind);
+ return next;
+ });
+ }, []);
+
+ const onNodeClick = useCallback<NodeMouseHandler>((_, node) => {
+ setSelection((cur) => (cur?.type === "node" && cur.id === node.id ? null : { type: "node", id: node.id }));
+ }, []);
+
+ const onEdgeClick = useCallback<EdgeMouseHandler>((_, edge) => {
+ setSelection((cur) => (cur?.type === "edge" && cur.id === edge.id ? null : { type: "edge", id: edge.id }));
+ }, []);
+
+ const onPaneClick = useCallback(() => setSelection(null), []);
+ const selectNode = useCallback((id: string) => setSelection({ type: "node", id }), []);
+
+ // Collapse selection is keyed by id; collapsing changes node ids, so reset it.
+ const onToggleCollapsed = useCallback(() => {
+ setCollapsed((c) => !c);
+ setSelection(null);
+ }, []);
+
+ const isLoading = loading || layoutLoading;
+ const hasGraph = graph && graph.nodes.length > 0;
+ const hasEdges = (graph?.edges.length ?? 0) > 0;
+
+ return (
+ <div style={{ position: "relative", width: "100%", height: "100%", display: "flex", flexDirection: "column", background: "var(--color-bg-canvas)" }}>
+ <div
+ style={{
+ display: "flex",
+ alignItems: "center",
+ gap: 16,
+ padding: "8px 12px",
+ borderBottom: "1px solid var(--color-border-default)",
+ background: "var(--color-bg-surface)",
+ flexWrap: "wrap",
+ }}
+ >
+ <SystemMapFilters
+ availableKinds={availableKinds}
+ visibleKinds={visibleKinds}
+ onToggleKind={toggleKind}
+ collapsed={collapsed}
+ onToggleCollapsed={onToggleCollapsed}
+ />
+ <div style={{ marginLeft: "auto" }}>
+ <SystemMapLegend />
+ </div>
+ </div>
+
+ <div style={{ position: "relative", flex: 1, minHeight: 0 }}>
+ {error ? (
+ <Centered>
+ <EmptyState title="Couldn't load the system map" description={error.message} />
+ </Centered>
+ ) : !isLoading && !hasGraph ? (
+ <Centered>
+ <EmptyState
+ title="No services to map yet"
+ description="The system map appears once the workspace has at least two indexed repositories with detected cross-repo relationships."
+ />
+ </Centered>
+ ) : !isLoading && !hasEdges ? (
+ <Centered>
+ <EmptyState
+ title="No cross-repo relationships detected"
+ description="Services are indexed, but no HTTP, gRPC, event, package, or co-change links were found between them yet."
+ />
+ </Centered>
+ ) : null}
+
+ <ReactFlow
+ nodes={nodes}
+ edges={edges}
+ nodeTypes={systemMapNodeTypes}
+ edgeTypes={systemMapEdgeTypes}
+ onNodeClick={onNodeClick}
+ onEdgeClick={onEdgeClick}
+ onPaneClick={onPaneClick}
+ fitView
+ fitViewOptions={{ padding: 0.18 }}
+ minZoom={0.2}
+ maxZoom={2.5}
+ proOptions={{ hideAttribution: true }}
+ nodesDraggable={false}
+ nodesConnectable={false}
+ >
+ <Background variant={BackgroundVariant.Lines} gap={24} size={1} color="var(--color-diagram-grid)" />
+ <Controls showInteractive={false} />
+ <MiniMap pannable zoomable />
+ </ReactFlow>
+
+ {graph && (
+ <SystemMapInspector
+ selection={selection}
+ graph={graph}
+ {...(healthByRepo ? { healthByRepo } : {})}
+ onClose={() => setSelection(null)}
+ onSelectNode={selectNode}
+ {...(onOpenContract ? { onOpenContract } : {})}
+ />
+ )}
+ </div>
+ </div>
+ );
+}
+
+function Centered({ children }: { children: React.ReactNode }) {
+ return (
+ <div style={{ position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "center", zIndex: 3, pointerEvents: "none" }}>
+ {children}
+ </div>
+ );
+}
diff --git a/packages/ui/src/workspace/system-map/types.ts b/packages/ui/src/workspace/system-map/types.ts
new file mode 100644
index 000000000..87ab98924
--- /dev/null
+++ b/packages/ui/src/workspace/system-map/types.ts
@@ -0,0 +1,108 @@
+/**
+ * Internal data shapes for the Live System Map: the per-node / per-edge data
+ * React Flow carries, the optional health join, and the additive **overlay
+ * API** that later phases (blast-radius ripple, breaking-change badges,
+ * conformance violations) layer on top without touching this component.
+ */
+
+import type { SystemEdge, SystemNode } from "@repowise-dev/types";
+
+/** Repo-level health, joined client-side onto service nodes by repo alias. */
+export interface RepoHealth {
+ /** 0-100 health score. */
+ score: number;
+ /** Whether the score is canonical (computed) or derived (estimated). */
+ source: "canonical" | "derived";
+}
+
+/** React Flow node payload — the `SystemNode` plus its joined health, if any. */
+export interface SystemMapNodeData {
+ node: SystemNode;
+ health: RepoHealth | null;
+ /** Overlay state applied this render (Phase 3+ ripple / badges). */
+ overlay: NodeOverlayState | null;
+ [key: string]: unknown;
+}
+
+/** React Flow edge payload. */
+export interface SystemMapEdgeData {
+ edge: SystemEdge;
+ overlay: EdgeOverlayState | null;
+ [key: string]: unknown;
+}
+
+// ---------------------------------------------------------------------------
+// Overlay API — additive layers Phases 3-5 attach to the map. Phase 2 ships
+// the contract and renders it; it passes nothing, so the map is a faithful
+// render of the system graph. Later phases compute a `SystemMapOverlay` and
+// hand it in; the map dims/highlights/badges accordingly. Designing this now
+// is the D7 requirement (overlays must not fork the map component).
+// ---------------------------------------------------------------------------
+
+export type BadgeTone = "danger" | "warning" | "info";
+
+export interface SystemMapBadge {
+ label: string;
+ tone: BadgeTone;
+}
+
+/** Per-node overlay decoration resolved for one render. */
+export interface NodeOverlayState {
+ /** Emphasize this node (e.g. a blast-radius target or reachable service). */
+ highlighted?: boolean;
+ /** Fade this node (outside the current focus set). */
+ dimmed?: boolean;
+ /** Optional corner badge (e.g. "3 breaking"). */
+ badge?: SystemMapBadge;
+}
+
+/** Per-edge overlay decoration resolved for one render. */
+export interface EdgeOverlayState {
+ highlighted?: boolean;
+ dimmed?: boolean;
+ badge?: SystemMapBadge;
+}
+
+/**
+ * An additive overlay over the whole map. Sets are keyed by node/edge id; a
+ * later phase populates only what it needs. Empty/undefined means "no overlay,"
+ * which is exactly the Phase 2 default.
+ */
+export interface SystemMapOverlay {
+ highlightNodeIds?: ReadonlySet<string>;
+ dimNodeIds?: ReadonlySet<string>;
+ nodeBadges?: Readonly<Record<string, SystemMapBadge>>;
+ highlightEdgeIds?: ReadonlySet<string>;
+ dimEdgeIds?: ReadonlySet<string>;
+ edgeBadges?: Readonly<Record<string, SystemMapBadge>>;
+}
+
+export function resolveNodeOverlay(
+ overlay: SystemMapOverlay | undefined,
+ nodeId: string,
+): NodeOverlayState | null {
+ if (!overlay) return null;
+ const highlighted = overlay.highlightNodeIds?.has(nodeId) ?? false;
+ const dimmed = overlay.dimNodeIds?.has(nodeId) ?? false;
+ const badge = overlay.nodeBadges?.[nodeId];
+ if (!highlighted && !dimmed && !badge) return null;
+ return { highlighted, dimmed, ...(badge ? { badge } : {}) };
+}
+
+export function resolveEdgeOverlay(
+ overlay: SystemMapOverlay | undefined,
+ edgeId: string,
+): EdgeOverlayState | null {
+ if (!overlay) return null;
+ const highlighted = overlay.highlightEdgeIds?.has(edgeId) ?? false;
+ const dimmed = overlay.dimEdgeIds?.has(edgeId) ?? false;
+ const badge = overlay.edgeBadges?.[edgeId];
+ if (!highlighted && !dimmed && !badge) return null;
+ return { highlighted, dimmed, ...(badge ? { badge } : {}) };
+}
+
+/** Either a node or an edge selected in the map (drives the inspector). */
+export type SystemMapSelection =
+ | { type: "node"; id: string }
+ | { type: "edge"; id: string }
+ | null;
diff --git a/packages/ui/src/workspace/system-map/use-system-map-layout.ts b/packages/ui/src/workspace/system-map/use-system-map-layout.ts
new file mode 100644
index 000000000..6ec1c9ed4
--- /dev/null
+++ b/packages/ui/src/workspace/system-map/use-system-map-layout.ts
@@ -0,0 +1,96 @@
+"use client";
+
+/**
+ * Computes the React Flow node/edge arrays for the Live System Map: applies the
+ * view filters, runs the async ELK layout, then joins health + overlay onto
+ * each element. Mirrors the C4 view's `use-c4-layout` pattern (async layout,
+ * loading flag, cancel-on-unmount). Pure inputs in, render-ready arrays out.
+ */
+
+import { useEffect, useMemo, useState } from "react";
+import { MarkerType, type Edge, type Node } from "@xyflow/react";
+import type { SystemGraph } from "@repowise-dev/types";
+import { applyView, computeSystemMapPositions, type SystemMapView } from "./layout";
+import {
+ resolveEdgeOverlay,
+ resolveNodeOverlay,
+ type RepoHealth,
+ type SystemMapEdgeData,
+ type SystemMapNodeData,
+ type SystemMapOverlay,
+} from "./types";
+
+export interface UseSystemMapLayoutArgs {
+ graph: SystemGraph | null;
+ view: SystemMapView;
+ /** Repo health by repo alias, joined onto service nodes (optional). */
+ healthByRepo?: ReadonlyMap<string, RepoHealth>;
+ overlay?: SystemMapOverlay;
+}
+
+export interface SystemMapLayout {
+ nodes: Node<SystemMapNodeData>[];
+ edges: Edge<SystemMapEdgeData>[];
+ loading: boolean;
+}
+
+export function useSystemMapLayout({
+ graph,
+ view,
+ healthByRepo,
+ overlay,
+}: UseSystemMapLayoutArgs): SystemMapLayout {
+ const viewGraph = useMemo(() => (graph ? applyView(graph, view) : null), [graph, view]);
+ const [positions, setPositions] = useState<Map<string, { x: number; y: number }> | null>(null);
+ const [loading, setLoading] = useState(true);
+
+ useEffect(() => {
+ let cancelled = false;
+ if (!viewGraph || viewGraph.nodes.length === 0) {
+ setPositions(new Map());
+ setLoading(false);
+ return;
+ }
+ setLoading(true);
+ computeSystemMapPositions(viewGraph).then((pos) => {
+ if (!cancelled) {
+ setPositions(pos);
+ setLoading(false);
+ }
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [viewGraph]);
+
+ const nodes = useMemo<Node<SystemMapNodeData>[]>(() => {
+ if (!viewGraph || !positions) return [];
+ return viewGraph.nodes.map((node) => {
+ const pos = positions.get(node.id);
+ return {
+ id: node.id,
+ type: "systemService",
+ position: { x: pos?.x ?? 0, y: pos?.y ?? 0 },
+ data: {
+ node,
+ health: healthByRepo?.get(node.repo) ?? null,
+ overlay: resolveNodeOverlay(overlay, node.id),
+ },
+ };
+ });
+ }, [viewGraph, positions, healthByRepo, overlay]);
+
+ const edges = useMemo<Edge<SystemMapEdgeData>[]>(() => {
+ if (!viewGraph) return [];
+ return viewGraph.edges.map((edge) => ({
+ id: edge.id,
+ source: edge.source,
+ target: edge.target,
+ type: "systemEdge",
+ markerEnd: { type: MarkerType.ArrowClosed, width: 14, height: 14, color: "var(--color-diagram-edge)" },
+ data: { edge, overlay: resolveEdgeOverlay(overlay, edge.id) },
+ }));
+ }, [viewGraph, overlay]);
+
+ return { nodes, edges, loading };
+}
diff --git a/packages/ui/src/workspace/workspace-graph-node.tsx b/packages/ui/src/workspace/workspace-graph-node.tsx
index acb7374fd..4ee9f997c 100644
--- a/packages/ui/src/workspace/workspace-graph-node.tsx
+++ b/packages/ui/src/workspace/workspace-graph-node.tsx
@@ -15,13 +15,13 @@ export interface WorkspaceGraphNodeData {
topLanguage: string;
}
-function healthColor(score: number): string {
+export function healthColor(score: number): string {
if (score >= 70) return "var(--color-risk-low)";
if (score >= 40) return "var(--color-risk-medium)";
return "var(--color-risk-high)";
}
-function HealthRing({
+export function HealthRing({
score,
source,
size = 36,
diff --git a/packages/web/src/app/workspace/system-map/page.tsx b/packages/web/src/app/workspace/system-map/page.tsx
new file mode 100644
index 000000000..bc77bd45d
--- /dev/null
+++ b/packages/web/src/app/workspace/system-map/page.tsx
@@ -0,0 +1,89 @@
+"use client";
+
+import { useMemo } from "react";
+import { useRouter } from "next/navigation";
+import { Waypoints, Boxes, ArrowLeftRight, Share2 } from "lucide-react";
+import { SystemMap, type RepoHealth } from "@repowise-dev/ui/workspace/system-map";
+import { StatCard } from "@repowise-dev/ui/shared/stat-card";
+import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
+import {
+ useWorkspaceSystemGraph,
+ useWorkspaceGraph,
+} from "@/lib/hooks/use-workspace";
+
+export default function SystemMapPage() {
+ const router = useRouter();
+ const { data: graph, isLoading, error } = useWorkspaceSystemGraph();
+ const { data: repoGraph } = useWorkspaceGraph();
+
+ // Join repo health (from the repo-level graph) onto service nodes by alias.
+ // The map keys health by `SystemNode.repo`; the repo graph's node `name` is
+ // the repo alias.
+ const healthByRepo = useMemo<Map<string, RepoHealth>>(() => {
+ const m = new Map<string, RepoHealth>();
+ for (const n of repoGraph?.nodes ?? []) {
+ m.set(n.name, { score: n.health_score, source: n.health_score_source });
+ }
+ return m;
+ }, [repoGraph]);
+
+ const diag = graph?.diagnostics;
+ const serviceCount = graph?.nodes.length ?? 0;
+ const edgeCount = graph?.edges.length ?? 0;
+
+ return (
+ <div className="p-5 sm:p-8 space-y-6 max-w-[1400px]">
+ <div>
+ <div className="flex items-center gap-2.5 mb-1">
+ <Waypoints className="h-6 w-6 text-[var(--color-accent-primary)]" />
+ <h1 className="text-2xl font-semibold text-[var(--color-text-primary)]">
+ System Map
+ </h1>
+ </div>
+ <p className="text-sm text-[var(--color-text-secondary)]">
+ A live diagram of your services and the typed relationships between
+ them, derived from code on every update.
+ </p>
+ </div>
+
+ <div className="grid grid-cols-2 gap-3 lg:grid-cols-4">
+ <StatCard
+ label="Services"
+ value={isLoading ? "—" : serviceCount}
+ icon={<Boxes className="h-4 w-4" />}
+ />
+ <StatCard
+ label="Relationships"
+ value={isLoading ? "—" : edgeCount}
+ icon={<Share2 className="h-4 w-4 text-[var(--color-accent-secondary)]" />}
+ />
+ <StatCard
+ label="Providers / Consumers"
+ value={diag ? `${diag.total_providers} / ${diag.total_consumers}` : "—"}
+ icon={<ArrowLeftRight className="h-4 w-4 text-[var(--color-success)]" />}
+ />
+ <StatCard
+ label="Orphans / Weak links"
+ value={diag ? `${diag.orphan_providers.length} / ${diag.weak_link_count}` : "—"}
+ description="Providers with no consumer; low-confidence links"
+ icon={<Share2 className="h-4 w-4 text-[var(--color-warning)]" />}
+ />
+ </div>
+
+ <div className="rounded-lg overflow-hidden border border-[var(--color-border-default)] h-[calc(100vh-300px)] min-h-[560px]">
+ {isLoading ? (
+ <div className="p-4 h-full">
+ <Skeleton className="h-full w-full" />
+ </div>
+ ) : (
+ <SystemMap
+ graph={graph}
+ error={error ?? null}
+ healthByRepo={healthByRepo}
+ onOpenContract={() => router.push("/workspace/contracts")}
+ />
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/packages/web/src/components/layout/nav-items.ts b/packages/web/src/components/layout/nav-items.ts
index cceacf417..db07b3d41 100644
--- a/packages/web/src/components/layout/nav-items.ts
+++ b/packages/web/src/components/layout/nav-items.ts
@@ -45,6 +45,7 @@ export const GLOBAL_NAV: NavItem[] = [
export const WORKSPACE_NAV: NavItem[] = [
{ label: "Overview", href: "/workspace", icon: Layers, exact: true },
+ { label: "System Map", href: "/workspace/system-map", icon: Waypoints },
{ label: "Contracts", href: "/workspace/contracts", icon: Link2 },
{ label: "Co-Changes", href: "/workspace/co-changes", icon: GitMerge },
];
diff --git a/packages/web/src/lib/api/types/workspace.ts b/packages/web/src/lib/api/types/workspace.ts
index 1b121eafb..f89b2d912 100644
--- a/packages/web/src/lib/api/types/workspace.ts
+++ b/packages/web/src/lib/api/types/workspace.ts
@@ -124,3 +124,30 @@ export interface WorkspaceGraphResponse {
nodes: WorkspaceGraphNode[];
edges: WorkspaceGraphEdge[];
}
+
+// ---------------------------------------------------------------------------
+// System graph + extraction diagnostics — the canonical service-granular
+// shapes live in @repowise-dev/types; the wire responses match them 1:1, so we
+// re-export rather than re-derive (the repo-wide consolidation convention).
+// ---------------------------------------------------------------------------
+
+export type {
+ SystemNode,
+ SystemEdge,
+ SystemGraph,
+ SystemEdgeKind,
+ SystemEdgeMatchType,
+ ExtractionDiagnostics,
+ RepoDiagnostics,
+ UnmatchedConsumer,
+ UnmatchedReason,
+ OrphanProvider,
+} from "@repowise-dev/types";
+
+import type { SystemGraph, ExtractionDiagnostics } from "@repowise-dev/types";
+
+/** `GET /api/workspace/system-graph` — the full service-granular system graph. */
+export type WorkspaceSystemGraphResponse = SystemGraph;
+
+/** `GET /api/workspace/diagnostics` — extraction diagnostics standalone. */
+export type WorkspaceDiagnosticsResponse = ExtractionDiagnostics;
diff --git a/packages/web/src/lib/api/workspace.ts b/packages/web/src/lib/api/workspace.ts
index 5ea32ef58..1d5ed77fe 100644
--- a/packages/web/src/lib/api/workspace.ts
+++ b/packages/web/src/lib/api/workspace.ts
@@ -5,6 +5,8 @@ import type {
WorkspaceCoChangesResponse,
WorkspaceGraphResponse,
WorkspaceSyncResponse,
+ WorkspaceSystemGraphResponse,
+ WorkspaceDiagnosticsResponse,
} from "./types";
export async function getWorkspace(
@@ -45,6 +47,32 @@ export async function getWorkspaceGraph(): Promise<WorkspaceGraphResponse> {
return apiGet<WorkspaceGraphResponse>("/api/workspace/graph");
}
+/**
+ * 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.
+ */
+export async function getWorkspaceSystemGraph(
+ fetchOptions?: RequestInit,
+): Promise<WorkspaceSystemGraphResponse> {
+ return apiGet<WorkspaceSystemGraphResponse>(
+ "/api/workspace/system-graph",
+ undefined,
+ fetchOptions,
+ );
+}
+
+/** Extraction diagnostics (providers/consumers, unmatched-by-reason, orphans). */
+export async function getWorkspaceDiagnostics(
+ fetchOptions?: RequestInit,
+): Promise<WorkspaceDiagnosticsResponse> {
+ return apiGet<WorkspaceDiagnosticsResponse>(
+ "/api/workspace/diagnostics",
+ 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/web/src/lib/hooks/use-workspace.ts b/packages/web/src/lib/hooks/use-workspace.ts
index 9412f3065..e8eade8a6 100644
--- a/packages/web/src/lib/hooks/use-workspace.ts
+++ b/packages/web/src/lib/hooks/use-workspace.ts
@@ -5,11 +5,17 @@ import {
getWorkspace,
getWorkspaceContracts,
getWorkspaceCoChanges,
+ getWorkspaceSystemGraph,
+ getWorkspaceDiagnostics,
+ getWorkspaceGraph,
} from "@/lib/api/workspace";
import type {
WorkspaceResponse,
WorkspaceContractsResponse,
WorkspaceCoChangesResponse,
+ WorkspaceSystemGraphResponse,
+ WorkspaceDiagnosticsResponse,
+ WorkspaceGraphResponse,
} from "@/lib/api/types";
export function useWorkspace() {
@@ -53,3 +59,31 @@ export function useWorkspaceCoChanges(opts?: {
);
return { data: data ?? null, isLoading, error };
}
+
+export function useWorkspaceSystemGraph() {
+ const { data, error, isLoading } = useSWR<WorkspaceSystemGraphResponse>(
+ "workspace:system-graph",
+ () => getWorkspaceSystemGraph(),
+ { revalidateOnFocus: false },
+ );
+ return { data: data ?? null, isLoading, error };
+}
+
+export function useWorkspaceDiagnostics() {
+ const { data, error, isLoading } = useSWR<WorkspaceDiagnosticsResponse>(
+ "workspace:diagnostics",
+ () => getWorkspaceDiagnostics(),
+ { revalidateOnFocus: false },
+ );
+ return { data: data ?? null, isLoading, error };
+}
+
+/** Repo-level graph (carries the per-repo health score used by the map). */
+export function useWorkspaceGraph() {
+ const { data, error, isLoading } = useSWR<WorkspaceGraphResponse>(
+ "workspace:graph",
+ () => getWorkspaceGraph(),
+ { revalidateOnFocus: false },
+ );
+ return { data: data ?? null, isLoading, error };
+}