Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(workspace): move the System Map's chrome off the canvas, and fix repo view (#1616)
Raghav Chamadiyad5d7e45f01df
diff --git a/packages/ui/__tests__/workspace/system-map-logic.test.ts b/packages/ui/__tests__/workspace/system-map-logic.test.tsindex c858a4e2d..a1c3de42d 100644--- a/packages/ui/__tests__/workspace/system-map-logic.test.ts+++ b/packages/ui/__tests__/workspace/system-map-logic.test.ts@@ -1,7 +1,13 @@import { describe, it, expect } from "vitest";import type { SystemEdge, SystemGraph, SystemNode } from "@repowise-dev/types";import { collapseToRepos } from "../../src/workspace/system-map/collapse";-import { applyView } from "../../src/workspace/system-map/layout";+import {+ applyCollapse,+ applyView,+ computeSystemMapPositions,+ layoutSignature,+ SYSTEM_MAP_MAX_LAYOUT_NODES,+} from "../../src/workspace/system-map/layout";import {edgeKindStyle,matchTypeDash,@@ -487,3 +493,67 @@ describe("buildDsm", () => {expect(buildDsm(null)).toEqual({ axis: [], labels: [], cells: [] });});});++describe("layout stability under filtering", () => {+ const g = graph(+ [node("api", "api"), node("web", "web")],+ [+ edge("web", "api"),+ edge("api", "web", { id: "api->web:co", kind: "co_change", structural: false }),+ ],+ );++ it("lays out the whole shape while drawing only the filtered edges", () => {+ const all = new Set(["http", "co_change"] as const);+ const httpOnly = new Set(["http"] as const);++ // What we lay out keeps every edge, so a filter cannot move a node…+ expect(applyCollapse(g, false).edges).toHaveLength(2);++ // …while the drawn graph really does lose the filtered edge.+ expect(applyView(g, { visibleKinds: httpOnly, collapsed: false }).edges.map((e) => e.id)).toEqual([+ "web->api",+ ]);+ expect(applyView(g, { visibleKinds: all, collapsed: false }).edges).toHaveLength(2);++ // The property that matters: the layout input is filter-independent.+ expect(layoutSignature(applyView(g, { visibleKinds: all, collapsed: false }))).toBe(+ layoutSignature(applyCollapse(g, false)),+ );+ expect(layoutSignature(applyView(g, { visibleKinds: httpOnly, collapsed: false }))).not.toBe(+ layoutSignature(applyCollapse(g, false)),+ );+ });++ it("changes the layout signature when collapse changes the node set", () => {+ const withServices = graph(+ [node("api::svc/a", "api"), node("api::svc/b", "api"), node("web", "web")],+ [edge("web", "api::svc/a")],+ );+ expect(layoutSignature(applyCollapse(withServices, false))).not.toBe(+ layoutSignature(applyCollapse(withServices, true)),+ );+ });+});++describe("computeSystemMapPositions", () => {+ it("lays out a normal graph with ELK and reports it is not simplified", async () => {+ const result = await computeSystemMapPositions(+ graph([node("api", "api"), node("web", "web")], [edge("web", "api")]),+ );+ expect(result.simplified).toBe(false);+ expect(result.positions.size).toBe(2);+ });++ it("falls back to a grid above the layout bound and says so", async () => {+ const many = Array.from({ length: SYSTEM_MAP_MAX_LAYOUT_NODES + 1 }, (_, i) =>+ node(`n${i}`, `r${i}`),+ );+ const result = await computeSystemMapPositions(graph(many, []));+ expect(result.simplified).toBe(true);+ expect(result.positions.size).toBe(many.length);+ // A grid, not a pile: no two nodes share a position.+ const seen = new Set([...result.positions.values()].map((p) => `${p.x},${p.y}`));+ expect(seen.size).toBe(many.length);+ });+});diff --git a/packages/ui/__tests__/workspace/system-map-relayout.test.tsx b/packages/ui/__tests__/workspace/system-map-relayout.test.tsxnew file mode 100644index 000000000..207da9a2b--- /dev/null+++ b/packages/ui/__tests__/workspace/system-map-relayout.test.tsx@@ -0,0 +1,144 @@+/**+ * Guards how often the System Map runs ELK. The layered layout is synchronous+ * main-thread work with a fixed ~23ms floor even on the real 7-node workspace+ * graph, so paying it for a filter toggle is both a stall and a layout jump.+ *+ * Lives in its own file because it wraps the layout module to count calls,+ * which the other system-map tests import unmocked.+ */++import { describe, it, expect, vi, beforeAll, beforeEach } from "vitest";+import { render, screen, fireEvent } from "@testing-library/react";+import type { SystemEdge, SystemGraph, SystemNode } from "@repowise-dev/types";++const computePositions = vi.hoisted(() => vi.fn());++vi.mock("../../src/workspace/system-map/layout", async (importOriginal) => {+ const actual =+ await importOriginal<+ typeof import("../../src/workspace/system-map/layout")+ >();+ return {+ ...actual,+ // Wraps, rather than replaces, the real layout: the assertions are about+ // how often it runs and on what, not about what ELK returns.+ computeSystemMapPositions: (graph: SystemGraph) => {+ computePositions(graph);+ return actual.computeSystemMapPositions(graph);+ },+ };+});++const { SystemMap } = await import("../../src/workspace/system-map/system-map");++beforeAll(() => {+ class RO {+ observe() {}+ unobserve() {}+ disconnect() {}+ }+ vi.stubGlobal("ResizeObserver", RO);+});++beforeEach(() => computePositions.mockClear());++function node(id: string, repo: string): SystemNode {+ return {+ id,+ repo,+ service_path: id.includes("::") ? (id.split("::")[1] ?? null) : null,+ name: id,+ 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}`,+ source,+ target,+ kind: "http",+ match_type: "exact",+ confidence: 1,+ weight: 1,+ structural: true,+ contract_refs: [],+ ...over,+ };+}++const graph: SystemGraph = {+ version: 1,+ generated_at: "2026-06-19T00:00:00Z",+ nodes: [+ node("api::svc/a", "api"),+ node("api::svc/b", "api"),+ node("web", "web"),+ ],+ edges: [+ edge("web", "api::svc/a"),+ edge("api::svc/b", "web", {+ id: "api::svc/b->web:co",+ kind: "co_change",+ structural: false,+ }),+ ],+ diagnostics: {} as never,+};++describe("System Map relayout", () => {+ it("does not re-run ELK when an edge-kind filter is toggled", async () => {+ render(<SystemMap graph={graph} />);+ await screen.findByTitle(/toggle http edges/i);+ expect(computePositions).toHaveBeenCalledTimes(1);++ fireEvent.click(screen.getByTitle(/toggle co-change edges/i));+ await screen.findByTitle(/toggle http edges/i);+ fireEvent.click(screen.getByTitle(/toggle http edges/i));+ await screen.findByTitle(/toggle http edges/i);++ // Two filter toggles, still one layout: node placement describes the+ // system, not the current lens.+ expect(computePositions).toHaveBeenCalledTimes(1);+ });++ it("re-runs ELK when collapse changes the node set, then reuses the result", async () => {+ render(<SystemMap graph={graph} />);+ await screen.findByText("Service view");+ expect(computePositions).toHaveBeenCalledTimes(1);++ fireEvent.click(screen.getByText("Service view"));+ await screen.findByText("Repo view");+ // 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");+ // Both shapes are already cached for this mount.+ expect(computePositions).toHaveBeenCalledTimes(2);+ });++ it("lays out from every edge, not only the visible ones", async () => {+ render(<SystemMap graph={graph} />);+ await screen.findByTitle(/toggle http edges/i);+ fireEvent.click(screen.getByTitle(/toggle co-change edges/i));+ await screen.findByTitle(/toggle http edges/i);++ const laidOut = computePositions.mock.calls[0]?.[0] as SystemGraph;+ expect(laidOut.edges.map((e) => e.id).sort()).toEqual(+ ["api::svc/b->web:co", "web->api::svc/a"].sort(),+ );+ });+});diff --git a/packages/ui/__tests__/workspace/system-map.test.tsx b/packages/ui/__tests__/workspace/system-map.test.tsxindex 17e81bd7b..d21e27860 100644--- a/packages/ui/__tests__/workspace/system-map.test.tsx+++ b/packages/ui/__tests__/workspace/system-map.test.tsx@@ -1,5 +1,5 @@import { describe, it, expect, vi, beforeAll } from "vitest";-import { render, screen, fireEvent } from "@testing-library/react";+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";@@ -169,6 +169,182 @@ describe("SystemMapInspector", () => {);expect(container).toBeEmptyDOMElement();});++ it("shows co-change evidence as the file pair it is, not as a contract link", () => {+ const behavioral = graph(+ [node("web"), node("api")],+ [+ edge("web", "api", {+ kind: "co_change",+ structural: false,+ weight: 1,+ contract_refs: ["app/services/overview.py~src/lib/api/types.ts"],+ }),+ ],+ );+ render(+ <SystemMapInspector+ selection={{ type: "edge", id: "web->api" }}+ graph={behavioral}+ onClose={() => {}}+ onSelectNode={() => {}}+ onOpenContract={vi.fn()}+ />,+ );+ // 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();+ });++ 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();+ });+});++describe("SystemMap chrome placement", () => {+ const g = graph(+ [node("web", { kind: "frontend" }), node("api", { provider_count: 2 })],+ [edge("web", "api", { contract_refs: ["http:GET /v1/users"] })],+ );++ it("puts the inspector in a rail beside the canvas, not on it", 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 flow = container.querySelector(".react-flow")!;+ expect(flow.contains(rail)).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");+ 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();+ });++ it("notifies the current onSelectionChange, not the one it mounted with", async () => {+ const stale = vi.fn();+ const fresh = vi.fn();+ const { rerender } = render(+ <SystemMap graph={g} selection={{ type: "node", id: "api" }} onSelectionChange={stale} />,+ );+ await screen.findByRole("complementary");++ 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"));++ expect(fresh).toHaveBeenCalledWith({ type: "node", id: "web" });+ expect(stale).not.toHaveBeenCalled();+ });++ it("resolves a toggle against the current selection, not the mounted one", 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"));+ 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("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("web", { repo: "web", kind: "frontend" }),+ ],+ [edge("web", "api::svc/a")],+ );+ 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".+ 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();++ fireEvent.click(screen.getByText("Service view"));++ // Repo view: the same id now resolves.+ expect(await screen.findByText(/http relationship/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("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();++ fireEvent.click(screen.getByText("Service view"));++ // 2 + 3, not 2: the repo node is the merge, not the same-named service.+ expect(await screen.findByText("5 contracts")).toBeInTheDocument();+ });});describe("SystemMapBlastPanel", () => {diff --git a/packages/ui/src/workspace/system-map/index.ts b/packages/ui/src/workspace/system-map/index.tsindex 1fb33a2c7..f703cffd9 100644--- a/packages/ui/src/workspace/system-map/index.ts+++ b/packages/ui/src/workspace/system-map/index.ts@@ -28,7 +28,23 @@ export {type RoleStyle,} from "./architecture";export { useSystemMapLayout, type SystemMapLayout, type UseSystemMapLayoutArgs } from "./use-system-map-layout";-export { applyView, computeSystemMapPositions, SYSTEM_MAP_NODE_SIZE, type SystemMapView } from "./layout";+export {+ applyView,+ applyCollapse,+ computeSystemMapPositions,+ layoutSignature,+ SYSTEM_MAP_NODE_SIZE,+ SYSTEM_MAP_MAX_LAYOUT_NODES,+ type SystemMapView,+ type SystemMapPositions,+} from "./layout";+export {+ SystemMapRailPanel,+ RailChip,+ RailEyebrow,+ RailField,+ type SystemMapRailPanelProps,+} from "./system-map-rail";export { collapseToRepos } from "./collapse";export {SYSTEM_EDGE_KINDS,diff --git a/packages/ui/src/workspace/system-map/layout.ts b/packages/ui/src/workspace/system-map/layout.tsindex 0bd0e2828..fabc09dc2 100644--- a/packages/ui/src/workspace/system-map/layout.ts+++ b/packages/ui/src/workspace/system-map/layout.ts@@ -26,16 +26,66 @@ export interface SystemMapView {* isolated service is real signal, not noise to hide).*/export function applyView(graph: SystemGraph, view: SystemMapView): SystemGraph {- const base = view.collapsed ? collapseToRepos(graph) : graph;+ const base = applyCollapse(graph, view.collapsed);const edges = base.edges.filter((e) => view.visibleKinds.has(e.kind));return { ...base, edges };}-/** Position every node via the shared ELK layered layout. */-export async function computeSystemMapPositions(- graph: SystemGraph,-): Promise<Map<string, C4LayoutPosition>> {- return computeC4Layout(+/**+ * The collapse half of the view, without the edge-kind filter. This is what the+ * layout is computed from: collapsing genuinely changes the system's shape, but+ * hiding an edge kind is a lens on the same shape and must not move nodes.+ */+export function applyCollapse(graph: SystemGraph, collapsed: boolean): SystemGraph {+ return collapsed ? collapseToRepos(graph) : graph;+}++/**+ * Above this many nodes ELK's layered layout stops being worth its cost: it runs+ * on the main thread, and measured on the real workspace corpus it takes ~1.8s at+ * 500 nodes and ~3.4s at 1000, which is a frozen tab rather than a slow one. Past+ * the bound we fall back to a deterministic grid, matching the Sigma view's+ * `ELK_MAX_NODES` escape hatch. The map says when it has done so (`simplified`),+ * because a silently downgraded layout is a lie about the shape of the system.+ */+export const SYSTEM_MAP_MAX_LAYOUT_NODES = 500;++export interface SystemMapPositions {+ positions: Map<string, C4LayoutPosition>;+ /** True when the node count forced the grid fallback instead of ELK. */+ simplified: boolean;+}++/** Deterministic grid, used only past `SYSTEM_MAP_MAX_LAYOUT_NODES`. */+function gridPositions(graph: SystemGraph): Map<string, C4LayoutPosition> {+ const columns = Math.ceil(Math.sqrt(graph.nodes.length));+ const dx = SYSTEM_MAP_NODE_SIZE.width + 55;+ const dy = SYSTEM_MAP_NODE_SIZE.height + 90;+ const positions = new Map<string, C4LayoutPosition>();+ graph.nodes.forEach((n, i) => {+ positions.set(n.id, {+ x: (i % columns) * dx,+ y: Math.floor(i / columns) * dy,+ width: SYSTEM_MAP_NODE_SIZE.width,+ height: SYSTEM_MAP_NODE_SIZE.height,+ });+ });+ return positions;+}++/**+ * Position every node via the shared ELK layered layout.+ *+ * Takes the *unfiltered* edge set on purpose. Node positions describe the system,+ * not the current filter, so hiding an edge kind no longer rearranges the map+ * underneath the reader — and no longer pays ELK's ~23ms floor on every toggle.+ * The filtered edges are still the only ones drawn.+ */+export async function computeSystemMapPositions(graph: SystemGraph): Promise<SystemMapPositions> {+ if (graph.nodes.length > SYSTEM_MAP_MAX_LAYOUT_NODES) {+ return { positions: gridPositions(graph), simplified: true };+ }+ const positions = await computeC4Layout(graph.nodes.map((n) => ({id: n.id,width: SYSTEM_MAP_NODE_SIZE.width,@@ -43,4 +93,16 @@ export async function computeSystemMapPositions(})),graph.edges.map((e) => ({ id: e.id, source: e.source, target: e.target })),);+ return { positions, simplified: false };+}++/**+ * Identity of a layout: the node set plus the edges that shape it. Two views with+ * the same signature must get the same positions, which is what lets the hook+ * skip ELK when only the edge-kind filter moved.+ */+export function layoutSignature(graph: SystemGraph): string {+ const nodes = graph.nodes.map((n) => n.id).sort();+ const edges = graph.edges.map((e) => `${e.source}>${e.target}`).sort();+ return `${nodes.join("|")}#${edges.join("|")}`;}diff --git a/packages/ui/src/workspace/system-map/system-map-blast-panel.tsx b/packages/ui/src/workspace/system-map/system-map-blast-panel.tsxindex f73e6b107..755e00fa4 100644--- a/packages/ui/src/workspace/system-map/system-map-blast-panel.tsx+++ b/packages/ui/src/workspace/system-map/system-map-blast-panel.tsx@@ -7,11 +7,15 @@* co-changes historically). Clicking a service re-targets the ripple from it,* so you can walk the impact outward. Pure presentation — the host owns the* fetch and passes the result in; the ripple itself rides the map's overlay prop.+ *+ * Lives in the map's rail, as a card among the other panels, rather than floating+ * on the canvas.*/-import { X, Zap } from "lucide-react";+import { Zap } from "lucide-react";import type { CrossRepoBlastRadius, ImpactedNode } from "@repowise-dev/types";import { impactBadgeTone } from "./blast-radius";+import { RailChip, RailEyebrow, SystemMapRailPanel } from "./system-map-rail";export interface SystemMapBlastPanelProps {result: CrossRepoBlastRadius | null;@@ -21,22 +25,6 @@ export interface SystemMapBlastPanelProps {onClear: () => void;}-const panelStyle: React.CSSProperties = {- position: "absolute",- top: 12,- left: 12,- width: 290,- maxHeight: "calc(100% - 24px)",- overflowY: "auto",- background: "var(--color-bg-elevated)",- border: "1px solid var(--color-border-default)",- borderRadius: 10,- boxShadow: "0 8px 24px rgba(0,0,0,0.28)",- zIndex: 4,- fontSize: 12,- color: "var(--color-text-secondary)",-};-function toneColor(tone: "danger" | "warning" | "info"): string {switch (tone) {case "danger":@@ -62,46 +50,18 @@ function ImpactedRow({type="button"onClick={() => onSelect(node.id)}title={`Re-target the ripple from ${node.name}`}- style={{- display: "flex",- alignItems: "center",- gap: 8,- width: "100%",- textAlign: "left",- padding: "6px 12px",- cursor: "pointer",- background: "transparent",- borderBottom: "1px solid var(--color-border-subtle)",- }}+ className="flex w-full cursor-pointer items-center gap-2 border-b border-[var(--color-border-subtle)] px-3 py-1.5 text-left hover:bg-[var(--color-bg-overlay)]">- <span- title={`distance ${node.distance}`}- style={{- flexShrink: 0,- width: 22,- textAlign: "center",- color,- border: `1px solid color-mix(in srgb, ${color} 45%, transparent)`,- background: `color-mix(in srgb, ${color} 16%, transparent)`,- borderRadius: 4,- fontSize: 9,- fontWeight: 700,- padding: "1px 0",- }}- >- d{node.distance}+ <span title={`distance ${node.distance}`}>+ <RailChip color={color}>d{node.distance}</RailChip></span>- <span style={{ flex: 1, minWidth: 0 }}>- <span style={{ color: "var(--color-text-primary)", display: "block", fontWeight: 600 }}>- {node.name}- </span>- <span style={{ color: "var(--color-text-tertiary)", fontSize: 10 }}>+ <span className="min-w-0 flex-1">+ <span className="block truncate font-semibold text-[var(--color-text-primary)]">{node.name}</span>+ <span className="block truncate text-[10px] text-[var(--color-text-tertiary)]">{node.repo} · {node.edge_kinds.join(", ")}</span></span>- <span style={{ flexShrink: 0, color: "var(--color-text-tertiary)", fontVariantNumeric: "tabular-nums" }}>- {node.score.toFixed(2)}- </span>+ <span className="shrink-0 tabular-nums text-[var(--color-text-tertiary)]">{node.score.toFixed(2)}</span></button>);}@@ -118,18 +78,10 @@ function Section({if (nodes.length === 0) return null;return (<div>- <div- style={{- padding: "6px 12px",- fontSize: 10,- fontWeight: 700,- letterSpacing: 0.5,- textTransform: "uppercase",- color: "var(--color-text-tertiary)",- background: "var(--color-bg-surface)",- }}- >- {title} · {nodes.length}+ <div className="bg-[var(--color-bg-surface)] px-3 py-1.5">+ <RailEyebrow>+ {title} · {nodes.length}+ </RailEyebrow></div>{nodes.map((n) => (<ImpactedRow key={n.id} node={n} onSelect={onSelect} />@@ -150,41 +102,27 @@ export function SystemMapBlastPanel({const behavioral = result.impacted.filter((n) => !n.structural);const sourceLabel = result.targets.join(", ") || result.unresolved_targets.join(", ");- return (- <div style={panelStyle}>- <div- style={{- display: "flex",- alignItems: "center",- justifyContent: "space-between",- padding: "10px 12px",- borderBottom: "1px solid var(--color-border-default)",- }}- >- <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>- <Zap size={13} style={{ color: "var(--color-accent-primary)" }} />- <span style={{ fontSize: 10, fontWeight: 700, letterSpacing: 0.6, textTransform: "uppercase", color: "var(--color-text-tertiary)" }}>- Blast radius- </span>- </span>- <button type="button" onClick={onClear} aria-label="Clear blast radius" style={{ cursor: "pointer", color: "var(--color-text-tertiary)", display: "inline-flex" }}>- <X size={14} />- </button>- </div>-- <div style={{ padding: "8px 12px", borderBottom: "1px solid var(--color-border-default)" }}>- <div style={{ color: "var(--color-text-primary)", fontWeight: 600, wordBreak: "break-word" }}>- {sourceLabel || "—"}- </div>- <div style={{ color: "var(--color-text-tertiary)", fontSize: 11, marginTop: 2 }}>- {loading- ? "Computing impact…"- : `${result.total_impacted} impacted across ${result.impacted_repos.length} other repo(s)`}- </div>- </div>+ const repos = result.impacted_repos.length;+ return (+ <SystemMapRailPanel+ eyebrow="Blast radius"+ icon={<Zap size={13} style={{ color: "var(--color-accent-primary)" }} />}+ onClear={onClear}+ clearLabel="Clear blast radius"+ summary={+ <>+ <div className="break-words font-semibold text-[var(--color-text-primary)]">{sourceLabel || "—"}</div>+ <div className="mt-0.5">+ {loading+ ? "Computing impact…"+ : `${result.total_impacted} impacted across ${repos} other ${repos === 1 ? "repo" : "repos"}`}+ </div>+ </>+ }+ >{!loading && result.impacted.length === 0 && (- <div style={{ padding: "12px", color: "var(--color-text-tertiary)" }}>+ <div className="p-3 text-[var(--color-text-tertiary)]">{result.targets.length === 0? "No matching service in the graph.": "Nothing downstream — no other service depends on this one."}@@ -193,6 +131,6 @@ export function SystemMapBlastPanel({<Section title="Will break (dependency)" nodes={structural} onSelect={onSelectTarget} /><Section title="May drift (co-change)" nodes={behavioral} onSelect={onSelectTarget} />- </div>+ </SystemMapRailPanel>);}diff --git a/packages/ui/src/workspace/system-map/system-map-breaking-panel.tsx b/packages/ui/src/workspace/system-map/system-map-breaking-panel.tsxindex 79b5db046..c1708b6da 100644--- a/packages/ui/src/workspace/system-map/system-map-breaking-panel.tsx+++ b/packages/ui/src/workspace/system-map/system-map-breaking-panel.tsx@@ -8,8 +8,9 @@* passes the report in; the at-risk badges ride the map's overlay prop.*/-import { AlertTriangle, X } from "lucide-react";+import { AlertTriangle } from "lucide-react";import type { BreakingChange, BreakingChangeReport } from "@repowise-dev/types";+import { RailChip, SystemMapRailPanel } from "./system-map-rail";export interface SystemMapBreakingPanelProps {report: BreakingChangeReport | null;@@ -19,22 +20,6 @@ export interface SystemMapBreakingPanelProps {onClear: () => void;}-const panelStyle: React.CSSProperties = {- position: "absolute",- top: 12,- right: 12,- width: 320,- maxHeight: "calc(100% - 24px)",- overflowY: "auto",- background: "var(--color-bg-elevated)",- border: "1px solid var(--color-border-default)",- borderRadius: 10,- boxShadow: "0 8px 24px rgba(0,0,0,0.28)",- zIndex: 4,- fontSize: 12,- color: "var(--color-text-secondary)",-};-function severityColor(severity: string): string {return severity === "breaking" ? "var(--color-risk-high)" : "var(--color-warning)";}@@ -48,70 +33,44 @@ function ChangeRow({}) {const color = severityColor(change.severity);return (- <div style={{ padding: "8px 12px", borderBottom: "1px solid var(--color-border-subtle)" }}>- <div style={{ display: "flex", alignItems: "center", gap: 6 }}>- <span- style={{- flexShrink: 0,- color,- border: `1px solid color-mix(in srgb, ${color} 45%, transparent)`,- background: `color-mix(in srgb, ${color} 16%, transparent)`,- borderRadius: 4,- fontSize: 9,- fontWeight: 700,- textTransform: "uppercase",- padding: "1px 5px",- }}- >- {change.severity}- </span>+ <div className="border-b border-[var(--color-border-subtle)] px-3 py-2">+ <div className="flex items-center gap-1.5">+ <RailChip color={color}>{change.severity}</RailChip><buttontype="button"onClick={() => onSelectNode?.(change.provider_node_id)}+ disabled={!onSelectNode}title={`Provider: ${change.provider_repo} · ${change.provider_file}`}- style={{- flex: 1,- minWidth: 0,- textAlign: "left",- cursor: onSelectNode ? "pointer" : "default",- background: "transparent",- color: "var(--color-text-primary)",- fontWeight: 600,- overflow: "hidden",- textOverflow: "ellipsis",- whiteSpace: "nowrap",- }}+ className={`min-w-0 flex-1 truncate text-left font-semibold text-[var(--color-text-primary)] ${+ onSelectNode ? "cursor-pointer hover:underline" : "cursor-default"+ }`}>{change.contract_id}</button></div>- <div style={{ color: "var(--color-text-secondary)", marginTop: 3 }}>{change.detail}</div>- <div style={{ color: "var(--color-text-tertiary)", fontSize: 10, marginTop: 2 }}>+ <div className="mt-[3px] text-[var(--color-text-secondary)]">{change.detail}</div>+ <div className="mt-0.5 text-[10px] text-[var(--color-text-tertiary)]">{change.provider_repo} · {change.provider_file}</div>{change.impacted_consumers.length > 0 && (- <div style={{ marginTop: 6 }}>- <div style={{ fontSize: 10, fontWeight: 700, color: "var(--color-text-tertiary)" }}>- Endangers {change.impacted_consumers.length} consumer(s)+ <div className="mt-1.5">+ <div className="text-[10px] font-bold text-[var(--color-text-tertiary)]">+ {change.impacted_consumers.length === 1+ ? "Endangers 1 consumer"+ : `Endangers ${change.impacted_consumers.length} consumers`}</div>{change.impacted_consumers.map((c) => (<buttonkey={`${c.node_id}:${c.file}`}type="button"onClick={() => onSelectNode?.(c.node_id)}+ disabled={!onSelectNode}title={`Consumer: ${c.repo} · ${c.file}`}- style={{- display: "block",- width: "100%",- textAlign: "left",- cursor: onSelectNode ? "pointer" : "default",- background: "transparent",- color: "var(--color-text-secondary)",- fontSize: 11,- padding: "2px 0 2px 8px",- }}+ className={`block w-full truncate py-0.5 pl-2 text-left text-[11px] text-[var(--color-text-secondary)] ${+ onSelectNode ? "cursor-pointer hover:underline" : "cursor-default"+ }`}>- <span style={{ color: "var(--color-text-primary)" }}>{c.repo}</span> · {c.file}+ <span className="text-[var(--color-text-primary)]">{c.repo}</span> · {c.file}</button>))}</div>@@ -132,53 +91,21 @@ export function SystemMapBreakingPanel({a.severity === b.severity ? 0 : a.severity === "breaking" ? -1 : 1,);- return (- <div style={panelStyle}>- <div- style={{- display: "flex",- alignItems: "center",- justifyContent: "space-between",- padding: "10px 12px",- borderBottom: "1px solid var(--color-border-default)",- }}- >- <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>- <AlertTriangle size={13} style={{ color: "var(--color-risk-high)" }} />- <span- style={{- fontSize: 10,- fontWeight: 700,- letterSpacing: 0.6,- textTransform: "uppercase",- color: "var(--color-text-tertiary)",- }}- >- Breaking changes- </span>- </span>- <button- type="button"- onClick={onClear}- aria-label="Clear breaking changes"- style={{ cursor: "pointer", color: "var(--color-text-tertiary)", display: "inline-flex" }}- >- <X size={14} />- </button>- </div>-- <div style={{ padding: "8px 12px", borderBottom: "1px solid var(--color-border-default)" }}>- <div style={{ color: "var(--color-text-tertiary)", fontSize: 11 }}>- {loading- ? "Checking the latest update…"- : !report.generated_at- ? "Not yet checked"- : `${report.breaking_count} breaking, ${report.warning_count} warning across ${report.impacted_repos.length} repo(s)`}- </div>- </div>+ const repos = report.impacted_repos.length;+ const summary = `${report.breaking_count} breaking, ${report.warning_count} ${+ report.warning_count === 1 ? "warning" : "warnings"+ } across ${repos} ${repos === 1 ? "repo" : "repos"}`;+ return (+ <SystemMapRailPanel+ eyebrow="Breaking changes"+ icon={<AlertTriangle size={13} style={{ color: "var(--color-risk-high)" }} />}+ onClear={onClear}+ clearLabel="Clear breaking changes"+ summary={loading ? "Checking the latest update…" : !report.generated_at ? "Not yet checked" : summary}+ >{!loading && report.changes.length === 0 && (- <div style={{ padding: "12px", color: "var(--color-text-tertiary)" }}>+ <div className="p-3 text-[var(--color-text-tertiary)]">{/* No timestamp means detection never wrote a result here, so anempty change list is silence rather than an all-clear. */}{!report.generated_at@@ -194,6 +121,6 @@ export function SystemMapBreakingPanel({{...(onSelectNode ? { onSelectNode } : {})}/>))}- </div>+ </SystemMapRailPanel>);}diff --git a/packages/ui/src/workspace/system-map/system-map-conformance-panel.tsx b/packages/ui/src/workspace/system-map/system-map-conformance-panel.tsxindex 02ca165a3..3c75c10be 100644--- a/packages/ui/src/workspace/system-map/system-map-conformance-panel.tsx+++ b/packages/ui/src/workspace/system-map/system-map-conformance-panel.tsx@@ -8,12 +8,13 @@* the violation/cycle badges ride the map's overlay prop.*/-import { ShieldAlert, RefreshCw, X } from "lucide-react";+import { ShieldAlert, RefreshCw } from "lucide-react";import type {ConformanceReport,ConformanceViolation,DependencyCycle,} from "@repowise-dev/types";+import { RailChip, SystemMapRailPanel } from "./system-map-rail";export interface SystemMapConformancePanelProps {report: ConformanceReport | null;@@ -23,22 +24,6 @@ export interface SystemMapConformancePanelProps {onClear: () => void;}-const panelStyle: React.CSSProperties = {- position: "absolute",- top: 12,- right: 12,- width: 340,- maxHeight: "calc(100% - 24px)",- overflowY: "auto",- background: "var(--color-bg-elevated)",- border: "1px solid var(--color-border-default)",- borderRadius: 10,- boxShadow: "0 8px 24px rgba(0,0,0,0.28)",- zIndex: 4,- fontSize: 12,- color: "var(--color-text-secondary)",-};-function NodeButton({id,label,@@ -52,14 +37,11 @@ function NodeButton({<buttontype="button"onClick={() => onSelectNode?.(id)}+ disabled={!onSelectNode}title={id}- style={{- cursor: onSelectNode ? "pointer" : "default",- background: "transparent",- color: "var(--color-text-primary)",- fontWeight: 600,- padding: 0,- }}+ className={`p-0 font-semibold text-[var(--color-text-primary)] ${+ onSelectNode ? "cursor-pointer hover:underline" : "cursor-default"+ }`}>{label}</button>@@ -75,46 +57,30 @@ function ViolationRow({}) {const color = "var(--color-risk-high)";return (- <div style={{ padding: "8px 12px", borderBottom: "1px solid var(--color-border-subtle)" }}>- <div style={{ display: "flex", alignItems: "center", gap: 6, flexWrap: "wrap" }}>- <span- style={{- flexShrink: 0,- color,- border: `1px solid color-mix(in srgb, ${color} 45%, transparent)`,- background: `color-mix(in srgb, ${color} 16%, transparent)`,- borderRadius: 4,- fontSize: 9,- fontWeight: 700,- textTransform: "uppercase",- padding: "1px 5px",- }}- >- violation- </span>+ <div className="border-b border-[var(--color-border-subtle)] px-3 py-2">+ <div className="flex flex-wrap items-center gap-1.5">+ <RailChip color={color}>violation</RailChip><NodeButtonid={violation.source}label={violation.source_name || violation.source}{...(onSelectNode ? { onSelectNode } : {})}/>- <span style={{ color: "var(--color-text-tertiary)" }}>→</span>+ <span className="text-[var(--color-text-tertiary)]">→</span><NodeButtonid={violation.target}label={violation.target_name || violation.target}{...(onSelectNode ? { onSelectNode } : {})}/>- <span style={{ color: "var(--color-text-tertiary)", fontSize: 10 }}>- ({violation.edge_kind})- </span>+ <span className="text-[10px] text-[var(--color-text-tertiary)]">({violation.edge_kind})</span></div>- <div style={{ color: "var(--color-text-secondary)", marginTop: 3 }}>+ <div className="mt-[3px] text-[var(--color-text-secondary)]">breaks rule{" "}- <code style={{ color: "var(--color-warning)" }}>+ <code className="text-[var(--color-warning)]">{violation.rule_source} !-> {violation.rule_target}</code></div>{violation.rule_description && (- <div style={{ color: "var(--color-text-tertiary)", fontSize: 10, marginTop: 2 }}>+ <div className="mt-0.5 text-[10px] text-[var(--color-text-tertiary)]">{violation.rule_description}</div>)}@@ -131,34 +97,18 @@ function CycleRow({}) {const color = "var(--color-warning)";return (- <div style={{ padding: "8px 12px", borderBottom: "1px solid var(--color-border-subtle)" }}>- <div style={{ display: "flex", alignItems: "center", gap: 6 }}>- <span- style={{- flexShrink: 0,- color,- border: `1px solid color-mix(in srgb, ${color} 45%, transparent)`,- background: `color-mix(in srgb, ${color} 16%, transparent)`,- borderRadius: 4,- fontSize: 9,- fontWeight: 700,- textTransform: "uppercase",- padding: "1px 5px",- }}- >- cycle · {cycle.length}- </span>+ <div className="border-b border-[var(--color-border-subtle)] px-3 py-2">+ <div className="flex items-center gap-1.5">+ <RailChip color={color}>cycle · {cycle.length}</RailChip></div>- <div style={{ marginTop: 4, display: "flex", flexWrap: "wrap", alignItems: "center", gap: 4 }}>+ <div className="mt-1 flex flex-wrap items-center gap-1">{cycle.nodes.map((nid, i) => (- <span key={nid} style={{ display: "inline-flex", alignItems: "center", gap: 4 }}>+ <span key={nid} className="inline-flex items-center gap-1"><NodeButton id={nid} label={nid} {...(onSelectNode ? { onSelectNode } : {})} />- {i < cycle.nodes.length - 1 && (- <span style={{ color: "var(--color-text-tertiary)" }}>→</span>- )}+ {i < cycle.nodes.length - 1 && <span className="text-[var(--color-text-tertiary)]">→</span>}</span>))}- <span style={{ color: "var(--color-text-tertiary)" }}>↩</span>+ <span className="text-[var(--color-text-tertiary)]">↩</span></div></div>);@@ -177,64 +127,29 @@ export function SystemMapConformancePanel({const totalCycles = report.total_cycles ?? report.cycle_count;const cycleSummary =totalCycles > report.cycle_count- ? `${report.cycle_count} of ${totalCycles} cycle(s)`- : `${report.cycle_count} cycle(s)`;+ ? `${report.cycle_count} of ${totalCycles} cycles`+ : `${report.cycle_count} ${report.cycle_count === 1 ? "cycle" : "cycles"}`;+ const violations = `${report.violation_count} ${+ report.violation_count === 1 ? "violation" : "violations"+ }`;+ const rules = `${report.rules_evaluated} ${report.rules_evaluated === 1 ? "rule" : "rules"}`;return (- <div style={panelStyle}>- <div- style={{- display: "flex",- alignItems: "center",- justifyContent: "space-between",- padding: "10px 12px",- borderBottom: "1px solid var(--color-border-default)",- }}- >- <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>- <ShieldAlert size={13} style={{ color: "var(--color-risk-high)" }} />- <span- style={{- fontSize: 10,- fontWeight: 700,- letterSpacing: 0.6,- textTransform: "uppercase",- color: "var(--color-text-tertiary)",- }}- >- Architecture conformance- </span>- </span>- <button- type="button"- onClick={onClear}- aria-label="Clear conformance"- style={{ cursor: "pointer", color: "var(--color-text-tertiary)", display: "inline-flex" }}- >- <X size={14} />- </button>- </div>-- <div style={{ padding: "8px 12px", borderBottom: "1px solid var(--color-border-default)" }}>- <div style={{ color: "var(--color-text-tertiary)", fontSize: 11 }}>- {loading- ? "Checking the latest update…"- : !report.generated_at- ? "Not yet checked"- : `${report.violation_count} violation(s), ${cycleSummary} from ${report.rules_evaluated} rule(s)`}- </div>- </div>-+ <SystemMapRailPanel+ eyebrow="Architecture conformance"+ icon={<ShieldAlert size={13} style={{ color: "var(--color-risk-high)" }} />}+ onClear={onClear}+ clearLabel="Clear conformance"+ summary={+ loading+ ? "Checking the latest update…"+ : !report.generated_at+ ? "Not yet checked"+ : `${violations}, ${cycleSummary} from ${rules}`+ }+ >{!loading && report.violations.length === 0 && report.cycles.length === 0 && (- <div- style={{- padding: "12px",- color: "var(--color-text-tertiary)",- display: "flex",- alignItems: "center",- gap: 6,- }}- >+ <div className="flex items-center gap-1.5 p-3 text-[var(--color-text-tertiary)]"><RefreshCw size={12} />{/* An unstamped report is one the checker never wrote a result into.Reporting its zeros as "no violations" is the failure this panel@@ -257,6 +172,6 @@ export function SystemMapConformancePanel({{report.cycles.map((c) => (<CycleRow key={c.nodes.join("->")} cycle={c} {...(onSelectNode ? { onSelectNode } : {})} />))}- </div>+ </SystemMapRailPanel>);}diff --git a/packages/ui/src/workspace/system-map/system-map-filters.tsx b/packages/ui/src/workspace/system-map/system-map-filters.tsxindex 07a6acd1f..fc8a473ea 100644--- a/packages/ui/src/workspace/system-map/system-map-filters.tsx+++ b/packages/ui/src/workspace/system-map/system-map-filters.tsx@@ -8,6 +8,7 @@*/import type { SystemEdgeKind } from "@repowise-dev/types";+import { Separator } from "../../ui/separator";import { EDGE_KIND_ORDER, SYSTEM_EDGE_KINDS } from "./edge-kinds";export interface SystemMapFiltersProps {@@ -28,8 +29,15 @@ export function SystemMapFilters({}: 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"+ }`;+return (- <div style={{ display: "flex", flexWrap: "wrap", alignItems: "center", gap: 8 }}>+ <div className="flex flex-wrap items-center gap-2">{kinds.map((kind) => {const s = SYSTEM_EDGE_KINDS[kind];const Icon = s.icon;@@ -41,42 +49,20 @@ export function SystemMapFilters({onClick={() => onToggleKind(kind)}aria-pressed={active}title={`Toggle ${s.label} edges`}- style={{- display: "inline-flex",- alignItems: "center",- gap: 5,- padding: "3px 9px",- borderRadius: 999,- fontSize: 11,- fontWeight: 500,- cursor: "pointer",- color: active ? "var(--color-text-primary)" : "var(--color-text-tertiary)",- background: active ? "var(--color-bg-elevated)" : "transparent",- border: `1px solid ${active ? "var(--color-border-default)" : "var(--color-border-subtle)"}`,- opacity: active ? 1 : 0.6,- }}+ className={pill(active)}><Icon size={11} style={{ color: s.color }} aria-hidden />{s.label}</button>);})}- <div style={{ width: 1, height: 18, background: "var(--color-border-default)" }} />+ <Separator orientation="vertical" className="h-[18px]" /><buttontype="button"onClick={onToggleCollapsed}aria-pressed={collapsed}title="Group services into one node per repository"- style={{- padding: "3px 9px",- borderRadius: 999,- fontSize: 11,- fontWeight: 500,- cursor: "pointer",- color: collapsed ? "var(--color-text-primary)" : "var(--color-text-tertiary)",- background: collapsed ? "var(--color-bg-elevated)" : "transparent",- border: `1px solid ${collapsed ? "var(--color-border-default)" : "var(--color-border-subtle)"}`,- }}+ className={`${pill(collapsed)} opacity-100`}>{collapsed ? "Repo view" : "Service view"}</button>diff --git a/packages/ui/src/workspace/system-map/system-map-inspector.tsx b/packages/ui/src/workspace/system-map/system-map-inspector.tsxindex a41ad0d03..2a449f68b 100644--- a/packages/ui/src/workspace/system-map/system-map-inspector.tsx+++ b/packages/ui/src/workspace/system-map/system-map-inspector.tsx@@ -1,14 +1,16 @@"use client";/**- * Right-rail inspector for the Live System Map. Mirrors the C4 node inspector- * idiom (absolute panel, top-right, close button) but is driven by the current- * selection: a service node (health, provider/consumer counts, contract types,- * connected services) or an edge (kind, match type, confidence, weight, and the- * underlying contract refs with a hook to open them on the Contracts surface).+ * 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 { X } from "lucide-react";import type {NodeArchitectureRole,SystemEdge,@@ -19,10 +21,12 @@ 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). */@@ -34,52 +38,6 @@ export interface SystemMapInspectorProps {onOpenContract?: (contractId: string) => void;}-const panelStyle: React.CSSProperties = {- position: "absolute",- top: 12,- right: 12,- width: 300,- maxHeight: "calc(100% - 24px)",- overflowY: "auto",- background: "var(--color-bg-elevated)",- border: "1px solid var(--color-border-default)",- borderRadius: 10,- boxShadow: "0 8px 24px rgba(0,0,0,0.28)",- zIndex: 4,- fontSize: 12,- color: "var(--color-text-secondary)",-};--function Header({ kind, onClose }: { kind: string; onClose: () => void }) {- return (- <div- style={{- display: "flex",- alignItems: "center",- justifyContent: "space-between",- padding: "10px 12px",- borderBottom: "1px solid var(--color-border-default)",- }}- >- <span style={{ fontSize: 10, fontWeight: 700, letterSpacing: 0.6, textTransform: "uppercase", color: "var(--color-text-tertiary)" }}>- {kind}- </span>- <button type="button" onClick={onClose} aria-label="Close inspector" style={{ cursor: "pointer", color: "var(--color-text-tertiary)", display: "inline-flex" }}>- <X size={14} />- </button>- </div>- );-}--function Field({ label, value }: { label: string; value: React.ReactNode }) {- return (- <div style={{ display: "flex", justifyContent: "space-between", gap: 12, padding: "3px 0" }}>- <span style={{ color: "var(--color-text-tertiary)" }}>{label}</span>- <span style={{ color: "var(--color-text-primary)", textAlign: "right", wordBreak: "break-word" }}>{value}</span>- </div>- );-}-function NodeBody({node,graph,@@ -99,42 +57,85 @@ function NodeBody({const neighbour = (id: string) => graph.nodes.find((n) => n.id === id)?.name ?? id;return (- <div style={{ padding: "10px 12px", display: "flex", flexDirection: "column", gap: 8 }}>- <div style={{ display: "flex", alignItems: "center", gap: 10 }}>+ <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>- <div style={{ fontSize: 14, fontWeight: 600, color: "var(--color-text-primary)" }}>{node.name}</div>- <div style={{ fontSize: 11, color: "var(--color-text-tertiary)" }}>{kind.label} · {node.repo}</div>+ <div 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 && (- <Field+ <RailFieldlabel="Role"value={- <span title={roleStyle(role.role).description} style={{ display: "inline-flex", alignItems: "center", gap: 5 }}>- <span style={{ width: 7, height: 7, borderRadius: "50%", background: roleStyle(role.role).color }} />+ <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 && (- <Field+ <RailFieldlabel="Visibility (in / out)"value={`${role.visibility_fan_in} / ${role.visibility_fan_out}`}/>)}- {node.service_path && <Field label="Path" value={<span style={{ fontFamily: "var(--font-mono, monospace)", fontSize: 11 }}>{node.service_path}</span>} />}- <Field label="Provides" value={`${node.provider_count} contracts`} />- <Field label="Consumes" value={`${node.consumer_count} contracts`} />- <Field label="Types" value={node.contract_types.length ? node.contract_types.join(", ") : "none"} />- {node.is_orphan_provider && <Field label="Status" value={<span style={{ color: "var(--color-warning)" }}>Orphan provider</span>} />}- {node.is_orphan_consumer && <Field label="Status" value={<span style={{ color: "var(--color-warning)" }}>Orphan consumer</span>} />}- {node.is_isolated && <Field label="Status" value={<span style={{ color: "var(--color-text-tertiary)" }}>Isolated</span>} />}+ {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} />+ <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>);}@@ -155,10 +156,10 @@ function NeighbourList({if (edges.length === 0) return null;return (<div>- <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: 0.4, textTransform: "uppercase", color: "var(--color-text-tertiary)", marginBottom: 3 }}>- {title}+ <div className="mb-[3px]">+ <RailEyebrow>{title}</RailEyebrow></div>- <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>+ <div className="flex flex-col gap-0.5">{edges.map((e) => {const id = resolve(e);const s = edgeKindStyle(e.kind);@@ -167,11 +168,14 @@ function NeighbourList({key={e.id}type="button"onClick={() => onSelectNode(id)}- style={{ display: "flex", alignItems: "center", gap: 6, padding: "2px 4px", borderRadius: 4, cursor: "pointer", textAlign: "left", color: "var(--color-text-secondary)" }}+ 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 style={{ width: 7, height: 7, borderRadius: "50%", background: s.color, flexShrink: 0 }} />- <span style={{ flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{neighbour(id)}</span>- <span style={{ fontSize: 10, color: "var(--color-text-tertiary)" }}>{s.label}</span>+ <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>);})}@@ -180,6 +184,89 @@ function NeighbourList({);}+/**+ * 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,@@ -195,87 +282,79 @@ function EdgeBody({const name = (id: string) => graph.nodes.find((n) => n.id === id)?.name ?? id;const Icon = s.icon;return (- <div style={{ padding: "10px 12px", display: "flex", flexDirection: "column", gap: 8 }}>- <div style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 13, color: "var(--color-text-primary)" }}>+ <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>- <Field label="From" value={<LinkText label={name(edge.source)} onClick={() => onSelectNode(edge.source)} />} />- <Field label="To" value={<LinkText label={name(edge.target)} onClick={() => onSelectNode(edge.target)} />} />- <Field label="Match" value={matchTypeLabel(edge.match_type)} />- <Field label="Confidence" value={`${Math.round(edge.confidence * 100)}%`} />- <Field label="Weight" value={String(edge.weight)} />- <Field label="Nature" value={edge.structural ? "Structural" : "Behavioral"} />+ <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>- {edge.contract_refs.length > 0 && (- <div>- <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: 0.4, textTransform: "uppercase", color: "var(--color-text-tertiary)", marginBottom: 3 }}>- {/* Back-pointers are capped per edge while `weight` counts every- contributor, so the two numbers diverge silently once an edge- is busy enough. Name the cap instead of showing two figures- the reader has to reconcile. */}- {edge.weight > edge.contract_refs.length- ? `Evidence (${edge.contract_refs.length} of ${edge.weight})`- : `Evidence (${edge.contract_refs.length})`}- </div>- <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>- {edge.contract_refs.map((ref) => (- <button- key={ref}- type="button"- onClick={onOpenContract ? () => onOpenContract(ref) : undefined}- disabled={!onOpenContract}- title={onOpenContract ? "Open on the Contracts page" : ref}- style={{- fontFamily: "var(--font-mono, monospace)",- fontSize: 10.5,- textAlign: "left",- color: onOpenContract ? "var(--color-accent-primary)" : "var(--color-text-tertiary)",- cursor: onOpenContract ? "pointer" : "default",- overflow: "hidden",- textOverflow: "ellipsis",- whiteSpace: "nowrap",- }}- >- {ref}- </button>- ))}- </div>- </div>- )}+ <EdgeEvidence edge={edge} {...(onOpenContract ? { onOpenContract } : {})} /></div>);}function LinkText({ label, onClick }: { label: string; onClick: () => void }) {return (- <button type="button" onClick={onClick} style={{ color: "var(--color-accent-primary)", cursor: "pointer" }}>+ <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) {+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 (- <div style={panelStyle}>- <Header kind="Service" onClose={onClose} />- <NodeBody node={node} graph={graph} health={healthByRepo?.get(node.repo) ?? null} role={roleByNodeId?.get(node.id) ?? null} onSelectNode={onSelectNode} />- </div>+ <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 (- <div style={panelStyle}>- <Header kind="Relationship" onClose={onClose} />- <EdgeBody edge={edge} graph={graph} onSelectNode={onSelectNode} {...(onOpenContract ? { onOpenContract } : {})} />- </div>+ <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.tsxindex ce679bae6..d88611157 100644--- a/packages/ui/src/workspace/system-map/system-map-legend.tsx+++ b/packages/ui/src/workspace/system-map/system-map-legend.tsx@@ -1,21 +1,19 @@"use client";/**- * Static legend for the Live System Map: what the edge colours/glyphs mean- * (by kind), what the dash patterns mean (by match confidence), and the node- * health scale. Reads the same registries the map renders from, so the two can- * never drift.+ * 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.*/import { EDGE_KIND_ORDER, SYSTEM_EDGE_KINDS } from "./edge-kinds";-function Row({ children }: { children: React.ReactNode }) {- return <div style={{ display: "flex", flexWrap: "wrap", gap: 10, alignItems: "center" }}>{children}</div>;-}-function Item({ swatch, label }: { swatch: React.ReactNode; label: string }) {return (- <span style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 10.5, color: "var(--color-text-secondary)" }}>+ <span className="inline-flex items-center gap-1.5 text-[10.5px] text-[var(--color-text-secondary)]">{swatch}{label}</span>@@ -36,42 +34,31 @@ function dashLine(dash: string, label: string) {);}+function Dot({ color }: { color: string }) {+ return <span className="inline-block h-2.5 w-2.5 rounded-full" style={{ background: color }} />;+}+export function SystemMapLegend() {return (- <div- style={{- display: "flex",- flexDirection: "column",- gap: 6,- padding: "8px 10px",- background: "var(--color-bg-surface)",- border: "1px solid var(--color-border-default)",- borderRadius: 8,- maxWidth: 460,- }}- >- <Row>+ <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 />} />;})}- </Row>- <Row>+ </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)")}- </Row>- <Row>- <span style={{ fontSize: 10.5, color: "var(--color-text-tertiary)" }}>Node ring = repo health:</span>+ </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" />- </Row>+ </div></div>);}--function Dot({ color }: { color: string }) {- return <span style={{ width: 10, height: 10, borderRadius: "50%", background: color, display: "inline-block" }} />;-}diff --git a/packages/ui/src/workspace/system-map/system-map-rail.tsx b/packages/ui/src/workspace/system-map/system-map-rail.tsxnew file mode 100644index 000000000..fc542f934--- /dev/null+++ b/packages/ui/src/workspace/system-map/system-map-rail.tsx@@ -0,0 +1,119 @@+"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.+ */++import { X } from "lucide-react";+import { Card } from "../../ui/card";++export interface SystemMapRailPanelProps {+ /** Small-caps panel identity, e.g. "Blast radius". */+ eyebrow: string;+ /** Optional leading glyph, already coloured by the caller. */+ icon?: React.ReactNode;+ /** One-line status under the header (counts, "not yet checked", errors). */+ summary?: React.ReactNode;+ onClear: () => void;+ /** Accessible name for the dismiss button, e.g. "Clear blast radius". */+ clearLabel: string;+ children?: React.ReactNode;+}++/** Small-caps eyebrow, the rail's one label idiom. */+export function RailEyebrow({ children }: { children: React.ReactNode }) {+ return (+ <span className="text-[10px] font-bold uppercase tracking-[0.06em] text-[var(--color-text-tertiary)]">+ {children}+ </span>+ );+}++/** 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+ * feature owns.+ */+export function RailChip({+ color,+ children,+}: {+ color: string;+ children: React.ReactNode;+}) {+ return (+ <span+ className="shrink-0 rounded-[var(--radius-sm)] px-1.5 py-px text-[9px] font-bold uppercase"+ style={{+ color,+ border: `1px solid color-mix(in srgb, ${color} 45%, transparent)`,+ background: `color-mix(in srgb, ${color} 16%, transparent)`,+ }}+ >+ {children}+ </span>+ );+}++export function SystemMapRailPanel({+ eyebrow,+ icon,+ summary,+ onClear,+ clearLabel,+ children,+}: SystemMapRailPanelProps) {+ return (+ <Card className="overflow-hidden bg-[var(--color-bg-elevated)] text-xs text-[var(--color-text-secondary)] shadow-[var(--shadow-lg)]">+ <div className="flex items-center justify-between gap-2 border-b border-[var(--color-border-default)] px-3 py-2.5">+ <span className="inline-flex min-w-0 items-center gap-1.5">+ {icon}+ <RailEyebrow>{eyebrow}</RailEyebrow>+ </span>+ <button+ type="button"+ onClick={onClear}+ aria-label={clearLabel}+ className="inline-flex shrink-0 cursor-pointer text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)]"+ >+ <X size={14} />+ </button>+ </div>++ {summary !== undefined && (+ <div className="border-b border-[var(--color-border-default)] px-3 py-2 text-[11px] text-[var(--color-text-tertiary)]">+ {summary}+ </div>+ )}++ {children}+ </Card>+ );+}diff --git a/packages/ui/src/workspace/system-map/system-map.tsx b/packages/ui/src/workspace/system-map/system-map.tsxindex 0b90a74da..c3577908f 100644--- a/packages/ui/src/workspace/system-map/system-map.tsx+++ b/packages/ui/src/workspace/system-map/system-map.tsx@@ -10,7 +10,7 @@* prop without forking this component.*/-import { useCallback, useMemo, useState } from "react";+import { useCallback, useMemo, useRef, useState } from "react";import {Background,BackgroundVariant,@@ -30,7 +30,7 @@ import { SystemMapLegend } from "./system-map-legend";import { SystemMapFilters } from "./system-map-filters";import { SystemMapInspector } from "./system-map-inspector";import { useSystemMapLayout } from "./use-system-map-layout";-import type { SystemMapView } from "./layout";+import { SYSTEM_MAP_MAX_LAYOUT_NODES, type SystemMapView } from "./layout";import type { RepoHealth, SystemMapOverlay, SystemMapSelection } from "./types";import { toFriendlyMessage } from "../../lib/errors";@@ -46,6 +46,16 @@ export interface SystemMapProps {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;+ /** Controlled selection, so the host can put it in the URL. */+ selection?: SystemMapSelection;+ onSelectionChange?: (selection: SystemMapSelection) => void;}export function SystemMap(props: SystemMapProps) {@@ -56,7 +66,18 @@ export function SystemMap(props: SystemMapProps) {);}-function SystemMapInner({ graph, loading, error, healthByRepo, overlay, roleByNodeId, onOpenContract }: SystemMapProps) {+function SystemMapInner({+ graph,+ loading,+ error,+ healthByRepo,+ overlay,+ roleByNodeId,+ onOpenContract,+ rail,+ selection: controlledSelection,+ onSelectionChange,+}: SystemMapProps) {const availableKinds = useMemo<Set<SystemEdgeKind>>(() => new Set((graph?.edges ?? []).map((e) => e.kind)),[graph],@@ -64,7 +85,28 @@ function SystemMapInner({ graph, loading, error, healthByRepo, overlay, roleByNoconst [hiddenKinds, setHiddenKinds] = useState<Set<SystemEdgeKind>>(() => new Set());const [collapsed, setCollapsed] = useState(false);- const [selection, setSelection] = useState<SystemMapSelection>(null);+ 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);+ }+ },+ [],+ );const visibleKinds = useMemo<Set<SystemEdgeKind>>(() => new Set([...availableKinds].filter((k) => !hiddenKinds.has(k))),@@ -73,7 +115,7 @@ function SystemMapInner({ graph, loading, error, healthByRepo, overlay, roleByNoconst view = useMemo<SystemMapView>(() => ({ visibleKinds, collapsed }), [visibleKinds, collapsed]);- const { nodes, edges, loading: layoutLoading } = useSystemMapLayout({+ const { nodes, edges, loading: layoutLoading, viewGraph, simplified } = useSystemMapLayout({graph,view,...(healthByRepo ? { healthByRepo } : {}),@@ -110,19 +152,13 @@ function SystemMapInner({ graph, loading, error, healthByRepo, overlay, roleByNoconst hasGraph = graph && graph.nodes.length > 0;const hasEdges = (graph?.edges.length ?? 0) > 0;+ const hasRail = Boolean(rail) || selection !== null;+return (- <div style={{ position: "relative", width: "100%", height: "100%", display: "flex", flexDirection: "column", background: "var(--color-bg-canvas)" }}>- <div- style={{- display: "flex",- alignItems: "center",- gap: 16,- padding: "8px 12px",- borderBottom: "1px solid var(--color-border-default)",- background: "var(--color-bg-surface)",- flexWrap: "wrap",- }}- >+ <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"><SystemMapFiltersavailableKinds={availableKinds}visibleKinds={visibleKinds}@@ -130,13 +166,19 @@ function SystemMapInner({ graph, loading, error, healthByRepo, overlay, roleByNocollapsed={collapsed}onToggleCollapsed={onToggleCollapsed}/>- <div style={{ marginLeft: "auto" }}>- <SystemMapLegend />- </div></div>- <div style={{ position: "relative", flex: 1, minHeight: 0 }}>- {error ? (+ {/* 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>@@ -176,26 +218,47 @@ function SystemMapInner({ graph, loading, error, healthByRepo, overlay, roleByNo<Controls showInteractive={false} /><MiniMap pannable zoomable /></ReactFlow>+ </div>++ {/* The key reads as a caption under the field, not as a card on it. */}+ <SystemMapLegend />- {graph && (- <SystemMapInspector- selection={selection}- graph={graph}- {...(healthByRepo ? { healthByRepo } : {})}- {...(roleByNodeId ? { roleByNodeId } : {})}- onClose={() => setSelection(null)}- onSelectNode={selectNode}- {...(onOpenContract ? { onOpenContract } : {})}- />+ {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>++ {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 } : {})}+ />+ )}+ {rail}+ </aside>)}</div></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.+ */function Centered({ children }: { children: React.ReactNode }) {return (- <div style={{ position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "center", zIndex: 3, pointerEvents: "none" }}>+ <div className="pointer-events-none absolute inset-0 z-[3] flex items-center justify-center">{children}</div>);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.tsindex 6ec1c9ed4..8953cd8f6 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@@ -7,10 +7,16 @@* loading flag, cancel-on-unmount). Pure inputs in, render-ready arrays out.*/-import { useEffect, useMemo, useState } from "react";+import { useEffect, useMemo, useRef, useState } from "react";import { MarkerType, type Edge, type Node } from "@xyflow/react";import type { SystemGraph } from "@repowise-dev/types";-import { applyView, computeSystemMapPositions, type SystemMapView } from "./layout";+import {+ applyCollapse,+ applyView,+ computeSystemMapPositions,+ layoutSignature,+ type SystemMapView,+} from "./layout";import {resolveEdgeOverlay,resolveNodeOverlay,@@ -32,6 +38,14 @@ export interface SystemMapLayout {nodes: Node<SystemMapNodeData>[];edges: Edge<SystemMapEdgeData>[];loading: boolean;+ /**+ * The graph actually on screen (collapse + filters applied). The inspector+ * must resolve selections against this, not the raw graph: in repo view the+ * ids it can be handed only exist here.+ */+ viewGraph: SystemGraph | null;+ /** True when the node count forced the grid fallback instead of ELK. */+ simplified: boolean;}export function useSystemMapLayout({@@ -41,27 +55,65 @@ export function useSystemMapLayout({overlay,}: UseSystemMapLayoutArgs): SystemMapLayout {const viewGraph = useMemo(() => (graph ? applyView(graph, view) : null), [graph, view]);- const [positions, setPositions] = useState<Map<string, { x: number; y: number }> | null>(null);++ // Laid out from the collapse state only. Toggling an edge-kind filter leaves+ // this identical, so the effect below sees the same signature and never+ // re-runs ELK — the map holds still and the ~23ms main-thread cost is not paid.+ const layoutGraph = useMemo(+ () => (graph ? applyCollapse(graph, view.collapsed) : null),+ [graph, view.collapsed],+ );+ const signature = useMemo(+ () => (layoutGraph ? layoutSignature(layoutGraph) : null),+ [layoutGraph],+ );++ const [layout, setLayout] = useState<{+ positions: Map<string, { x: number; y: number }>;+ simplified: boolean;+ } | null>(null);const [loading, setLoading] = useState(true);+ // Positions keyed by layout signature, so collapsing and un-collapsing is free+ // after the first pass in each direction. Dropped whenever a new graph arrives:+ // one graph has only the two collapse shapes, so holding entries for superseded+ // graphs would grow the map for refetches it can never serve again.+ const cache = useRef(+ new Map<string, { positions: Map<string, { x: number; y: number }>; simplified: boolean }>(),+ );+ const cachedGraph = useRef(graph);+ if (cachedGraph.current !== graph) {+ cachedGraph.current = graph;+ cache.current.clear();+ }+useEffect(() => {let cancelled = false;- if (!viewGraph || viewGraph.nodes.length === 0) {- setPositions(new Map());+ if (!layoutGraph || !signature || layoutGraph.nodes.length === 0) {+ setLayout({ positions: new Map(), simplified: false });+ setLoading(false);+ return;+ }+ const cached = cache.current.get(signature);+ if (cached) {+ setLayout(cached);setLoading(false);return;}setLoading(true);- computeSystemMapPositions(viewGraph).then((pos) => {+ computeSystemMapPositions(layoutGraph).then((result) => {+ cache.current.set(signature, result);if (!cancelled) {- setPositions(pos);+ setLayout(result);setLoading(false);}});return () => {cancelled = true;};- }, [viewGraph]);+ }, [layoutGraph, signature]);++ const positions = layout?.positions ?? null;const nodes = useMemo<Node<SystemMapNodeData>[]>(() => {if (!viewGraph || !positions) return [];@@ -92,5 +144,5 @@ export function useSystemMapLayout({}));}, [viewGraph, overlay]);- return { nodes, edges, loading };+ return { nodes, edges, loading, viewGraph, simplified: layout?.simplified ?? false };}diff --git a/packages/web/src/app/workspace/system-map/page.tsx b/packages/web/src/app/workspace/system-map/page.tsxindex ea49ceb6c..c106367e0 100644--- a/packages/web/src/app/workspace/system-map/page.tsx+++ b/packages/web/src/app/workspace/system-map/page.tsx@@ -1,7 +1,7 @@"use client";-import { useMemo, useState } from "react";-import { useRouter } from "next/navigation";+import { useCallback, useMemo, useState } from "react";+import { useRouter, useSearchParams } from "next/navigation";import { Waypoints, Boxes, ArrowLeftRight, Share2, Zap, AlertTriangle, ShieldAlert, Gauge } from "lucide-react";import {SystemMap,@@ -13,6 +13,7 @@ import {buildConformanceOverlay,buildArchitectureOverlay,type RepoHealth,+ 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";@@ -28,9 +29,33 @@ import {export default function SystemMapPage() {const router = useRouter();+ const searchParams = useSearchParams();const { data: graph, isLoading, error } = useWorkspaceSystemGraph();const { data: repoGraph } = useWorkspaceGraph();+ // Selection lives in the URL so a service or seam you found can be linked to.+ const selection = useMemo<SystemMapSelection>(() => {+ const node = searchParams.get("node");+ if (node) return { type: "node", id: node };+ const edge = searchParams.get("edge");+ if (edge) return { type: "edge", id: edge };+ return null;+ }, [searchParams]);++ const onSelectionChange = useCallback(+ (next: SystemMapSelection) => {+ const params = new URLSearchParams(searchParams.toString());+ params.delete("node");+ params.delete("edge");+ if (next) params.set(next.type, next.id);+ const query = params.toString();+ // `replace`, not `push`: clicking around a diagram should not build a+ // back-button history of every node you glanced at.+ 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.@@ -86,6 +111,17 @@ export default function SystemMapPage() {return undefined;}, [graph, blast, showBreaking, breaking, showConformance, conformance, showArchitecture, 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 diag = graph?.diagnostics;const serviceCount = graph?.nodes.length ?? 0;const edgeCount = graph?.edges.length ?? 0;@@ -248,44 +284,50 @@ export default function SystemMapPage() {)}</div>- <div className="relative rounded-lg overflow-hidden border border-[var(--color-border-default)] h-[calc(100vh-360px)] min-h-[560px]">+ <div className="rounded-lg overflow-hidden border border-[var(--color-border-default)] h-[calc(100vh-360px)] min-h-[560px]">{isLoading ? (<div className="p-4 h-full"><Skeleton className="h-full w-full" /></div>) : (- <>- <SystemMap- graph={graph}- error={error ?? null}- healthByRepo={healthByRepo}- {...(overlay ? { overlay } : {})}- roleByNodeId={roleByNodeId}- onOpenContract={() => router.push("/workspace/contracts")}- />- <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)}- />- )}- </>+ <SystemMap+ graph={graph}+ error={error ?? null}+ healthByRepo={healthByRepo}+ {...(overlay ? { overlay } : {})}+ roleByNodeId={roleByNodeId}+ 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+ }+ />)}</div></div>