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): replace the System Map inspector with a drawer, lenses and findings (#2500)

Raghav Chamadiya00308ac086d1
diff --git a/packages/ui/__tests__/workspace/system-map-ai-prompt.test.ts b/packages/ui/__tests__/workspace/system-map-ai-prompt.test.ts
new file mode 100644
index 000000000..89b119ba4
--- /dev/null
+++ b/packages/ui/__tests__/workspace/system-map-ai-prompt.test.ts
@@ -0,0 +1,253 @@
+import { describe, it, expect } from "vitest";
+import type { SystemEdge, SystemGraph, SystemNode, WorkspaceContractLinkEntry } from "@repowise-dev/types/workspace";
+import {
+ SYSTEM_MAP_PROMPT_MAX_ROWS,
+ buildBlastRadiusAiPrompt,
+ buildCycleAiPrompt,
+ buildEdgeAiPrompt,
+ buildServiceAiPrompt,
+} from "../../src/workspace/system-map/system-map-ai-prompt";
+import {
+ edgeLinks,
+ edgeSentence,
+ healthMark,
+ serviceDiagnostics,
+ serviceResolver,
+ summarizeServiceContracts,
+ weightLabel,
+} from "../../src/workspace/system-map/system-map-model";
+
+function node(id: string, repo: string, service_path: string | null = null): SystemNode {
+ return {
+ id,
+ repo,
+ service_path,
+ name: service_path ? service_path.split("/").pop()! : repo,
+ kind: "service",
+ provider_count: 0,
+ consumer_count: 0,
+ contract_types: [],
+ is_orphan_provider: false,
+ is_orphan_consumer: false,
+ is_isolated: false,
+ };
+}
+
+function edge(source: string, target: string, over: Partial<SystemEdge> = {}): SystemEdge {
+ return {
+ id: `${source}->${target}:http`,
+ source,
+ target,
+ kind: "http",
+ match_type: "exact",
+ confidence: 0.85,
+ weight: 1,
+ structural: true,
+ contract_refs: [],
+ ...over,
+ };
+}
+
+function link(over: Partial<WorkspaceContractLinkEntry>): WorkspaceContractLinkEntry {
+ return {
+ contract_id: "http::GET::/users",
+ contract_type: "http",
+ match_type: "exact",
+ confidence: 0.85,
+ provider_repo: "api",
+ provider_file: "routes.py",
+ provider_symbol: "",
+ consumer_repo: "mono",
+ consumer_file: "packages/web/client.ts",
+ consumer_symbol: "",
+ provider_service: null,
+ consumer_service: "packages/web",
+ provider_symbol_id: null,
+ consumer_symbol_id: null,
+ ...over,
+ };
+}
+
+const graph: SystemGraph = {
+ version: 1,
+ generated_at: "t",
+ nodes: [node("api", "api"), node("mono", "mono"), node("mono::packages/web", "mono", "packages/web")],
+ edges: [edge("mono::packages/web", "api")],
+ diagnostics: {
+ total_providers: 0,
+ total_consumers: 0,
+ total_links: 0,
+ weak_link_count: 0,
+ repo_breakdown: [],
+ unmatched_consumers: [
+ { repo: "mono", file_path: "packages/web/a.ts", contract_id: "http::GET::/x", contract_type: "http", reason: "no_provider" },
+ { repo: "mono", file_path: "scripts/b.ts", contract_id: "http::GET::/y", contract_type: "http", reason: "external_host" },
+ ],
+ unmatched_by_reason: {},
+ orphan_providers: [{ repo: "api", file_path: "routes.py", contract_id: "http::GET::/z", contract_type: "http" }],
+ providers_by_layer: {},
+ consumers_by_layer: {},
+ http_consumers_unresolved: 0,
+ http_consumer_coverage: null,
+ },
+};
+
+describe("system map model", () => {
+ it("reads health in the canonical three bands", () => {
+ expect(healthMark(85)).toMatchObject({ value: "8.5", label: "Healthy" });
+ expect(healthMark(67.4)).toMatchObject({ value: "6.7", label: "Warning" });
+ expect(healthMark(30)).toMatchObject({ label: "Alert" });
+ });
+
+ it("puts a file in its deepest service, else the repo root, and in its repo when collapsed", () => {
+ const resolve = serviceResolver(graph, false);
+ expect(resolve("mono", "packages/web/src/x.ts")).toBe("mono::packages/web");
+ expect(resolve("mono", "packages/website/x.ts")).toBe("mono");
+ expect(serviceResolver(graph, true)("mono", "packages/web/x.ts")).toBe("mono");
+ });
+
+ it("counts a service's contracts by role and type, most linked first", () => {
+ const summary = summarizeServiceContracts(
+ {
+ contracts: [
+ { contract_id: "http::GET::/a", contract_type: "http", role: "consumer", repo: "mono", file_path: "packages/web/c.ts" },
+ { contract_id: "http::GET::/users", contract_type: "http", role: "consumer", repo: "mono", file_path: "packages/web/client.ts" },
+ { contract_id: "code::x", contract_type: "code", role: "provider", repo: "mono", file_path: "packages/web/i.ts" },
+ { contract_id: "http::GET::/other", contract_type: "http", role: "provider", repo: "mono", file_path: "server/r.py" },
+ ],
+ links: [link({})],
+ total: 4,
+ },
+ "mono::packages/web",
+ serviceResolver(graph, false),
+ );
+ expect(summary.consumes).toEqual({ http: 2 });
+ expect(summary.provides).toEqual({ code: 1 });
+ expect(summary.rows[0]).toMatchObject({ contract_id: "http::GET::/users", link_count: 1 });
+ });
+
+ it("attributes unmatched consumers and unused providers to the owning service", () => {
+ const resolve = serviceResolver(graph, false);
+ expect(serviceDiagnostics(graph.diagnostics, "mono::packages/web", resolve)).toEqual({
+ unmatched: 1,
+ unmatchedByReason: { no_provider: 1 },
+ unusedProviders: 0,
+ });
+ expect(serviceDiagnostics(graph.diagnostics, "api", resolve).unusedProviders).toBe(1);
+ });
+
+ it("joins an edge to the links it aggregates, consumer to provider", () => {
+ const e = graph.edges[0]!;
+ const links = edgeLinks(
+ e,
+ [link({}), link({ consumer_file: "server/r.py" }), link({ contract_type: "code" }), link({})],
+ serviceResolver(graph, false),
+ );
+ // Wrong service, wrong type and a duplicate are all dropped.
+ expect(links).toHaveLength(1);
+ });
+
+ it("names the weight's unit and says the relationship as a sentence", () => {
+ expect(weightLabel({ kind: "http", weight: 180 })).toBe("180 endpoints called");
+ expect(weightLabel({ kind: "co_change", weight: 1 })).toBe("1 file pair changed together");
+ expect(edgeSentence({ kind: "db" }, "backend", "core")).toBe("backend uses database tables core defines.");
+ });
+});
+
+describe("system map AI prompts", () => {
+ it("service prompt carries location, counts, neighbours, contracts and the MCP tools", () => {
+ const text = buildServiceAiPrompt({
+ service: { id: "backend", name: "backend", repo: "backend", service_path: null },
+ health: { value: "7.2", label: "Warning" },
+ role: { label: "Core", reaches: 4, reachedBy: 1 },
+ provides: { http: 293, data: 161 },
+ consumes: { http: 34 },
+ contracts: [{ contract_id: "http::GET::/repos", role: "provider", repo: "backend", file_path: "app/r.py", line: 12, link_count: 3 }],
+ contractTotal: 488,
+ dependsOn: [{ id: "frontend", name: "frontend", kind: "HTTP", weight: 1, weight_label: "1 endpoint called" }],
+ dependedOnBy: [],
+ unmatched: 35,
+ unmatchedByReason: { external_host: 23 },
+ unusedProviders: 293,
+ cycles: [["backend", "frontend"]],
+ flavor: "claude-code-mcp",
+ });
+ expect(text).toContain("## Service: backend (`backend`)");
+ expect(text).toContain("Provides: 293 http, 161 data");
+ expect(text).toContain("`http::GET::/repos` (provider) at `backend:app/r.py:12`, 3 matched links");
+ expect(text).toContain("487 more contracts not listed");
+ expect(text).toContain("backend -> frontend -> backend");
+ expect(text).toContain('get_blast_radius(target="backend")');
+ expect(text).not.toContain("—");
+ });
+
+ it("edge prompt lists resolved links and caps them", () => {
+ const evidence = Array.from({ length: SYSTEM_MAP_PROMPT_MAX_ROWS + 3 }, (_, i) => ({
+ contract_id: `http::GET::/r${i}`,
+ provider_repo: "backend",
+ provider_file: "app/r.py",
+ consumer_repo: "frontend",
+ consumer_file: "src/client.ts",
+ }));
+ const text = buildEdgeAiPrompt({
+ edge: { id: "frontend->backend:http", kind: "http", match_type: "exact", confidence: 0.85, weight: 180, structural: true },
+ source: { id: "frontend", name: "frontend" },
+ target: { id: "backend", name: "backend" },
+ sentence: "frontend calls backend over HTTP.",
+ weightLabel: "180 endpoints called",
+ evidence,
+ refs: [],
+ flavor: "generic",
+ });
+ expect(text).toContain("frontend calls backend over HTTP.");
+ expect(text).toContain("Confidence: 85%");
+ expect(text).toContain("provider `backend:app/r.py`, consumer `frontend:src/client.ts`");
+ expect(text).toContain("...and 3 more links not listed here.");
+ expect(text).not.toContain("get_blast_radius");
+ });
+
+ 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 },
+ source: { id: "a", name: "a" },
+ target: { id: "b", name: "b" },
+ sentence: "Files in a and b change in the same commits.",
+ weightLabel: "2 file pairs changed together",
+ evidence: [],
+ refs: [],
+ pairs: [["x.py", "y.ts"]],
+ });
+ expect(text).toContain("`x.py` with `y.ts`");
+ expect(text).toContain("hidden dependency");
+ });
+
+ it("cycle prompt names the loop and every edge with its evidence", () => {
+ const text = buildCycleAiPrompt({
+ names: ["backend", "frontend"],
+ ids: ["backend", "frontend"],
+ edges: [
+ { id: "backend->frontend:http", source: "backend", target: "frontend", kind: "http", weight_label: "1 endpoint called", refs: ["http::POST::/api/revalidate/snapshot"] },
+ { id: "frontend->backend:http", source: "frontend", target: "backend", kind: "http", weight_label: "180 endpoints called", refs: [] },
+ ],
+ flavor: "claude-code-mcp",
+ });
+ expect(text).toContain("## Dependency cycle: backend -> frontend -> backend");
+ expect(text).toContain("`http::POST::/api/revalidate/snapshot`");
+ expect(text).toContain("get_blast_radius");
+ });
+
+ it("blast radius prompt splits structural from co-change", () => {
+ const text = buildBlastRadiusAiPrompt({
+ target: { id: "backend", name: "backend" },
+ impacted: [
+ { id: "frontend", name: "frontend", repo: "frontend", distance: 1, score: 0.51, structural: true, edge_kinds: ["http"] },
+ { id: "ui", name: "ui", repo: "repowise", distance: 2, score: 0.1, structural: false, edge_kinds: ["co_change"] },
+ ],
+ includeBehavioral: true,
+ });
+ expect(text).toContain("1 through structural dependencies, 1 only through co-change");
+ expect(text).toContain("## Will break (structural)");
+ expect(text).toContain("## May drift (co-change only)");
+ expect(text).toContain("**ui** (`ui`, repo repowise): 2 hops, impact 0.10");
+ });
+});
diff --git a/packages/ui/__tests__/workspace/system-map-relayout.test.tsx b/packages/ui/__tests__/workspace/system-map-relayout.test.tsx
index 207da9a2b..787ea68a9 100644
--- a/packages/ui/__tests__/workspace/system-map-relayout.test.tsx
+++ b/packages/ui/__tests__/workspace/system-map-relayout.test.tsx
@@ -114,18 +114,18 @@ describe("System Map relayout", () => {
it("re-runs ELK when collapse changes the node set, then reuses the result", async () => {
render(<SystemMap graph={graph} />);
- await screen.findByText("Service view");
+ await screen.findByText(/drawing 3 services/i);
expect(computePositions).toHaveBeenCalledTimes(1);
- fireEvent.click(screen.getByText("Service view"));
- await screen.findByText("Repo view");
+ fireEvent.click(screen.getByRole("radio", { name: "Repositories" }));
+ await screen.findByText(/drawing 2 repositories/i);
// Collapsing genuinely changes the shape, so it earns a layout.
expect(computePositions).toHaveBeenCalledTimes(2);
- fireEvent.click(screen.getByText("Repo view"));
- await screen.findByText("Service view");
- fireEvent.click(screen.getByText("Service view"));
- await screen.findByText("Repo view");
+ fireEvent.click(screen.getByRole("radio", { name: "Services" }));
+ await screen.findByText(/drawing 3 services/i);
+ fireEvent.click(screen.getByRole("radio", { name: "Repositories" }));
+ await screen.findByText(/drawing 2 repositories/i);
// Both shapes are already cached for this mount.
expect(computePositions).toHaveBeenCalledTimes(2);
});
diff --git a/packages/ui/__tests__/workspace/system-map.test.tsx b/packages/ui/__tests__/workspace/system-map.test.tsx
index d21e27860..c2264a47e 100644
--- a/packages/ui/__tests__/workspace/system-map.test.tsx
+++ b/packages/ui/__tests__/workspace/system-map.test.tsx
@@ -2,9 +2,12 @@ import { describe, it, expect, vi, beforeAll } from "vitest";
import { render, screen, fireEvent, within } from "@testing-library/react";
import type { CrossRepoBlastRadius, 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 { Segmented, 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";
+import { SystemMapDrawer, selectionRepo } from "../../src/workspace/system-map/system-map-drawer";
+import { SystemMapFindings } from "../../src/workspace/system-map/system-map-findings";
+import { resolveViewSelection } from "../../src/workspace/system-map/system-map-model";
+import { collapseToRepos } from "../../src/workspace/system-map/collapse";
import { SystemMapBlastPanel } from "../../src/workspace/system-map/system-map-blast-panel";
import { SystemMapBreakingPanel } from "../../src/workspace/system-map/system-map-breaking-panel";
import type { BreakingChange, BreakingChangeReport } from "@repowise-dev/types";
@@ -75,99 +78,255 @@ describe("SystemMap empty states", () => {
});
describe("SystemMapFilters", () => {
- it("only offers edge kinds present in the graph and toggles them", () => {
+ it("only offers edge kinds present in the graph, with counts, and toggles them", () => {
const onToggleKind = vi.fn();
render(
<SystemMapFilters
- availableKinds={new Set(["http", "co_change"])}
+ kindCounts={new Map([["http", 3], ["co_change", 10]])}
visibleKinds={new Set(["http", "co_change"])}
onToggleKind={onToggleKind}
+ canCollapse
collapsed={false}
- onToggleCollapsed={() => {}}
+ onCollapsedChange={() => {}}
/>,
);
- 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(screen.getByTitle("Toggle HTTP edges")).toHaveTextContent("3");
+ expect(screen.getByTitle("Toggle Co-change edges")).toHaveTextContent("10");
+ expect(screen.queryByTitle("Toggle gRPC edges")).not.toBeInTheDocument();
+ fireEvent.click(screen.getByTitle("Toggle HTTP edges"));
expect(onToggleKind).toHaveBeenCalledWith("http");
});
- it("toggles the collapse view", () => {
- const onToggleCollapsed = vi.fn();
- render(
+ it("switches between services and repositories, and hides the switch when it would change nothing", () => {
+ const onCollapsedChange = vi.fn();
+ const { rerender } = render(
+ <SystemMapFilters
+ kindCounts={new Map([["http", 1]])}
+ visibleKinds={new Set(["http"])}
+ onToggleKind={() => {}}
+ canCollapse
+ collapsed={false}
+ onCollapsedChange={onCollapsedChange}
+ />,
+ );
+ fireEvent.click(screen.getByRole("radio", { name: "Repositories" }));
+ expect(onCollapsedChange).toHaveBeenCalledWith(true);
+
+ rerender(
<SystemMapFilters
- availableKinds={new Set(["http"])}
+ kindCounts={new Map([["http", 1]])}
visibleKinds={new Set(["http"])}
onToggleKind={() => {}}
+ canCollapse={false}
collapsed={false}
- onToggleCollapsed={onToggleCollapsed}
+ onCollapsedChange={onCollapsedChange}
+ />,
+ );
+ expect(screen.queryByRole("radio", { name: "Repositories" })).not.toBeInTheDocument();
+ });
+});
+
+describe("Segmented", () => {
+ it("keeps a disabled option visible with its reason", () => {
+ const onChange = vi.fn();
+ render(
+ <Segmented
+ label="Map lens"
+ value="none"
+ options={[
+ { value: "none", label: "None" },
+ { value: "breaking", label: "Breaking changes", count: "0", disabledReason: "No provider contract changed." },
+ ]}
+ onChange={onChange}
+ />,
+ );
+ const option = screen.getByRole("radio", { name: /breaking changes/i });
+ expect(option).toHaveAttribute("aria-disabled", "true");
+ expect(option).toHaveAccessibleDescription("No provider contract changed.");
+ fireEvent.click(option);
+ expect(onChange).not.toHaveBeenCalled();
+ // A tap shows the reason as visible text, not only a tooltip.
+ expect(screen.getByText("No provider contract changed.", { selector: "p" })).toBeInTheDocument();
+ });
+
+ it("keeps the group in the tab order when the active option is disabled", () => {
+ render(
+ <Segmented
+ label="Map lens"
+ value="breaking"
+ options={[
+ { value: "none", label: "None" },
+ { value: "breaking", label: "Breaking changes", disabledReason: "Nothing changed." },
+ ]}
+ onChange={() => {}}
+ />,
+ );
+ expect(screen.getByRole("radio", { name: "None" })).toHaveAttribute("tabindex", "0");
+ expect(screen.getByRole("radio", { name: /breaking changes/i })).toHaveAttribute("tabindex", "-1");
+ });
+});
+
+describe("SystemMapFindings", () => {
+ const g = graph([node("a"), node("b")], [edge("a", "b"), edge("b", "a", { id: "b->a" })]);
+ const base = { graph: g, onSelect: () => {}, onLensChange: () => {} };
+ const conformance = {
+ version: 1,
+ generated_at: "t",
+ rules_evaluated: 0,
+ violations: [],
+ cycles: [],
+ violation_count: 0,
+ cycle_count: 0,
+ total_cycles: 0,
+ violating_repos: [],
+ };
+ const breaking = {
+ version: 1,
+ generated_at: "t",
+ changes: [],
+ total: 0,
+ breaking_count: 0,
+ warning_count: 0,
+ impacted_repos: [],
+ impacted_services: [],
+ total_impacted_consumers: 0,
+ };
+
+ it("does not call the workspace clean while a report is loading or failed", () => {
+ const { rerender } = render(<SystemMapFindings {...base} conformance={null} breaking={breaking} />);
+ expect(screen.queryByText(/no dependency cycles/i)).not.toBeInTheDocument();
+ expect(screen.getByText(/loading the conformance report/i)).toBeInTheDocument();
+
+ rerender(<SystemMapFindings {...base} conformance={null} conformanceError breaking={breaking} />);
+ expect(screen.getByText("Could not load the conformance report.")).toBeInTheDocument();
+ expect(screen.queryByText(/no dependency cycles/i)).not.toBeInTheDocument();
+
+ rerender(<SystemMapFindings {...base} conformance={conformance} breaking={breaking} />);
+ expect(screen.getByText(/no dependency cycles, rule violations or breaking changes/i)).toBeInTheDocument();
+ });
+
+ it("lists a cycle with a prompt to break it", () => {
+ render(
+ <SystemMapFindings
+ {...base}
+ conformance={{ ...conformance, cycles: [{ nodes: ["a", "b"], edge_ids: ["a->b", "b->a"], length: 2 }], cycle_count: 1, total_cycles: 1 }}
+ breaking={breaking}
/>,
);
- fireEvent.click(screen.getByRole("button", { name: /service view/i }));
- expect(onToggleCollapsed).toHaveBeenCalled();
+ expect(screen.getByRole("button", { name: "Break the cycle" })).toBeInTheDocument();
+ expect(screen.queryByText(/no dependency cycles/i)).not.toBeInTheDocument();
+ });
+});
+
+describe("resolveViewSelection", () => {
+ const raw = graph(
+ [node("api::svc/a", { repo: "api", service_path: "svc/a" }), node("api::svc/b", { repo: "api", service_path: "svc/b" }), node("web")],
+ [edge("web", "api::svc/a", { id: "web->api::svc/a:http" }), edge("api::svc/a", "api::svc/b", { id: "a->b:package", kind: "package" })],
+ );
+
+ it("maps a service onto its repository node in repo view", () => {
+ const view = collapseToRepos(raw);
+ expect(resolveViewSelection({ type: "node", id: "api::svc/a" }, raw, view, true).selection).toEqual({ type: "node", id: "api" });
+ });
+
+ it("maps a cross-repo edge onto the merged edge, and asks for services for an edge inside one repo", () => {
+ const view = collapseToRepos(raw);
+ expect(resolveViewSelection({ type: "edge", id: "web->api::svc/a:http" }, raw, view, true).selection).toEqual({
+ type: "edge",
+ id: "web->api::http",
+ });
+ expect(resolveViewSelection({ type: "edge", id: "a->b:package" }, raw, view, true).fix).toEqual({ kind: "expand" });
+ });
+
+ it("asks for a hidden edge kind to be shown", () => {
+ const view = { ...raw, edges: raw.edges.filter((e) => e.kind !== "package") };
+ expect(resolveViewSelection({ type: "edge", id: "a->b:package" }, raw, view, false).fix).toEqual({
+ kind: "show-edge-kind",
+ edgeKind: "package",
+ });
});
});
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();
+ it("keys only the line styles drawn, plus the three health bands", () => {
+ render(<SystemMapLegend matchTypes={new Set(["exact", "inferred"])} />);
+ expect(screen.getByText(/structural, exact match/i)).toBeInTheDocument();
+ expect(screen.getByText(/co-change from git history/i)).toBeInTheDocument();
+ expect(screen.queryByText(/candidate/i)).not.toBeInTheDocument();
+ expect(screen.getByText("Healthy 8+")).toBeInTheDocument();
+ expect(screen.getByText("Alert below 4")).toBeInTheDocument();
});
});
-describe("SystemMapInspector", () => {
+describe("SystemMapDrawer", () => {
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 }),
+ node("api", { provider_count: 2, contract_types: ["http"] }),
],
- [edge("web", "api", { contract_refs: ["http:GET /v1/users"] })],
+ [edge("web", "api", { weight: 2, contract_refs: ["http::GET::/v1/users", "http::GET::/v1/users"] })],
);
+ const base = { graph: g, rawGraph: g, collapsed: false, onClose: () => {} };
- it("renders a selected service with its counts and connections", () => {
- const onSelectNode = vi.fn();
+ it("renders a service with its role, neighbours and contracts, and selects a neighbour", () => {
+ const onSelect = vi.fn();
render(
- <SystemMapInspector
+ <SystemMapDrawer
+ {...base}
selection={{ type: "node", id: "api" }}
- graph={g}
- onClose={() => {}}
- onSelectNode={onSelectNode}
+ onSelect={onSelect}
+ roleByNodeId={
+ new Map([
+ ["api", { id: "api", repo: "api", name: "api", visibility_fan_in: 2, visibility_fan_out: 1, role: "shared" as const }],
+ ])
+ }
+ repoContracts={{
+ contracts: [
+ { contract_id: "http::GET::/v1/users", contract_type: "http", role: "provider", repo: "api", file_path: "routes.py", line: 4 },
+ ],
+ links: [],
+ total: 1,
+ }}
+ contractHref={(r) => `/c?contract=${r.contract_id}&repo=${r.repo}&file=${r.file_path ?? ""}`}
/>,
);
- 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");
+ expect(screen.getByText("Shared")).toBeInTheDocument();
+ expect(screen.getByText(/1 service reaches it/i)).toBeInTheDocument();
+ expect(screen.getByRole("link", { name: "http::GET::/v1/users" })).toHaveAttribute(
+ "href",
+ "/c?contract=http::GET::/v1/users&repo=api&file=routes.py",
+ );
+ fireEvent.click(screen.getByRole("button", { name: /^web/ }));
+ expect(onSelect).toHaveBeenCalledWith({ type: "node", id: "web" });
});
- it("renders a selected edge and opens its contract evidence", () => {
- const onOpenContract = vi.fn();
+ it("offers the blast radius for a service", () => {
+ const onShowBlastRadius = vi.fn();
render(
- <SystemMapInspector
- selection={{ type: "edge", id: "web->api" }}
- graph={g}
- onClose={() => {}}
- onSelectNode={() => {}}
- onOpenContract={onOpenContract}
- />,
+ <SystemMapDrawer {...base} selection={{ type: "node", id: "api" }} onSelect={() => {}} onShowBlastRadius={onShowBlastRadius} />,
);
- 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");
+ fireEvent.click(screen.getByRole("button", { name: "Show blast radius" }));
+ expect(onShowBlastRadius).toHaveBeenCalledWith("api");
});
- it("renders nothing when there is no selection", () => {
- const { container } = render(
- <SystemMapInspector selection={null} graph={g} onClose={() => {}} onSelectNode={() => {}} />,
+ it("renders a relationship as a sentence with its weight unit and deduplicated evidence", () => {
+ render(
+ <SystemMapDrawer
+ {...base}
+ selection={{ type: "edge", id: "web->api" }}
+ onSelect={() => {}}
+ contractHref={(r) => `/c?contract=${r.contract_id}&repo=${r.repo}`}
+ />,
+ );
+ expect(screen.getByText("web calls api over HTTP.")).toBeInTheDocument();
+ expect(screen.getByText("2 endpoints called")).toBeInTheDocument();
+ expect(screen.getByText("90%")).toBeInTheDocument();
+ // Two refs, one contract: listed once, linked to the provider side.
+ expect(screen.getAllByRole("link", { name: "http::GET::/v1/users" })).toHaveLength(1);
+ expect(screen.getByRole("link", { name: "http::GET::/v1/users" })).toHaveAttribute(
+ "href",
+ "/c?contract=http::GET::/v1/users&repo=api",
);
- expect(container).toBeEmptyDOMElement();
});
it("shows co-change evidence as the file pair it is, not as a contract link", () => {
@@ -176,6 +335,7 @@ describe("SystemMapInspector", () => {
[
edge("web", "api", {
kind: "co_change",
+ match_type: "inferred",
structural: false,
weight: 1,
contract_refs: ["app/services/overview.py~src/lib/api/types.ts"],
@@ -183,34 +343,38 @@ describe("SystemMapInspector", () => {
],
);
render(
- <SystemMapInspector
- selection={{ type: "edge", id: "web->api" }}
+ <SystemMapDrawer
graph={behavioral}
+ rawGraph={behavioral}
+ collapsed={false}
onClose={() => {}}
- onSelectNode={() => {}}
- onOpenContract={vi.fn()}
+ onSelect={() => {}}
+ selection={{ type: "edge", id: "web->api" }}
+ contractHref={() => "/c"}
/>,
);
- // Both sides of the pair are shown, split on the "~" separator.
- expect(screen.getByText("app/services/overview.py")).toBeInTheDocument();
- expect(screen.getByText(/src\/lib\/api\/types\.ts/)).toBeInTheDocument();
- expect(screen.getByText(/co-changed files/i)).toBeInTheDocument();
- // A file pair cannot be resolved as a contract, so nothing offers to try.
- expect(screen.queryByTitle(/contracts page/i)).not.toBeInTheDocument();
- expect(screen.queryByText("app/services/overview.py~src/lib/api/types.ts")).not.toBeInTheDocument();
+ expect(screen.getByText("web/app/services/overview.py")).toBeInTheDocument();
+ expect(screen.getByText("with api/src/lib/api/types.ts")).toBeInTheDocument();
+ expect(screen.queryByRole("link", { name: /overview\.py/ })).not.toBeInTheDocument();
});
- it("still offers the Contracts drill-down for structural evidence", () => {
- render(
- <SystemMapInspector
- selection={{ type: "edge", id: "web->api" }}
- graph={g}
- onClose={() => {}}
- onSelectNode={() => {}}
- onOpenContract={vi.fn()}
- />,
- );
- expect(screen.getByTitle(/contracts page/i)).toBeInTheDocument();
+ it("renders nothing when there is no selection", () => {
+ render(<SystemMapDrawer {...base} selection={null} onSelect={() => {}} />);
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+ });
+});
+
+describe("selectionRepo", () => {
+ const g = graph(
+ [node("api::svc/a", { repo: "api", service_path: "svc/a" }), node("web")],
+ [edge("web", "api::svc/a")],
+ );
+ it("names the repository a node, edge or collapsed id lives in", () => {
+ expect(selectionRepo(g, { type: "node", id: "api::svc/a" })).toBe("api");
+ expect(selectionRepo(g, { type: "node", id: "api" })).toBe("api");
+ expect(selectionRepo(g, { type: "edge", id: "web->api::svc/a" })).toBe("web");
+ expect(selectionRepo(g, { type: "edge", id: "web->api::http" })).toBe("web");
+ expect(selectionRepo(g, null)).toBeNull();
});
});
@@ -220,34 +384,21 @@ describe("SystemMap chrome placement", () => {
[edge("web", "api", { contract_refs: ["http:GET /v1/users"] })],
);
- it("puts the inspector in a rail beside the canvas, not on it", async () => {
+ it("opens the drawer outside the canvas for a selection", async () => {
const { container } = render(
<SystemMap graph={g} selection={{ type: "node", id: "api" }} onSelectionChange={() => {}} />,
);
- const rail = await screen.findByRole("complementary");
- // The inspector renders inside the rail…
- expect(within(rail).getByText("2 contracts")).toBeInTheDocument();
- // …and the rail is a peer of the canvas, not a child of it.
+ const dialog = await screen.findByRole("dialog");
+ expect(within(dialog).getByText(/api provides 2 contracts/i)).toBeInTheDocument();
const flow = container.querySelector(".react-flow")!;
- expect(flow.contains(rail)).toBe(false);
+ expect(flow.contains(dialog)).toBe(false);
});
- it("keeps host panels off the canvas too", async () => {
- const { container } = render(
- <SystemMap
- graph={g}
- selection={{ type: "node", id: "api" }}
- onSelectionChange={() => {}}
- rail={<div>host panel</div>}
- />,
- );
- const rail = await screen.findByRole("complementary");
+ it("puts the host's toolbar in the section header, not on the canvas", () => {
+ const { container } = render(<SystemMap graph={g} toolbar={<div>lens bar</div>} />);
const flow = container.querySelector(".react-flow")! as HTMLElement;
- // The host's panel and the inspector share the rail rather than stacking on
- // the same canvas corner, which is what they used to do.
- expect(within(rail).getByText("host panel")).toBeInTheDocument();
- expect(within(flow).queryByText("host panel")).toBeNull();
- expect(within(flow).queryByText("2 contracts")).toBeNull();
+ expect(screen.getByText("lens bar")).toBeInTheDocument();
+ expect(within(flow).queryByText("lens bar")).toBeNull();
});
it("notifies the current onSelectionChange, not the one it mounted with", async () => {
@@ -256,50 +407,35 @@ describe("SystemMap chrome placement", () => {
const { rerender } = render(
<SystemMap graph={g} selection={{ type: "node", id: "api" }} onSelectionChange={stale} />,
);
- await screen.findByRole("complementary");
+ await screen.findByRole("dialog");
rerender(<SystemMap graph={g} selection={{ type: "node", id: "api" }} onSelectionChange={fresh} />);
- // "Depended on by" lists web; selecting it goes through a handler that is
- // memoised once for the component's lifetime.
- fireEvent.click(screen.getByText("web"));
+ // "Depended on by" lists web; selecting it goes through a lifetime-memoised handler.
+ fireEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: /^web/ }));
expect(fresh).toHaveBeenCalledWith({ type: "node", id: "web" });
expect(stale).not.toHaveBeenCalled();
});
- it("resolves a toggle against the current selection, not the mounted one", async () => {
+ it("closing the drawer clears the selection the host holds", async () => {
const onSelectionChange = vi.fn();
- const { rerender } = render(
- <SystemMap graph={g} selection={null} onSelectionChange={onSelectionChange} rail={<div>open</div>} />,
- );
- await screen.findByRole("complementary");
-
- // Selection arrives from the host after mount (e.g. from the URL).
- rerender(
- <SystemMap
- graph={g}
- selection={{ type: "node", id: "api" }}
- onSelectionChange={onSelectionChange}
- rail={<div>open</div>}
- />,
- );
-
- // Closing reads the live selection through the same lifetime-memoised path.
- fireEvent.click(screen.getByLabelText("Close inspector"));
+ render(<SystemMap graph={g} selection={{ type: "node", id: "api" }} onSelectionChange={onSelectionChange} />);
+ await screen.findByRole("dialog");
+ fireEvent.click(screen.getByLabelText("Close panel"));
expect(onSelectionChange).toHaveBeenCalledWith(null);
});
- it("collapses the rail column when nothing is selected and no panel is open", () => {
- const { container } = render(<SystemMap graph={g} rail={null} />);
- expect(container.querySelector("aside")).toBeNull();
+ it("states what it draws", async () => {
+ render(<SystemMap graph={g} />);
+ expect(await screen.findByText(/drawing 2 services and 1 relationship\./i)).toBeInTheDocument();
});
it("resolves a collapsed-view selection against the graph actually drawn", async () => {
const withServices = graph(
[
- node("api::svc/a", { repo: "api", provider_count: 2 }),
- node("api::svc/b", { repo: "api", provider_count: 3 }),
+ node("api::svc/a", { repo: "api", service_path: "svc/a", provider_count: 2 }),
+ node("api::svc/b", { repo: "api", service_path: "svc/b", provider_count: 3 }),
node("web", { repo: "web", kind: "frontend" }),
],
[edge("web", "api::svc/a")],
@@ -307,43 +443,34 @@ describe("SystemMap chrome placement", () => {
render(
<SystemMap
graph={withServices}
- // A collapsed edge id: it exists only once services are merged. The
- // uncollapsed graph spells the same edge "web->api::svc/a".
+ // A collapsed edge id: it exists only once services are merged.
selection={{ type: "edge", id: "web->api::http" }}
onSelectionChange={() => {}}
/>,
);
- // Service view: the id is not in the drawn graph, so there is no inspector.
- expect(screen.queryByText(/http relationship/i)).not.toBeInTheDocument();
+ expect(screen.queryByText(/web calls api over HTTP/i)).not.toBeInTheDocument();
- fireEvent.click(screen.getByText("Service view"));
+ fireEvent.click(await screen.findByRole("radio", { name: "Repositories" }));
- // Repo view: the same id now resolves.
- expect(await screen.findByText(/http relationship/i)).toBeInTheDocument();
+ expect(await screen.findByText(/web calls api over HTTP/i)).toBeInTheDocument();
});
it("shows the merged counts in repo view rather than a same-named service's", async () => {
const withServices = graph(
[
node("api", { repo: "api", provider_count: 2 }),
- node("api::svc/b", { repo: "api", provider_count: 3 }),
+ node("api::svc/b", { repo: "api", service_path: "svc/b", provider_count: 3 }),
node("web", { repo: "web", kind: "frontend" }),
],
[edge("web", "api")],
);
- render(
- <SystemMap
- graph={withServices}
- selection={{ type: "node", id: "api" }}
- onSelectionChange={() => {}}
- />,
- );
- expect(await screen.findByText("2 contracts")).toBeInTheDocument();
+ render(<SystemMap graph={withServices} selection={{ type: "node", id: "api" }} onSelectionChange={() => {}} />);
+ expect(await screen.findByText(/api provides 2 contracts/i)).toBeInTheDocument();
- fireEvent.click(screen.getByText("Service view"));
+ fireEvent.click(screen.getByRole("radio", { name: "Repositories" }));
// 2 + 3, not 2: the repo node is the merge, not the same-named service.
- expect(await screen.findByText("5 contracts")).toBeInTheDocument();
+ expect(await screen.findByText(/api provides 5 contracts/i)).toBeInTheDocument();
});
});
diff --git a/packages/ui/src/shared/adaptive-panel.tsx b/packages/ui/src/shared/adaptive-panel.tsx
index 0d03ad3d3..002ff5ed1 100644
--- a/packages/ui/src/shared/adaptive-panel.tsx
+++ b/packages/ui/src/shared/adaptive-panel.tsx
@@ -34,6 +34,8 @@ export interface AdaptivePanelProps {
* (no focus trap, overlay only on mobile). Default true.
*/
modal?: boolean | undefined;
+ /** Radix's outside-interaction hook; `preventDefault()` keeps a non-modal panel open. */
+ onInteractOutside?: ((event: Event) => void) | undefined;
className?: string | undefined;
}
@@ -49,6 +51,7 @@ export function AdaptivePanel({
sheetHeightClassName = "max-h-[85dvh]",
hideHeader,
modal = true,
+ onInteractOutside,
className,
}: AdaptivePanelProps) {
const contentRef = React.useRef<HTMLDivElement>(null);
@@ -91,6 +94,7 @@ export function AdaptivePanel({
<DialogPrimitive.Content
ref={contentRef}
aria-describedby={undefined}
+ {...(onInteractOutside ? { onInteractOutside } : {})}
className={cn(
"fixed z-[var(--z-modal)] flex flex-col bg-[var(--color-bg-surface)] shadow-2xl",
"data-[state=open]:animate-in data-[state=closed]:animate-out",
diff --git a/packages/ui/src/workspace/system-map/architecture.ts b/packages/ui/src/workspace/system-map/architecture.ts
index 33928b2ed..26e73296a 100644
--- a/packages/ui/src/workspace/system-map/architecture.ts
+++ b/packages/ui/src/workspace/system-map/architecture.ts
@@ -24,7 +24,7 @@ export const ROLE_STYLE: Record<NodeRole, RoleStyle> = {
core: {
label: "Core",
color: "var(--color-warning)",
- description: "In the largest cyclic group — the architectural center.",
+ description: "In the largest cyclic group: the architectural center.",
},
shared: {
label: "Shared",
diff --git a/packages/ui/src/workspace/system-map/index.ts b/packages/ui/src/workspace/system-map/index.ts
index f703cffd9..f460f7fee 100644
--- a/packages/ui/src/workspace/system-map/index.ts
+++ b/packages/ui/src/workspace/system-map/index.ts
@@ -1,13 +1,57 @@
/**
- * 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.
+ * Live System Map public surface: the map, its lens control, drawer, lens
+ * results and findings; the overlay builders for each lens; the AI prompt
+ * builders and the pure model helpers behind them; layout, registries and
+ * overlay types. The rail panels stay exported for hosts that still use them.
*/
-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 {
+ SystemMap,
+ SYSTEM_MAP_CANVAS_HEIGHT,
+ SYSTEM_MAP_MINIMAP_MIN_NODES,
+ type SystemMapProps,
+} from "./system-map";
+export { SystemMapLegend, type SystemMapLegendProps } from "./system-map-legend";
+export {
+ SystemMapFilters,
+ Segmented,
+ type SystemMapFiltersProps,
+ type SegmentOption,
+} from "./system-map-filters";
+export { SystemMapLensControl, type SystemMapLens, type SystemMapLensControlProps } from "./system-map-lens";
+export {
+ SystemMapDrawer,
+ selectionRepo,
+ cyclePrompt,
+ type ContractRef,
+ type SystemMapDrawerData,
+ type SystemMapDrawerProps,
+ type SystemMapPromptState,
+} from "./system-map-drawer";
+export { SystemMapLensResults, type SystemMapLensResultsProps } from "./system-map-lens-results";
+export { SystemMapFindings, type SystemMapFindingsProps } from "./system-map-findings";
+export {
+ buildServiceAiPrompt,
+ buildEdgeAiPrompt,
+ buildCycleAiPrompt,
+ buildBlastRadiusAiPrompt,
+ SYSTEM_MAP_PROMPT_MAX_ROWS,
+} from "./system-map-ai-prompt";
+export {
+ healthMark,
+ serviceResolver,
+ summarizeServiceContracts,
+ serviceDiagnostics,
+ edgeLinks,
+ edgeSentence,
+ weightLabel,
+ weightShort,
+ plural,
+ unmatchedReasonList,
+ resolveViewSelection,
+ type SystemMapContract,
+ type SystemMapRepoContracts,
+} from "./system-map-model";
export { SystemMapBlastPanel, type SystemMapBlastPanelProps } from "./system-map-blast-panel";
export { buildBlastRadiusOverlay, impactBadgeTone } from "./blast-radius";
export {
@@ -42,7 +86,6 @@ export {
SystemMapRailPanel,
RailChip,
RailEyebrow,
- RailField,
type SystemMapRailPanelProps,
} from "./system-map-rail";
export { collapseToRepos } from "./collapse";
diff --git a/packages/ui/src/workspace/system-map/layout.ts b/packages/ui/src/workspace/system-map/layout.ts
index fabc09dc2..335be2c92 100644
--- a/packages/ui/src/workspace/system-map/layout.ts
+++ b/packages/ui/src/workspace/system-map/layout.ts
@@ -11,7 +11,7 @@ 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 const SYSTEM_MAP_NODE_SIZE = { width: 208, height: 96 } as const;
export interface SystemMapView {
/** Edge kinds to keep; an edge survives only if its kind is in the set. */
@@ -91,7 +91,11 @@ export async function computeSystemMapPositions(graph: SystemGraph): Promise<Sys
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 })),
+ // Structural edges only: placement should read as dependency direction,
+ // and co-change pairs are undirected history that would add layers.
+ graph.edges
+ .filter((e) => e.structural)
+ .map((e) => ({ id: e.id, source: e.source, target: e.target })),
);
return { positions, simplified: false };
}
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
new file mode 100644
index 000000000..e1ca2cd18
--- /dev/null
+++ b/packages/ui/src/workspace/system-map/system-map-ai-prompt.ts
@@ -0,0 +1,361 @@
+/**
+ * AI-agent prompts for the System Map: one service, one relationship, one
+ * dependency cycle, one blast radius. Pure string builders in the shape of
+ * `health/ai-prompt-builder.ts` (preamble, evidence, tasks, constraints, what
+ * to hand back), so the agent can start without asking what we meant.
+ *
+ * Every figure comes from the system graph the map drew. The prompts say so,
+ * and tell the agent to confirm each relationship in code before acting on it.
+ */
+
+import type { AiPromptFlavor } from "../../health/ai-prompt-builder";
+
+/** Evidence rows listed in full before the prompt says how many it left out. */
+export const SYSTEM_MAP_PROMPT_MAX_ROWS = 25;
+
+const PREAMBLE: Record<AiPromptFlavor, string> = {
+ generic:
+ "You are a senior engineer working across the repositories of one workspace. The facts below come from repowise's system graph, which is built from code and git history. Treat them as leads, not ground truth: open the files, confirm each relationship in code, and say plainly when one is wrong.",
+ "claude-code":
+ "You are Claude Code working across the repositories of one workspace. The facts below come from repowise's system graph, which is built from code and git history. Treat them as leads: use Read, Grep and Glob in each repository to confirm every relationship before you rely on it, and say plainly when one is wrong. Use TodoWrite for multi-step work.",
+ "claude-code-mcp":
+ "You are Claude Code working across the repositories of one workspace, indexed by repowise and exposed through its MCP tools. The facts below come from repowise's system graph. Pull what repowise already computed before reading files by hand: `get_blast_radius` for cross-repo impact, `search_codebase` to find a route, table or symbol by name, `get_context([...])` for a file's skeleton, `get_symbol(\"file::Name\")` for one body, `get_risk([...])` before editing, and `get_why(...)` for the decision behind the current shape. Confirm each relationship in code and say plainly when one is wrong.",
+ cursor:
+ "Work across the repositories of this workspace. The facts below come from repowise's system graph, which is built from code and git history. Treat them as leads: use @file and @codebase to confirm each relationship in code before acting on it, and say plainly when one is wrong.",
+};
+
+function bullets(items: (string | null | undefined | false)[]): string {
+ return items.filter(Boolean).map((s) => `- ${s}`).join("\n");
+}
+
+function numbered(items: string[]): string {
+ return items.map((s, i) => `${i + 1}. ${s}`).join("\n");
+}
+
+function countsLine(counts: Record<string, number>): string {
+ const entries = Object.entries(counts).sort((a, b) => b[1] - a[1]);
+ return entries.length === 0 ? "none" : entries.map(([t, n]) => `${n} ${t}`).join(", ");
+}
+
+function capped<T>(rows: T[], render: (row: T) => string, noun: string): string {
+ const shown = rows.slice(0, SYSTEM_MAP_PROMPT_MAX_ROWS).map(render).join("\n");
+ const hidden = rows.length - SYSTEM_MAP_PROMPT_MAX_ROWS;
+ return hidden > 0 ? `${shown}\n- ...and ${hidden} more ${noun} not listed here.` : shown;
+}
+
+function assemble(sections: (string | null | false)[]): string {
+ return sections.filter((s): s is string => Boolean(s)).join("\n\n");
+}
+
+// ---------------------------------------------------------------------------
+// Service
+// ---------------------------------------------------------------------------
+
+export interface PromptContractRow {
+ contract_id: string;
+ role: string;
+ repo: string;
+ file_path: string;
+ line?: number | null;
+ link_count?: number;
+}
+
+export interface PromptNeighbour {
+ id: string;
+ name: string;
+ kind: string;
+ weight: number;
+ /** Sentence form of the weight, e.g. "180 endpoints called". */
+ weight_label: string;
+}
+
+export interface BuildServicePromptOptions {
+ service: { id: string; name: string; repo: string; service_path: string | null };
+ /** 0-10, already in the product's scale. */
+ health?: { value: string; label: string } | null;
+ role?: { label: string; reaches: number; reachedBy: number } | null;
+ provides: Record<string, number>;
+ consumes: Record<string, number>;
+ /** Top contracts, ordered by how much rides on them. */
+ contracts: PromptContractRow[];
+ /** Contracts the service declares; above `contracts.length` when trimmed. */
+ contractTotal: number;
+ dependsOn: PromptNeighbour[];
+ dependedOnBy: PromptNeighbour[];
+ unmatched: number;
+ unmatchedByReason?: Record<string, number>;
+ unusedProviders: number;
+ /** Each cycle as the service names in traversal order. */
+ cycles: string[][];
+ flavor?: AiPromptFlavor;
+}
+
+function neighbourLine(n: PromptNeighbour): string {
+ return `**${n.name}** (\`${n.id}\`) via ${n.kind}, ${n.weight_label}`;
+}
+
+function contractLine(c: PromptContractRow): string {
+ const where = `${c.repo}:${c.file_path}${c.line ? `:${c.line}` : ""}`;
+ const links =
+ c.link_count === undefined ? "" : `, ${c.link_count} matched ${c.link_count === 1 ? "link" : "links"}`;
+ return `- \`${c.contract_id}\` (${c.role}) at \`${where}\`${links}`;
+}
+
+export function buildServiceAiPrompt(o: BuildServicePromptOptions): string {
+ const flavor = o.flavor ?? "generic";
+ const s = o.service;
+ const location = s.service_path ? `${s.repo} / ${s.service_path}` : s.repo;
+ const contractsBlock =
+ o.contracts.length === 0
+ ? "No contracts were extracted for this service."
+ : `${o.contracts.slice(0, SYSTEM_MAP_PROMPT_MAX_ROWS).map(contractLine).join("\n")}${
+ o.contractTotal > Math.min(o.contracts.length, SYSTEM_MAP_PROMPT_MAX_ROWS)
+ ? `\n- ...${o.contractTotal - Math.min(o.contracts.length, SYSTEM_MAP_PROMPT_MAX_ROWS)} more contracts not listed here.`
+ : ""
+ }`;
+
+ const reasons = o.unmatchedByReason ? countsLine(o.unmatchedByReason) : null;
+
+ return assemble([
+ PREAMBLE[flavor],
+ `## Service: ${s.name} (\`${s.id}\`)`,
+ bullets([
+ `Location: \`${location}\``,
+ o.health ? `Repository health: ${o.health.value} out of 10 (${o.health.label})` : null,
+ o.role
+ ? `Architecture role: ${o.role.label}. It reaches ${o.role.reaches} other ${o.role.reaches === 1 ? "service" : "services"} through structural dependencies, and ${o.role.reachedBy} can reach it.`
+ : null,
+ `Provides: ${countsLine(o.provides)}`,
+ `Consumes: ${countsLine(o.consumes)}`,
+ o.unmatched > 0
+ ? `Consumers that match no provider in the workspace: ${o.unmatched}${reasons ? ` (${reasons})` : ""}`
+ : null,
+ o.unusedProviders > 0
+ ? `Providers no workspace consumer calls: ${o.unusedProviders}. They may still be called from outside the workspace.`
+ : null,
+ ]),
+ o.cycles.length > 0
+ ? `## Dependency cycles through this service\n\n${bullets(o.cycles.map((c) => `${c.join(" -> ")} -> ${c[0]}`))}`
+ : null,
+ `## Depends on\n\n${o.dependsOn.length ? bullets(o.dependsOn.map(neighbourLine)) : "Nothing in the workspace."}`,
+ `## Depended on by\n\n${o.dependedOnBy.length ? bullets(o.dependedOnBy.map(neighbourLine)) : "Nothing in the workspace."}`,
+ `## Contracts (most linked first)\n\n${contractsBlock}`,
+ "## Task\n\nBefore anyone changes this service, map what it exposes and who would feel a change. Do not edit code.",
+ `## What I expect back\n\n${numbered([
+ "The public surface: each provided contract that has consumers, with the consuming service and file.",
+ "Which dependents would break on a change (structural) and which only tend to change alongside it (co-change).",
+ "Any relationship above that the code does not support, with the file you checked.",
+ "The riskiest contract to change, and the tests in the consuming repositories that would catch a break.",
+ ])}`,
+ flavor === "claude-code-mcp"
+ ? `Start with \`get_blast_radius(target="${s.id}")\`, then \`get_context\` on the provider files listed above and \`get_risk\` on the ones with the most links.`
+ : "Start from the provider files listed above, then search each dependent repository for the routes, symbols and tables they name.",
+ ]);
+}
+
+// ---------------------------------------------------------------------------
+// Edge
+// ---------------------------------------------------------------------------
+
+export interface PromptEdgeEvidence {
+ contract_id: string;
+ provider_repo: string;
+ provider_file: string;
+ consumer_repo: string;
+ consumer_file: string;
+ match_type?: string;
+ confidence?: number;
+}
+
+export interface BuildEdgePromptOptions {
+ edge: {
+ id: string;
+ kind: string;
+ match_type: string;
+ confidence: number;
+ weight: number;
+ structural: boolean;
+ };
+ source: { id: string; name: string };
+ target: { id: string; name: string };
+ /** One sentence: "frontend calls backend over HTTP." */
+ sentence: string;
+ weightLabel: string;
+ /** Resolved links, when the host has them. */
+ evidence: PromptEdgeEvidence[];
+ /** Contract ids from the edge itself, used when no links were resolved. */
+ refs: string[];
+ /** Co-change file pairs, for behavioral edges. */
+ pairs?: [string, string | null][];
+ /** Cycles this edge sits on, as service names. */
+ cycles?: string[][];
+ flavor?: AiPromptFlavor;
+}
+
+export function buildEdgeAiPrompt(o: BuildEdgePromptOptions): string {
+ const flavor = o.flavor ?? "generic";
+ const e = o.edge;
+ const evidence = o.edge.structural
+ ? o.evidence.length > 0
+ ? capped(
+ o.evidence,
+ (l) =>
+ `- \`${l.contract_id}\`: provider \`${l.provider_repo}:${l.provider_file}\`, consumer \`${l.consumer_repo}:${l.consumer_file}\``,
+ "links",
+ )
+ : o.refs.length > 0
+ ? capped(o.refs, (r) => `- \`${r}\``, "contract ids")
+ : "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.";
+
+ const task = e.structural
+ ? `Verify this dependency exists in code and document it. For each piece of evidence, find the call, import or query in \`${o.source.name}\` and the declaration in \`${o.target.name}\` it resolves to. Flag any link that is a false match.`
+ : `Check whether this co-change hides a real dependency. Files that change together without a declared contract often share an undocumented format, a copied type or a coordinated release. Decide which it is for the pairs above.`;
+
+ return assemble([
+ PREAMBLE[flavor],
+ `## Relationship: ${o.source.name} -> ${o.target.name} (\`${e.id}\`)`,
+ bullets([
+ o.sentence,
+ `Kind: ${e.kind}. Match: ${e.match_type}. Confidence: ${Math.round(e.confidence * 100)}%.`,
+ `Weight: ${o.weightLabel}.`,
+ e.structural
+ ? "Structural: built from a contract or import in code. Changing the provider side can break the consumer."
+ : "Behavioral: built from git history. It says the files change together, not that one calls the other.",
+ ]),
+ o.cycles && o.cycles.length > 0
+ ? `## This edge closes a dependency cycle\n\n${bullets(o.cycles.map((c) => `${c.join(" -> ")} -> ${c[0]}`))}`
+ : null,
+ `## Evidence\n\n${evidence}`,
+ `## Task\n\n${task}`,
+ `## What I expect back\n\n${numbered(
+ e.structural
+ ? [
+ "Each confirmed link as consumer file and symbol, provider file and symbol.",
+ "Any link that does not hold, and why.",
+ "A short paragraph for the consumer repository's docs describing this dependency and what a breaking change on the provider side looks like.",
+ "Tests on the consumer side that exercise it, or a note that none do.",
+ ]
+ : [
+ "For each file pair: a real shared dependency, a coincidence of workflow, or unknown.",
+ "If there is a hidden dependency, the contract that should be declared and where.",
+ ],
+ )}`,
+ flavor === "claude-code-mcp"
+ ? `Use \`search_codebase\` for each contract id in both repositories, \`get_context\` on the files above, and \`get_blast_radius(target="${o.target.id}")\` to see what else rides on the provider.`
+ : "Open both sides of each piece of evidence before you write anything.",
+ ]);
+}
+
+// ---------------------------------------------------------------------------
+// Cycle
+// ---------------------------------------------------------------------------
+
+export interface PromptCycleEdge {
+ id: string;
+ source: string;
+ target: string;
+ kind: string;
+ weight_label: string;
+ /** A few contract ids that make up the edge. */
+ refs: string[];
+}
+
+export interface BuildCyclePromptOptions {
+ /** Service names in traversal order. */
+ names: string[];
+ ids: string[];
+ edges: PromptCycleEdge[];
+ flavor?: AiPromptFlavor;
+}
+
+export function buildCycleAiPrompt(o: BuildCyclePromptOptions): string {
+ const flavor = o.flavor ?? "generic";
+ const loop = `${o.names.join(" -> ")} -> ${o.names[0] ?? ""}`;
+ const edges = o.edges
+ .map((e) => {
+ const refs = e.refs.slice(0, 8).map((r) => `\`${r}\``).join(", ");
+ const more = e.refs.length > 8 ? ` and ${e.refs.length - 8} more` : "";
+ return `- **${e.source} -> ${e.target}** (${e.kind}, ${e.weight_label}, \`${e.id}\`)${refs ? `: ${refs}${more}` : ""}`;
+ })
+ .join("\n");
+
+ return assemble([
+ PREAMBLE[flavor],
+ `## Dependency cycle: ${loop}`,
+ bullets([
+ `Services: ${o.ids.map((id) => `\`${id}\``).join(", ")}`,
+ "A cycle means none of these services can change its contract, build or deploy without the others. It counts against the workspace architecture score.",
+ ]),
+ `## Edges in the cycle\n\n${edges}`,
+ "## Task\n\nPropose how to break this cycle. Usually one edge is the odd one out: a callback, a webhook, a shared type or a revalidation hook that points the wrong way. Find it, confirm it in code, and pick a fix: invert it (events or a callback interface), move the shared piece into a package both depend on, or route it through a service already downstream of both.",
+ `## Hard constraints\n\n${bullets([
+ "Preserve behavior. Keep every public contract stable until its consumers have moved.",
+ "Change one edge at a time so each step is reviewable and revertible.",
+ "Do not break the cycle by deleting a feature.",
+ ])}`,
+ `## What I expect back\n\n${numbered([
+ "The edge you would cut, with the exact files and symbols that create it.",
+ "The fix and why it beats the alternatives.",
+ "The change plan across repositories, in merge order.",
+ "Tests that would catch the cycle coming back.",
+ ])}`,
+ flavor === "claude-code-mcp"
+ ? `Run \`get_blast_radius\` on each of ${o.ids.map((id) => `\`${id}\``).join(", ")} and \`search_codebase\` for the contract ids above before choosing the edge to cut.`
+ : "Locate the code behind each edge before choosing which one to cut.",
+ ]);
+}
+
+// ---------------------------------------------------------------------------
+// Blast radius
+// ---------------------------------------------------------------------------
+
+export interface PromptImpacted {
+ id: string;
+ name: string;
+ repo: string;
+ distance: number;
+ score: number;
+ structural: boolean;
+ edge_kinds: string[];
+}
+
+export interface BuildBlastRadiusPromptOptions {
+ target: { id: string; name: string };
+ impacted: PromptImpacted[];
+ includeBehavioral: boolean;
+ flavor?: AiPromptFlavor;
+}
+
+export function buildBlastRadiusAiPrompt(o: BuildBlastRadiusPromptOptions): string {
+ const flavor = o.flavor ?? "generic";
+ const structural = o.impacted.filter((n) => n.structural);
+ const behavioral = o.impacted.filter((n) => !n.structural);
+ const row = (n: PromptImpacted) =>
+ `- **${n.name}** (\`${n.id}\`, repo ${n.repo}): ${n.distance} ${n.distance === 1 ? "hop" : "hops"}, impact ${n.score.toFixed(2)}, via ${n.edge_kinds.join(", ")}`;
+
+ return assemble([
+ PREAMBLE[flavor],
+ `## Blast radius of ${o.target.name} (\`${o.target.id}\`)`,
+ bullets([
+ `${o.impacted.length} downstream ${o.impacted.length === 1 ? "service is" : "services are"} reachable: ${structural.length} through structural dependencies, ${behavioral.length} only through co-change.`,
+ o.includeBehavioral
+ ? "Co-change paths are included at half weight. They mean the files change together, not that one calls the other."
+ : "Co-change paths are excluded; every service below is reached through contracts or imports.",
+ "Impact is 0 to 1, with distance decay: nearer and structural ranks higher.",
+ ]),
+ structural.length ? `## Will break (structural)\n\n${capped(structural, row, "services")}` : null,
+ behavioral.length ? `## May drift (co-change only)\n\n${capped(behavioral, row, "services")}` : null,
+ `## Task\n\nA change to ${o.target.name} is planned. For each structurally impacted service, find the exact contracts it uses from ${o.target.name} and the tests that exercise them. For co-change services, say whether they need a coordinated change or can be left alone.`,
+ `## What I expect back\n\n${numbered([
+ "Per impacted service: the contracts it depends on, with consumer files.",
+ "The tests to run in each repository before merging.",
+ "The order to land changes across repositories so nothing breaks in between.",
+ ])}`,
+ flavor === "claude-code-mcp"
+ ? `Confirm with \`get_blast_radius(target="${o.target.id}")\`, then \`search_codebase\` and \`get_context\` in each impacted repository.`
+ : "Search each impacted repository for the routes, symbols and tables it takes from the target before planning.",
+ ]);
+}
diff --git a/packages/ui/src/workspace/system-map/system-map-drawer.tsx b/packages/ui/src/workspace/system-map/system-map-drawer.tsx
new file mode 100644
index 000000000..cbae429df
--- /dev/null
+++ b/packages/ui/src/workspace/system-map/system-map-drawer.tsx
@@ -0,0 +1,829 @@
+"use client";
+
+/**
+ * The System Map's detail drawer: one service or one relationship, with
+ * everything needed to act on it. It is the shared `AdaptivePanel`, non-modal,
+ * so the map stays interactive behind it and a click on another node swaps the
+ * subject without closing and reopening.
+ *
+ * Resolves the selection against the *drawn* graph. In repo view the ids the
+ * map hands back are collapsed ones that only exist there.
+ *
+ * Presentation only. The host fetches the focused repository's contracts and
+ * owns every route; the drawer takes href builders, not a router.
+ */
+
+import { useMemo, useState, type ElementType, type ReactNode } from "react";
+import type {
+ DependencyCycle,
+ NodeArchitectureRole,
+ SystemEdge,
+ SystemGraph,
+ SystemNode,
+ WorkspaceContractLinkEntry,
+} from "@repowise-dev/types/workspace";
+import { AdaptivePanel } from "../../shared/adaptive-panel";
+import { AiPromptButton } from "../../health/ai-prompt-button";
+import { AiPromptModal } from "../../health/ai-prompt-modal";
+import type { AiPromptFlavor } from "../../health/ai-prompt-builder";
+import { roleStyle } from "./architecture";
+import { edgeKindStyle, matchTypeLabel } from "./edge-kinds";
+import { nodeKindStyle } from "./node-kinds";
+import { MICRO_LABEL } from "./system-map-filters";
+import {
+ BEHAVIORAL_MEANING,
+ STRUCTURAL_MEANING,
+ coChangePairs,
+ cyclesThrough,
+ cyclesWithEdge,
+ edgeLinks,
+ edgeSentence,
+ healthMark,
+ neighbourGroups,
+ nodeLocation,
+ plural,
+ serviceDiagnostics,
+ serviceResolver,
+ summarizeServiceContracts,
+ uniqueRefs,
+ unmatchedReasonList,
+ weightLabel,
+ type ServiceResolver,
+ type SystemMapRepoContracts,
+} from "./system-map-model";
+import {
+ buildCycleAiPrompt,
+ buildEdgeAiPrompt,
+ buildServiceAiPrompt,
+} from "./system-map-ai-prompt";
+import type { RepoHealth, SystemMapSelection } from "./types";
+
+/** Contracts listed in the drawer before it hands off to the Contracts page. */
+export const DRAWER_CONTRACT_ROWS = 8;
+/** Evidence rows listed on an edge before it hands off. */
+export const DRAWER_EVIDENCE_ROWS = 20;
+
+export interface ContractRef {
+ contract_id: string;
+ repo: string;
+ file_path?: string | undefined;
+}
+
+/** What the host supplies beyond the graph: data it fetched and its routes. */
+export interface SystemMapDrawerData {
+ /** Contracts of the repository the selection lives in (see `selectionRepo`). */
+ repoContracts?: SystemMapRepoContracts | null | undefined;
+ repoContractsLoading?: boolean | undefined;
+ cycles?: readonly DependencyCycle[] | undefined;
+ contractHref?: ((ref: ContractRef) => string) | undefined;
+ /** The Contracts page filtered to one repository. */
+ contractsHref?: ((repo: string) => string) | undefined;
+ repoHref?: ((repo: string) => string | null) | undefined;
+ coChangesHref?: string | undefined;
+ LinkComponent?: ElementType | undefined;
+ onShowBlastRadius?: ((nodeId: string) => void) | undefined;
+}
+
+export interface SystemMapDrawerProps extends SystemMapDrawerData {
+ selection: SystemMapSelection;
+ /** The drawn graph (collapse + filters applied). */
+ graph: SystemGraph;
+ /** The raw graph, for diagnostics and service boundaries. */
+ rawGraph: SystemGraph;
+ collapsed: boolean;
+ healthByRepo?: ReadonlyMap<string, RepoHealth> | undefined;
+ roleByNodeId?: ReadonlyMap<string, NodeArchitectureRole> | undefined;
+ onClose: () => void;
+ onSelect: (selection: SystemMapSelection) => void;
+}
+
+/**
+ * The repository whose contracts the drawer needs for a selection, so the host
+ * can fetch before the drawer asks. Accepts raw and collapsed ids.
+ */
+export function selectionRepo(graph: SystemGraph | null, selection: SystemMapSelection): string | null {
+ if (!graph || !selection) return null;
+ const repoOfNode = (id: string) =>
+ graph.nodes.find((n) => n.id === id)?.repo ?? (graph.nodes.some((n) => n.repo === id) ? id : null);
+ if (selection.type === "node") return repoOfNode(selection.id);
+ const edge = graph.edges.find((e) => e.id === selection.id);
+ if (edge) return repoOfNode(edge.source);
+ const source = selection.id.split("->")[0];
+ return source ? repoOfNode(source) : null;
+}
+
+interface PromptState {
+ title: string;
+ description: string;
+ build: (flavor: AiPromptFlavor) => string;
+}
+
+export function SystemMapDrawer(props: SystemMapDrawerProps) {
+ const { selection, graph, rawGraph, collapsed, onClose } = props;
+ const [prompt, setPrompt] = useState<PromptState | null>(null);
+ const resolve = useMemo(() => serviceResolver(rawGraph, collapsed), [rawGraph, collapsed]);
+
+ const node = selection?.type === "node" ? graph.nodes.find((n) => n.id === selection.id) ?? null : null;
+ const edge = selection?.type === "edge" ? graph.edges.find((e) => e.id === selection.id) ?? null : null;
+ const open = Boolean(node || edge);
+ const name = (id: string) => graph.nodes.find((n) => n.id === id)?.name ?? id;
+
+ return (
+ <>
+ <AdaptivePanel
+ open={open}
+ onOpenChange={(next) => {
+ if (!next) onClose();
+ }}
+ modal={false}
+ // The map, the rows below it and the drawer are one workspace: a click
+ // elsewhere selects something else or does nothing, never closes this.
+ onInteractOutside={(e) => e.preventDefault()}
+ eyebrow={node ? nodeKindStyle(node.kind).label : "Relationship"}
+ title={node ? node.name : edge ? `${name(edge.source)} → ${name(edge.target)}` : ""}
+ widthClassName="md:max-w-[480px]"
+ >
+ {node && <NodeBody {...props} node={node} resolve={resolve} onPrompt={setPrompt} />}
+ {edge && <EdgeBody {...props} edge={edge} resolve={resolve} onPrompt={setPrompt} />}
+ </AdaptivePanel>
+ <AiPromptModal
+ open={prompt !== null}
+ onOpenChange={(o) => !o && setPrompt(null)}
+ getPrompt={prompt?.build ?? null}
+ {...(prompt ? { title: prompt.title, description: prompt.description } : {})}
+ />
+ </>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Shared bits
+// ---------------------------------------------------------------------------
+
+function Section({ title, aside, children }: { title: string; aside?: ReactNode; children: ReactNode }) {
+ return (
+ <section className="flex flex-col gap-2">
+ <div className="flex items-baseline justify-between gap-3">
+ <h3 className={MICRO_LABEL}>{title}</h3>
+ {aside}
+ </div>
+ {children}
+ </section>
+ );
+}
+
+function Facts({ items }: { items: { label: string; value: ReactNode }[] }) {
+ return (
+ <dl className="grid grid-cols-2 border-y border-[var(--color-border-default)]">
+ {items.map((f, i) => (
+ <div
+ key={f.label}
+ className={[
+ "min-w-0 px-3 py-2.5 border-[var(--color-border-default)]",
+ i % 2 === 1 ? "border-l" : "",
+ i >= 2 ? "border-t" : "",
+ ]
+ .filter(Boolean)
+ .join(" ")}
+ >
+ <dt className={MICRO_LABEL}>{f.label}</dt>
+ <dd className="mt-1 text-[15px] text-[var(--color-text-primary)]">{f.value}</dd>
+ </div>
+ ))}
+ </dl>
+ );
+}
+
+function Anchor({
+ href,
+ LinkComponent,
+ children,
+ className,
+}: {
+ href: string;
+ LinkComponent?: ElementType | undefined;
+ children: ReactNode;
+ className?: string;
+}) {
+ const A = LinkComponent ?? "a";
+ return (
+ <A
+ href={href}
+ className={`text-[var(--color-accent-primary)] hover:underline ${className ?? ""}`}
+ >
+ {children}
+ </A>
+ );
+}
+
+function SelectButton({ onClick, children, title }: { onClick: () => void; children: ReactNode; title?: string }) {
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ title={title}
+ className="cursor-pointer text-left font-medium text-[var(--color-accent-primary)] hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ >
+ {children}
+ </button>
+ );
+}
+
+function distinct(groups: { edges: SystemEdge[] }[], pick: (e: SystemEdge) => string): number {
+ return new Set(groups.flatMap((g) => g.edges.map(pick))).size;
+}
+
+type BodyProps<T> = SystemMapDrawerProps & {
+ resolve: ServiceResolver;
+ onPrompt: (p: PromptState) => void;
+} & T;
+
+// ---------------------------------------------------------------------------
+// Service
+// ---------------------------------------------------------------------------
+
+function NodeBody({
+ node,
+ graph,
+ rawGraph,
+ collapsed,
+ healthByRepo,
+ roleByNodeId,
+ repoContracts,
+ repoContractsLoading,
+ cycles = [],
+ contractHref,
+ contractsHref,
+ repoHref,
+ LinkComponent,
+ onShowBlastRadius,
+ onSelect,
+ resolve,
+ onPrompt,
+}: BodyProps<{ node: SystemNode }>) {
+ const health = healthByRepo?.get(node.repo);
+ const mark = health ? healthMark(health.score) : null;
+ // Roles are computed per service, so a merged repo node has none.
+ const role = collapsed ? undefined : roleByNodeId?.get(node.id);
+ const style = role ? roleStyle(role.role) : null;
+ const reaches = role ? Math.max(role.visibility_fan_out - 1, 0) : 0;
+ const reachedBy = role ? Math.max(role.visibility_fan_in - 1, 0) : 0;
+
+ 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 summary = useMemo(
+ () => (repoContracts ? summarizeServiceContracts(repoContracts, node.id, resolve) : null),
+ [repoContracts, node.id, resolve],
+ );
+ const capped = repoContracts ? repoContracts.total > repoContracts.contracts.length : false;
+ const name = (id: string) => graph.nodes.find((n) => n.id === id)?.name ?? id;
+ const overview = repoHref?.(node.repo) ?? null;
+
+ const neighbours = (groups: typeof out, pick: (e: SystemEdge) => string) =>
+ groups.flatMap((g) =>
+ g.edges.map((e) => ({
+ id: pick(e),
+ name: name(pick(e)),
+ kind: edgeKindStyle(e.kind).label,
+ weight: e.weight,
+ weight_label: weightLabel(e),
+ })),
+ );
+
+ const openServicePrompt = () =>
+ onPrompt({
+ title: "Map this service before a change",
+ description: `A ready-to-paste prompt that has your agent map what ${node.name} exposes and who would feel a change, before anyone edits it.`,
+ build: (flavor) =>
+ buildServiceAiPrompt({
+ service: { id: node.id, name: node.name, repo: node.repo, service_path: node.service_path },
+ health: mark ? { value: mark.value, label: mark.label } : null,
+ role: style ? { label: style.label, reaches, reachedBy } : null,
+ provides: summary?.provides ?? {},
+ consumes: summary?.consumes ?? {},
+ contracts: summary?.rows ?? [],
+ contractTotal: summary ? summary.providedTotal + summary.consumedTotal : node.provider_count + node.consumer_count,
+ dependsOn: neighbours(out, (e) => e.target),
+ dependedOnBy: neighbours(incoming, (e) => e.source),
+ unmatched: diag.unmatched,
+ unmatchedByReason: diag.unmatchedByReason,
+ unusedProviders: diag.unusedProviders,
+ cycles: myCycles.map((c) => c.nodes.map(name)),
+ flavor,
+ }),
+ });
+
+ return (
+ <div className="flex flex-col gap-6 px-4 py-4">
+ <div className="flex flex-col gap-2">
+ <p className="font-mono text-xs text-[var(--color-text-tertiary)] [overflow-wrap:anywhere]">
+ {nodeLocation(node)}
+ </p>
+ <p className="text-[15px] leading-relaxed text-[var(--color-text-primary)] [text-wrap:pretty]">
+ {node.name} provides {plural(node.provider_count, "contract", "contracts")} and consumes{" "}
+ {node.consumer_count.toLocaleString()}
+ {node.contract_types.length > 0 ? ` (${node.contract_types.join(", ")})` : ""}.
+ {out.length + incoming.length === 0 && " It has no relationships with other services."}
+ </p>
+ </div>
+
+ <Facts
+ items={[
+ {
+ label: "Repository health",
+ value: mark ? (
+ <span className="inline-flex items-center gap-1.5">
+ <span aria-hidden className="h-1.5 w-1.5 rounded-full" style={{ background: mark.color }} />
+ <span className="font-semibold tabular-nums">{mark.value}</span>
+ <span className="text-xs text-[var(--color-text-secondary)]">{mark.label}</span>
+ </span>
+ ) : (
+ <span className="text-xs text-[var(--color-text-tertiary)]">Not scored yet</span>
+ ),
+ },
+ {
+ label: "Architecture role",
+ value: style ? style.label : <span className="text-xs text-[var(--color-text-tertiary)]">{collapsed ? "Per service only" : "Not computed"}</span>,
+ },
+ { label: "Outgoing to", value: <span className="tabular-nums">{plural(distinct(out, (e) => e.target), "service", "services")}</span> },
+ { label: "Incoming from", value: <span className="tabular-nums">{plural(distinct(incoming, (e) => e.source), "service", "services")}</span> },
+ ]}
+ />
+
+ {(style || mark) && (
+ <p className="-mt-3 text-xs leading-relaxed text-[var(--color-text-secondary)] [text-wrap:pretty]">
+ {style &&
+ `${style.label}: ${style.description} Through structural dependencies it reaches ${plural(reaches, "other service", "other services")}, and ${plural(reachedBy, "service reaches", "services reach")} it. `}
+ {mark && `Health is the ${node.repo} repository's score, shared by every service in it.`}
+ </p>
+ )}
+
+ <div className="flex flex-wrap items-center gap-x-4 gap-y-2">
+ {onShowBlastRadius && (
+ <button
+ type="button"
+ onClick={() => onShowBlastRadius(node.id)}
+ className="rounded-md border border-[var(--color-border-hover)] px-2.5 py-1 text-xs font-medium text-[var(--color-text-primary)] hover:bg-[var(--color-bg-elevated)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ >
+ Show blast radius
+ </button>
+ )}
+ <AiPromptButton label="Map before a change" onClick={openServicePrompt} />
+ {overview && (
+ <Anchor href={overview} LinkComponent={LinkComponent} className="text-xs font-medium">
+ {node.repo} overview →
+ </Anchor>
+ )}
+ </div>
+
+ {(myCycles.length > 0 || diag.unmatched > 0 || diag.unusedProviders > 0) && (
+ <Section title="Findings">
+ <ul className="m-0 flex list-none flex-col gap-2 p-0 text-xs leading-relaxed text-[var(--color-text-secondary)]">
+ {myCycles.map((c) => (
+ <li key={c.edge_ids.join("|")} className="flex flex-wrap items-center gap-x-2 gap-y-1">
+ <span className="inline-flex items-center gap-1.5">
+ <span aria-hidden className="h-1.5 w-1.5 rounded-full bg-[var(--color-warning)]" />
+ In a dependency cycle:
+ </span>
+ {c.nodes.map((id, i) => (
+ <span key={id} className="inline-flex items-center gap-1">
+ {id === node.id ? (
+ <span className="font-medium text-[var(--color-text-primary)]">{name(id)}</span>
+ ) : (
+ <SelectButton onClick={() => onSelect({ type: "node", id })}>{name(id)}</SelectButton>
+ )}
+ <span aria-hidden>{i < c.nodes.length - 1 ? "→" : "↩"}</span>
+ </span>
+ ))}
+ <AiPromptButton
+ variant="icon"
+ label="Break this cycle with AI"
+ onClick={() => onPrompt(cyclePrompt(c, rawGraph))}
+ />
+ </li>
+ ))}
+ {diag.unmatched > 0 && (
+ <li>
+ {plural(diag.unmatched, "call", "calls")} from here match no provider in the workspace:{" "}
+ {unmatchedReasonList(diag.unmatchedByReason)}.
+ </li>
+ )}
+ {diag.unusedProviders > 0 && (
+ <li className="text-[var(--color-text-tertiary)]">
+ {plural(diag.unusedProviders, "provided contract has", "provided contracts have")} no consumer in
+ the workspace. Callers outside it are not counted.
+ </li>
+ )}
+ </ul>
+ </Section>
+ )}
+
+ <Section title="Outgoing: depends on or changes with">
+ <NeighbourList groups={out} pick={(e) => e.target} name={name} onSelect={onSelect} empty="Nothing in the workspace." />
+ </Section>
+ <Section title="Incoming: depended on or changes with">
+ <NeighbourList groups={incoming} pick={(e) => e.source} name={name} onSelect={onSelect} empty="Nothing in the workspace." />
+ </Section>
+
+ <Section
+ title="Contracts"
+ aside={
+ contractsHref && (
+ <Anchor href={contractsHref(node.repo)} LinkComponent={LinkComponent} className="text-xs font-medium">
+ All in {node.repo} →
+ </Anchor>
+ )
+ }
+ >
+ {repoContractsLoading && !summary ? (
+ <p className="text-xs text-[var(--color-text-tertiary)]">Loading contracts…</p>
+ ) : !summary ? (
+ <p className="text-xs text-[var(--color-text-tertiary)]">Contract detail is not available here.</p>
+ ) : summary.rows.length === 0 ? (
+ <p className="text-xs text-[var(--color-text-tertiary)]">No contracts were extracted for this service.</p>
+ ) : (
+ <>
+ <TypeTable provides={summary.provides} consumes={summary.consumes} />
+ <ul className="m-0 mt-1 flex list-none flex-col divide-y divide-[var(--color-border-default)] p-0">
+ {summary.rows.slice(0, DRAWER_CONTRACT_ROWS).map((c) => (
+ <li key={`${c.file_path}:${c.contract_id}`} className="flex flex-col gap-0.5 py-2">
+ <div className="flex items-baseline justify-between gap-3">
+ {contractHref ? (
+ <Anchor
+ href={contractHref({ contract_id: c.contract_id, repo: c.repo, file_path: c.file_path })}
+ LinkComponent={LinkComponent}
+ className="min-w-0 font-mono text-xs [overflow-wrap:anywhere]"
+ >
+ {c.contract_id}
+ </Anchor>
+ ) : (
+ <span className="min-w-0 font-mono text-xs [overflow-wrap:anywhere]">{c.contract_id}</span>
+ )}
+ <span className="shrink-0 font-mono text-[10px] tabular-nums text-[var(--color-text-tertiary)]">
+ {c.role} · {plural(c.link_count, "link", "links")}
+ </span>
+ </div>
+ <span className="font-mono text-[10px] text-[var(--color-text-tertiary)] [overflow-wrap:anywhere]">
+ {c.file_path}
+ {c.line ? `:${c.line}` : ""}
+ </span>
+ </li>
+ ))}
+ </ul>
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ {`Showing ${Math.min(summary.rows.length, DRAWER_CONTRACT_ROWS)} of ${summary.rows.length.toLocaleString()}, most linked first.`}
+ {capped &&
+ ` Counted from the first ${repoContracts!.contracts.length.toLocaleString()} of ${repoContracts!.total.toLocaleString()} contracts in ${node.repo}.`}
+ </p>
+ </>
+ )}
+ </Section>
+ </div>
+ );
+}
+
+function TypeTable({ provides, consumes }: { provides: Record<string, number>; consumes: Record<string, number> }) {
+ const types = [...new Set([...Object.keys(provides), ...Object.keys(consumes)])].sort();
+ return (
+ <table className="w-full text-xs tabular-nums">
+ <thead>
+ <tr className={MICRO_LABEL}>
+ <th className="py-1 text-left font-normal">Type</th>
+ <th className="py-1 text-right font-normal">Provides</th>
+ <th className="py-1 text-right font-normal">Consumes</th>
+ </tr>
+ </thead>
+ <tbody>
+ {types.map((t) => (
+ <tr key={t} className="border-t border-[var(--color-border-default)]">
+ <td className="py-1 font-mono text-[var(--color-text-secondary)]">{t}</td>
+ <td className="py-1 text-right text-[var(--color-text-primary)]">{(provides[t] ?? 0).toLocaleString()}</td>
+ <td className="py-1 text-right text-[var(--color-text-primary)]">{(consumes[t] ?? 0).toLocaleString()}</td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ );
+}
+
+function NeighbourList({
+ groups,
+ pick,
+ name,
+ onSelect,
+ empty,
+}: {
+ groups: ReturnType<typeof neighbourGroups>;
+ pick: (e: SystemEdge) => string;
+ name: (id: string) => string;
+ onSelect: (s: SystemMapSelection) => void;
+ empty: string;
+}) {
+ if (groups.length === 0) return <p className="text-xs text-[var(--color-text-tertiary)]">{empty}</p>;
+ return (
+ <div className="flex flex-col gap-2">
+ {groups.map((g) => {
+ const s = edgeKindStyle(g.kind);
+ const Icon = s.icon;
+ return (
+ <div key={g.kind} className="flex flex-col gap-1">
+ <span className="inline-flex items-center gap-1.5 text-xs text-[var(--color-text-tertiary)]">
+ <Icon size={12} aria-hidden />
+ {s.label} · {g.kind === "co_change" ? "behavioral" : "structural"}
+ </span>
+ <ul className="m-0 flex list-none flex-col p-0">
+ {g.edges.map((e) => (
+ <li key={e.id}>
+ <button
+ type="button"
+ onClick={() => onSelect({ type: "node", id: pick(e) })}
+ className="flex w-full cursor-pointer items-baseline justify-between gap-3 rounded px-1.5 py-1 text-left text-[15px] text-[var(--color-text-primary)] hover:bg-[var(--color-bg-elevated)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ >
+ <span className="min-w-0 [overflow-wrap:anywhere]">{name(pick(e))}</span>
+ <span className="shrink-0 font-mono text-[10px] tabular-nums text-[var(--color-text-tertiary)]">
+ {weightLabel(e)}
+ </span>
+ </button>
+ </li>
+ ))}
+ </ul>
+ </div>
+ );
+ })}
+ </div>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Relationship
+// ---------------------------------------------------------------------------
+
+const MATCH_MEANING: Record<string, string> = {
+ exact: "the call resolves to exactly this provider",
+ manual: "declared by hand in the workspace config",
+ candidate: "a heuristic match; verify before relying on it",
+ inferred: "inferred from commits, not from code",
+};
+
+function EdgeBody({
+ edge,
+ graph,
+ rawGraph,
+ repoContracts,
+ repoContractsLoading,
+ cycles = [],
+ collapsed,
+ contractHref,
+ contractsHref,
+ coChangesHref,
+ LinkComponent,
+ onSelect,
+ resolve,
+ onPrompt,
+}: BodyProps<{ edge: SystemEdge }>) {
+ const style = edgeKindStyle(edge.kind);
+ const Icon = style.icon;
+ const nodeOf = (id: string) => graph.nodes.find((n) => n.id === id);
+ const source = nodeOf(edge.source);
+ const target = nodeOf(edge.target);
+ const sourceName = source?.name ?? edge.source;
+ const targetName = target?.name ?? edge.target;
+ const sentence = edgeSentence(edge, sourceName, targetName);
+
+ const links = useMemo<WorkspaceContractLinkEntry[] | null>(
+ () => (repoContracts && edge.structural ? edgeLinks(edge, repoContracts.links, resolve) : null),
+ [repoContracts, edge, resolve],
+ );
+ const refs = uniqueRefs(edge);
+ const pairs = edge.structural ? [] : coChangePairs(edge);
+ const myCycles = collapsed ? [] : cyclesWithEdge(cycles, edge.id);
+ const name = (id: string) => nodeOf(id)?.name ?? id;
+
+ const openEdgePrompt = () =>
+ onPrompt({
+ title: edge.structural ? "Verify this dependency" : "Check this co-change",
+ description: edge.structural
+ ? `A ready-to-paste prompt that has your agent confirm ${sourceName} → ${targetName} in code and document it.`
+ : `A ready-to-paste prompt that has your agent decide whether ${sourceName} and ${targetName} share a hidden dependency.`,
+ build: (flavor) =>
+ buildEdgeAiPrompt({
+ edge,
+ source: { id: edge.source, name: sourceName },
+ target: { id: edge.target, name: targetName },
+ sentence,
+ weightLabel: weightLabel(edge),
+ evidence: links ?? [],
+ refs,
+ pairs,
+ cycles: myCycles.map((c) => c.nodes.map(name)),
+ flavor,
+ }),
+ });
+
+ return (
+ <div className="flex flex-col gap-6 px-4 py-4">
+ <div className="flex flex-col gap-2">
+ <p className="inline-flex items-center gap-1.5 text-xs text-[var(--color-text-tertiary)]">
+ <Icon size={12} aria-hidden />
+ {style.label} · {edge.structural ? "structural" : "behavioral"}
+ </p>
+ <p className="text-[15px] leading-relaxed text-[var(--color-text-primary)] [text-wrap:pretty]">{sentence}</p>
+ <p className="text-xs leading-relaxed text-[var(--color-text-secondary)] [text-wrap:pretty]">
+ {edge.structural ? STRUCTURAL_MEANING : BEHAVIORAL_MEANING}
+ </p>
+ </div>
+
+ <Facts
+ items={[
+ {
+ label: "From",
+ value: <SelectButton onClick={() => onSelect({ type: "node", id: edge.source })}>{sourceName}</SelectButton>,
+ },
+ {
+ label: "To",
+ value: <SelectButton onClick={() => onSelect({ type: "node", id: edge.target })}>{targetName}</SelectButton>,
+ },
+ {
+ label: "Match",
+ value: (
+ <span title={MATCH_MEANING[edge.match_type]}>
+ {matchTypeLabel(edge.match_type)}
+ <span className="block text-xs text-[var(--color-text-tertiary)]">{MATCH_MEANING[edge.match_type]}</span>
+ </span>
+ ),
+ },
+ {
+ label: "Confidence",
+ value: <span className="tabular-nums">{Math.round(edge.confidence * 100)}%</span>,
+ },
+ { label: "Weight", value: <span className="tabular-nums">{weightLabel(edge)}</span> },
+ {
+ label: "Evidence kept",
+ value: (
+ <span className="tabular-nums">
+ {plural(edge.structural ? refs.length : pairs.length, "reference", "references")}
+ </span>
+ ),
+ },
+ ]}
+ />
+
+ <div className="flex flex-wrap items-center gap-x-4 gap-y-2">
+ <AiPromptButton
+ label={edge.structural ? "Verify this dependency" : "Check this co-change"}
+ onClick={openEdgePrompt}
+ />
+ </div>
+
+ {myCycles.length > 0 && (
+ <Section title="Dependency cycle">
+ {myCycles.map((c) => (
+ <div key={c.edge_ids.join("|")} className="flex flex-wrap items-center gap-2 text-xs text-[var(--color-text-secondary)]">
+ <span aria-hidden className="h-1.5 w-1.5 rounded-full bg-[var(--color-warning)]" />
+ This edge closes a cycle: {c.nodes.map(name).join(" → ")} → {name(c.nodes[0] ?? "")}.
+ <AiPromptButton label="Break the cycle" onClick={() => onPrompt(cyclePrompt(c, rawGraph))} />
+ </div>
+ ))}
+ </Section>
+ )}
+
+ {edge.structural ? (
+ <Section
+ title="Contract evidence"
+ aside={
+ contractsHref &&
+ target && (
+ <Anchor href={contractsHref(target.repo)} LinkComponent={LinkComponent} className="text-xs font-medium">
+ All in {target.repo} →
+ </Anchor>
+ )
+ }
+ >
+ {repoContractsLoading && !links ? (
+ <p className="text-xs text-[var(--color-text-tertiary)]">Loading the links behind this edge…</p>
+ ) : links && links.length > 0 ? (
+ <>
+ <ul className="m-0 flex list-none flex-col divide-y divide-[var(--color-border-default)] p-0">
+ {links.slice(0, DRAWER_EVIDENCE_ROWS).map((l) => (
+ <li key={`${l.contract_id}|${l.provider_file}|${l.consumer_file}`} className="flex flex-col gap-0.5 py-2">
+ {contractHref ? (
+ <Anchor
+ href={contractHref({ contract_id: l.contract_id, repo: l.provider_repo, file_path: l.provider_file })}
+ LinkComponent={LinkComponent}
+ className="font-mono text-xs [overflow-wrap:anywhere]"
+ >
+ {l.contract_id}
+ </Anchor>
+ ) : (
+ <span className="font-mono text-xs [overflow-wrap:anywhere]">{l.contract_id}</span>
+ )}
+ <span className="font-mono text-[10px] text-[var(--color-text-tertiary)] [overflow-wrap:anywhere]">
+ provides {l.provider_repo}/{l.provider_file}
+ </span>
+ <span className="font-mono text-[10px] text-[var(--color-text-tertiary)] [overflow-wrap:anywhere]">
+ calls from {l.consumer_repo}/{l.consumer_file}
+ </span>
+ </li>
+ ))}
+ </ul>
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ {`Showing ${Math.min(links.length, DRAWER_EVIDENCE_ROWS)} of ${plural(links.length, "matched link", "matched links")}.`}
+ </p>
+ </>
+ ) : refs.length > 0 ? (
+ <>
+ <ul className="m-0 flex list-none flex-col gap-1 p-0">
+ {refs.slice(0, DRAWER_EVIDENCE_ROWS).map((ref) => (
+ <li key={ref}>
+ {contractHref && target ? (
+ <Anchor
+ href={contractHref({ contract_id: ref, repo: target.repo })}
+ LinkComponent={LinkComponent}
+ className="font-mono text-xs [overflow-wrap:anywhere]"
+ >
+ {ref}
+ </Anchor>
+ ) : (
+ <span className="font-mono text-xs [overflow-wrap:anywhere]">{ref}</span>
+ )}
+ </li>
+ ))}
+ </ul>
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ {`Showing ${Math.min(refs.length, DRAWER_EVIDENCE_ROWS)} of ${refs.length} contract ids the graph kept 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>
+ )}
+ </Section>
+ ) : (
+ <Section
+ title="Files that changed together"
+ aside={
+ coChangesHref && (
+ <Anchor href={coChangesHref} LinkComponent={LinkComponent} className="text-xs font-medium">
+ All co-changes →
+ </Anchor>
+ )
+ }
+ >
+ {pairs.length === 0 ? (
+ <p className="text-xs text-[var(--color-text-tertiary)]">The graph kept no file pairs for this edge.</p>
+ ) : (
+ <>
+ <ul className="m-0 flex list-none flex-col divide-y divide-[var(--color-border-default)] p-0">
+ {pairs.slice(0, DRAWER_EVIDENCE_ROWS).map(([a, b]) => (
+ <li key={`${a}~${b}`} className="flex flex-col gap-0.5 py-1.5 font-mono text-[10px] leading-snug">
+ <span className="text-[var(--color-text-secondary)] [overflow-wrap:anywhere]">
+ {sourceName}/{a}
+ </span>
+ {b && (
+ <span className="text-[var(--color-text-tertiary)] [overflow-wrap:anywhere]">
+ with {targetName}/{b}
+ </span>
+ )}
+ </li>
+ ))}
+ </ul>
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ {`Showing ${Math.min(pairs.length, DRAWER_EVIDENCE_ROWS)} of ${plural(edge.weight, "file pair", "file pairs")}.`}
+ </p>
+ </>
+ )}
+ </Section>
+ )}
+ </div>
+ );
+}
+
+/** The cycle prompt, shared by the drawer and the findings below the map. */
+export function cyclePrompt(cycle: DependencyCycle, graph: SystemGraph): PromptState {
+ const name = (id: string) => graph.nodes.find((n) => n.id === id)?.name ?? id;
+ const names = cycle.nodes.map(name);
+ return {
+ title: "Break this dependency cycle",
+ description: `A ready-to-paste prompt that has your agent find the edge that closes ${names.join(" → ")} and propose how to cut it.`,
+ build: (flavor) =>
+ buildCycleAiPrompt({
+ names,
+ ids: cycle.nodes,
+ edges: cycle.edge_ids.map((id) => {
+ const e = graph.edges.find((x) => x.id === id);
+ return {
+ id,
+ source: e ? name(e.source) : id,
+ target: e ? name(e.target) : "",
+ kind: e?.kind ?? "unknown",
+ weight_label: e ? weightLabel(e) : "unknown weight",
+ refs: e ? uniqueRefs(e) : [],
+ };
+ }),
+ flavor,
+ }),
+ };
+}
+
+export type { PromptState as SystemMapPromptState };
diff --git a/packages/ui/src/workspace/system-map/system-map-edge.tsx b/packages/ui/src/workspace/system-map/system-map-edge.tsx
index 89095d021..1825af603 100644
--- a/packages/ui/src/workspace/system-map/system-map-edge.tsx
+++ b/packages/ui/src/workspace/system-map/system-map-edge.tsx
@@ -1,26 +1,39 @@
"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.
+ * A typed system-map edge. Structural edges are solid ink, co-change edges a
+ * quieter dotted line; the dash follows match confidence (exact solid,
+ * candidate dashed, inferred dotted). Kind is named in the label, the legend
+ * and the drawer rather than in a hue per transport.
+ *
+ * Labels show only for the edges touching what the reader hovers or selects,
+ * plus edges a lens badged. Drawn always, a busy pair's labels land on top of
+ * each other and none of them can be read.
*/
import { memo } from "react";
import { BaseEdge, EdgeLabelRenderer, getSmoothStepPath, type EdgeProps } from "@xyflow/react";
import { edgeKindStyle, matchTypeDash } from "./edge-kinds";
+import { useEdgeActive } from "./system-map-focus";
+import { weightShort } from "./system-map-model";
import type { SystemMapEdgeData } from "./types";
function strokeWidth(weight: number): number {
- return Math.min(1 + Math.log2(weight + 1) * 0.5, 3);
+ return Math.min(1 + Math.log2(weight + 1) * 0.4, 3.2);
+}
+
+function badgeColor(tone: "danger" | "warning" | "info"): string {
+ if (tone === "danger") return "var(--color-error)";
+ if (tone === "warning") return "var(--color-warning)";
+ return "var(--color-text-secondary)";
}
function SystemMapEdgeInner(props: EdgeProps) {
- const { id, sourceX, sourceY, targetX, targetY, sourcePosition, targetPosition, markerEnd, data, selected } = props;
+ const { id, source, target, sourceX, sourceY, targetX, targetY, sourcePosition, targetPosition, markerEnd, data } =
+ props;
const { edge, overlay } = data as unknown as SystemMapEdgeData;
const style = edgeKindStyle(edge.kind);
+ const active = useEdgeActive(id, source, target);
const [edgePath, labelX, labelY] = getSmoothStepPath({
sourceX,
@@ -32,30 +45,35 @@ function SystemMapEdgeInner(props: EdgeProps) {
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 dimmed = (overlay?.dimmed ?? false) && !active;
+ const lensed = overlay?.highlighted ?? false;
+ const stroke = active
+ ? "var(--color-accent-primary)"
+ : lensed
+ ? "var(--color-text-primary)"
+ : edge.structural
+ ? "var(--color-diagram-edge)"
+ : "var(--color-text-tertiary)";
+ const width = active || lensed ? Math.max(2, strokeWidth(edge.weight)) : strokeWidth(edge.weight);
+ const showLabel = !dimmed && (active || Boolean(overlay?.badge));
const Icon = style.icon;
- const label = edge.weight > 1 ? `${style.label} ×${edge.weight}` : style.label;
return (
- <>
+ <g className="sm-edge" data-active={active || lensed ? "" : undefined}>
<BaseEdge
id={id}
path={edgePath}
{...(markerEnd ? { markerEnd } : {})}
+ interactionWidth={16}
style={{
stroke,
- strokeWidth: emphasized ? 2.5 : strokeWidth(edge.weight),
- strokeDasharray: dash,
- opacity,
- animation: emphasized ? "edgeFlow 1.5s linear infinite" : "none",
+ strokeWidth: width,
+ strokeDasharray: matchTypeDash(edge.match_type),
+ opacity: dimmed ? 0.1 : 1,
+ transition: "opacity 120ms, stroke 120ms",
}}
/>
- {!dimmed && (
+ {showLabel && (
<EdgeLabelRenderer>
<div
className="nodrag nopan"
@@ -67,29 +85,28 @@ function SystemMapEdgeInner(props: EdgeProps) {
gap: 4,
background: "var(--color-bg-surface)",
color: "var(--color-text-secondary)",
- padding: "2px 7px",
- borderRadius: 6,
+ padding: "2px 6px",
+ borderRadius: 4,
fontFamily: "var(--font-mono, ui-monospace, monospace)",
- fontSize: 9.5,
- fontWeight: 500,
- letterSpacing: 0.3,
+ fontSize: 10,
+ lineHeight: "14px",
pointerEvents: "none",
- border: emphasized
- ? "1px solid var(--color-viz-selection)"
- : "1px solid var(--color-border-default)",
+ border: `1px solid ${active ? "var(--color-accent-primary)" : "var(--color-border-hover)"}`,
whiteSpace: "nowrap",
- opacity: emphasized ? 1 : 0.92,
+ zIndex: active ? 2 : 1,
}}
>
- <Icon size={10} aria-hidden style={{ color: style.color, flexShrink: 0 }} />
- {label}
+ <Icon size={10} aria-hidden style={{ flexShrink: 0 }} />
+ {style.label} · {weightShort(edge)}
{overlay?.badge && (
- <span style={{ color: "var(--color-risk-high)", fontWeight: 700 }}>· {overlay.badge.label}</span>
+ <span style={{ color: badgeColor(overlay.badge.tone), fontWeight: 600 }}>
+ · {overlay.badge.label}
+ </span>
)}
</div>
</EdgeLabelRenderer>
)}
- </>
+ </g>
);
}
diff --git a/packages/ui/src/workspace/system-map/system-map-filters.tsx b/packages/ui/src/workspace/system-map/system-map-filters.tsx
index fc8a473ea..0d573db6b 100644
--- a/packages/ui/src/workspace/system-map/system-map-filters.tsx
+++ b/packages/ui/src/workspace/system-map/system-map-filters.tsx
@@ -1,71 +1,187 @@
"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.
+ * The map's section-header controls: which edge kinds are drawn, and whether
+ * services or whole repositories are the nodes. Only kinds present in the
+ * graph are offered, each with its count, so the row never shows a dead
+ * filter. Pure controlled components; state lives in the map.
*/
+import { useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from "react";
import type { SystemEdgeKind } from "@repowise-dev/types";
-import { Separator } from "../../ui/separator";
import { EDGE_KIND_ORDER, SYSTEM_EDGE_KINDS } from "./edge-kinds";
+export const MICRO_LABEL =
+ "font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]";
+
+export interface SegmentOption<T extends string> {
+ value: T;
+ label: string;
+ /** Figure after the label, e.g. a finding count. */
+ count?: string | undefined;
+ /** Set to disable the option; the reason is its tooltip and accessible description. */
+ disabledReason?: string | undefined;
+ hint?: string | undefined;
+}
+
+/**
+ * One axis, one control: a radiogroup of mutually exclusive options. A
+ * disabled option stays visible with its reason rather than vanishing, so the
+ * reader learns the lens exists and why it has nothing to show.
+ */
+export function Segmented<T extends string>({
+ label,
+ value,
+ options,
+ onChange,
+}: {
+ label: string;
+ value: T;
+ options: SegmentOption<T>[];
+ onChange: (value: T) => void;
+}) {
+ const refs = useRef<(HTMLButtonElement | null)[]>([]);
+ const [reason, setReason] = useState<string | null>(null);
+ // The roving tab stop: the active option, or the first enabled one when the
+ // active option is disabled, so the group never drops out of the tab order.
+ const activeIndex = options.findIndex((o) => o.value === value && !o.disabledReason);
+ const tabStop = activeIndex >= 0 ? activeIndex : Math.max(options.findIndex((o) => !o.disabledReason), 0);
+
+ // Arrows walk every option, disabled ones included, so a keyboard reader can
+ // reach a disabled lens and hear why; only enabled ones are selected.
+ const onKeyDown = (e: ReactKeyboardEvent) => {
+ const i = refs.current.findIndex((el) => el === document.activeElement);
+ const from = i >= 0 ? i : tabStop;
+ let next: number;
+ if (e.key === "ArrowRight" || e.key === "ArrowDown") next = (from + 1) % options.length;
+ else if (e.key === "ArrowLeft" || e.key === "ArrowUp") next = (from - 1 + options.length) % options.length;
+ else return;
+ e.preventDefault();
+ refs.current[next]?.focus();
+ const target = options[next];
+ if (target && !target.disabledReason) onChange(target.value);
+ };
+
+ return (
+ <div className="flex min-w-0 flex-col gap-1">
+ <div
+ role="radiogroup"
+ aria-label={label}
+ onKeyDown={onKeyDown}
+ className="inline-flex max-w-full flex-wrap self-start rounded-md border border-[var(--color-border-default)] p-0.5"
+ >
+ {options.map((o, i) => {
+ const active = o.value === value && !o.disabledReason;
+ const reasonId = o.disabledReason ? `sm-reason-${label}-${o.value}`.replace(/\s+/g, "-") : undefined;
+ const show = o.disabledReason ? () => setReason(o.disabledReason ?? null) : undefined;
+ return (
+ <button
+ key={o.value}
+ ref={(el) => {
+ refs.current[i] = el;
+ }}
+ type="button"
+ role="radio"
+ aria-checked={active}
+ aria-disabled={o.disabledReason ? true : undefined}
+ aria-describedby={reasonId}
+ tabIndex={i === tabStop ? 0 : -1}
+ title={o.disabledReason ?? o.hint}
+ onClick={() => (o.disabledReason ? show?.() : onChange(o.value))}
+ onMouseEnter={show}
+ onFocus={show}
+ onMouseLeave={o.disabledReason ? () => setReason(null) : undefined}
+ onBlur={o.disabledReason ? () => setReason(null) : undefined}
+ className={`inline-flex items-center gap-1.5 rounded px-2.5 py-1 text-xs transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)] ${
+ active
+ ? "bg-[var(--color-bg-elevated)] font-semibold text-[var(--color-text-primary)]"
+ : o.disabledReason
+ ? "cursor-not-allowed font-medium text-[var(--color-text-tertiary)]"
+ : "font-medium text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]"
+ }`}
+ >
+ {o.label}
+ {o.count !== undefined && (
+ <span className="font-mono text-[10px] tabular-nums text-[var(--color-text-tertiary)]">{o.count}</span>
+ )}
+ {reasonId && (
+ <span id={reasonId} className="sr-only">
+ {o.disabledReason}
+ </span>
+ )}
+ </button>
+ );
+ })}
+ </div>
+ {reason && <p className="text-xs text-[var(--color-text-tertiary)]">{reason}</p>}
+ </div>
+ );
+}
+
export interface SystemMapFiltersProps {
- /** Edge kinds present in the (uncollapsed) graph; only these are shown. */
- availableKinds: ReadonlySet<SystemEdgeKind>;
+ /** Edges per kind in the drawn shape (before the kind filter); only these kinds are offered. */
+ kindCounts: ReadonlyMap<SystemEdgeKind, number>;
visibleKinds: ReadonlySet<SystemEdgeKind>;
onToggleKind: (kind: SystemEdgeKind) => void;
+ /** Whether the repo view would differ from the service view; the switch hides otherwise. */
+ canCollapse: boolean;
collapsed: boolean;
- onToggleCollapsed: () => void;
+ onCollapsedChange: (collapsed: boolean) => void;
}
export function SystemMapFilters({
- availableKinds,
+ kindCounts,
visibleKinds,
onToggleKind,
+ canCollapse,
collapsed,
- onToggleCollapsed,
+ onCollapsedChange,
}: SystemMapFiltersProps) {
- const kinds = EDGE_KIND_ORDER.filter((k) => availableKinds.has(k));
-
- const pill = (active: boolean) =>
- `inline-flex cursor-pointer items-center gap-1.5 rounded-full border px-2.5 py-[3px] text-[11px] font-medium ${
- active
- ? "border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] text-[var(--color-text-primary)]"
- : "border-[var(--color-border-subtle)] bg-transparent text-[var(--color-text-tertiary)] opacity-60"
- }`;
+ const kinds = EDGE_KIND_ORDER.filter((k) => (kindCounts.get(k) ?? 0) > 0);
return (
- <div className="flex flex-wrap items-center gap-2">
- {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`}
- className={pill(active)}
- >
- <Icon size={11} style={{ color: s.color }} aria-hidden />
- {s.label}
- </button>
- );
- })}
- <Separator orientation="vertical" className="h-[18px]" />
- <button
- type="button"
- onClick={onToggleCollapsed}
- aria-pressed={collapsed}
- title="Group services into one node per repository"
- className={`${pill(collapsed)} opacity-100`}
- >
- {collapsed ? "Repo view" : "Service view"}
- </button>
+ <div className="flex min-w-0 flex-wrap items-center gap-x-4 gap-y-2">
+ {kinds.length > 0 && (
+ <div className="flex min-w-0 flex-wrap items-center gap-1.5" role="group" aria-label="Edge kinds drawn">
+ <span className={`${MICRO_LABEL} mr-1`}>Edges</span>
+ {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`}
+ className={`inline-flex items-center gap-1.5 rounded-md border px-2 py-1 text-xs transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)] ${
+ active
+ ? "border-[var(--color-border-hover)] bg-[var(--color-bg-surface)] text-[var(--color-text-primary)]"
+ : "border-dashed border-[var(--color-border-default)] text-[var(--color-text-tertiary)] line-through"
+ }`}
+ >
+ <Icon size={12} aria-hidden />
+ {s.label}
+ <span className="font-mono text-[10px] tabular-nums text-[var(--color-text-tertiary)] no-underline">
+ {kindCounts.get(kind)}
+ </span>
+ </button>
+ );
+ })}
+ </div>
+ )}
+ {canCollapse && (
+ <Segmented
+ label="Nodes"
+ value={collapsed ? "repos" : "services"}
+ options={[
+ { value: "services", label: "Services", hint: "One node per detected service" },
+ { value: "repos", label: "Repositories", hint: "Group services into one node per repository" },
+ ]}
+ onChange={(v) => onCollapsedChange(v === "repos")}
+ />
+ )}
</div>
);
}
diff --git a/packages/ui/src/workspace/system-map/system-map-findings.tsx b/packages/ui/src/workspace/system-map/system-map-findings.tsx
new file mode 100644
index 000000000..7e94b6813
--- /dev/null
+++ b/packages/ui/src/workspace/system-map/system-map-findings.tsx
@@ -0,0 +1,178 @@
+"use client";
+
+/**
+ * "Needs attention": the findings the map's shape implies, listed whether or
+ * not a lens is on. A dependency cycle is visible as two arrows on the canvas
+ * but easy to miss there; here it is a named row with the action that fixes
+ * it. Quiet states stay quiet: a clean check is one sentence, not a row of
+ * green badges.
+ */
+
+import { useState } from "react";
+import type {
+ BreakingChangeReport,
+ ConformanceReport,
+ ExtractionDiagnostics,
+ SystemGraph,
+} from "@repowise-dev/types/workspace";
+import { OverviewSection } from "../../overview/section";
+import { AiPromptButton } from "../../health/ai-prompt-button";
+import { AiPromptModal } from "../../health/ai-prompt-modal";
+import { buildConformanceAiPrompt } from "../../health/ai-prompt-builder";
+import { CycleRow } from "./system-map-lens-results";
+import type { SystemMapPromptState } from "./system-map-drawer";
+import type { SystemMapLens } from "./system-map-lens";
+import { plural, unmatchedReasonList } from "./system-map-model";
+import type { SystemMapSelection } from "./types";
+
+export interface SystemMapFindingsProps {
+ graph: SystemGraph;
+ conformance: ConformanceReport | null;
+ breaking: BreakingChangeReport | null;
+ diagnostics?: ExtractionDiagnostics | null | undefined;
+ /** The request for a report failed; without these a missing report reads as loading. */
+ conformanceError?: boolean | undefined;
+ breakingError?: boolean | undefined;
+ onSelect: (selection: SystemMapSelection) => void;
+ onLensChange: (lens: SystemMapLens) => void;
+ /** Where unmatched consumers are reviewed (the Contracts page). */
+ unmatchedHref?: string | undefined;
+ conformanceHref?: string | undefined;
+ LinkComponent?: React.ElementType | undefined;
+}
+
+export function SystemMapFindings({
+ graph,
+ conformance,
+ breaking,
+ diagnostics,
+ conformanceError,
+ breakingError,
+ onSelect,
+ onLensChange,
+ unmatchedHref,
+ conformanceHref,
+ LinkComponent,
+}: SystemMapFindingsProps) {
+ const [prompt, setPrompt] = useState<SystemMapPromptState | null>(null);
+ const A = LinkComponent ?? "a";
+
+ const cycles = conformance?.cycles ?? [];
+ const totalCycles = conformance ? (conformance.total_cycles ?? conformance.cycle_count) : 0;
+ const violations = conformance?.violations ?? [];
+ const breakingCount = breaking?.breaking_count ?? 0;
+ const unmatched = diagnostics?.unmatched_consumers.length ?? 0;
+ const reasons = unmatchedReasonList(diagnostics?.unmatched_by_reason ?? {});
+ // An all-clear needs both reports loaded and actually run; a missing report
+ // is not a clean one.
+ const clean =
+ Boolean(conformance?.generated_at && breaking?.generated_at) &&
+ cycles.length === 0 &&
+ violations.length === 0 &&
+ breakingCount === 0;
+
+ const status: string[] = [];
+ if (conformanceError) status.push("Could not load the conformance report.");
+ else if (!conformance) status.push("Loading the conformance report…");
+ else if (!conformance.generated_at)
+ status.push("Conformance has not been checked yet. Run a workspace update to produce a result.");
+ if (breakingError) status.push("Could not load the breaking-change report.");
+ else if (!breaking) status.push("Loading the breaking-change report…");
+ else if (!breaking.generated_at)
+ status.push("Breaking-change detection has not run yet. Run a workspace update to produce a result.");
+
+ return (
+ <OverviewSection
+ title="Needs attention"
+ description="Findings from the most recent workspace update. Each names the services involved; click one to open it on the map."
+ >
+ <ul className="m-0 flex list-none flex-col divide-y divide-[var(--color-border-default)] border-t border-[var(--color-border-default)] p-0">
+ {cycles.map((c) => (
+ <CycleRow key={c.edge_ids.join("|")} cycle={c} graph={graph} onSelect={onSelect} onPrompt={setPrompt} />
+ ))}
+ {totalCycles > cycles.length && (
+ <li className="py-3 text-xs text-[var(--color-text-secondary)]">
+ {`${totalCycles - cycles.length} more ${totalCycles - cycles.length === 1 ? "cycle is" : "cycles are"} not listed; the report keeps the first ${cycles.length}.`}
+ </li>
+ )}
+ {violations.length > 0 && (
+ <li className="flex flex-wrap items-center justify-between gap-3 py-3">
+ <span className="flex items-center gap-2 text-[15px] text-[var(--color-text-primary)]">
+ <span aria-hidden className="h-1.5 w-1.5 rounded-full bg-[var(--color-error)]" />
+ {plural(violations.length, "dependency breaks", "dependencies break")} a declared architecture rule.
+ <button
+ type="button"
+ onClick={() => onLensChange("conformance")}
+ className="cursor-pointer text-xs font-medium text-[var(--color-accent-primary)] hover:underline"
+ >
+ Show on map
+ </button>
+ </span>
+ <AiPromptButton
+ label="Fix violations"
+ onClick={() =>
+ setPrompt({
+ title: "AI conformance fix",
+ description: "A ready-to-paste prompt that has your agent remove the dependencies your rules forbid.",
+ build: (flavor) => buildConformanceAiPrompt({ violations, flavor }),
+ })
+ }
+ />
+ </li>
+ )}
+ {breakingCount > 0 && breaking && (
+ <li className="flex flex-wrap items-center justify-between gap-3 py-3">
+ <span className="flex items-center gap-2 text-[15px] text-[var(--color-text-primary)]">
+ <span aria-hidden className="h-1.5 w-1.5 rounded-full bg-[var(--color-error)]" />
+ {plural(breakingCount, "provider change breaks", "provider changes break")} compatibility, exposing{" "}
+ {plural(breaking.total_impacted_consumers, "consumer", "consumers")}.
+ </span>
+ <button
+ type="button"
+ onClick={() => onLensChange("breaking")}
+ className="cursor-pointer rounded-md border border-[var(--color-border-hover)] px-2.5 py-1 text-xs font-medium text-[var(--color-text-primary)] hover:bg-[var(--color-bg-elevated)]"
+ >
+ Show on map
+ </button>
+ </li>
+ )}
+ {clean && (
+ <li className="py-3 text-[15px] text-[var(--color-text-secondary)]">
+ No dependency cycles, rule violations or breaking changes.
+ </li>
+ )}
+ {unmatched > 0 && (
+ <li className="flex flex-wrap items-baseline justify-between gap-3 py-3">
+ <span className="text-[15px] text-[var(--color-text-secondary)]">
+ {plural(unmatched, "call", "calls")} to a contract match no provider in the workspace
+ {reasons && `: ${reasons}`}.
+ </span>
+ {unmatchedHref && (
+ <A href={unmatchedHref} className="whitespace-nowrap text-xs font-medium text-[var(--color-accent-primary)] hover:underline">
+ Review on Contracts →
+ </A>
+ )}
+ </li>
+ )}
+ {status.map((line) => (
+ <li key={line} className="py-3 text-xs text-[var(--color-text-tertiary)]">
+ {line}
+ </li>
+ ))}
+ {conformanceHref && cycles.length + violations.length > 0 && (
+ <li className="py-3">
+ <A href={conformanceHref} className="text-xs font-medium text-[var(--color-accent-primary)] hover:underline">
+ See the dependency matrix on Conformance →
+ </A>
+ </li>
+ )}
+ </ul>
+ <AiPromptModal
+ open={prompt !== null}
+ onOpenChange={(o) => !o && setPrompt(null)}
+ getPrompt={prompt?.build ?? null}
+ {...(prompt ? { title: prompt.title, description: prompt.description } : {})}
+ />
+ </OverviewSection>
+ );
+}
diff --git a/packages/ui/src/workspace/system-map/system-map-focus.ts b/packages/ui/src/workspace/system-map/system-map-focus.ts
new file mode 100644
index 000000000..f41dc18fa
--- /dev/null
+++ b/packages/ui/src/workspace/system-map/system-map-focus.ts
@@ -0,0 +1,72 @@
+/**
+ * Hover and selection for the map's edges, outside React state.
+ *
+ * Every edge asks one question: am I touching what the reader is pointing at?
+ * Held in React state, a hover would re-render every edge on the canvas; here
+ * each edge subscribes to its own boolean, so a hover re-renders only the
+ * edges whose answer changed. The fade of everything else is one attribute on
+ * the canvas and a CSS rule, not a render.
+ */
+
+import { createContext, useContext, useSyncExternalStore } from "react";
+
+interface Focus {
+ node: string | null;
+ edge: string | null;
+}
+
+export interface SystemMapFocusStore {
+ subscribe: (listener: () => void) => () => void;
+ setHover: (focus: Partial<Focus>) => void;
+ setSelected: (focus: Focus) => void;
+ /** True when anything is hovered or selected. */
+ focused: () => boolean;
+ edgeActive: (id: string, source: string, target: string) => boolean;
+}
+
+export function createSystemMapFocusStore(): SystemMapFocusStore {
+ let hover: Focus = { node: null, edge: null };
+ let selected: Focus = { node: null, edge: null };
+ const listeners = new Set<() => void>();
+ const emit = () => listeners.forEach((l) => l());
+
+ return {
+ subscribe(listener) {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ },
+ setHover(next) {
+ const merged = { ...hover, ...next };
+ if (merged.node === hover.node && merged.edge === hover.edge) return;
+ hover = merged;
+ emit();
+ },
+ setSelected(next) {
+ if (next.node === selected.node && next.edge === selected.edge) return;
+ selected = next;
+ emit();
+ },
+ focused: () => Boolean(hover.node || hover.edge || selected.node || selected.edge),
+ edgeActive(id, source, target) {
+ if (id === hover.edge || id === selected.edge) return true;
+ for (const n of [hover.node, selected.node]) {
+ if (n && (n === source || n === target)) return true;
+ }
+ return false;
+ },
+ };
+}
+
+export const SystemMapFocusContext = createContext<SystemMapFocusStore | null>(null);
+
+const never = () => () => {};
+
+/** Whether this edge touches the hovered or selected object. */
+export function useEdgeActive(id: string, source: string, target: string): boolean {
+ const store = useContext(SystemMapFocusContext);
+ return useSyncExternalStore(
+ store ? store.subscribe : never,
+ () => (store ? store.edgeActive(id, source, target) : false),
+ () => false,
+ );
+}
diff --git a/packages/ui/src/workspace/system-map/system-map-inspector.tsx b/packages/ui/src/workspace/system-map/system-map-inspector.tsx
deleted file mode 100644
index 2a449f68b..000000000
--- a/packages/ui/src/workspace/system-map/system-map-inspector.tsx
+++ /dev/null
@@ -1,360 +0,0 @@
-"use client";
-
-/**
- * Selection detail for the Live System Map: a service node (health, role,
- * fan-in/out, neighbours) or an edge (kind, match, confidence, and the evidence
- * behind it). Rendered as a card in the map's rail — it used to float over the
- * canvas at the same corner two other panels also claimed.
- *
- * Resolves the selection against the *view* graph. In repo view the ids the map
- * hands back are collapsed ones, which either miss the raw graph entirely (edge
- * ids differ) or hit a same-named service node holding un-merged numbers.
- */
-
-import type {
- NodeArchitectureRole,
- SystemEdge,
- SystemGraph,
- SystemNode,
-} from "@repowise-dev/types";
-import { HealthRing } from "../workspace-graph-node";
-import { roleStyle } from "./architecture";
-import { edgeKindStyle, matchTypeLabel } from "./edge-kinds";
-import { nodeKindStyle } from "./node-kinds";
-import { RailEyebrow, RailField, SystemMapRailPanel } from "./system-map-rail";
-import type { RepoHealth, SystemMapSelection } from "./types";
-
-export interface SystemMapInspectorProps {
- selection: SystemMapSelection;
- /** The graph on screen (collapse + filters applied), not the raw graph. */
- graph: SystemGraph;
- healthByRepo?: ReadonlyMap<string, RepoHealth>;
- /** Per-service architecture role + visibility profile (Phase 6, optional). */
- roleByNodeId?: ReadonlyMap<string, NodeArchitectureRole>;
- 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;
-}
-
-function NodeBody({
- node,
- graph,
- health,
- role,
- onSelectNode,
-}: {
- node: SystemNode;
- graph: SystemGraph;
- health: RepoHealth | null;
- role: NodeArchitectureRole | 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 className="flex flex-col gap-2 px-3 py-2.5">
- <div className="flex items-center gap-2.5">
- {health && <HealthRing score={health.score} source={health.source} size={36} />}
- <div className="min-w-0">
- <div className="text-sm font-semibold text-[var(--color-text-primary)]">{node.name}</div>
- <div className="text-[11px] text-[var(--color-text-tertiary)]">
- {kind.label} · {node.repo}
- </div>
- </div>
- </div>
- <div>
- {role && (
- <RailField
- label="Role"
- value={
- <span
- title={roleStyle(role.role).description}
- className="inline-flex items-center gap-1.5"
- >
- <span
- className="h-[7px] w-[7px] rounded-full"
- style={{ background: roleStyle(role.role).color }}
- />
- {roleStyle(role.role).label}
- </span>
- }
- />
- )}
- {role && (
- <RailField
- label="Visibility (in / out)"
- value={`${role.visibility_fan_in} / ${role.visibility_fan_out}`}
- />
- )}
- {node.service_path && (
- <RailField
- label="Path"
- value={<span className="font-mono text-[11px]">{node.service_path}</span>}
- />
- )}
- <RailField label="Provides" value={`${node.provider_count} contracts`} />
- <RailField label="Consumes" value={`${node.consumer_count} contracts`} />
- <RailField
- label="Types"
- value={node.contract_types.length ? node.contract_types.join(", ") : "none"}
- />
- {node.is_orphan_provider && (
- <RailField
- label="Status"
- value={<span className="text-[var(--color-warning)]">Orphan provider</span>}
- />
- )}
- {node.is_orphan_consumer && (
- <RailField
- label="Status"
- value={<span className="text-[var(--color-warning)]">Orphan consumer</span>}
- />
- )}
- {node.is_isolated && (
- <RailField
- label="Status"
- value={<span className="text-[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 className="mb-[3px]">
- <RailEyebrow>{title}</RailEyebrow>
- </div>
- <div className="flex flex-col gap-0.5">
- {edges.map((e) => {
- const id = resolve(e);
- const s = edgeKindStyle(e.kind);
- return (
- <button
- key={e.id}
- type="button"
- onClick={() => onSelectNode(id)}
- className="flex cursor-pointer items-center gap-1.5 rounded-[var(--radius-sm)] px-1 py-0.5 text-left text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-overlay)]"
- >
- <span
- className="h-[7px] w-[7px] shrink-0 rounded-full"
- style={{ background: s.color }}
- />
- <span className="flex-1 truncate">{neighbour(id)}</span>
- <span className="text-[10px] text-[var(--color-text-tertiary)]">{s.label}</span>
- </button>
- );
- })}
- </div>
- </div>
- );
-}
-
-/**
- * Evidence behind an edge.
- *
- * Structural edges cite contract ids (`http::POST::/feedback`), which the
- * Contracts surface can resolve. Behavioral (co-change) edges cite
- * `source_file~target_file` pairs, which it cannot — every ref used to be
- * rendered as a button captioned "Open on the Contracts page", promising a
- * destination that could never answer. Those are shown as the file pair they
- * are.
- */
-function EdgeEvidence({
- edge,
- onOpenContract,
-}: {
- edge: SystemEdge;
- onOpenContract?: (contractId: string) => void;
-}) {
- if (edge.contract_refs.length === 0) return null;
-
- // Back-pointers are capped per edge while `weight` counts every contributor,
- // so the two diverge once an edge is busy enough. Name the cap instead of
- // showing two figures the reader has to reconcile.
- const count =
- edge.weight > edge.contract_refs.length
- ? `${edge.contract_refs.length} of ${edge.weight}`
- : `${edge.contract_refs.length}`;
-
- if (!edge.structural) {
- return (
- <div>
- <div className="mb-[3px]">
- <RailEyebrow>{`Co-changed files (${count})`}</RailEyebrow>
- </div>
- <div className="flex flex-col gap-1">
- {edge.contract_refs.map((ref) => {
- const split = ref.indexOf("~");
- const source = split === -1 ? ref : ref.slice(0, split);
- const target = split === -1 ? null : ref.slice(split + 1);
- return (
- <div key={ref} className="font-mono text-[10.5px] leading-tight">
- <div className="truncate text-[var(--color-text-secondary)]" title={source}>
- {source}
- </div>
- {target && (
- <div className="truncate text-[var(--color-text-tertiary)]" title={target}>
- ↔ {target}
- </div>
- )}
- </div>
- );
- })}
- </div>
- </div>
- );
- }
-
- return (
- <div>
- <div className="mb-[3px]">
- <RailEyebrow>{`Evidence (${count})`}</RailEyebrow>
- </div>
- <div className="flex flex-col gap-0.5">
- {edge.contract_refs.map((ref) => (
- <button
- key={ref}
- type="button"
- onClick={onOpenContract ? () => onOpenContract(ref) : undefined}
- disabled={!onOpenContract}
- title={onOpenContract ? `Find ${ref} on the Contracts page` : ref}
- className={`truncate text-left font-mono text-[10.5px] ${
- onOpenContract
- ? "cursor-pointer text-[var(--color-accent-primary)] hover:underline"
- : "cursor-default text-[var(--color-text-tertiary)]"
- }`}
- >
- {ref}
- </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 className="flex flex-col gap-2 px-3 py-2.5">
- <div className="flex items-center gap-1.5 text-[13px] text-[var(--color-text-primary)]">
- <Icon size={13} style={{ color: s.color }} aria-hidden />
- {s.label} relationship
- </div>
- <div>
- <RailField
- label="From"
- value={<LinkText label={name(edge.source)} onClick={() => onSelectNode(edge.source)} />}
- />
- <RailField
- label="To"
- value={<LinkText label={name(edge.target)} onClick={() => onSelectNode(edge.target)} />}
- />
- <RailField label="Match" value={matchTypeLabel(edge.match_type)} />
- <RailField label="Confidence" value={`${Math.round(edge.confidence * 100)}%`} />
- <RailField label="Weight" value={String(edge.weight)} />
- <RailField label="Nature" value={edge.structural ? "Structural" : "Behavioral"} />
- </div>
- <EdgeEvidence edge={edge} {...(onOpenContract ? { onOpenContract } : {})} />
- </div>
- );
-}
-
-function LinkText({ label, onClick }: { label: string; onClick: () => void }) {
- return (
- <button
- type="button"
- onClick={onClick}
- className="cursor-pointer text-[var(--color-accent-primary)] hover:underline"
- >
- {label}
- </button>
- );
-}
-
-export function SystemMapInspector({
- selection,
- graph,
- healthByRepo,
- roleByNodeId,
- 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 (
- <SystemMapRailPanel eyebrow="Service" onClear={onClose} clearLabel="Close inspector">
- <NodeBody
- node={node}
- graph={graph}
- health={healthByRepo?.get(node.repo) ?? null}
- role={roleByNodeId?.get(node.id) ?? null}
- onSelectNode={onSelectNode}
- />
- </SystemMapRailPanel>
- );
- }
-
- const edge = graph.edges.find((e) => e.id === selection.id);
- if (!edge) return null;
- return (
- <SystemMapRailPanel eyebrow="Relationship" onClear={onClose} clearLabel="Close inspector">
- <EdgeBody
- edge={edge}
- graph={graph}
- onSelectNode={onSelectNode}
- {...(onOpenContract ? { onOpenContract } : {})}
- />
- </SystemMapRailPanel>
- );
-}
diff --git a/packages/ui/src/workspace/system-map/system-map-legend.tsx b/packages/ui/src/workspace/system-map/system-map-legend.tsx
index d88611157..6c60871bb 100644
--- a/packages/ui/src/workspace/system-map/system-map-legend.tsx
+++ b/packages/ui/src/workspace/system-map/system-map-legend.tsx
@@ -1,64 +1,78 @@
"use client";
/**
- * Key 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.
- *
- * Rendered as a hairline caption row under the canvas, not as a card on it — a
- * key is a caption, and the diagram is the thing the reader came for.
+ * Key for the Live System Map, as one caption row between the controls and
+ * the canvas: the line styles actually drawn (structural ink, co-change
+ * dotted, candidate dashed), the health mark's three bands, and how to get
+ * more. Reads the same registries the map renders from, so the two cannot
+ * drift, and lists only what the graph contains.
*/
-import { EDGE_KIND_ORDER, SYSTEM_EDGE_KINDS } from "./edge-kinds";
+import type { SystemEdgeMatchType } from "@repowise-dev/types";
+import { matchTypeDash } from "./edge-kinds";
function Item({ swatch, label }: { swatch: React.ReactNode; label: string }) {
return (
- <span className="inline-flex items-center gap-1.5 text-[10.5px] text-[var(--color-text-secondary)]">
+ <span className="inline-flex items-center gap-1.5 text-xs text-[var(--color-text-secondary)]">
{swatch}
{label}
</span>
);
}
-function dashLine(dash: string, label: string) {
+function Line({ dash, color }: { dash: string; color: 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>
- }
- />
+ <svg width={22} height={6} aria-hidden>
+ <line x1={0} y1={3} x2={22} y2={3} stroke={color} strokeWidth={1.75} strokeDasharray={dash} />
+ </svg>
);
}
function Dot({ color }: { color: string }) {
- return <span className="inline-block h-2.5 w-2.5 rounded-full" style={{ background: color }} />;
+ return <span aria-hidden className="inline-block h-1.5 w-1.5 rounded-full" style={{ background: color }} />;
}
-export function SystemMapLegend() {
+const LINE_LABEL: Record<SystemEdgeMatchType, string> = {
+ exact: "Structural, exact match",
+ manual: "Structural, declared by hand",
+ candidate: "Structural, candidate match",
+ inferred: "Co-change from git history",
+};
+
+export interface SystemMapLegendProps {
+ /** Match types present on the drawn edges; only these get a key. */
+ matchTypes?: ReadonlySet<SystemEdgeMatchType>;
+}
+
+export function SystemMapLegend({ matchTypes }: SystemMapLegendProps) {
+ const order: SystemEdgeMatchType[] = ["exact", "manual", "candidate", "inferred"];
+ const shown = order.filter((m) => !matchTypes || matchTypes.has(m));
+ // Exact and manual draw the same solid line; one key covers both.
+ const lines = shown.filter((m) => !(m === "manual" && shown.includes("exact")));
+
return (
- <div className="flex flex-wrap items-center gap-x-4 gap-y-1.5 border-t border-[var(--color-border-subtle)] px-1 pt-2">
- <div className="flex flex-wrap items-center gap-2.5">
- {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 />} />;
- })}
- </div>
- <div className="flex flex-wrap items-center gap-2.5">
- {dashLine("none", "Exact / manual")}
- {dashLine("6 4", "Candidate")}
- {dashLine("2 4", "Inferred (co-change)")}
- </div>
- <div className="flex flex-wrap items-center gap-2.5">
- <span className="text-[10.5px] text-[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" />
- </div>
+ <div className="flex flex-wrap items-center gap-x-5 gap-y-1.5">
+ {lines.map((m) => (
+ <Item
+ key={m}
+ label={m === "exact" && shown.includes("manual") ? "Structural, exact or declared" : LINE_LABEL[m]}
+ swatch={
+ <Line
+ dash={matchTypeDash(m)}
+ color={m === "inferred" ? "var(--color-text-tertiary)" : "var(--color-diagram-edge)"}
+ />
+ }
+ />
+ ))}
+ <span className="inline-flex items-center gap-2.5">
+ <span className="text-xs text-[var(--color-text-tertiary)]">Repository health</span>
+ <Item swatch={<Dot color="var(--color-success)" />} label="Healthy 8+" />
+ <Item swatch={<Dot color="var(--color-warning)" />} label="Warning 4 to 8" />
+ <Item swatch={<Dot color="var(--color-error)" />} label="Alert below 4" />
+ </span>
+ <span className="text-xs text-[var(--color-text-tertiary)]">
+ Hover a line for its kind and weight. Click a service or line for details.
+ </span>
</div>
);
}
diff --git a/packages/ui/src/workspace/system-map/system-map-lens-results.tsx b/packages/ui/src/workspace/system-map/system-map-lens-results.tsx
new file mode 100644
index 000000000..7f04820d3
--- /dev/null
+++ b/packages/ui/src/workspace/system-map/system-map-lens-results.tsx
@@ -0,0 +1,448 @@
+"use client";
+
+/**
+ * What the active lens found, as rows under the canvas. The canvas keeps the
+ * width and carries the overlay; the list carries the names, figures and
+ * actions, and every row selects its service on the map.
+ */
+
+import { useState } from "react";
+import type {
+ ArchitectureMetrics,
+ BreakingChangeReport,
+ ConformanceReport,
+ CrossRepoBlastRadius,
+ ImpactedNode,
+ NodeArchitectureRole,
+ SystemGraph,
+} from "@repowise-dev/types/workspace";
+import { OverviewSection } from "../../overview/section";
+import { ResponsiveTable, type ResponsiveColumn } from "../../shared/responsive-table";
+import { AiPromptButton } from "../../health/ai-prompt-button";
+import { AiPromptModal } from "../../health/ai-prompt-modal";
+import { buildConformanceAiPrompt } from "../../health/ai-prompt-builder";
+import {
+ BreakingChangeRow,
+ breakingChangeKey,
+ breakingChangeSummary,
+ sortChangesBySeverity,
+} from "../breaking-change-row";
+import { ROLE_ORDER, roleStyle } from "./architecture";
+import { edgeKindStyle } from "./edge-kinds";
+import { cyclePrompt, type SystemMapPromptState } from "./system-map-drawer";
+import { buildBlastRadiusAiPrompt } from "./system-map-ai-prompt";
+import type { SystemMapLens } from "./system-map-lens";
+import { plural } from "./system-map-model";
+import type { SystemMapSelection } from "./types";
+
+export interface SystemMapLensResultsProps {
+ lens: SystemMapLens;
+ graph: SystemGraph;
+ selection: SystemMapSelection;
+ onSelect: (selection: SystemMapSelection) => void;
+ blastTarget: string | null;
+ blast: CrossRepoBlastRadius | null;
+ blastLoading?: boolean;
+ /** The blast-radius request failed. */
+ blastError?: boolean;
+ includeBehavioral: boolean;
+ breaking: BreakingChangeReport | null;
+ conformance: ConformanceReport | null;
+ architecture: ArchitectureMetrics | null;
+ conformanceHref?: string | undefined;
+ LinkComponent?: React.ElementType | undefined;
+}
+
+function Muted({ children }: { children: React.ReactNode }) {
+ return <p className="text-xs text-[var(--color-text-tertiary)]">{children}</p>;
+}
+
+export function SystemMapLensResults(props: SystemMapLensResultsProps) {
+ const [prompt, setPrompt] = useState<SystemMapPromptState | null>(null);
+ if (props.lens === "none") return null;
+
+ return (
+ <>
+ {props.lens === "blast" && <BlastResults {...props} onPrompt={setPrompt} />}
+ {props.lens === "breaking" && <BreakingResults {...props} />}
+ {props.lens === "conformance" && <ConformanceResults {...props} onPrompt={setPrompt} />}
+ {props.lens === "core" && <CoreResults {...props} />}
+ <AiPromptModal
+ open={prompt !== null}
+ onOpenChange={(o) => !o && setPrompt(null)}
+ getPrompt={prompt?.build ?? null}
+ {...(prompt ? { title: prompt.title, description: prompt.description } : {})}
+ />
+ </>
+ );
+}
+
+type WithPrompt = SystemMapLensResultsProps & { onPrompt: (p: SystemMapPromptState) => void };
+
+// ---------------------------------------------------------------------------
+// Blast radius
+// ---------------------------------------------------------------------------
+
+function BlastResults({ graph, blastTarget, blast, blastLoading, blastError, includeBehavioral, selection, onSelect, onPrompt }: WithPrompt) {
+ const name = (id: string) => graph.nodes.find((n) => n.id === id)?.name ?? id;
+ const targetName = blastTarget ? name(blastTarget) : null;
+
+ if (!blastTarget) {
+ return (
+ <OverviewSection title="Blast radius">
+ <Muted>Choose the service a change starts in, from the lens bar or with Show blast radius in its drawer.</Muted>
+ </OverviewSection>
+ );
+ }
+ if (!blast) {
+ return (
+ <OverviewSection title={`If ${targetName} changes`}>
+ <Muted>
+ {blastError
+ ? "The trace failed. The service may no longer be in the graph, or the server could not be reached."
+ : blastLoading
+ ? "Tracing what depends on it…"
+ : "No result for this service."}
+ </Muted>
+ </OverviewSection>
+ );
+ }
+
+ const structural = blast.impacted.filter((n) => n.structural).length;
+ const behavioral = blast.impacted.length - structural;
+ const repos = blast.impacted_repos.length;
+ const description =
+ blast.impacted.length === 0
+ ? `Nothing in the workspace depends on ${targetName}${includeBehavioral ? ", and nothing changes alongside it" : ""}.`
+ : `${plural(blast.impacted.length, "service", "services")} in ${plural(repos, "other repository", "other repositories")} can feel it: ${structural} through a contract or import (will break), ${behavioral} only through co-change (may drift). Impact runs 0 to 1 and falls with each hop.${includeBehavioral ? "" : " Co-change is excluded."}`;
+
+ const columns: ResponsiveColumn<ImpactedNode>[] = [
+ {
+ key: "name",
+ header: "Service",
+ priority: 1,
+ render: (n) => (
+ <span className="flex flex-col">
+ <span className="text-[15px] font-medium text-[var(--color-text-primary)]">{n.name}</span>
+ <span className="font-mono text-[10px] text-[var(--color-text-tertiary)]">
+ {n.id.includes("::") ? n.id.replace("::", " / ") : `${n.repo} repository`}
+ </span>
+ </span>
+ ),
+ },
+ {
+ key: "nature",
+ header: "Reached through",
+ priority: 1,
+ render: (n) =>
+ n.structural ? (
+ <span className="text-[var(--color-text-primary)]">Contract or import</span>
+ ) : (
+ <span className="text-[var(--color-text-secondary)]">Co-change only</span>
+ ),
+ },
+ {
+ key: "distance",
+ header: "Distance",
+ align: "right",
+ priority: 2,
+ render: (n) => <span className="tabular-nums">{plural(n.distance, "hop", "hops")}</span>,
+ },
+ {
+ key: "via",
+ header: "Via",
+ priority: 3,
+ render: (n) => (
+ <span className="text-xs text-[var(--color-text-secondary)]">
+ {n.edge_kinds.map((k) => edgeKindStyle(k).label).join(", ")}
+ </span>
+ ),
+ },
+ {
+ key: "score",
+ header: "Impact",
+ align: "right",
+ priority: 1,
+ render: (n) => <span className="font-mono tabular-nums">{n.score.toFixed(2)}</span>,
+ },
+ ];
+
+ return (
+ <OverviewSection
+ title={`If ${targetName} changes`}
+ description={description}
+ action={
+ blast.impacted.length > 0 ? (
+ <AiPromptButton
+ label="Plan this change"
+ onClick={() =>
+ onPrompt({
+ title: "Plan a change across the blast radius",
+ description: `A ready-to-paste prompt that has your agent find the contracts and tests each impacted service needs before ${targetName} changes.`,
+ build: (flavor) =>
+ buildBlastRadiusAiPrompt({
+ target: { id: blastTarget, name: targetName ?? blastTarget },
+ impacted: blast.impacted,
+ includeBehavioral,
+ flavor,
+ }),
+ })
+ }
+ />
+ ) : undefined
+ }
+ >
+ {blast.impacted.length > 0 && (
+ <ResponsiveTable
+ columns={columns}
+ rows={blast.impacted}
+ rowKey={(n) => n.id}
+ onRowClick={(n) => onSelect({ type: "node", id: n.id })}
+ selectedKey={selection?.type === "node" ? selection.id : null}
+ caption={`Services impacted if ${targetName} changes`}
+ virtualize={{ threshold: 60, maxHeight: 520 }}
+ />
+ )}
+ </OverviewSection>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Breaking changes
+// ---------------------------------------------------------------------------
+
+function BreakingResults({ breaking, onSelect }: SystemMapLensResultsProps) {
+ if (!breaking) return null;
+ const sorted = sortChangesBySeverity(breaking.changes);
+ return (
+ <OverviewSection
+ title="Breaking changes"
+ description={`${breakingChangeSummary(breaking)} in the most recent update. A consumer is marked exposed when it links to the changed endpoint; that does not prove it uses the changed field.`}
+ >
+ <div className="border-t border-[var(--color-border-default)]">
+ {sorted.map((change) => (
+ <BreakingChangeRow
+ key={breakingChangeKey(change)}
+ change={change}
+ onSelectNode={(id) => onSelect({ type: "node", id })}
+ />
+ ))}
+ </div>
+ </OverviewSection>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Conformance
+// ---------------------------------------------------------------------------
+
+function ConformanceResults({ conformance, graph, onSelect, onPrompt, conformanceHref, LinkComponent }: WithPrompt) {
+ if (!conformance) return null;
+ const name = (id: string) => graph.nodes.find((n) => n.id === id)?.name ?? id;
+ const total = conformance.total_cycles ?? conformance.cycle_count;
+ const A = LinkComponent ?? "a";
+ const rules =
+ conformance.rules_evaluated === 0
+ ? "No dependency rules are declared, so only cycles are checked."
+ : `${plural(conformance.rules_evaluated, "rule", "rules")} checked, ${plural(conformance.violation_count, "violation", "violations")}.`;
+ const cycles =
+ total > conformance.cycle_count
+ ? `${conformance.cycle_count} of ${plural(total, "dependency cycle", "dependency cycles")} listed.`
+ : `${plural(conformance.cycle_count, "dependency cycle", "dependency cycles")}.`;
+
+ return (
+ <OverviewSection
+ title="Conformance"
+ description={`${rules} ${cycles}`}
+ action={
+ conformanceHref ? (
+ <A href={conformanceHref} className="whitespace-nowrap text-xs font-medium text-[var(--color-accent-primary)] hover:underline">
+ Dependency matrix →
+ </A>
+ ) : undefined
+ }
+ >
+ <ul className="m-0 flex list-none flex-col divide-y divide-[var(--color-border-default)] border-t border-[var(--color-border-default)] p-0">
+ {conformance.violations.length > 0 && (
+ <li className="flex flex-wrap items-center justify-between gap-3 py-3">
+ <span className="text-[15px] text-[var(--color-text-primary)]">
+ {plural(conformance.violations.length, "dependency breaks", "dependencies break")} a declared rule.
+ </span>
+ <AiPromptButton
+ label="Fix violations"
+ onClick={() =>
+ onPrompt({
+ title: "AI conformance fix",
+ description: "A ready-to-paste prompt that has your agent remove the dependencies your rules forbid.",
+ build: (flavor) => buildConformanceAiPrompt({ violations: conformance.violations, flavor }),
+ })
+ }
+ />
+ </li>
+ )}
+ {conformance.violations.map((v) => (
+ <li key={`${v.edge_id}:${v.rule_source}:${v.rule_target}`} className="flex flex-wrap items-baseline gap-x-2 gap-y-1 py-2.5 text-[15px]">
+ <span className="inline-flex items-center gap-1.5">
+ <span aria-hidden className="h-1.5 w-1.5 rounded-full bg-[var(--color-error)]" />
+ <span className="text-xs text-[var(--color-text-secondary)]">Violation</span>
+ </span>
+ <NodeLink id={v.source} label={v.source_name || name(v.source)} onSelect={onSelect} />
+ <span aria-hidden>→</span>
+ <NodeLink id={v.target} label={v.target_name || name(v.target)} onSelect={onSelect} />
+ <span className="font-mono text-xs text-[var(--color-text-tertiary)]">
+ breaks {v.rule_source} !-&gt; {v.rule_target}
+ </span>
+ </li>
+ ))}
+ {conformance.cycles.map((c) => (
+ <CycleRow key={c.edge_ids.join("|")} cycle={c} graph={graph} onSelect={onSelect} onPrompt={onPrompt} />
+ ))}
+ </ul>
+ </OverviewSection>
+ );
+}
+
+export function NodeLink({
+ id,
+ label,
+ onSelect,
+}: {
+ id: string;
+ label: string;
+ onSelect: (s: SystemMapSelection) => void;
+}) {
+ return (
+ <button
+ type="button"
+ onClick={() => onSelect({ type: "node", id })}
+ className="cursor-pointer font-medium text-[var(--color-accent-primary)] hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ >
+ {label}
+ </button>
+ );
+}
+
+export function CycleRow({
+ cycle,
+ graph,
+ onSelect,
+ onPrompt,
+}: {
+ cycle: ConformanceReport["cycles"][number];
+ graph: SystemGraph;
+ onSelect: (s: SystemMapSelection) => void;
+ onPrompt: (p: SystemMapPromptState) => void;
+}) {
+ const name = (id: string) => graph.nodes.find((n) => n.id === id)?.name ?? id;
+ return (
+ <li className="flex flex-wrap items-center justify-between gap-3 py-3">
+ <div className="flex min-w-0 flex-col gap-1">
+ <span className="flex flex-wrap items-center gap-x-2 gap-y-1 text-[15px] text-[var(--color-text-primary)]">
+ <span className="inline-flex items-center gap-1.5">
+ <span aria-hidden className="h-1.5 w-1.5 rounded-full bg-[var(--color-warning)]" />
+ <span className="text-xs text-[var(--color-text-secondary)]">Cycle</span>
+ </span>
+ {cycle.nodes.map((id) => (
+ <span key={id} className="inline-flex items-center gap-2">
+ <NodeLink id={id} label={name(id)} onSelect={onSelect} />
+ <span aria-hidden className="text-[var(--color-text-tertiary)]">→</span>
+ </span>
+ ))}
+ <NodeLink id={cycle.nodes[0] ?? ""} label={name(cycle.nodes[0] ?? "")} onSelect={onSelect} />
+ </span>
+ <span className="flex flex-wrap gap-x-3 text-xs text-[var(--color-text-secondary)]">
+ {`${plural(cycle.length, "service depends", "services depend")} on each other, so none can change a contract, build or deploy alone. Edges:`}
+ {cycle.edge_ids.map((eid) => {
+ const e = graph.edges.find((x) => x.id === eid);
+ return (
+ <button
+ key={eid}
+ type="button"
+ onClick={() => onSelect({ type: "edge", id: eid })}
+ className="cursor-pointer font-mono text-[var(--color-accent-primary)] hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ >
+ {e ? `${name(e.source)} → ${name(e.target)} ${edgeKindStyle(e.kind).label}` : eid}
+ </button>
+ );
+ })}
+ </span>
+ </div>
+ <AiPromptButton label="Break the cycle" onClick={() => onPrompt(cyclePrompt(cycle, graph))} />
+ </li>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Core and roles
+// ---------------------------------------------------------------------------
+
+function CoreResults({ architecture, graph, selection, onSelect }: SystemMapLensResultsProps) {
+ if (!architecture) return null;
+ const name = (id: string) => graph.nodes.find((n) => n.id === id)?.name ?? id;
+ const roles = [...architecture.roles].sort(
+ (a, b) =>
+ ROLE_ORDER.indexOf(a.role) - ROLE_ORDER.indexOf(b.role) ||
+ b.visibility_fan_in - a.visibility_fan_in ||
+ a.name.localeCompare(b.name),
+ );
+ const breakdown = ROLE_ORDER.filter((r) => (architecture.role_breakdown[r] ?? 0) > 0)
+ .map((r) => `${architecture.role_breakdown[r]} ${roleStyle(r).label.toLowerCase()}`)
+ .join(", ");
+ const core = architecture.core_members.map(name);
+ const description =
+ architecture.core_size === 0
+ ? `No services form a cycle, so there is no cyclic core. Roles: ${breakdown}.`
+ : `${core.join(" and ")} form the cyclic core: ${architecture.core_size} of ${architecture.node_count} services that all reach each other through contracts or imports. Roles: ${breakdown}. Reach counts other services along structural dependencies.`;
+
+ const columns: ResponsiveColumn<NodeArchitectureRole>[] = [
+ {
+ key: "name",
+ header: "Service",
+ priority: 1,
+ render: (r) => (
+ <span className="flex flex-col">
+ <span className="text-[15px] font-medium text-[var(--color-text-primary)]">{r.name}</span>
+ <span className="font-mono text-[10px] text-[var(--color-text-tertiary)]">{r.repo}</span>
+ </span>
+ ),
+ },
+ {
+ key: "role",
+ header: "Role",
+ priority: 1,
+ render: (r) => (
+ <span title={roleStyle(r.role).description} className="text-[var(--color-text-primary)]">
+ {roleStyle(r.role).label}
+ </span>
+ ),
+ },
+ {
+ key: "reaches",
+ header: "Reaches",
+ align: "right",
+ priority: 2,
+ render: (r) => <span className="tabular-nums">{Math.max(r.visibility_fan_out - 1, 0)}</span>,
+ },
+ {
+ key: "reached",
+ header: "Reached by",
+ align: "right",
+ priority: 2,
+ render: (r) => <span className="tabular-nums">{Math.max(r.visibility_fan_in - 1, 0)}</span>,
+ },
+ ];
+
+ return (
+ <OverviewSection title="Architectural core and roles" description={description}>
+ <ResponsiveTable
+ columns={columns}
+ rows={roles}
+ rowKey={(r) => r.id}
+ onRowClick={(r) => onSelect({ type: "node", id: r.id })}
+ selectedKey={selection?.type === "node" ? selection.id : null}
+ caption="Architecture role of each service"
+ virtualize={{ threshold: 60, maxHeight: 520 }}
+ />
+ </OverviewSection>
+ );
+}
diff --git a/packages/ui/src/workspace/system-map/system-map-lens.tsx b/packages/ui/src/workspace/system-map/system-map-lens.tsx
new file mode 100644
index 000000000..80d07a63a
--- /dev/null
+++ b/packages/ui/src/workspace/system-map/system-map-lens.tsx
@@ -0,0 +1,76 @@
+"use client";
+
+/**
+ * The lens: what the map is currently answering. Blast radius, breaking
+ * changes, conformance and the cyclic core each recolour the same canvas, so
+ * they are one axis and one control. The blast-radius target picker appears
+ * only while that lens is on, because it means nothing otherwise.
+ */
+
+import type { SystemNode } from "@repowise-dev/types";
+import { MICRO_LABEL, Segmented, type SegmentOption } from "./system-map-filters";
+
+export type SystemMapLens = "none" | "blast" | "breaking" | "conformance" | "core";
+
+export interface SystemMapLensControlProps {
+ value: SystemMapLens;
+ /** Options after the host has decided counts and disabled reasons. */
+ options: SegmentOption<SystemMapLens>[];
+ onChange: (lens: SystemMapLens) => void;
+ /** Services the blast radius can start from. */
+ nodes: readonly SystemNode[];
+ blastTarget: string | null;
+ onBlastTargetChange: (id: string | null) => void;
+ includeBehavioral: boolean;
+ onIncludeBehavioralChange: (include: boolean) => void;
+}
+
+export function SystemMapLensControl({
+ value,
+ options,
+ onChange,
+ nodes,
+ blastTarget,
+ onBlastTargetChange,
+ includeBehavioral,
+ onIncludeBehavioralChange,
+}: SystemMapLensControlProps) {
+ const sorted = [...nodes].sort((a, b) => a.repo.localeCompare(b.repo) || a.name.localeCompare(b.name));
+
+ return (
+ <div className="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-2">
+ <span className={MICRO_LABEL}>Lens</span>
+ <Segmented label="Map lens" value={value} options={options} onChange={onChange} />
+ {value === "blast" && (
+ <>
+ <label className="inline-flex min-w-0 items-center gap-1.5 text-xs text-[var(--color-text-secondary)]">
+ <span className="sr-only">Service the change starts in</span>
+ <span aria-hidden>If</span>
+ <select
+ value={blastTarget ?? ""}
+ onChange={(e) => onBlastTargetChange(e.target.value || null)}
+ className="min-w-0 max-w-[16rem] rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2 py-1 text-xs text-[var(--color-text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ >
+ <option value="">choose a service</option>
+ {sorted.map((n) => (
+ <option key={n.id} value={n.id}>
+ {n.service_path ? `${n.repo} / ${n.name}` : n.name}
+ </option>
+ ))}
+ </select>
+ <span aria-hidden>changes</span>
+ </label>
+ <label className="inline-flex items-center gap-1.5 text-xs text-[var(--color-text-secondary)]">
+ <input
+ type="checkbox"
+ checked={includeBehavioral}
+ onChange={(e) => onIncludeBehavioralChange(e.target.checked)}
+ className="accent-[var(--color-accent-primary)]"
+ />
+ Include co-change
+ </label>
+ </>
+ )}
+ </div>
+ );
+}
diff --git a/packages/ui/src/workspace/system-map/system-map-model.ts b/packages/ui/src/workspace/system-map/system-map-model.ts
new file mode 100644
index 000000000..bc5d079d7
--- /dev/null
+++ b/packages/ui/src/workspace/system-map/system-map-model.ts
@@ -0,0 +1,420 @@
+/**
+ * Pure joins the System Map's drawer, findings and prompts read from. The
+ * system graph names services; contracts, links and diagnostics name files.
+ * Everything here maps one onto the other, so the drawer, the rows below the
+ * map and the AI prompts count the same things the same way.
+ */
+
+import type {
+ DependencyCycle,
+ ExtractionDiagnostics,
+ SystemEdge,
+ SystemEdgeKind,
+ SystemGraph,
+ SystemNode,
+ WorkspaceContractLinkEntry,
+} from "@repowise-dev/types/workspace";
+
+/** The contract fields the map reads. Structural, so the host's wire type fits. */
+export interface SystemMapContract {
+ contract_id: string;
+ contract_type: string;
+ role: string;
+ repo: string;
+ file_path: string;
+ line?: number | null;
+ symbol_name?: string;
+}
+
+/** Everything the host fetched about one repository's contracts. */
+export interface SystemMapRepoContracts {
+ contracts: SystemMapContract[];
+ links: WorkspaceContractLinkEntry[];
+ /** Contracts the repo declares; above `contracts.length` when the fetch was capped. */
+ total: number;
+}
+
+// ---------------------------------------------------------------------------
+// Health: the canonical three bands beside a health mark.
+// ---------------------------------------------------------------------------
+
+export interface HealthMark {
+ /** 0-10, one decimal. */
+ value: string;
+ label: "Healthy" | "Warning" | "Alert";
+ color: string;
+}
+
+/** Repo health arrives 0-100; the product reads it 0-10 in three bands. */
+export function healthMark(score100: number): HealthMark {
+ const score = score100 / 10;
+ const value = score.toFixed(1);
+ if (score >= 8) return { value, label: "Healthy", color: "var(--color-success)" };
+ if (score >= 4) return { value, label: "Warning", color: "var(--color-warning)" };
+ return { value, label: "Alert", color: "var(--color-error)" };
+}
+
+// ---------------------------------------------------------------------------
+// Files to services.
+// ---------------------------------------------------------------------------
+
+/**
+ * Resolves `(repo, file)` to the node that owns it on the drawn graph. A file
+ * belongs to the deepest declared service path containing it, else to the
+ * repo-root node; in repo view every file belongs to its repo.
+ */
+export type ServiceResolver = (repo: string, file: string) => string;
+
+export function serviceResolver(graph: SystemGraph, collapsed: boolean): ServiceResolver {
+ if (collapsed) return (repo) => repo;
+ const paths = new Map<string, string[]>();
+ for (const n of graph.nodes) {
+ if (!n.service_path) continue;
+ const list = paths.get(n.repo) ?? [];
+ list.push(n.service_path);
+ paths.set(n.repo, list);
+ }
+ // Longest first, so a nested service wins over its parent.
+ for (const list of paths.values()) list.sort((a, b) => b.length - a.length);
+ return (repo, file) => {
+ for (const p of paths.get(repo) ?? []) {
+ if (file === p || file.startsWith(`${p}/`)) return `${repo}::${p}`;
+ }
+ return repo;
+ };
+}
+
+// ---------------------------------------------------------------------------
+// A service's contracts.
+// ---------------------------------------------------------------------------
+
+export interface ServiceContractRow extends SystemMapContract {
+ /** Matched links this contract takes part in, on its own side. */
+ link_count: number;
+}
+
+export interface ServiceContractSummary {
+ provides: Record<string, number>;
+ consumes: Record<string, number>;
+ providedTotal: number;
+ consumedTotal: number;
+ /** Linked contracts first, then providers, then by id. */
+ rows: ServiceContractRow[];
+}
+
+function linkKey(repo: string, file: string, id: string): string {
+ return `${repo}\u0000${file}\u0000${id}`;
+}
+
+export function summarizeServiceContracts(
+ data: SystemMapRepoContracts,
+ nodeId: string,
+ resolve: ServiceResolver,
+): ServiceContractSummary {
+ const linkCount = new Map<string, number>();
+ for (const lk of data.links) {
+ const p = linkKey(lk.provider_repo, lk.provider_file, lk.contract_id);
+ const c = linkKey(lk.consumer_repo, lk.consumer_file, lk.contract_id);
+ linkCount.set(p, (linkCount.get(p) ?? 0) + 1);
+ linkCount.set(c, (linkCount.get(c) ?? 0) + 1);
+ }
+
+ const provides: Record<string, number> = {};
+ const consumes: Record<string, number> = {};
+ const rows: ServiceContractRow[] = [];
+ const seen = new Set<string>();
+ for (const c of data.contracts) {
+ if (resolve(c.repo, c.file_path) !== nodeId) continue;
+ const bucket = c.role === "consumer" ? consumes : provides;
+ bucket[c.contract_type] = (bucket[c.contract_type] ?? 0) + 1;
+ // One file can declare the same id twice; the Contracts page keys on the
+ // triple, so the list does too.
+ const key = linkKey(c.repo, c.file_path, c.contract_id);
+ if (seen.has(key)) continue;
+ seen.add(key);
+ rows.push({ ...c, link_count: linkCount.get(key) ?? 0 });
+ }
+ rows.sort(
+ (a, b) =>
+ b.link_count - a.link_count ||
+ Number(a.role === "consumer") - Number(b.role === "consumer") ||
+ a.contract_id.localeCompare(b.contract_id),
+ );
+
+ const sum = (r: Record<string, number>) => Object.values(r).reduce((a, b) => a + b, 0);
+ return { provides, consumes, providedTotal: sum(provides), consumedTotal: sum(consumes), rows };
+}
+
+// ---------------------------------------------------------------------------
+// A service's diagnostics.
+// ---------------------------------------------------------------------------
+
+export interface ServiceDiagnostics {
+ unmatched: number;
+ unmatchedByReason: Record<string, number>;
+ unusedProviders: number;
+}
+
+export function serviceDiagnostics(
+ diagnostics: ExtractionDiagnostics | null | undefined,
+ nodeId: string,
+ resolve: ServiceResolver,
+): ServiceDiagnostics {
+ const out: ServiceDiagnostics = { unmatched: 0, unmatchedByReason: {}, unusedProviders: 0 };
+ if (!diagnostics) return out;
+ for (const u of diagnostics.unmatched_consumers ?? []) {
+ if (resolve(u.repo, u.file_path) !== nodeId) continue;
+ out.unmatched += 1;
+ out.unmatchedByReason[u.reason] = (out.unmatchedByReason[u.reason] ?? 0) + 1;
+ }
+ for (const o of diagnostics.orphan_providers ?? []) {
+ if (resolve(o.repo, o.file_path) === nodeId) out.unusedProviders += 1;
+ }
+ return out;
+}
+
+// ---------------------------------------------------------------------------
+// An edge's evidence.
+// ---------------------------------------------------------------------------
+
+/** The contract type each structural edge kind is built from. */
+const KIND_CONTRACT_TYPE: Partial<Record<SystemEdgeKind, string>> = {
+ http: "http",
+ grpc: "grpc",
+ socket: "socket",
+ event: "topic",
+ package: "code",
+ db: "data",
+};
+
+/**
+ * The matched links an edge aggregates. Edge direction is consumer to
+ * provider, so the link's consumer must resolve to the source and its provider
+ * to the target. The edge's own refs are capped; the links are not.
+ */
+export function edgeLinks(
+ edge: SystemEdge,
+ links: readonly WorkspaceContractLinkEntry[],
+ resolve: ServiceResolver,
+): WorkspaceContractLinkEntry[] {
+ if (!edge.structural) return [];
+ const type = KIND_CONTRACT_TYPE[edge.kind];
+ const refs = new Set(edge.contract_refs);
+ const seen = new Set<string>();
+ const out: WorkspaceContractLinkEntry[] = [];
+ for (const lk of links) {
+ if (type ? lk.contract_type !== type : !refs.has(lk.contract_id)) continue;
+ if (resolve(lk.consumer_repo, lk.consumer_file) !== edge.source) continue;
+ if (resolve(lk.provider_repo, lk.provider_file) !== edge.target) continue;
+ const key = `${linkKey(lk.provider_repo, lk.provider_file, lk.contract_id)}\u0000${lk.consumer_file}`;
+ if (seen.has(key)) continue;
+ seen.add(key);
+ out.push(lk);
+ }
+ out.sort((a, b) => a.contract_id.localeCompare(b.contract_id));
+ return out;
+}
+
+/** Co-change refs are `source_file~target_file`. */
+export function coChangePairs(edge: SystemEdge): [string, string | null][] {
+ return edge.contract_refs.map((ref) => {
+ const split = ref.indexOf("~");
+ return split === -1 ? [ref, null] : [ref.slice(0, split), ref.slice(split + 1)];
+ });
+}
+
+/** 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)];
+}
+
+// ---------------------------------------------------------------------------
+// Words.
+// ---------------------------------------------------------------------------
+
+/** What an edge's weight counts, singular and plural. */
+const WEIGHT_UNIT: Record<SystemEdgeKind, [string, string]> = {
+ http: ["endpoint called", "endpoints called"],
+ grpc: ["method called", "methods called"],
+ socket: ["socket channel", "socket channels"],
+ event: ["topic", "topics"],
+ package: ["symbol imported", "symbols imported"],
+ db: ["table use", "table uses"],
+ co_change: ["file pair changed together", "file pairs changed together"],
+};
+
+export function weightLabel(edge: Pick<SystemEdge, "kind" | "weight">): string {
+ const unit = WEIGHT_UNIT[edge.kind] ?? ["contract", "contracts"];
+ return `${edge.weight.toLocaleString()} ${edge.weight === 1 ? unit[0] : unit[1]}`;
+}
+
+/** The canvas label's unit: short, because it sits on a line between two boxes. */
+const SHORT_UNIT: Record<SystemEdgeKind, string> = {
+ http: "endpoints",
+ grpc: "methods",
+ socket: "channels",
+ event: "topics",
+ package: "symbols",
+ db: "table uses",
+ co_change: "file pairs",
+};
+
+export function weightShort(edge: Pick<SystemEdge, "kind" | "weight">): string {
+ return `${edge.weight.toLocaleString()} ${SHORT_UNIT[edge.kind] ?? "contracts"}`;
+}
+
+/** The relationship as a sentence a developer would say. */
+export function edgeSentence(
+ edge: Pick<SystemEdge, "kind">,
+ source: string,
+ target: string,
+): string {
+ switch (edge.kind) {
+ case "http":
+ return `${source} calls ${target} over HTTP.`;
+ case "grpc":
+ return `${source} calls ${target} over gRPC.`;
+ case "socket":
+ return `${source} connects to ${target} over a socket.`;
+ case "event":
+ return `${source} consumes events ${target} publishes.`;
+ case "package":
+ return `${source} imports code from ${target}.`;
+ case "db":
+ return `${source} uses database tables ${target} defines.`;
+ case "co_change":
+ return `Files in ${source} and ${target} change in the same commits.`;
+ default:
+ return `${source} depends on ${target}.`;
+ }
+}
+
+export const STRUCTURAL_MEANING =
+ "Structural: a contract or import in code. Changing the provider side can break the consumer.";
+export const BEHAVIORAL_MEANING =
+ "Behavioral: a pattern in git history, not a call. These services tend to change together, which does not prove one depends on the other.";
+
+// ---------------------------------------------------------------------------
+// Cycles and neighbours.
+// ---------------------------------------------------------------------------
+
+export function cyclesThrough(cycles: readonly DependencyCycle[], nodeId: string): DependencyCycle[] {
+ return cycles.filter((c) => c.nodes.includes(nodeId));
+}
+
+export function cyclesWithEdge(cycles: readonly DependencyCycle[], edgeId: string): DependencyCycle[] {
+ return cycles.filter((c) => c.edge_ids.includes(edgeId));
+}
+
+export interface NeighbourGroup {
+ kind: SystemEdgeKind;
+ edges: SystemEdge[];
+}
+
+/** A node's edges in one direction, grouped by kind, heaviest first. */
+export function neighbourGroups(
+ graph: SystemGraph,
+ nodeId: string,
+ direction: "out" | "in",
+): NeighbourGroup[] {
+ const byKind = new Map<SystemEdgeKind, SystemEdge[]>();
+ for (const e of graph.edges) {
+ if ((direction === "out" ? e.source : e.target) !== nodeId) continue;
+ const list = byKind.get(e.kind) ?? [];
+ list.push(e);
+ byKind.set(e.kind, list);
+ }
+ const groups = [...byKind.entries()].map(([kind, edges]) => ({
+ kind,
+ edges: edges.sort((a, b) => b.weight - a.weight),
+ }));
+ // Structural before behavioral, then by how much rides on the group.
+ groups.sort(
+ (a, b) =>
+ Number(a.kind === "co_change") - Number(b.kind === "co_change") ||
+ b.edges.reduce((s, e) => s + e.weight, 0) - a.edges.reduce((s, e) => s + e.weight, 0),
+ );
+ return groups;
+}
+
+export function nodeName(graph: SystemGraph, id: string): string {
+ return graph.nodes.find((n) => n.id === id)?.name ?? id;
+}
+
+/** Where a service lives: "repo / service/path", or "repo repository" for a repo root. */
+export function nodeLocation(node: Pick<SystemNode, "repo" | "service_path">): string {
+ return node.service_path ? `${node.repo} / ${node.service_path}` : `${node.repo} repository`;
+}
+
+// ---------------------------------------------------------------------------
+// Shared wording.
+// ---------------------------------------------------------------------------
+
+export function plural(n: number, one: string, many: string): string {
+ return `${n.toLocaleString()} ${n === 1 ? one : many}`;
+}
+
+/** Why a consumer matched no provider, as the tail of "N calls ...". */
+const UNMATCHED_REASON: Record<string, string> = {
+ no_provider: "have no provider anywhere",
+ external_host: "call a third-party host",
+ internal_only: "stay inside their own service",
+ unlinked: "have a provider that did not link",
+};
+
+/** "54 have no provider anywhere, 26 call a third-party host", largest first. */
+export function unmatchedReasonList(byReason: Record<string, number>): string {
+ return Object.entries(byReason)
+ .sort((a, b) => b[1] - a[1])
+ .map(([r, n]) => `${n.toLocaleString()} ${UNMATCHED_REASON[r] ?? r}`)
+ .join(", ");
+}
+
+// ---------------------------------------------------------------------------
+// Selections against the drawn graph.
+// ---------------------------------------------------------------------------
+
+export type ViewSelectionFix = { kind: "show-edge-kind"; edgeKind: SystemEdgeKind } | { kind: "expand" } | null;
+
+/**
+ * Lists below the map, and the URL, name raw service and edge ids. The drawn
+ * graph may be collapsed to repositories or missing a hidden edge kind. Maps
+ * the selection onto what is drawn, or says what the map must change to draw
+ * it: show a hidden kind, or return to the service view for an edge inside
+ * one repository.
+ */
+export function resolveViewSelection(
+ selection: { type: "node" | "edge"; id: string } | null,
+ raw: SystemGraph,
+ view: SystemGraph,
+ collapsed: boolean,
+): { selection: { type: "node" | "edge"; id: string } | null; fix: ViewSelectionFix } {
+ if (!selection) return { selection: null, fix: null };
+ const drawn =
+ selection.type === "node"
+ ? view.nodes.some((n) => n.id === selection.id)
+ : view.edges.some((e) => e.id === selection.id);
+ if (drawn) return { selection, fix: null };
+
+ const repoOf = (id: string) => raw.nodes.find((n) => n.id === id)?.repo;
+ if (selection.type === "node") {
+ const repo = collapsed ? repoOf(selection.id) : undefined;
+ return { selection: repo ? { type: "node", id: repo } : null, fix: null };
+ }
+
+ const edge = raw.edges.find((e) => e.id === selection.id);
+ if (!edge) {
+ // A collapsed id whose kind is hidden.
+ const kind = selection.id.split("::").pop() as SystemEdgeKind | undefined;
+ const known = kind && raw.edges.some((e) => e.kind === kind);
+ return { selection: null, fix: collapsed && known ? { kind: "show-edge-kind", edgeKind: kind } : null };
+ }
+ if (!collapsed) return { selection: null, fix: { kind: "show-edge-kind", edgeKind: edge.kind } };
+ const src = repoOf(edge.source);
+ const tgt = repoOf(edge.target);
+ if (!src || !tgt || src === tgt) return { selection: null, fix: { kind: "expand" } };
+ const merged = `${src}->${tgt}::${edge.kind}`;
+ return view.edges.some((e) => e.id === merged)
+ ? { selection: { type: "edge", id: merged }, fix: null }
+ : { selection: null, fix: { kind: "show-edge-kind", edgeKind: edge.kind } };
+}
diff --git a/packages/ui/src/workspace/system-map/system-map-node.tsx b/packages/ui/src/workspace/system-map/system-map-node.tsx
index 3781092ad..6d0a09d57 100644
--- a/packages/ui/src/workspace/system-map/system-map-node.tsx
+++ b/packages/ui/src/workspace/system-map/system-map-node.tsx
@@ -1,93 +1,161 @@
"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.
+ * A service on the Live System Map: a surface-plane object with a hairline
+ * border, named in full, with where it lives, its repository's health mark in
+ * the canonical three bands, and how many contracts it provides and consumes.
+ *
+ * The architecture role is a word, not a colour: the health mark already owns
+ * green, amber and red on this object, and a second mark in the same
+ * vocabulary would read as a second health reading.
*/
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 { Handle, Position, type NodeProps } from "@xyflow/react";
+import { healthMark } from "./system-map-model";
+import { SYSTEM_MAP_NODE_SIZE } from "./layout";
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 badgeColor(tone: "danger" | "warning" | "info"): string {
+ if (tone === "danger") return "var(--color-error)";
+ if (tone === "warning") return "var(--color-warning)";
+ return "var(--color-text-secondary)";
}
-function Flag({ label, title, tone }: { label: string; title: string; tone: "danger" | "warning" | "info" }) {
- const color = flagColor(tone);
+function SystemMapNodeInner({ data, selected }: NodeProps) {
+ const { node, health, overlay, role } = data as unknown as SystemMapNodeData;
+ const mark = health ? healthMark(health.score) : null;
+ const lensed = overlay?.highlighted ?? false;
+ const dimmed = overlay?.dimmed ?? false;
+ const where = node.service_path ? `${node.repo} / ${node.service_path}` : `${node.repo} repository`;
+
+ const border = selected
+ ? "var(--color-accent-primary)"
+ : lensed
+ ? "var(--color-text-primary)"
+ : "var(--color-border-hover)";
+
return (
- <span
- title={title}
+ <div
+ className="sm-node"
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,
+ position: "relative",
+ width: SYSTEM_MAP_NODE_SIZE.width,
+ height: SYSTEM_MAP_NODE_SIZE.height,
+ boxSizing: "border-box",
+ display: "flex",
+ flexDirection: "column",
+ gap: 3,
+ padding: "9px 12px",
+ borderRadius: 8,
+ background: "var(--color-bg-surface)",
+ border: `1px solid ${border}`,
+ boxShadow: selected ? "0 0 0 2px color-mix(in srgb, var(--color-accent-primary) 35%, transparent)" : "var(--shadow-sm)",
+ opacity: dimmed ? 0.35 : 1,
+ cursor: "pointer",
+ transition: "opacity 120ms, border-color 120ms",
}}
>
- {label}
- </span>
- );
-}
+ <Handle type="target" position={Position.Top} style={{ opacity: 0, pointerEvents: "none" }} />
-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} />
+ <span
+ style={{
+ position: "absolute",
+ top: -9,
+ right: 10,
+ padding: "0 6px",
+ borderRadius: 4,
+ background: "var(--color-bg-surface)",
+ border: `1px solid ${badgeColor(overlay.badge.tone)}`,
+ color: badgeColor(overlay.badge.tone),
+ fontFamily: "var(--font-mono, ui-monospace, monospace)",
+ fontSize: 10,
+ lineHeight: "16px",
+ fontWeight: 600,
+ }}
+ >
+ {overlay.badge.label}
+ </span>
)}
- {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 style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", gap: 8, minWidth: 0 }}>
+ <span
+ title={node.name}
+ style={{
+ minWidth: 0,
+ overflow: "hidden",
+ textOverflow: "ellipsis",
+ whiteSpace: "nowrap",
+ fontSize: 15,
+ lineHeight: "20px",
+ fontWeight: 600,
+ color: "var(--color-text-primary)",
+ }}
+ >
+ {node.name}
+ </span>
+ {role && (
+ <span
+ style={{
+ flexShrink: 0,
+ fontFamily: "var(--font-mono, ui-monospace, monospace)",
+ fontSize: 10,
+ letterSpacing: "0.08em",
+ textTransform: "uppercase",
+ color: "var(--color-text-tertiary)",
+ }}
+ >
+ {role}
+ </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}
- />
+ <span
+ title={where}
+ style={{
+ overflow: "hidden",
+ textOverflow: "ellipsis",
+ whiteSpace: "nowrap",
+ fontFamily: "var(--font-mono, ui-monospace, monospace)",
+ fontSize: 10,
+ lineHeight: "14px",
+ color: "var(--color-text-tertiary)",
+ }}
+ >
+ {where}
+ </span>
+
+ <div style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 12, lineHeight: "16px" }}>
+ {mark ? (
+ <>
+ <span aria-hidden style={{ width: 6, height: 6, borderRadius: 999, background: mark.color, flexShrink: 0 }} />
+ <span style={{ fontVariantNumeric: "tabular-nums", color: "var(--color-text-primary)", fontWeight: 600 }}>
+ {mark.value}
+ </span>
+ <span style={{ color: "var(--color-text-secondary)" }}>{mark.label}</span>
+ </>
+ ) : (
+ <span style={{ color: "var(--color-text-tertiary)" }}>No health score</span>
+ )}
+ </div>
+
+ <span
+ style={{
+ fontFamily: "var(--font-mono, ui-monospace, monospace)",
+ fontSize: 10,
+ lineHeight: "14px",
+ fontVariantNumeric: "tabular-nums",
+ color: "var(--color-text-secondary)",
+ }}
+ >
+ {node.is_isolated
+ ? "no cross-service edges"
+ : `${node.provider_count.toLocaleString()} provided · ${node.consumer_count.toLocaleString()} consumed`}
+ </span>
+
+ <Handle type="source" position={Position.Bottom} style={{ opacity: 0, pointerEvents: "none" }} />
+ </div>
);
}
diff --git a/packages/ui/src/workspace/system-map/system-map-rail.tsx b/packages/ui/src/workspace/system-map/system-map-rail.tsx
index fc542f934..e2fcd03f4 100644
--- a/packages/ui/src/workspace/system-map/system-map-rail.tsx
+++ b/packages/ui/src/workspace/system-map/system-map-rail.tsx
@@ -1,16 +1,10 @@
"use client";
/**
- * Shared shell for everything in the System Map's rail: the inspector and the
- * blast-radius / breaking-change / conformance panels.
- *
- * These were four independently-written `position: absolute` cards floating on
- * the canvas, three of which claimed the same top-right corner and physically
- * stacked on each other whenever a selection and an overlay were both active.
- * A diagram is the one thing on its page that cannot be read past, so the rail
- * is now a grid peer of the canvas (see `SystemMap`) and a panel is just a card
- * in a column. Nothing here positions itself; the rail owns placement and the
- * single scroll region, so panels never grow their own nested scrollbar.
+ * Card shell for the blast-radius, breaking-change and conformance rail panels.
+ * The OSS map lists lens results below the canvas instead; these stay for
+ * hosts that still render a rail beside it. `RailChip` is also used by
+ * `BreakingChangeRow`.
*/
import { X } from "lucide-react";
@@ -38,24 +32,6 @@ export function RailEyebrow({ children }: { children: React.ReactNode }) {
);
}
-/** Label/value row used by the inspector's fact lists. */
-export function RailField({
- label,
- value,
-}: {
- label: string;
- value: React.ReactNode;
-}) {
- return (
- <div className="flex justify-between gap-3 py-[3px]">
- <span className="text-[var(--color-text-tertiary)]">{label}</span>
- <span className="break-words text-right text-[var(--color-text-primary)]">
- {value}
- </span>
- </div>
- );
-}
-
/**
* Severity chip. Replaces four hand-rolled copies of the same colour-mix pill.
* The caller passes the token so the chip stays in whatever colour band its
diff --git a/packages/ui/src/workspace/system-map/system-map.tsx b/packages/ui/src/workspace/system-map/system-map.tsx
index c3577908f..dc1346bbf 100644
--- a/packages/ui/src/workspace/system-map/system-map.tsx
+++ b/packages/ui/src/workspace/system-map/system-map.tsx
@@ -1,16 +1,17 @@
"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.
+ * The Live System Map: a code-derived diagram of the workspace's services
+ * (nodes) and their typed relationships (edges), laid out with the shared ELK
+ * stack and explored through a detail drawer.
+ *
+ * A canvas surface: the controls sit in the section header, the key in one
+ * row under them, and the canvas takes the width. The host supplies the graph,
+ * the lens control (`toolbar`) and the drawer's data; this component owns the
+ * edge-kind filter, the service/repository switch, hover and selection.
*/
-import { useCallback, useMemo, useRef, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import {
Background,
BackgroundVariant,
@@ -18,41 +19,54 @@ import {
MiniMap,
ReactFlow,
ReactFlowProvider,
+ useReactFlow,
+ useStore,
+ type EdgeChange,
type EdgeMouseHandler,
+ type NodeChange,
type NodeMouseHandler,
} from "@xyflow/react";
import "@xyflow/react/dist/style.css";
-import type { NodeArchitectureRole, SystemEdgeKind, SystemGraph } from "@repowise-dev/types";
+import type { NodeArchitectureRole, SystemEdgeKind, SystemEdgeMatchType, 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 { SystemMapDrawer, type SystemMapDrawerData } from "./system-map-drawer";
+import { SystemMapFocusContext, createSystemMapFocusStore } from "./system-map-focus";
+import { edgeKindStyle } from "./edge-kinds";
import { useSystemMapLayout } from "./use-system-map-layout";
-import { SYSTEM_MAP_MAX_LAYOUT_NODES, type SystemMapView } from "./layout";
+import { resolveViewSelection } from "./system-map-model";
+import { SYSTEM_MAP_MAX_LAYOUT_NODES, SYSTEM_MAP_NODE_SIZE, applyCollapse, type SystemMapView } from "./layout";
import type { RepoHealth, SystemMapOverlay, SystemMapSelection } from "./types";
import { toFriendlyMessage } from "../../lib/errors";
+/** Below this many nodes the whole map fits on screen and a minimap is noise. */
+export const SYSTEM_MAP_MINIMAP_MIN_NODES = 40;
+
+/** The canvas's height, shared with the host's loading placeholder so nothing reflows. */
+export const SYSTEM_MAP_CANVAS_HEIGHT = "h-[420px] sm:h-[clamp(460px,calc(100dvh-240px),800px)]";
+
+/** Width the drawer takes on desktop; selections are kept clear of it. */
+const DRAWER_WIDTH = 480;
+
+const FIT_OPTIONS = { padding: 0.08, maxZoom: 1.2 } as const;
+
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). */
+ /** Additive decoration from the active lens (ripple, badges, violations). */
overlay?: SystemMapOverlay;
- /** Per-service architecture role + visibility, shown in the inspector (optional). */
+ /** Per-service architecture role, named on nodes and in the drawer (optional). */
roleByNodeId?: ReadonlyMap<string, NodeArchitectureRole>;
- /** Open a contract on the Contracts surface (edge drill-down). */
- onOpenContract?: (contractId: string) => void;
- /**
- * Host-owned cards for the map's rail (blast radius, breaking changes,
- * conformance). They share the rail with the inspector and its scroll
- * region, which is what stops them landing on the canvas or on each other.
- * Pass `null` when none are active so the rail column collapses.
- */
- rail?: React.ReactNode;
+ /** The lens control, placed at the head of the section header. */
+ toolbar?: ReactNode;
+ /** Data and routes for the detail drawer. */
+ drawer?: SystemMapDrawerData;
/** Controlled selection, so the host can put it in the URL. */
selection?: SystemMapSelection;
onSelectionChange?: (selection: SystemMapSelection) => void;
@@ -66,6 +80,10 @@ export function SystemMap(props: SystemMapProps) {
);
}
+function sameSelection(a: SystemMapSelection, b: SystemMapSelection): boolean {
+ return a?.type === b?.type && a?.id === b?.id;
+}
+
function SystemMapInner({
graph,
loading,
@@ -73,55 +91,110 @@ function SystemMapInner({
healthByRepo,
overlay,
roleByNodeId,
- onOpenContract,
- rail,
+ toolbar,
+ drawer,
selection: controlledSelection,
onSelectionChange,
}: 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 [uncontrolledSelection, setUncontrolledSelection] = useState<SystemMapSelection>(null);
const isControlled = onSelectionChange !== undefined;
const selection = isControlled ? (controlledSelection ?? null) : uncontrolledSelection;
- // The click handlers below are memoised for the component's lifetime, so
- // `setSelection` has to be stable too — a version that closed over the current
- // props would be captured once and then toggle against, and notify, whatever
- // was live at mount. Read the controlled props through a ref instead.
- const latest = useRef({ controlledSelection, onSelectionChange });
- latest.current = { controlledSelection, onSelectionChange };
-
- const setSelection = useCallback(
- (next: SystemMapSelection | ((cur: SystemMapSelection) => SystemMapSelection)) => {
- const { controlledSelection: current, onSelectionChange: notify } = latest.current;
- if (notify) {
- notify(typeof next === "function" ? next(current ?? null) : next);
- } else {
- setUncontrolledSelection(next);
- }
- },
- [],
- );
+ // Handlers below are memoised for the component's lifetime, so they read the
+ // live props through a ref. A click also fires React Flow's own selection
+ // change; `last` drops the duplicate so the host sees one update.
+ const latest = useRef({ selection, onSelectionChange });
+ latest.current = { selection, onSelectionChange };
+ const last = useRef<SystemMapSelection>(selection);
+ last.current = selection;
+
+ const setSelection = useCallback((next: SystemMapSelection) => {
+ if (sameSelection(last.current, next)) return;
+ last.current = next;
+ const notify = latest.current.onSelectionChange;
+ if (notify) notify(next);
+ else setUncontrolledSelection(next);
+ }, []);
+ // The collapse-applied shape, before the kind filter: what the filter offers.
+ const shaped = useMemo(() => (graph ? applyCollapse(graph, collapsed) : null), [graph, collapsed]);
+ const kindCounts = useMemo(() => {
+ const m = new Map<SystemEdgeKind, number>();
+ for (const e of shaped?.edges ?? []) m.set(e.kind, (m.get(e.kind) ?? 0) + 1);
+ return m;
+ }, [shaped]);
const visibleKinds = useMemo<Set<SystemEdgeKind>>(
- () => new Set([...availableKinds].filter((k) => !hiddenKinds.has(k))),
- [availableKinds, hiddenKinds],
+ () => new Set([...kindCounts.keys()].filter((k) => !hiddenKinds.has(k))),
+ [kindCounts, hiddenKinds],
);
-
const view = useMemo<SystemMapView>(() => ({ visibleKinds, collapsed }), [visibleKinds, collapsed]);
const { nodes, edges, loading: layoutLoading, viewGraph, simplified } = useSystemMapLayout({
graph,
view,
...(healthByRepo ? { healthByRepo } : {}),
- ...(overlay ? { overlay } : {}),
+ // Overlays are keyed by service; on merged repo nodes only the repo roots
+ // would match, which marks some repositories and not others. Off instead.
+ ...(overlay && !collapsed ? { overlay } : {}),
+ ...(roleByNodeId ? { roleByNodeId } : {}),
});
+ // Lists and the URL name raw ids; map them onto what is drawn, and show a
+ // hidden kind or the service view when that is the only way to draw them.
+ const resolved = useMemo(
+ () =>
+ graph && viewGraph
+ ? resolveViewSelection(selection, graph, viewGraph, collapsed)
+ : { selection: null, fix: null },
+ [selection, graph, viewGraph, collapsed],
+ );
+ const drawnSelection = resolved.selection;
+ const fixKey = resolved.fix ? `${resolved.fix.kind}:${"edgeKind" in resolved.fix ? resolved.fix.edgeKind : ""}` : "";
+ useEffect(() => {
+ const fix = resolved.fix;
+ if (!fix) return;
+ if (fix.kind === "expand") setCollapsed(false);
+ else
+ setHiddenKinds((prev) => {
+ if (!prev.has(fix.edgeKind)) return prev;
+ const next = new Set(prev);
+ next.delete(fix.edgeKind);
+ return next;
+ });
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [fixKey]);
+
+ // Only the selected node gets a new object, so React Flow re-renders one node.
+ const selectedNode = drawnSelection?.type === "node" ? drawnSelection.id : null;
+ const drawnNodes = useMemo(
+ () => (selectedNode ? nodes.map((n) => (n.id === selectedNode ? { ...n, selected: true } : n)) : nodes),
+ [nodes, selectedNode],
+ );
+
+ const matchTypes = useMemo(
+ () => new Set<SystemEdgeMatchType>((viewGraph?.edges ?? []).map((e) => e.match_type)),
+ [viewGraph],
+ );
+
+ // Hover and selection for edges live outside React state (see system-map-focus).
+ const focus = useMemo(() => createSystemMapFocusStore(), []);
+ const canvasRef = useRef<HTMLDivElement>(null);
+ useEffect(
+ () =>
+ focus.subscribe(() => {
+ canvasRef.current?.toggleAttribute("data-focused", focus.focused());
+ }),
+ [focus],
+ );
+ useEffect(() => {
+ focus.setSelected({
+ node: drawnSelection?.type === "node" ? drawnSelection.id : null,
+ edge: drawnSelection?.type === "edge" ? drawnSelection.id : null,
+ });
+ }, [focus, drawnSelection]);
+
const toggleKind = useCallback((kind: SystemEdgeKind) => {
setHiddenKinds((prev) => {
const next = new Set(prev);
@@ -131,130 +204,290 @@ function SystemMapInner({
});
}, []);
- 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 }), []);
+ const onNodeClick = useCallback<NodeMouseHandler>((_, node) => setSelection({ type: "node", id: node.id }), [setSelection]);
+ const onEdgeClick = useCallback<EdgeMouseHandler>((_, edge) => setSelection({ type: "edge", id: edge.id }), [setSelection]);
+ // Keyboard selection (Enter or Space on a focused node or edge) arrives as a
+ // React Flow selection change, and lands on the same object a click would.
+ const onNodesChange = useCallback(
+ (changes: NodeChange[]) => {
+ for (const c of changes) if (c.type === "select" && c.selected) setSelection({ type: "node", id: c.id });
+ },
+ [setSelection],
+ );
+ const onEdgesChange = useCallback(
+ (changes: EdgeChange[]) => {
+ for (const c of changes) if (c.type === "select" && c.selected) setSelection({ type: "edge", id: c.id });
+ },
+ [setSelection],
+ );
+ const onPaneClick = useCallback(() => setSelection(null), [setSelection]);
+ const onNodeMouseEnter = useCallback<NodeMouseHandler>((_, n) => focus.setHover({ node: n.id }), [focus]);
+ const onNodeMouseLeave = useCallback<NodeMouseHandler>(() => focus.setHover({ node: null }), [focus]);
+ const onEdgeMouseEnter = useCallback<EdgeMouseHandler>((_, e) => focus.setHover({ edge: e.id }), [focus]);
+ const onEdgeMouseLeave = useCallback<EdgeMouseHandler>(() => focus.setHover({ edge: null }), [focus]);
- // Collapse selection is keyed by id; collapsing changes node ids, so reset it.
- const onToggleCollapsed = useCallback(() => {
- setCollapsed((c) => !c);
- setSelection(null);
- }, []);
+ // Collapsing changes node ids, so a selection cannot survive it.
+ const onCollapsedChange = useCallback(
+ (next: boolean) => {
+ setCollapsed(next);
+ setSelection(null);
+ },
+ [setSelection],
+ );
const isLoading = loading || layoutLoading;
- const hasGraph = graph && graph.nodes.length > 0;
+ const hasGraph = Boolean(graph && graph.nodes.length > 0);
const hasEdges = (graph?.edges.length ?? 0) > 0;
-
- const hasRail = Boolean(rail) || selection !== null;
+ const canCollapse = Boolean(graph?.nodes.some((n) => n.service_path));
return (
- <div className="flex h-full w-full flex-col bg-[var(--color-bg-canvas)]">
- {/* Lens control in the section header: it acts on the canvas, so it sits
- above it rather than on it. */}
- <div className="flex flex-wrap items-center gap-4 border-b border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-3 py-2">
- <SystemMapFilters
- availableKinds={availableKinds}
- visibleKinds={visibleKinds}
- onToggleKind={toggleKind}
- collapsed={collapsed}
- onToggleCollapsed={onToggleCollapsed}
- />
- </div>
+ <SystemMapFocusContext.Provider value={focus}>
+ <div className="flex min-w-0 flex-col gap-3">
+ {/* Section header: the lens, then what is drawn. Nothing sits on the canvas. */}
+ <div className="flex min-w-0 flex-wrap items-center justify-between gap-x-6 gap-y-3">
+ {toolbar}
+ <SystemMapFilters
+ kindCounts={kindCounts}
+ visibleKinds={visibleKinds}
+ onToggleKind={toggleKind}
+ canCollapse={canCollapse}
+ collapsed={collapsed}
+ onCollapsedChange={onCollapsedChange}
+ />
+ </div>
+
+ <SystemMapLegend matchTypes={matchTypes} />
- {/* Canvas and rail are grid peers, so a panel can never land on the map.
- Below `lg` the rail relocates under the canvas rather than covering
- it. */}
- <div
- className={`grid min-h-0 flex-1 gap-4 p-3 ${
- hasRail ? "grid-cols-1 lg:grid-cols-[minmax(0,1fr)_320px]" : "grid-cols-1"
- }`}
- >
- <div className="flex min-h-0 flex-col gap-2">
- <div className="relative min-h-0 flex-1">
- {error ? (
- <Centered>
- <EmptyState title="Couldn't load the system map" description={toFriendlyMessage(error)} />
- </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}
+ <div
+ ref={canvasRef}
+ className={`sm-canvas relative min-w-0 overflow-hidden rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-root)] ${SYSTEM_MAP_CANVAS_HEIGHT}`}
>
- <Background variant={BackgroundVariant.Lines} gap={24} size={1} color="var(--color-diagram-grid)" />
- <Controls showInteractive={false} />
- <MiniMap pannable zoomable />
- </ReactFlow>
- </div>
-
- {/* The key reads as a caption under the field, not as a card on it. */}
- <SystemMapLegend />
-
- {simplified && (
- <p className="px-1 text-[11px] text-[var(--color-warning)]">
- {`Layout simplified: above ${SYSTEM_MAP_MAX_LAYOUT_NODES} services the map falls back to a grid, so node placement no longer reflects dependency direction.`}
- </p>
- )}
- </div>
+ <style>{".sm-canvas[data-focused] .sm-edge:not([data-active]){opacity:.22}.sm-canvas .sm-edge{transition:opacity 120ms}"}</style>
+ {error ? (
+ <Centered>
+ <EmptyState title="Couldn't load the system map" description={toFriendlyMessage(error)} />
+ </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, database or co-change links were found between them yet."
+ />
+ </Centered>
+ ) : null}
- {hasRail && (
- <aside className="flex min-h-0 flex-col gap-3 overflow-y-auto lg:max-h-full">
- {viewGraph && (
- <SystemMapInspector
- selection={selection}
- graph={viewGraph}
- {...(healthByRepo ? { healthByRepo } : {})}
- {...(roleByNodeId ? { roleByNodeId } : {})}
- onClose={() => setSelection(null)}
- onSelectNode={selectNode}
- {...(onOpenContract ? { onOpenContract } : {})}
+ <ReactFlow
+ nodes={drawnNodes}
+ edges={edges}
+ nodeTypes={systemMapNodeTypes}
+ edgeTypes={systemMapEdgeTypes}
+ onNodeClick={onNodeClick}
+ onEdgeClick={onEdgeClick}
+ onNodesChange={onNodesChange}
+ onEdgesChange={onEdgesChange}
+ onPaneClick={onPaneClick}
+ onNodeMouseEnter={onNodeMouseEnter}
+ onNodeMouseLeave={onNodeMouseLeave}
+ onEdgeMouseEnter={onEdgeMouseEnter}
+ onEdgeMouseLeave={onEdgeMouseLeave}
+ fitView
+ fitViewOptions={FIT_OPTIONS}
+ minZoom={0.15}
+ maxZoom={2}
+ proOptions={{ hideAttribution: true }}
+ nodesDraggable={false}
+ nodesConnectable={false}
+ ariaLabelConfig={{ "node.a11yDescription.default": "Press Enter to open this service's details." }}
+ >
+ <Background variant={BackgroundVariant.Dots} gap={20} size={1} color="var(--color-border-hover)" />
+ <Controls showInteractive={false} />
+ {nodes.length >= SYSTEM_MAP_MINIMAP_MIN_NODES && (
+ <MiniMap
+ pannable
+ zoomable
+ bgColor="var(--color-bg-surface)"
+ maskColor="color-mix(in srgb, var(--color-bg-root) 70%, transparent)"
+ nodeColor="var(--color-border-hover)"
+ nodeStrokeColor="var(--color-text-tertiary)"
+ style={{ border: "1px solid var(--color-border-default)" }}
/>
)}
- {rail}
- </aside>
+ <Viewport fitKey={`${collapsed}:${nodes.length}`} ready={nodes.length > 0} selection={drawnSelection} canvas={canvasRef} />
+ </ReactFlow>
+ </div>
+
+ {graph && viewGraph && <ScopeCaption graph={graph} viewGraph={viewGraph} collapsed={collapsed} lensed={Boolean(overlay)} hidden={hiddenKinds} kindCounts={kindCounts} simplified={simplified} />}
+
+ {graph && viewGraph && (
+ <SystemMapDrawer
+ {...drawer}
+ selection={drawnSelection}
+ graph={viewGraph}
+ rawGraph={graph}
+ collapsed={collapsed}
+ healthByRepo={healthByRepo}
+ roleByNodeId={roleByNodeId}
+ onClose={() => setSelection(null)}
+ onSelect={setSelection}
+ />
)}
</div>
+ </SystemMapFocusContext.Provider>
+ );
+}
+
+/**
+ * Owns the viewport. Fits the drawing once the layout lands and when the canvas
+ * resizes (`fitView` on mount alone fit an empty field, because the async
+ * layout places nodes after React Flow's first pass). Then, on desktop, where
+ * the drawer covers the canvas's right edge, pans the selection into the
+ * uncovered part without changing the zoom. A selection from a list below the
+ * map, or from the URL, would otherwise open a drawer about something hidden.
+ */
+function Viewport({
+ fitKey,
+ ready,
+ selection,
+ canvas,
+}: {
+ fitKey: string;
+ ready: boolean;
+ selection: SystemMapSelection;
+ canvas: React.RefObject<HTMLDivElement | null>;
+}) {
+ const rf = useReactFlow();
+ // Not useNodesInitialized: controlled nodes that ignore dimension changes
+ // never report it. The layout's node count is the signal instead.
+ const initialized = ready;
+ const width = useStore((s) => s.width);
+ const height = useStore((s) => s.height);
+ const latestSelection = useRef(selection);
+ latestSelection.current = selection;
+
+ const reveal = useCallback(
+ (sel: SystemMapSelection) => {
+ if (!sel || typeof window === "undefined" || window.innerWidth < 768) return;
+ const el = canvas.current;
+ if (!el) return;
+ const ids =
+ sel.type === "node" ? [sel.id] : (() => {
+ const e = rf.getEdge(sel.id);
+ return e ? [e.source, e.target] : [];
+ })();
+ const points = ids
+ .map((id) => rf.getInternalNode(id))
+ .filter((n): n is NonNullable<typeof n> => Boolean(n))
+ .map((n) => ({
+ x: n.internals.positionAbsolute.x + SYSTEM_MAP_NODE_SIZE.width / 2,
+ y: n.internals.positionAbsolute.y + SYSTEM_MAP_NODE_SIZE.height / 2,
+ }));
+ if (points.length === 0) return;
+ const center = {
+ x: points.reduce((a, p) => a + p.x, 0) / points.length,
+ y: points.reduce((a, p) => a + p.y, 0) / points.length,
+ };
+ const rect = el.getBoundingClientRect();
+ const visibleRight = Math.max(Math.min(rect.right, window.innerWidth - DRAWER_WIDTH), rect.left + 240);
+ const screen = rf.flowToScreenPosition(center);
+ const margin = SYSTEM_MAP_NODE_SIZE.width / 2;
+ const inView =
+ screen.x > rect.left + margin &&
+ screen.x < visibleRight - margin &&
+ screen.y > rect.top + 40 &&
+ screen.y < rect.bottom - 40;
+ if (inView) return;
+ const { zoom } = rf.getViewport();
+ // Only move on the axis that hides it, so the map shifts as little as possible.
+ const xInView = screen.x > rect.left + margin && screen.x < visibleRight - margin;
+ const targetX = xInView ? screen.x - rect.left : (visibleRight - rect.left) / 2;
+ const yInView = screen.y > rect.top + 40 && screen.y < rect.bottom - 40;
+ const targetY = yInView ? screen.y - rect.top : rect.height / 2;
+ void rf.setViewport({ x: targetX - center.x * zoom, y: targetY - center.y * zoom, zoom }, { duration: 250 });
+ },
+ [rf, canvas],
+ );
+
+ useEffect(() => {
+ if (!initialized || width === 0 || height === 0) return;
+ // fitView is queued inside React Flow, so the reveal waits a beat for the
+ // fitted viewport rather than reading the one it replaces.
+ let reveal2 = 0;
+ const id = requestAnimationFrame(() => {
+ void rf.fitView(FIT_OPTIONS);
+ reveal2 = window.setTimeout(() => reveal(latestSelection.current), 80);
+ });
+ return () => {
+ cancelAnimationFrame(id);
+ window.clearTimeout(reveal2);
+ };
+ }, [rf, initialized, fitKey, width, height, reveal]);
+
+ const selKey = selection ? `${selection.type}:${selection.id}` : "";
+ useEffect(() => {
+ if (initialized) reveal(latestSelection.current);
+ }, [selKey, initialized, reveal]);
+
+ return null;
+}
+
+/** What is drawn and what is not, stated beside the canvas. */
+function ScopeCaption({
+ graph,
+ viewGraph,
+ collapsed,
+ lensed,
+ hidden,
+ kindCounts,
+ simplified,
+}: {
+ graph: SystemGraph;
+ viewGraph: SystemGraph;
+ collapsed: boolean;
+ lensed: boolean;
+ hidden: ReadonlySet<SystemEdgeKind>;
+ kindCounts: ReadonlyMap<SystemEdgeKind, number>;
+ simplified: boolean;
+}) {
+ const repoOf = new Map(graph.nodes.map((n) => [n.id, n.repo]));
+ const intraRepo = graph.edges.filter((e) => repoOf.get(e.source) === repoOf.get(e.target)).length;
+ const hiddenParts = [...hidden]
+ .filter((k) => (kindCounts.get(k) ?? 0) > 0)
+ .map((k) => `${kindCounts.get(k)} ${edgeKindStyle(k).label}`);
+ const nodes = viewGraph.nodes.length;
+ const edges = viewGraph.edges.length;
+
+ const parts = [
+ collapsed
+ ? `Drawing ${nodes} ${nodes === 1 ? "repository" : "repositories"} and ${edges} ${edges === 1 ? "relationship" : "relationships"}. Edges of one kind between the same two repositories are merged, and ${intraRepo} ${intraRepo === 1 ? "relationship" : "relationships"} inside a repository ${intraRepo === 1 ? "is" : "are"} not drawn.`
+ : `Drawing ${nodes} ${nodes === 1 ? "service" : "services"} and ${edges} ${edges === 1 ? "relationship" : "relationships"}.`,
+ hiddenParts.length > 0 ? `Hidden by the edge filter: ${hiddenParts.join(", ")}.` : null,
+ // Lens results name services, and a merged node is several of them.
+ collapsed && lensed ? "Lens marks are drawn per service, so they are off in this view; switch to Services to see them." : null,
+ "Placement follows structural dependencies; co-change lines do not move services.",
+ ];
+
+ return (
+ <div className="flex flex-col gap-1">
+ <p className="text-xs text-[var(--color-text-tertiary)]">{parts.filter(Boolean).join(" ")}</p>
+ {simplified && (
+ <p className="text-xs text-[var(--color-warning)]">
+ {`Layout simplified: above ${SYSTEM_MAP_MAX_LAYOUT_NODES} services the map falls back to a grid, so placement no longer reflects dependency direction.`}
+ </p>
+ )}
</div>
);
}
/**
- * Empty/error state centred over the canvas box. This one is deliberately
- * absolute: it is the canvas's own "nothing to draw" copy, not chrome competing
- * with a diagram that is there to be read.
+ * Empty/error state centred over the canvas box. Deliberately absolute: it is
+ * the canvas's own "nothing to draw" copy, not chrome competing with a diagram.
*/
function Centered({ children }: { children: React.ReactNode }) {
return (
diff --git a/packages/ui/src/workspace/system-map/types.ts b/packages/ui/src/workspace/system-map/types.ts
index 87ab98924..dff9e6721 100644
--- a/packages/ui/src/workspace/system-map/types.ts
+++ b/packages/ui/src/workspace/system-map/types.ts
@@ -21,6 +21,8 @@ export interface SystemMapNodeData {
health: RepoHealth | null;
/** Overlay state applied this render (Phase 3+ ripple / badges). */
overlay: NodeOverlayState | null;
+ /** Architecture role label ("Core", "Shared"...), named in text on the node. */
+ role: string | null;
[key: string]: unknown;
}
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
index 8953cd8f6..7f9c39eb3 100644
--- a/packages/ui/src/workspace/system-map/use-system-map-layout.ts
+++ b/packages/ui/src/workspace/system-map/use-system-map-layout.ts
@@ -9,7 +9,8 @@
import { useEffect, useMemo, useRef, useState } from "react";
import { MarkerType, type Edge, type Node } from "@xyflow/react";
-import type { SystemGraph } from "@repowise-dev/types";
+import type { NodeArchitectureRole, SystemGraph } from "@repowise-dev/types";
+import { roleStyle } from "./architecture";
import {
applyCollapse,
applyView,
@@ -32,6 +33,8 @@ export interface UseSystemMapLayoutArgs {
/** Repo health by repo alias, joined onto service nodes (optional). */
healthByRepo?: ReadonlyMap<string, RepoHealth>;
overlay?: SystemMapOverlay;
+ /** Per-service role, named on the node. Service ids only, so not in repo view. */
+ roleByNodeId?: ReadonlyMap<string, NodeArchitectureRole>;
}
export interface SystemMapLayout {
@@ -53,6 +56,7 @@ export function useSystemMapLayout({
view,
healthByRepo,
overlay,
+ roleByNodeId,
}: UseSystemMapLayoutArgs): SystemMapLayout {
const viewGraph = useMemo(() => (graph ? applyView(graph, view) : null), [graph, view]);
@@ -127,10 +131,14 @@ export function useSystemMapLayout({
node,
health: healthByRepo?.get(node.repo) ?? null,
overlay: resolveNodeOverlay(overlay, node.id),
+ role: (() => {
+ const r = view.collapsed ? undefined : roleByNodeId?.get(node.id);
+ return r ? roleStyle(r.role).label : null;
+ })(),
},
};
});
- }, [viewGraph, positions, healthByRepo, overlay]);
+ }, [viewGraph, positions, healthByRepo, overlay, roleByNodeId, view.collapsed]);
const edges = useMemo<Edge<SystemMapEdgeData>[]>(() => {
if (!viewGraph) return [];
diff --git a/packages/web/src/app/workspace/system-map/page.tsx b/packages/web/src/app/workspace/system-map/page.tsx
index c106367e0..66ad69476 100644
--- a/packages/web/src/app/workspace/system-map/page.tsx
+++ b/packages/web/src/app/workspace/system-map/page.tsx
@@ -1,23 +1,34 @@
"use client";
import { useCallback, useMemo, useState } from "react";
+import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
-import { Waypoints, Boxes, ArrowLeftRight, Share2, Zap, AlertTriangle, ShieldAlert, Gauge } from "lucide-react";
+import { Waypoints } from "lucide-react";
import {
SystemMap,
- SystemMapBlastPanel,
- SystemMapBreakingPanel,
- SystemMapConformancePanel,
+ SYSTEM_MAP_CANVAS_HEIGHT,
+ SystemMapFindings,
+ SystemMapLensControl,
+ SystemMapLensResults,
+ buildArchitectureOverlay,
buildBlastRadiusOverlay,
buildBreakingChangeOverlay,
buildConformanceOverlay,
- buildArchitectureOverlay,
+ plural,
+ selectionRepo,
+ type ContractRef,
type RepoHealth,
+ type SegmentOption,
+ type SystemMapLens,
type SystemMapSelection,
} from "@repowise-dev/ui/workspace/system-map";
-import type { NodeArchitectureRole } from "@/lib/api/types";
-import { MetricCard } from "@repowise-dev/ui/shared/metric-card";
+import { PageShell } from "@repowise-dev/ui/shared/page-shell";
+import { PageLede } from "@repowise-dev/ui/shared/page-lede";
+import { StatRibbon, type RibbonStat } from "@repowise-dev/ui/stats/stat-ribbon";
+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 type { NodeArchitectureRole, SystemGraph, ConformanceReport } from "@/lib/api/types";
import {
useWorkspaceSystemGraph,
useWorkspaceGraph,
@@ -26,14 +37,34 @@ import {
useWorkspaceConformance,
useWorkspaceArchitecture,
} from "@/lib/hooks/use-workspace";
+import { useRepoContracts } from "./use-repo-contracts";
+
+const LENSES: readonly SystemMapLens[] = ["none", "blast", "breaking", "conformance", "core"];
+
+function contractHref(ref: ContractRef): string {
+ const params = new URLSearchParams({ contract: ref.contract_id, repo: ref.repo });
+ if (ref.file_path) params.set("file", ref.file_path);
+ return `/workspace/contracts?${params.toString()}`;
+}
+
+function contractsHref(repo: string): string {
+ return `/workspace/contracts?${new URLSearchParams({ repo }).toString()}`;
+}
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();
const { data: repoGraph } = useWorkspaceGraph();
+ const { data: architecture, error: architectureError } = useWorkspaceArchitecture();
+ const { data: conformance, error: conformanceError } = useWorkspaceConformance();
+ const { data: breaking, error: breakingError } = useWorkspaceBreakingChanges();
- // Selection lives in the URL so a service or seam you found can be linked to.
+ // Selection, lens and blast target live in the URL, so a view can be linked to.
const selection = useMemo<SystemMapSelection>(() => {
const node = searchParams.get("node");
if (node) return { type: "node", id: node };
@@ -41,47 +72,63 @@ export default function SystemMapPage() {
if (edge) return { type: "edge", id: edge };
return null;
}, [searchParams]);
+ const lensOptions = useMemo(
+ () =>
+ lensOptionsFor(graph, breaking, conformance, architecture, {
+ breaking: Boolean(breakingError),
+ conformance: Boolean(conformanceError),
+ architecture: Boolean(architectureError),
+ }),
+ [graph, breaking, conformance, architecture, breakingError, conformanceError, architectureError],
+ );
+ // A lens from the URL that cannot act here (0 findings, or its report
+ // failed) reads as no lens, rather than a checked option nobody can reach.
+ const lensParam = searchParams.get("lens") as SystemMapLens | null;
+ const lens: SystemMapLens =
+ lensParam && LENSES.includes(lensParam) && !lensOptions.find((o) => o.value === lensParam)?.disabledReason
+ ? lensParam
+ : "none";
+ const blastTarget = lens === "blast" ? searchParams.get("from") : null;
- const onSelectionChange = useCallback(
- (next: SystemMapSelection) => {
+ const replaceParams = useCallback(
+ (edit: (p: URLSearchParams) => void) => {
const params = new URLSearchParams(searchParams.toString());
- params.delete("node");
- params.delete("edge");
- if (next) params.set(next.type, next.id);
+ edit(params);
const query = params.toString();
- // `replace`, not `push`: clicking around a diagram should not build a
- // back-button history of every node you glanced at.
+ // `replace`, not `push`: exploring a diagram should not fill the back button.
router.replace(query ? `?${query}` : "/workspace/system-map", { scroll: false });
},
[router, searchParams],
);
- // Blast-radius target. Driven by a page-level picker (and re-targetable from
- // the impacted panel) so the map component stays unchanged — the ripple rides
- // its existing `overlay` prop.
- const [blastTarget, setBlastTarget] = useState<string | null>(null);
- const [includeBehavioral, setIncludeBehavioral] = useState(true);
- const { data: blast, isLoading: blastLoading } = useWorkspaceBlastRadius(blastTarget, {
- includeBehavioral,
- });
+ const onSelectionChange = useCallback(
+ (next: SystemMapSelection) =>
+ replaceParams((p) => {
+ p.delete("node");
+ p.delete("edge");
+ if (next) p.set(next.type, next.id);
+ }),
+ [replaceParams],
+ );
- // Breaking-change guard. Lazy-fetched the first time it's toggled on; its
- // at-risk badges ride the map's overlay prop when no blast target is focused.
- const [showBreaking, setShowBreaking] = useState(false);
- const { data: breaking, isLoading: breakingLoading } =
- useWorkspaceBreakingChanges(showBreaking);
+ const setLens = useCallback(
+ (next: SystemMapLens, from?: string | null) =>
+ replaceParams((p) => {
+ if (next === "none") p.delete("lens");
+ else p.set("lens", next);
+ if (next === "blast" && from !== undefined) {
+ if (from) p.set("from", from);
+ else p.delete("from");
+ } else if (next !== "blast") p.delete("from");
+ }),
+ [replaceParams],
+ );
- // Architecture conformance. Lazy-fetched on toggle; violation/cycle badges ride
- // the same overlay prop when no blast target or breaking-change view is active.
- const [showConformance, setShowConformance] = useState(false);
- const { data: conformance, isLoading: conformanceLoading } =
- useWorkspaceConformance(showConformance);
+ const [includeBehavioral, setIncludeBehavioral] = useState(true);
+ const { data: blast, isLoading: blastLoading, error: blastError } = useWorkspaceBlastRadius(blastTarget, { includeBehavioral });
- // Architecture metrics. Always fetched (cheap, deterministic): it feeds the
- // score stat and the per-service role shown in the inspector. The cyclic-core
- // highlight is an opt-in overlay toggle.
- const { data: architecture } = useWorkspaceArchitecture();
- const [showArchitecture, setShowArchitecture] = useState(false);
+ const focusRepo = useMemo(() => selectionRepo(graph, selection), [graph, selection]);
+ const { data: repoContracts, isLoading: repoContractsLoading } = useRepoContracts(focusRepo);
const roleByNodeId = useMemo<Map<string, NodeArchitectureRole>>(() => {
const m = new Map<string, NodeArchitectureRole>();
@@ -89,247 +136,285 @@ export default function SystemMapPage() {
return m;
}, [architecture]);
- // 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>();
+ // Repo health by alias; the repo graph's node `name` is the alias.
+ const { healthByRepo, repoIdByAlias } = useMemo(() => {
+ const health = new Map<string, RepoHealth>();
+ const ids = new Map<string, string>();
for (const n of repoGraph?.nodes ?? []) {
- m.set(n.name, { score: n.health_score, source: n.health_score_source });
+ health.set(n.name, { score: n.health_score, source: n.health_score_source });
+ ids.set(n.name, n.repo_id);
}
- return m;
+ return { healthByRepo: health, repoIdByAlias: ids };
}, [repoGraph]);
- // A blast-radius selection focuses the map (dim + ripple) and takes precedence;
- // otherwise the breaking-change overlay badges the at-risk seams additively.
const overlay = useMemo(() => {
if (!graph) return undefined;
- if (blast) return buildBlastRadiusOverlay(graph, blast);
- if (showConformance && conformance) return buildConformanceOverlay(graph, conformance);
- if (showBreaking && breaking) return buildBreakingChangeOverlay(graph, breaking);
- if (showArchitecture && architecture) return buildArchitectureOverlay(graph, architecture);
+ if (lens === "blast" && blast) return buildBlastRadiusOverlay(graph, blast);
+ if (lens === "breaking" && breaking) return buildBreakingChangeOverlay(graph, breaking);
+ if (lens === "conformance" && conformance) return buildConformanceOverlay(graph, conformance);
+ if (lens === "core" && architecture) {
+ // Nodes already name their role; a "core" badge would say it twice.
+ const { nodeBadges: _named, ...core } = buildArchitectureOverlay(graph, architecture);
+ return core;
+ }
return undefined;
- }, [graph, blast, showBreaking, breaking, showConformance, conformance, showArchitecture, architecture]);
+ }, [graph, lens, blast, breaking, conformance, architecture]);
- // Contract ids are `<type>::<method>::<path>`, and the Contracts page filters
- // by type, not by id. Carry the type across so the drill-down lands on the
- // right family instead of on an unfiltered list.
- const openContract = useCallback(
- (contractId: string) => {
- const type = contractId.split("::")[0];
- router.push(type ? `/workspace/contracts?type=${encodeURIComponent(type)}` : "/workspace/contracts");
- },
- [router],
+ const drawer = useMemo(
+ () => ({
+ repoContracts,
+ repoContractsLoading,
+ cycles: conformance?.cycles ?? [],
+ contractHref,
+ contractsHref,
+ repoHref: (alias: string) => {
+ const id = repoIdByAlias.get(alias);
+ return id ? `/repos/${id}/overview` : null;
+ },
+ coChangesHref: "/workspace/co-changes",
+ LinkComponent: Link,
+ onShowBlastRadius: (id: string) => setLens("blast", id),
+ }),
+ [repoContracts, repoContractsLoading, conformance, repoIdByAlias, setLens],
);
- 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-5">
- <MetricCard
- label="Architecture score"
- value={architecture ? `${architecture.score.toFixed(1)} / 10` : "—"}
- description={
- architecture
- ? `${architecture.propagation_cost_pct.toFixed(1)}% propagation cost`
- : "Coupling + core roll-up"
- }
- icon={<Gauge className="h-4 w-4 text-[var(--color-accent-primary)]" />}
- />
- <MetricCard
- label="Services"
- value={isLoading ? "—" : serviceCount}
- icon={<Boxes className="h-4 w-4" />}
- />
- <MetricCard
- label="Relationships"
- value={isLoading ? "—" : edgeCount}
- icon={<Share2 className="h-4 w-4 text-[var(--color-accent-secondary)]" />}
- />
- <MetricCard
- label="Providers / Consumers"
- value={diag ? `${diag.total_providers} / ${diag.total_consumers}` : "—"}
- icon={<ArrowLeftRight className="h-4 w-4 text-[var(--color-success)]" />}
- />
- <MetricCard
- 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>
-
- {/* Blast-radius controls: pick a service to see what breaks downstream. */}
- <div className="flex flex-wrap items-center gap-3 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-4 py-2.5">
- <span className="inline-flex items-center gap-1.5 text-sm font-medium text-[var(--color-text-primary)]">
- <Zap className="h-4 w-4 text-[var(--color-accent-primary)]" />
- Blast radius
- </span>
- <select
- aria-label="Blast-radius source service"
- className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-canvas)] px-2 py-1 text-sm text-[var(--color-text-primary)]"
- value={blastTarget ?? ""}
- onChange={(e) => setBlastTarget(e.target.value || null)}
- disabled={!graph || serviceCount === 0}
- >
- <option value="">Select a service…</option>
- {(graph?.nodes ?? [])
- .slice()
- .sort((a, b) => a.id.localeCompare(b.id))
- .map((n) => (
- <option key={n.id} value={n.id}>
- {n.service_path ? `${n.repo} · ${n.name}` : n.name}
- </option>
- ))}
- </select>
- <label className="inline-flex items-center gap-1.5 text-sm text-[var(--color-text-secondary)]">
- <input
- type="checkbox"
- checked={includeBehavioral}
- onChange={(e) => setIncludeBehavioral(e.target.checked)}
- />
- Include co-change
- </label>
- <button
- type="button"
- onClick={() => {
- setShowArchitecture((v) => !v);
- if (!showArchitecture) {
- setShowBreaking(false);
- setShowConformance(false);
- }
- }}
- aria-pressed={showArchitecture}
- className={`ml-auto inline-flex items-center gap-1.5 rounded-md border px-2.5 py-1 text-sm ${
- showArchitecture
- ? "border-[var(--color-accent-primary)] text-[var(--color-accent-primary)]"
- : "border-[var(--color-border-default)] text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]"
- }`}
- title="Highlight the cyclic architectural core"
- >
- <Gauge className="h-4 w-4" />
- Core
- {showArchitecture && architecture && architecture.core_size > 0 && (
- <span className="font-semibold">· {architecture.core_size}</span>
- )}
- </button>
- <button
- type="button"
- onClick={() => {
- setShowConformance((v) => !v);
- if (!showConformance) {
- setShowBreaking(false);
- setShowArchitecture(false);
- }
- }}
- aria-pressed={showConformance}
- className={`inline-flex items-center gap-1.5 rounded-md border px-2.5 py-1 text-sm ${
- showConformance
- ? "border-[var(--color-risk-high)] text-[var(--color-risk-high)]"
- : "border-[var(--color-border-default)] text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]"
- }`}
- >
- <ShieldAlert className="h-4 w-4" />
- Conformance
- {showConformance && conformance && conformance.violation_count > 0 && (
- <span className="font-semibold">· {conformance.violation_count}</span>
- )}
- </button>
- <button
- type="button"
- onClick={() => {
- setShowBreaking((v) => !v);
- if (!showBreaking) {
- setShowConformance(false);
- setShowArchitecture(false);
- }
- }}
- aria-pressed={showBreaking}
- className={`inline-flex items-center gap-1.5 rounded-md border px-2.5 py-1 text-sm ${
- showBreaking
- ? "border-[var(--color-risk-high)] text-[var(--color-risk-high)]"
- : "border-[var(--color-border-default)] text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]"
- }`}
- >
- <AlertTriangle className="h-4 w-4" />
- Breaking changes
- {showBreaking && breaking && breaking.breaking_count > 0 && (
- <span className="font-semibold">· {breaking.breaking_count}</span>
- )}
- </button>
- {blastTarget && (
- <button
- type="button"
- onClick={() => setBlastTarget(null)}
- className="text-sm text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)]"
- >
- Clear
- </button>
- )}
- </div>
+ <PageShell
+ title="System map"
+ icon={<Waypoints className="h-5 w-5 text-[var(--color-text-tertiary)]" />}
+ description="Services and the typed relationships between them, rebuilt from code and git history on every workspace update."
+ maxWidth="wide"
+ >
+ {graph && <Lede graph={graph} architecture={architecture} conformance={conformance} />}
+ {graph && <StatRibbon stats={ribbon(graph, architecture)} LinkComponent={Link} />}
- <div className="rounded-lg overflow-hidden border border-[var(--color-border-default)] h-[calc(100vh-360px)] min-h-[560px]">
+ <OverviewSection
+ title="Services and relationships"
+ description="Each box is a service; each line is a contract, import or co-change between two of them. Pick a lens to ask the map one question at a time."
+ >
{isLoading ? (
- <div className="p-4 h-full">
- <Skeleton className="h-full w-full" />
+ // Same rows as the loaded map: lens, filters, legend, then the canvas.
+ <div className="flex flex-col gap-3" aria-hidden>
+ <Skeleton className="h-8 w-[480px] max-w-full" />
+ <Skeleton className="h-8 w-[640px] max-w-full" />
+ <Skeleton className="h-10 w-full" />
+ <Skeleton className={`w-full rounded-lg ${SYSTEM_MAP_CANVAS_HEIGHT}`} />
</div>
) : (
<SystemMap
graph={graph}
error={error ?? null}
healthByRepo={healthByRepo}
- {...(overlay ? { overlay } : {})}
roleByNodeId={roleByNodeId}
+ {...(overlay ? { overlay } : {})}
selection={selection}
onSelectionChange={onSelectionChange}
- onOpenContract={openContract}
- rail={
- blast || showBreaking || showConformance ? (
- <>
- <SystemMapBlastPanel
- result={blast}
- loading={blastLoading}
- onSelectTarget={setBlastTarget}
- onClear={() => setBlastTarget(null)}
- />
- {showBreaking && (
- <SystemMapBreakingPanel
- report={breaking}
- loading={breakingLoading}
- onSelectNode={setBlastTarget}
- onClear={() => setShowBreaking(false)}
- />
- )}
- {showConformance && (
- <SystemMapConformancePanel
- report={conformance}
- loading={conformanceLoading}
- onSelectNode={setBlastTarget}
- onClear={() => setShowConformance(false)}
- />
- )}
- </>
- ) : null
+ drawer={drawer}
+ toolbar={
+ <SystemMapLensControl
+ value={lens}
+ options={lensOptions}
+ onChange={(next) => setLens(next, next === "blast" ? (selection?.type === "node" ? selection.id : null) : undefined)}
+ nodes={graph?.nodes ?? []}
+ blastTarget={blastTarget}
+ onBlastTargetChange={(id) => setLens("blast", id)}
+ includeBehavioral={includeBehavioral}
+ onIncludeBehavioralChange={setIncludeBehavioral}
+ />
}
/>
)}
- </div>
- </div>
+ </OverviewSection>
+
+ {graph && (
+ <SystemMapLensResults
+ lens={lens}
+ graph={graph}
+ selection={selection}
+ onSelect={onSelectionChange}
+ blastTarget={blastTarget}
+ blast={blast}
+ blastLoading={blastLoading}
+ blastError={Boolean(blastError)}
+ includeBehavioral={includeBehavioral}
+ breaking={breaking}
+ conformance={conformance}
+ architecture={architecture}
+ conformanceHref="/workspace/conformance"
+ LinkComponent={Link}
+ />
+ )}
+
+ {graph && (
+ <SystemMapFindings
+ graph={graph}
+ conformance={conformance}
+ breaking={breaking}
+ diagnostics={graph.diagnostics}
+ conformanceError={Boolean(conformanceError)}
+ breakingError={Boolean(breakingError)}
+ onSelect={onSelectionChange}
+ onLensChange={(next) => setLens(next)}
+ unmatchedHref="/workspace/contracts?role=consumer&linked=no"
+ conformanceHref="/workspace/conformance"
+ LinkComponent={Link}
+ />
+ )}
+ </PageShell>
);
}
+
+/** Counts and disabled reasons for each lens, from data already on the page. */
+function lensOptionsFor(
+ graph: SystemGraph | null,
+ breaking: ReturnType<typeof useWorkspaceBreakingChanges>["data"],
+ conformance: ConformanceReport | null,
+ architecture: ReturnType<typeof useWorkspaceArchitecture>["data"],
+ failed: { breaking: boolean; conformance: boolean; architecture: boolean },
+): SegmentOption<SystemMapLens>[] {
+ const hasEdges = (graph?.edges.length ?? 0) > 0;
+ const breakingTotal = breaking ? breaking.breaking_count + breaking.warning_count : 0;
+ const findings = conformance ? conformance.violation_count + (conformance.total_cycles ?? conformance.cycle_count) : 0;
+ return [
+ { value: "none", label: "None", hint: "The map as extracted, no lens" },
+ {
+ value: "blast",
+ label: "Blast radius",
+ hint: "What depends on one service, directly or through others",
+ disabledReason: hasEdges ? undefined : "No relationships to trace yet.",
+ },
+ {
+ value: "breaking",
+ label: "Breaking changes",
+ count: breaking ? String(breakingTotal) : undefined,
+ disabledReason: failed.breaking
+ ? "Could not load the breaking-change report."
+ : !breaking
+ ? "Loading the breaking-change report."
+ : !breaking.generated_at
+ ? "Breaking-change detection has not run. Run a workspace update."
+ : breakingTotal === 0
+ ? "No provider contract changed incompatibly in the most recent update."
+ : undefined,
+ },
+ {
+ value: "conformance",
+ label: "Conformance",
+ count: conformance ? String(findings) : undefined,
+ hint: "Rule violations and dependency cycles",
+ disabledReason: failed.conformance
+ ? "Could not load the conformance report."
+ : !conformance
+ ? "Loading the conformance report."
+ : !conformance.generated_at
+ ? "Conformance has not been checked. Run a workspace update."
+ : findings === 0
+ ? "No rule violations or dependency cycles."
+ : undefined,
+ },
+ {
+ value: "core",
+ label: "Core",
+ count: architecture ? String(architecture.core_size) : undefined,
+ hint: "The largest group of services that all depend on each other, and every service's role",
+ disabledReason: failed.architecture
+ ? "Could not load the architecture metrics."
+ : !architecture
+ ? "Loading architecture metrics."
+ : architecture.core_size === 0 && architecture.roles.length === 0
+ ? "No services to classify."
+ : undefined,
+ },
+ ];
+}
+
+function Lede({
+ graph,
+ architecture,
+ conformance,
+}: {
+ graph: SystemGraph;
+ architecture: ReturnType<typeof useWorkspaceArchitecture>["data"];
+ conformance: ConformanceReport | null;
+}) {
+ const name = (id: string) => graph.nodes.find((n) => n.id === id)?.name ?? id;
+ const repos = new Set(graph.nodes.map((n) => n.repo)).size;
+ const structural = graph.edges.filter((e) => e.structural).length;
+ const behavioral = graph.edges.length - structural;
+ const cycles = conformance?.cycles ?? [];
+ const totalCycles = conformance ? (conformance.total_cycles ?? conformance.cycle_count) : 0;
+ const first = cycles[0];
+
+ return (
+ <PageLede
+ label="Architecture score"
+ labelHint="A 1 to 10 roll-up of propagation cost, the size of the cyclic core, dependency cycles and rule violations, over structural edges only. Higher means less coupled."
+ value={architecture ? architecture.score.toFixed(1) : "–"}
+ unit="out of 10"
+ layout="beside"
+ >
+ <p>
+ {plural(graph.nodes.length, "service", "services")} in {plural(repos, "repository", "repositories")}, joined by{" "}
+ {plural(graph.edges.length, "relationship", "relationships")}: {structural} structural (a contract or import
+ in code) and {behavioral} co-change (files that change in the same commits, not a call).
+ </p>
+ {first ? (
+ <p>
+ <span className="font-medium text-[var(--color-text-primary)]">
+ {first.nodes.map(name).join(" and ")} depend on each other
+ </span>
+ , a dependency cycle: none of them can change a contract, build or deploy alone.
+ {totalCycles > 1 ? ` ${plural(totalCycles - 1, "more cycle is", "more cycles are")} listed under Needs attention.` : " It is listed under Needs attention with a prompt to break it."}
+ </p>
+ ) : conformance?.generated_at ? (
+ <p>No dependency cycles: every service can change without a loop back to itself.</p>
+ ) : null}
+ {architecture && (
+ <p>
+ On average a service reaches {architecture.propagation_cost_pct.toFixed(1)}% of the others through
+ dependencies, and {architecture.core_size > 0 ? `${plural(architecture.core_size, "service forms", "services form")} the cyclic core` : "there is no cyclic core"}
+ . Those two figures drive the score.
+ </p>
+ )}
+ </PageLede>
+ );
+}
+
+function ribbon(
+ graph: SystemGraph,
+ architecture: ReturnType<typeof useWorkspaceArchitecture>["data"],
+): 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 [
+ {
+ label: "Services",
+ value: formatNumber(graph.nodes.length),
+ sub: `in ${plural(repos, "repository", "repositories")}`,
+ },
+ {
+ label: "Relationships",
+ value: formatNumber(graph.edges.length),
+ sub: `${structural} structural, ${graph.edges.length - structural} co-change`,
+ },
+ {
+ label: "Propagation cost",
+ value: architecture ? `${architecture.propagation_cost_pct.toFixed(1)}%` : "–",
+ sub: "of other services the average one reaches",
+ hint: "The share of other services the average service can reach through structural dependencies. 0% is fully decoupled, 100% is everything reaching everything.",
+ },
+ {
+ label: "Contract links",
+ value: diag ? formatNumber(diag.total_links) : "–",
+ sub: diag ? `from ${formatNumber(diag.total_providers)} providers, ${formatNumber(diag.total_consumers)} consumers` : undefined,
+ hint: "Consumer calls matched to the provider that serves them, across services.",
+ },
+ {
+ label: "Unmatched consumers",
+ value: diag ? formatNumber(diag.unmatched_consumers.length) : "–",
+ sub: "calls with no provider in the workspace",
+ hint: "Consumer contracts that matched no provider: missing, a third-party host, or inside the same service.",
+ },
+ ];
+}
diff --git a/packages/web/src/app/workspace/system-map/use-repo-contracts.ts b/packages/web/src/app/workspace/system-map/use-repo-contracts.ts
new file mode 100644
index 000000000..1bc62e88a
--- /dev/null
+++ b/packages/web/src/app/workspace/system-map/use-repo-contracts.ts
@@ -0,0 +1,43 @@
+"use client";
+
+import useSWR from "swr";
+import type { SystemMapRepoContracts } from "@repowise-dev/ui/workspace/system-map";
+import { getWorkspaceContracts } from "@/lib/api/workspace";
+
+/** The endpoint's page ceiling. */
+const PAGE = 1000;
+/**
+ * Pages fetched for one repository. The drawer states when a repository has
+ * more contracts than this, and counts from what it has. Ceiling: a repository
+ * past 5,000 contracts wants a server-side per-service filter on
+ * /api/workspace/contracts instead of client paging.
+ */
+const MAX_PAGES = 5;
+
+/**
+ * Every contract and matched link for one repository, fetched only once the
+ * drawer needs it (a service or relationship is selected). Keyed by repo, so
+ * the node and edge drawers share one fetch.
+ */
+export function useRepoContracts(repo: string | null) {
+ const { data, isLoading } = useSWR<SystemMapRepoContracts>(
+ repo ? `workspace:system-map:repo-contracts:${repo}` : null,
+ async () => {
+ const first = await getWorkspaceContracts({ repo: repo as string, limit: PAGE });
+ const pages = Math.min(Math.ceil(first.total_contracts / PAGE), MAX_PAGES);
+ // Later pages in parallel; links are not paged, so the first page's set is complete.
+ const rest = await Promise.all(
+ Array.from({ length: Math.max(pages - 1, 0) }, (_, i) =>
+ getWorkspaceContracts({ repo: repo as string, limit: PAGE, offset: (i + 1) * PAGE }),
+ ),
+ );
+ return {
+ contracts: [...first.contracts, ...rest.flatMap((r) => r.contracts)],
+ links: first.links,
+ total: first.total_contracts,
+ };
+ },
+ { revalidateOnFocus: false },
+ );
+ return { data: data ?? null, isLoading };
+}