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(ui): system map levels model (groups, bands, focus, draw budget) (#4603)
Raghav Chamadiya434bfe82eed5
diff --git a/packages/ui/__tests__/workspace/fixtures/eshop-system-graph.ts b/packages/ui/__tests__/workspace/fixtures/eshop-system-graph.tsnew file mode 100644index 000000000..8a27dd2f6--- /dev/null+++ b/packages/ui/__tests__/workspace/fixtures/eshop-system-graph.ts@@ -0,0 +1,91 @@+/**+ * The eShop reference estate's system graph (18 services, 44 edges), cut to the+ * fields the levels model reads. Real shape: one service per repo, package+ * edges fanning into shared libraries, events both ways between catalog.api+ * and ordering.api, and one gateway-routed HTTP link.+ */++import type { LinkStrategyWire, SystemEdgeKind } from "@repowise-dev/types";+import type { LevelsGraph } from "../../../src/workspace/system-map/level-types";++type Row = [source: string, target: string, kind: string, weight: number, strategy: string];++const SERVICES = [+ "basket.api",+ "catalog.api",+ "clientapp",+ "eshop.servicedefaults",+ "eventbus",+ "eventbusrabbitmq",+ "hybridapp",+ "identity.api",+ "integrationeventlogef",+ "ordering.api",+ "ordering.domain",+ "ordering.infrastructure",+ "orderprocessor",+ "paymentprocessor",+ "webapp",+ "webappcomponents",+ "webhookclient",+ "webhooks.api",+];++const EDGES: Row[] = [+ ["basket.api", "eshop.servicedefaults", "package", 1, "manifest"],+ ["basket.api", "eventbusrabbitmq", "package", 1, "manifest"],+ ["basket.api", "ordering.api", "event", 1, "exact_id"],+ ["catalog.api", "eshop.servicedefaults", "package", 1, "manifest"],+ ["catalog.api", "eventbusrabbitmq", "package", 1, "manifest"],+ ["catalog.api", "integrationeventlogef", "package", 1, "manifest"],+ ["catalog.api", "ordering.api", "event", 2, "exact_id"],+ ["clientapp", "basket.api", "grpc", 1, "exact_id"],+ ["clientapp", "catalog.api", "http", 4, "unique_path"],+ ["clientapp", "ordering.api", "http", 4, "unique_path"],+ ["eventbusrabbitmq", "eventbus", "package", 1, "manifest"],+ ["hybridapp", "catalog.api", "http", 5, "exact_id"],+ ["identity.api", "eshop.servicedefaults", "package", 1, "manifest"],+ ["integrationeventlogef", "eventbus", "package", 1, "manifest"],+ ["ordering.api", "catalog.api", "event", 2, "exact_id"],+ ["ordering.api", "eshop.servicedefaults", "package", 1, "manifest"],+ ["ordering.api", "eventbusrabbitmq", "package", 1, "manifest"],+ ["ordering.api", "integrationeventlogef", "package", 1, "manifest"],+ ["ordering.api", "ordering.domain", "package", 1, "manifest"],+ ["ordering.api", "ordering.infrastructure", "package", 1, "manifest"],+ ["ordering.api", "orderprocessor", "event", 1, "exact_id"],+ ["ordering.api", "paymentprocessor", "event", 2, "exact_id"],+ ["ordering.infrastructure", "integrationeventlogef", "package", 1, "manifest"],+ ["ordering.infrastructure", "ordering.domain", "package", 1, "manifest"],+ ["orderprocessor", "eshop.servicedefaults", "package", 1, "manifest"],+ ["orderprocessor", "eventbusrabbitmq", "package", 1, "manifest"],+ ["paymentprocessor", "eshop.servicedefaults", "package", 1, "manifest"],+ ["paymentprocessor", "eventbusrabbitmq", "package", 1, "manifest"],+ ["paymentprocessor", "ordering.api", "event", 1, "exact_id"],+ ["webapp", "basket.api", "grpc", 2, "exact_id"],+ ["webapp", "catalog.api", "http", 2, "gateway_route"],+ ["webapp", "eshop.servicedefaults", "package", 1, "manifest"],+ ["webapp", "eventbusrabbitmq", "package", 1, "manifest"],+ ["webapp", "ordering.api", "event", 6, "exact_id"],+ ["webapp", "ordering.api", "http", 2, "service_mapped"],+ ["webapp", "webappcomponents", "package", 1, "manifest"],+ ["webappcomponents", "catalog.api", "http", 6, "exact_id"],+ ["webhookclient", "eshop.servicedefaults", "package", 1, "manifest"],+ ["webhookclient", "webhooks.api", "http", 2, "service_mapped"],+ ["webhooks.api", "catalog.api", "event", 1, "exact_id"],+ ["webhooks.api", "eshop.servicedefaults", "package", 1, "manifest"],+ ["webhooks.api", "eventbusrabbitmq", "package", 1, "manifest"],+ ["webhooks.api", "integrationeventlogef", "package", 1, "manifest"],+ ["webhooks.api", "ordering.api", "event", 2, "exact_id"],+];++export const ESHOP_GRAPH: LevelsGraph = {+ nodes: SERVICES.map((id) => ({ id, name: id, repo: id })),+ edges: EDGES.map(([source, target, kind, weight, strategy]) => ({+ id: `${source}->${target}:${kind}`,+ source,+ target,+ kind: kind as SystemEdgeKind,+ weight,+ strategy: strategy as LinkStrategyWire,+ })),+};diff --git a/packages/ui/__tests__/workspace/system-map-between.test.ts b/packages/ui/__tests__/workspace/system-map-between.test.tsnew file mode 100644index 000000000..5c46d009f--- /dev/null+++ b/packages/ui/__tests__/workspace/system-map-between.test.ts@@ -0,0 +1,110 @@+import { describe, expect, it } from "vitest";+import { buildAdjacency, servicesBetween, shortestPaths } from "../../src/workspace/system-map/between";+import type { EdgeFamily } from "../../src/workspace/system-map/edge-families";+import type { LevelsEdge, LevelsGraph } from "../../src/workspace/system-map/level-types";+import { ESHOP_GRAPH } from "./fixtures/eshop-system-graph";++function edge(source: string, target: string, kind: LevelsEdge["kind"] = "http", weight = 1): LevelsEdge {+ return { id: `${source}->${target}:${kind}`, source, target, kind, weight, strategy: null };+}++function graphOf(edges: LevelsEdge[]): LevelsGraph {+ const ids = new Set(edges.flatMap((e) => [e.source, e.target]));+ return { nodes: [...ids].map((id) => ({ id, name: id, repo: id })), edges };+}++describe("servicesBetween on eShop", () => {+ it("sums every direct link one way and reports none the other", () => {+ const r = servicesBetween(ESHOP_GRAPH, "webapp", "ordering.api")!;+ expect(r.aToB).toMatchObject({ links: 8, edges: 2, kinds: { event: 6, http: 2 } });+ expect(r.bToA).toBeNull();+ expect(r.pathsAToB).toHaveLength(1);+ expect(r.pathsAToB[0]!.nodes).toEqual(["webapp", "ordering.api"]);+ expect(r.pathsBToA).toEqual([]);+ });++ it("counts links a gateway route made", () => {+ const r = servicesBetween(ESHOP_GRAPH, "webapp", "catalog.api")!;+ expect(r.aToB).toMatchObject({ links: 2, gatewayLinks: 2 });+ });++ it("reports both directions of a cycle", () => {+ const r = servicesBetween(ESHOP_GRAPH, "catalog.api", "ordering.api")!;+ expect(r.aToB?.links).toBe(2);+ expect(r.bToA?.links).toBe(2);+ });++ it("finds the path through one service when there is no direct link", () => {+ const r = servicesBetween(ESHOP_GRAPH, "webhookclient", "catalog.api")!;+ expect(r.aToB).toBeNull();+ expect(r.pathsAToB).toHaveLength(1);+ const [path] = r.pathsAToB;+ expect(path!.nodes).toEqual(["webhookclient", "webhooks.api", "catalog.api"]);+ expect(path!.hops.map((h) => Object.keys(h.summary.kinds))).toEqual([["http"], ["event"]]);+ });++ it("walks the map's default families: a package edge is a route only when Build is on", () => {+ expect(servicesBetween(ESHOP_GRAPH, "identity.api", "eshop.servicedefaults")!.pathsAToB).toEqual([]);+ const build = servicesBetween(ESHOP_GRAPH, "identity.api", "eshop.servicedefaults", {+ families: new Set<EdgeFamily>(["build"]),+ })!;+ expect(build.aToB?.kinds).toEqual({ package: 1 });+ });++ it("returns null for an unknown service or the same service twice", () => {+ expect(servicesBetween(ESHOP_GRAPH, "webapp", "nope")).toBeNull();+ expect(servicesBetween(ESHOP_GRAPH, "webapp", "webapp")).toBeNull();+ });+});++describe("server-sent families", () => {+ it("follows an edge's family from the payload over the kind registry", () => {+ const g = graphOf([{ ...edge("a", "b", "http"), family: "build" }, { ...edge("b", "c", "package"), family: "runtime" }]);+ const r = servicesBetween(g, "a", "c")!;+ expect(r.pathsAToB).toEqual([]);+ expect(servicesBetween(g, "b", "c")!.aToB?.kinds).toEqual({ package: 1 });+ });++ it("falls back to the registry for a family it does not know", () => {+ const g = graphOf([{ ...edge("a", "b", "http"), family: "telepathy" as never }]);+ expect(servicesBetween(g, "a", "b")!.aToB?.links).toBe(1);+ });+});++describe("shortestPaths", () => {+ const families = new Set<EdgeFamily>(["runtime"]);++ it("ranks two-hop paths by their weakest hop, then by id, and caps them", () => {+ const g = graphOf([+ edge("a", "x", "http", 5),+ edge("x", "b", "http", 1),+ edge("a", "y", "http", 3),+ edge("y", "b", "event", 3),+ edge("a", "z", "http", 3),+ edge("z", "b", "http", 3),+ edge("a", "w", "http", 2),+ edge("w", "b", "http", 2),+ ]);+ const adj = buildAdjacency(g.edges, families);+ expect(shortestPaths(adj, "a", "b").map((p) => p.nodes[1])).toEqual(["y", "z", "w"]);+ expect(shortestPaths(adj, "a", "b", 2, 10).map((p) => p.nodes[1])).toEqual(["y", "z", "w", "x"]);+ });++ it("stops at one hop when asked, and goes no further than two", () => {+ const g = graphOf([edge("a", "x"), edge("x", "y"), edge("y", "b"), edge("x", "b")]);+ const adj = buildAdjacency(g.edges, families);+ expect(shortestPaths(adj, "a", "b", 1)).toEqual([]);+ expect(shortestPaths(adj, "a", "b").map((p) => p.nodes)).toEqual([["a", "x", "b"]]);+ expect(shortestPaths(adj, "a", "y")).toHaveLength(1);+ const far = graphOf([edge("a", "x"), edge("x", "y"), edge("y", "b")]);+ expect(shortestPaths(buildAdjacency(far.edges, families), "a", "b")).toEqual([]);+ });++ it("ignores self-edges and terminates on cycles", () => {+ const g = graphOf([edge("a", "a"), edge("a", "x"), edge("x", "a"), edge("x", "x"), edge("x", "b")]);+ const adj = buildAdjacency(g.edges, families);+ expect(adj.get("a")?.has("a")).toBe(false);+ expect(shortestPaths(adj, "a", "b").map((p) => p.nodes)).toEqual([["a", "x", "b"]]);+ expect(shortestPaths(adj, "b", "a")).toEqual([]);+ });+});diff --git a/packages/ui/__tests__/workspace/system-map-draw-budget.test.ts b/packages/ui/__tests__/workspace/system-map-draw-budget.test.tsnew file mode 100644index 000000000..5ceeab028--- /dev/null+++ b/packages/ui/__tests__/workspace/system-map-draw-budget.test.ts@@ -0,0 +1,123 @@+import { describe, expect, it } from "vitest";+import { allocateSlots, capEdges, truncationReport, DRAW_BUDGET } from "../../src/workspace/system-map/draw-budget";+import { connectEdges, summarizeLinks } from "../../src/workspace/system-map/bands";+import {+ DEFAULT_EDGE_FAMILIES,+ EDGE_FAMILY_ORDER,+ edgeFamily,+ familyCounts,+ linkWeight,+} from "../../src/workspace/system-map/edge-families";+import { EDGE_KIND_ORDER, SYSTEM_EDGE_KINDS } from "../../src/workspace/system-map/edge-kinds";+import type { DrawnEdge, LevelsEdge } from "../../src/workspace/system-map/level-types";++function edge(source: string, target: string, kind: LevelsEdge["kind"] = "http", weight = 1): LevelsEdge {+ return { id: `${source}->${target}:${kind}`, source, target, kind, weight, strategy: null };+}++describe("edge families", () => {+ it("puts every registered kind in a family, Runtime and Data on by default", () => {+ for (const kind of EDGE_KIND_ORDER) expect(EDGE_FAMILY_ORDER).toContain(SYSTEM_EDGE_KINDS[kind].family);+ expect(["http", "grpc", "socket", "event"].map(edgeFamily)).toEqual(["runtime", "runtime", "runtime", "runtime"]);+ expect([edgeFamily("db"), edgeFamily("package"), edgeFamily("co_change")]).toEqual(["data", "build", "history"]);+ expect([...DEFAULT_EDGE_FAMILIES]).toEqual(["runtime", "data"]);+ });++ it("files an unknown kind under History, as core does", () => {+ expect(edgeFamily("graphql")).toBe("history");+ });++ it("counts edges and links per family present", () => {+ const counts = familyCounts([edge("a", "b", "http", 3), edge("a", "c", "package"), edge("b", "c", "event", 0)]);+ expect(counts).toEqual({ runtime: { edges: 2, links: 4 }, build: { edges: 1, links: 1 } });+ expect(linkWeight({ weight: 0 })).toBe(1);+ });+});++describe("allocateSlots", () => {+ it("keeps everything when it fits", () => {+ expect(allocateSlots([{ size: 10 }, { size: 5 }], 15)).toEqual([10, 5]);+ });++ it("caps the big container first and leaves room for its +N more", () => {+ // 300 + 35 into 119: the open group keeps all 35, the root keeps 83 plus one "+N more".+ expect(allocateSlots([{ size: 300 }, { size: 35 }], 119)).toEqual([83, 35]);+ });++ it("honours a container's own limit", () => {+ expect(allocateSlots([{ size: 45, limit: 30 }, { size: 3 }], 119)).toEqual([30, 3]);+ });++ it("hands slots the shared cap leaves over to containers still folding", () => {+ // Cap 4 fits (4 + 4 + 2 = 10); the one spare slot goes to the first container.+ expect(allocateSlots([{ size: 10 }, { size: 10 }], 11)).toEqual([5, 4]);+ // The last slot of a container that then fits whole also frees its "+N more".+ expect(allocateSlots([{ size: 3 }, { size: 10 }], 8)).toEqual([3, 4]);+ });++ it("keeps nothing when even one +N more per container does not fit", () => {+ expect(allocateSlots([{ size: 5 }, { size: 5 }], 1)).toEqual([0, 0]);+ expect(allocateSlots([], 10)).toEqual([]);+ });++ it("never exceeds capacity when it can be met", () => {+ for (const capacity of [3, 10, 50, 119]) {+ const sizes = [{ size: 80 }, { size: 7 }, { size: 41, limit: 30 }, { size: 0 }];+ const kept = allocateSlots(sizes, capacity);+ const cost = kept.reduce((s, k, i) => s + k + (k < sizes[i]!.size ? 1 : 0), 0);+ expect(cost).toBeLessThanOrEqual(capacity);+ }+ });+});++describe("capEdges", () => {+ const edges = [edge("a", "b", "http", 1), edge("b", "c", "http", 5), edge("c", "d", "http", 3)];+ const byId = new Map(edges.map((e) => [e.id, e]));+ const drawn: DrawnEdge[] = edges.map((e) => ({ type: "edge", id: e.id, source: e.source, target: e.target, edgeId: e.id }));++ it("keeps the strongest, in their original order, and counts the rest", () => {+ const r = capEdges(drawn, 2, byId);+ expect(r.edges.map((e) => e.id)).toEqual(["b->c:http", "c->d:http"]);+ expect(r).toMatchObject({ droppedEdges: 1, droppedLinks: 1 });+ });++ it("is a no-op under budget", () => {+ expect(capEdges(drawn, DRAW_BUDGET.edges, byId)).toMatchObject({ droppedEdges: 0, droppedLinks: 0 });+ });++ it("reports nothing when nothing was cut", () => {+ expect(truncationReport(DRAW_BUDGET, 0, 0, 0, 0)).toBeNull();+ expect(truncationReport(DRAW_BUDGET, 2, 0, 0, 0)).toMatchObject({ foldedServices: 2 });+ });+});++describe("connectEdges", () => {+ const where: Record<string, string> = { a: "a", b: "b", c: "group:g", d: "group:g", e: "tray:" };+ const cards = new Set(["a", "b"]);+ const run = (edges: LevelsEdge[]) => connectEdges(edges, (id) => where[id] ?? null, (id) => cards.has(id));++ it("keeps card-to-card edges single and bands the rest per ordered pair", () => {+ const edges = run([+ edge("a", "b", "http"),+ edge("a", "b", "event", 2),+ edge("a", "c", "http", 2),+ edge("a", "d", "grpc"),+ edge("c", "a", "event"),+ edge("c", "d", "http", 4),+ edge("e", "z"),+ ]);+ expect(edges.map((e) => e.id)).toEqual([+ "a->b:event",+ "a->b:http",+ "band:a>group:g",+ "band:group:g>a",+ ]);+ const band = edges[2] as Extract<DrawnEdge, { type: "band" }>;+ expect(band.summary).toEqual({ links: 3, edges: 2, kinds: { http: 2, grpc: 1 }, gatewayLinks: 0, edgeIds: ["a->c:http", "a->d:grpc"] });+ });++ it("summarizes gateway-routed links", () => {+ const s = summarizeLinks([{ ...edge("a", "b"), strategy: "gateway_route" }, edge("a", "b", "event")]);+ expect(s).toMatchObject({ links: 2, gatewayLinks: 1 });+ });+});diff --git a/packages/ui/__tests__/workspace/system-map-focus-columns.test.ts b/packages/ui/__tests__/workspace/system-map-focus-columns.test.tsnew file mode 100644index 000000000..e28139e5a--- /dev/null+++ b/packages/ui/__tests__/workspace/system-map-focus-columns.test.ts@@ -0,0 +1,146 @@+import { describe, expect, it } from "vitest";+import {+ focusColumns,+ focusMoreId,+ focusNodeId,+ placeFocusColumns,+} from "../../src/workspace/system-map/focus-columns";+import { buildLevelView } from "../../src/workspace/system-map/levels";+import { DRAW_BUDGET } from "../../src/workspace/system-map/draw-budget";+import { DEFAULT_EDGE_FAMILIES, type EdgeFamily } from "../../src/workspace/system-map/edge-families";+import type { DrawnServiceNode, LevelsEdge, LevelsGraph } from "../../src/workspace/system-map/level-types";+import { ESHOP_GRAPH } from "./fixtures/eshop-system-graph";++const opts = { families: DEFAULT_EDGE_FAMILIES, budget: DRAW_BUDGET };++function star(callers: number): LevelsGraph {+ const nodes = [{ id: "hub", name: "hub", repo: "hub" }];+ const edges: LevelsEdge[] = [];+ for (let i = 0; i < callers; i++) {+ const id = `c${String(i).padStart(3, "0")}`;+ nodes.push({ id, name: id, repo: id });+ edges.push({ id: `${id}->hub`, source: id, target: "hub", kind: "http", weight: 1 + (i % 5), strategy: null });+ }+ return { nodes, edges };+}++describe("focusColumns on eShop ordering.api", () => {+ const layout = focusColumns(ESHOP_GRAPH, "ordering.api", opts)!;++ it("lists callers and dependencies by link count, ties by id", () => {+ const [callers, deps] = layout.columns;+ expect(callers!.id).toBe("callers");+ expect(callers!.entries.map((e) => [e.serviceId, e.summary.links])).toEqual([+ ["webapp", 8],+ ["clientapp", 4],+ ["catalog.api", 2],+ ["webhooks.api", 2],+ ["basket.api", 1],+ ["paymentprocessor", 1],+ ]);+ expect(deps!.entries.map((e) => [e.serviceId, e.summary.links])).toEqual([+ ["catalog.api", 2],+ ["paymentprocessor", 2],+ ["orderprocessor", 1],+ ]);+ });++ it("names the kind mix and marks a service on both sides", () => {+ const webapp = layout.columns[0]!.entries[0]!;+ expect(webapp.summary.kinds).toEqual({ event: 6, http: 2 });+ expect(webapp.bothWays).toBe(false);+ const both = layout.columns[0]!.entries.filter((e) => e.bothWays).map((e) => e.serviceId);+ expect(both).toEqual(["catalog.api", "paymentprocessor"]);+ });++ it("draws one connector per pair, into and out of the focus", () => {+ expect(layout.connectors).toHaveLength(9);+ const webapp = layout.connectors.find((c) => c.source === focusNodeId("callers", "webapp"))!;+ expect(webapp.target).toBe("ordering.api");+ expect(webapp.summary.edgeIds).toEqual(["webapp->ordering.api:event", "webapp->ordering.api:http"]);+ expect(layout.connectors.some((c) => c.source === "ordering.api" && c.target === focusNodeId("dependencies", "catalog.api"))).toBe(true);+ });++ it("follows the family filter", () => {+ const build = focusColumns(ESHOP_GRAPH, "ordering.api", { ...opts, families: new Set<EdgeFamily>(["build"]) })!;+ expect(build.columns[0]!.entries).toEqual([]);+ expect(build.columns[1]!.entries.map((e) => e.serviceId)).toEqual([+ "eshop.servicedefaults",+ "eventbusrabbitmq",+ "integrationeventlogef",+ "ordering.domain",+ "ordering.infrastructure",+ ]);+ });++ it("returns null for an unknown focus", () => {+ expect(focusColumns(ESHOP_GRAPH, "nope", opts)).toBeNull();+ });+});++describe("two hops", () => {+ const layout = focusColumns(ESHOP_GRAPH, "ordering.api", { ...opts, hops: 2 })!;++ it("adds callers of callers far left and dependencies of dependencies far right", () => {+ expect(layout.columns.map((c) => c.id)).toEqual(["callers2", "callers", "dependencies", "dependencies2"]);+ expect(layout.columns[0]!.entries.map((e) => [e.serviceId, e.summary.links])).toEqual([+ ["webappcomponents", 6],+ ["hybridapp", 5],+ ["webhookclient", 2],+ ]);+ expect(layout.columns[3]!.entries).toEqual([]);+ });++ it("connects the outer ring to the inner ring, never repeating a ring-one service", () => {+ const outer = layout.connectors.filter((c) => c.source.startsWith("callers2:"));+ expect(outer.map((c) => `${c.source}>${c.target}`)).toEqual([+ "callers2:hybridapp>callers:catalog.api",+ "callers2:webappcomponents>callers:catalog.api",+ "callers2:webhookclient>callers:webhooks.api",+ ]);+ });+});++describe("focus budget", () => {+ it("folds a column past the node budget into its +N more", () => {+ const layout = focusColumns(star(200), "hub", opts)!;+ const callers = layout.columns[0]!;+ expect(callers.entries).toHaveLength(118);+ expect(callers.folded).toHaveLength(82);+ expect(layout.connectors.some((c) => c.source === focusMoreId("callers"))).toBe(true);+ const view = buildLevelView(star(200), { focus: "hub" });+ expect(view.nodes).toHaveLength(120);+ expect(view.truncation?.foldedServices).toBe(82);+ });+});++describe("placeFocusColumns", () => {+ const size = { width: 200, height: 60 };++ it("places columns left to right, each centred on the focus row", () => {+ const layout = focusColumns(ESHOP_GRAPH, "ordering.api", opts)!;+ const pos = placeFocusColumns(layout, { size });+ expect(pos.get("ordering.api")).toEqual({ x: 296, y: -30, width: 200, height: 60 });+ expect(pos.get(focusNodeId("callers", "webapp"))).toEqual({ x: 0, y: -220, width: 200, height: 60 });+ expect(pos.get(focusNodeId("callers", "paymentprocessor"))!.y).toBe(160);+ expect(pos.get(focusNodeId("dependencies", "catalog.api"))!.x).toBe(592);+ expect(pos.size).toBe(10);+ });++ it("puts the +N more node last in its column and is deterministic", () => {+ const layout = focusColumns(star(200), "hub", opts)!;+ const a = placeFocusColumns(layout, { size });+ const b = placeFocusColumns(focusColumns(star(200), "hub", opts)!, { size });+ expect([...a]).toEqual([...b]);+ const more = a.get(focusMoreId("callers"))!;+ expect(Math.max(...[...a.values()].filter((p) => p.x === 0).map((p) => p.y))).toBe(more.y);+ });++ it("gives the level view the same ids the placement uses", () => {+ const view = buildLevelView(ESHOP_GRAPH, { focus: "ordering.api" });+ const pos = placeFocusColumns(view.focus!, { size });+ expect(view.nodes.every((n) => pos.has(n.id))).toBe(true);+ const focus = view.nodes.find((n) => n.id === "ordering.api") as DrawnServiceNode;+ expect(focus.column).toBe("focus");+ });+});diff --git a/packages/ui/__tests__/workspace/system-map-levels.test.ts b/packages/ui/__tests__/workspace/system-map-levels.test.tsnew file mode 100644index 000000000..33d9367b3--- /dev/null+++ b/packages/ui/__tests__/workspace/system-map-levels.test.ts@@ -0,0 +1,328 @@+import { describe, expect, it } from "vitest";+import { buildLevelView, normalizeGraph } from "../../src/workspace/system-map/levels";+import {+ ESTATE_MORE_ID,+ TRAY_NODE_ID,+ activeGroups,+ groupNodeId,+} from "../../src/workspace/system-map/estate-view";+import { DEFAULT_EDGE_FAMILIES, type EdgeFamily } from "../../src/workspace/system-map/edge-families";+import type {+ DrawnBand,+ DrawnGroupNode,+ DrawnMoreNode,+ DrawnNode,+ DrawnTrayNode,+ LevelsEdge,+ LevelsGraph,+} from "../../src/workspace/system-map/level-types";+import { ESHOP_GRAPH } from "./fixtures/eshop-system-graph";++function edge(source: string, target: string, kind: LevelsEdge["kind"] = "http", weight = 1): LevelsEdge {+ return { id: `${source}->${target}:${kind}`, source, target, kind, weight, strategy: null };+}++/** `groups` groups of `size` services; each group is a chain, and group i calls group i+1. */+function groupedEstate(groups: number, size: number, extra: readonly LevelsEdge[] = []): LevelsGraph {+ const nodes = [];+ const edges: LevelsEdge[] = [];+ for (let g = 0; g < groups; g++) {+ for (let s = 0; s < size; s++) {+ nodes.push({ id: `g${g}.s${s}`, name: `g${g}.s${s}`, repo: `g${g}.s${s}`, group: `g${g}` });+ if (s > 0) edges.push(edge(`g${g}.s${s - 1}`, `g${g}.s${s}`));+ }+ if (g + 1 < groups) edges.push(edge(`g${g}.s0`, `g${g + 1}.s0`, "event", 3));+ }+ const meta = Array.from({ length: groups }, (_, g) => (g === 0 ? { id: "g0", label: "Storefront", source: "tag" } : { id: `g${g}` }));+ return { nodes, edges: [...edges, ...extra], groups: meta };+}++/** `n` ungrouped services in a ring of HTTP calls. */+function flatRing(n: number): LevelsGraph {+ const nodes = Array.from({ length: n }, (_, i) => ({ id: `s${String(i).padStart(4, "0")}`, name: `s${i}`, repo: `s${i}` }));+ const edges = nodes.map((node, i) => edge(node.id, nodes[(i + 1) % n]!.id, "http", 1 + (i % 7)));+ return { nodes, edges };+}++const ofType = <T extends DrawnNode["type"]>(nodes: DrawnNode[], type: T) =>+ nodes.filter((n): n is Extract<DrawnNode, { type: T }> => n.type === type);++describe("estate level on eShop (flat, under the grouping threshold)", () => {+ const view = buildLevelView(ESHOP_GRAPH);++ it("draws services directly with the unlinked ones in one tray", () => {+ expect(view.level).toBe("estate");+ expect(view.grouped).toBe(false);+ const tray = ofType(view.nodes, "tray")[0] as DrawnTrayNode;+ expect(tray.id).toBe(TRAY_NODE_ID);+ expect(tray.open).toBe(false);+ expect([...tray.serviceIds].sort()).toEqual([+ "eshop.servicedefaults",+ "eventbus",+ "eventbusrabbitmq",+ "identity.api",+ "integrationeventlogef",+ "ordering.domain",+ "ordering.infrastructure",+ ]);+ expect(ofType(view.nodes, "service")).toHaveLength(11);+ // Most-linked first: ordering.api carries 23 runtime links, catalog.api 22.+ expect(ofType(view.nodes, "service")[0]!.id).toBe("ordering.api");+ expect(view.truncation).toBeNull();+ });++ it("draws every runtime edge between two cards as itself and hides build by default", () => {+ expect(view.edges.every((e) => e.type === "edge")).toBe(true);+ expect(view.edges).toHaveLength(18);+ expect(view.familyCounts.build).toEqual({ edges: 26, links: 26 });+ expect(view.familyCounts.runtime?.edges).toBe(18);+ expect(view.familyCounts.data).toBeUndefined();+ });++ it("keeps both directions of a cycle", () => {+ const ids = view.edges.map((e) => e.id);+ expect(ids).toContain("catalog.api->ordering.api:event");+ expect(ids).toContain("ordering.api->catalog.api:event");+ });++ it("bands build links into the tray without moving any card", () => {+ const withBuild = buildLevelView(ESHOP_GRAPH, { families: new Set<EdgeFamily>(["runtime", "data", "build"]) });+ expect(withBuild.nodes).toEqual(view.nodes);+ const band = withBuild.edges.find((e) => e.id === `band:ordering.api>${TRAY_NODE_ID}`) as DrawnBand;+ expect(band.summary.links).toBe(5);+ expect(band.summary.kinds).toEqual({ package: 5 });+ // webapp -> webappcomponents joins two cards, so it stays a single edge.+ expect(withBuild.edges.find((e) => e.id === "webapp->webappcomponents:package")?.type).toBe("edge");+ });++ it("opens the tray into its own cards", () => {+ const open = buildLevelView(ESHOP_GRAPH, { openTray: true, families: new Set<EdgeFamily>(["runtime", "build"]) });+ expect(open.level).toBe("group");+ const tray = ofType(open.nodes, "tray")[0]!;+ expect(tray.open).toBe(true);+ const inside = ofType(open.nodes, "service").filter((n) => n.parentId === TRAY_NODE_ID);+ expect(inside).toHaveLength(7);+ expect(open.edges.every((e) => e.type === "edge")).toBe(true);+ // Container precedes its children, as React Flow requires.+ expect(open.nodes.indexOf(tray)).toBeLessThan(open.nodes.indexOf(inside[0]!));+ });+});++describe("grouping follows the payload", () => {+ it("stays flat when the payload carries no groups, whatever the nodes say", () => {+ const g = groupedEstate(4, 20);+ expect(activeGroups({ ...g, groups: undefined })).toBeNull();+ expect(activeGroups({ ...g, groups: [] })).toBeNull();+ expect(buildLevelView({ ...g, groups: null }).grouped).toBe(false);+ });++ it("trusts the server's groups on a small estate", () => {+ const g = groupedEstate(2, 3);+ expect(g.nodes).toHaveLength(6);+ const view = buildLevelView(g);+ expect(view.grouped).toBe(true);+ expect(view.nodes.map((n) => n.type)).toEqual(["group", "group"]);+ });++ it("draws a one-member group's service bare", () => {+ const g = groupedEstate(3, 20);+ const lone = { id: "lone", name: "lone", repo: "lone", group: "solo" };+ const view = buildLevelView({ ...g, nodes: [...g.nodes, lone], edges: [...g.edges, edge("lone", "g0.s0")] });+ expect(view.grouped).toBe(true);+ expect(view.nodes.find((n) => n.id === "lone")?.type).toBe("service");+ expect(view.nodes.some((n) => n.id === groupNodeId("solo"))).toBe(false);+ });+});++describe("estate level with groups", () => {+ const graph = groupedEstate(3, 20);++ it("draws one card per group and one band per ordered group pair", () => {+ const view = buildLevelView(graph);+ expect(view.grouped).toBe(true);+ expect(view.nodes.map((n) => n.type)).toEqual(["group", "group", "group"]);+ const g0 = view.nodes.find((n) => n.id === groupNodeId("g0")) as DrawnGroupNode;+ expect(g0.label).toBe("Storefront");+ expect(g0.source).toBe("tag");+ expect(g0.repoCount).toBe(20);+ expect(g0.linksOut).toBe(3);+ expect(g0.linksInside).toBe(19);+ expect(view.edges.map((e) => e.id)).toEqual(["band:group:g0>group:g1", "band:group:g1>group:g2"]);+ });++ it("keeps opposite bands apart when two groups call each other", () => {+ const view = buildLevelView(groupedEstate(3, 20, [edge("g1.s3", "g0.s4", "grpc", 2)]));+ const ids = view.edges.map((e) => e.id);+ expect(ids).toContain("band:group:g0>group:g1");+ expect(ids).toContain("band:group:g1>group:g0");+ const back = view.edges.find((e) => e.id === "band:group:g1>group:g0") as DrawnBand;+ expect(back.summary).toMatchObject({ links: 2, edges: 1, kinds: { grpc: 2 } });+ });++ it("opens a group into a container and bands its services to the closed groups", () => {+ const view = buildLevelView(graph, { open: ["g1", "nope"] });+ expect(view.level).toBe("group");+ const container = view.nodes.find((n) => n.id === groupNodeId("g1")) as DrawnGroupNode;+ expect(container.open).toBe(true);+ const children = ofType(view.nodes, "service").filter((n) => n.parentId === container.id);+ expect(children).toHaveLength(20);+ const ids = view.edges.map((e) => e.id);+ expect(ids).toContain("band:group:g0>g1.s0");+ expect(ids).toContain("band:g1.s0>group:g2");+ expect(ids).toContain("g1.s0->g1.s1:http");+ // Open and closed report the same numbers.+ const closed = buildLevelView(graph).nodes.find((n) => n.id === container.id) as DrawnGroupNode;+ expect([container.linksIn, container.linksOut, container.linksInside]).toEqual([+ closed.linksIn,+ closed.linksOut,+ closed.linksInside,+ ]);+ });++ it("opens a group over 40 services to its 30 most-linked plus +N more", () => {+ const big = groupedEstate(2, 45);+ const view = buildLevelView(big, { open: ["g0"] });+ const children = ofType(view.nodes, "service").filter((n) => n.parentId === groupNodeId("g0"));+ expect(children).toHaveLength(30);+ const more = view.nodes.find((n) => n.id === "more:group:g0") as DrawnMoreNode;+ expect(more.serviceIds).toHaveLength(15);+ expect(view.truncation?.foldedServices).toBe(15);+ // Edges to folded services land on the "+N more" node.+ expect(view.edges.some((e) => e.target === "more:group:g0" || e.source === "more:group:g0")).toBe(true);+ });++ it("keeps a grouped member with no runtime link in its group, not the tray", () => {+ const g = groupedEstate(3, 20);+ const nodes = [...g.nodes, { id: "g2.idle", name: "g2.idle", repo: "g2.idle", group: "g2" }];+ const view = buildLevelView({ ...g, nodes });+ expect(view.nodes.some((n) => n.type === "tray")).toBe(false);+ const g2 = view.nodes.find((n) => n.id === groupNodeId("g2")) as DrawnGroupNode;+ expect(g2.serviceIds).toContain("g2.idle");+ });+});++describe("draw budget", () => {+ it("folds a flat estate over budget into +N more and says so", () => {+ const view = buildLevelView(flatRing(300));+ expect(view.nodes).toHaveLength(120);+ const more = view.nodes.at(-1) as DrawnMoreNode;+ expect(more.id).toBe(ESTATE_MORE_ID);+ expect(more.serviceIds).toHaveLength(181);+ expect(view.truncation).toMatchObject({ foldedServices: 181, foldedGroups: 0 });+ // Edges into the folded services become bands on the "+N more" node.+ expect(view.edges.some((e) => e.type === "band" && (e.source === ESTATE_MORE_ID || e.target === ESTATE_MORE_ID))).toBe(true);+ });++ it("drops the weakest connectors past the edge budget and counts them", () => {+ const view = buildLevelView(flatRing(100), {}, { nodes: 120, edges: 40 });+ expect(view.edges).toHaveLength(40);+ expect(view.truncation?.droppedEdges).toBe(60);+ expect(view.truncation?.droppedLinks).toBeGreaterThan(0);+ });++ it("folds the weakest group cards when there are more groups than room", () => {+ const view = buildLevelView(groupedEstate(30, 2), {}, { nodes: 10, edges: 300 });+ expect(view.nodes).toHaveLength(10);+ const more = view.nodes.find((n) => n.id === ESTATE_MORE_ID) as DrawnMoreNode;+ expect(more.groupIds).toHaveLength(21);+ expect(view.truncation?.foldedGroups).toBe(21);+ });++ it("never folds a small open group to make room for the estate", () => {+ const g = groupedEstate(3, 20, flatRing(200).edges);+ const graph = { ...g, nodes: [...g.nodes, ...flatRing(200).nodes] };+ const view = buildLevelView(graph, { open: ["g0"] });+ expect(view.nodes.length).toBeLessThanOrEqual(120);+ expect(ofType(view.nodes, "service").filter((n) => n.parentId === groupNodeId("g0"))).toHaveLength(20);+ });+});++describe("level precedence and determinism", () => {+ it("between wins over focus, focus over open, unknown ids fall through", () => {+ expect(buildLevelView(ESHOP_GRAPH, { between: { a: "webapp", b: "ordering.api" }, focus: "webapp" }).level).toBe("between");+ expect(buildLevelView(ESHOP_GRAPH, { between: { a: "webapp", b: "missing" }, focus: "webapp" }).level).toBe("focus");+ expect(buildLevelView(ESHOP_GRAPH, { focus: "missing" }).level).toBe("estate");+ });++ it("draws the between level as the pair plus the services on its paths", () => {+ const view = buildLevelView(ESHOP_GRAPH, { between: { a: "webhookclient", b: "catalog.api" } });+ expect(view.nodes.map((n) => n.id)).toEqual(["catalog.api", "webhookclient", "webhooks.api"]);+ expect(view.edges.map((e) => e.id)).toEqual([+ "webhookclient->webhooks.api:http",+ "webhooks.api->catalog.api:event",+ ]);+ expect(view.between?.pathsAToB[0]?.nodes).toEqual(["webhookclient", "webhooks.api", "catalog.api"]);+ });++ it("returns the same view whatever order the payload arrives in", () => {+ const shuffled: LevelsGraph = {+ nodes: [...ESHOP_GRAPH.nodes].reverse(),+ edges: [...ESHOP_GRAPH.edges].reverse(),+ };+ for (const state of [+ {},+ { families: new Set<EdgeFamily>(["runtime", "build", "history", "data"]) },+ { focus: "ordering.api", hops: 2 as const },+ { between: { a: "webapp", b: "ordering.api" } },+ ]) {+ expect(buildLevelView(shuffled, state)).toEqual(buildLevelView(ESHOP_GRAPH, state));+ }+ const big = groupedEstate(5, 30);+ const bigShuffled = { ...big, nodes: [...big.nodes].reverse(), edges: [...big.edges].reverse() };+ expect(buildLevelView(bigShuffled, { open: ["g2"] })).toEqual(buildLevelView(big, { open: ["g2"] }));+ });++ it("drops dangling edges and duplicate ids instead of drawing phantoms", () => {+ const dirty: LevelsGraph = {+ nodes: [...ESHOP_GRAPH.nodes, ESHOP_GRAPH.nodes[0]!],+ edges: [...ESHOP_GRAPH.edges, ESHOP_GRAPH.edges[2]!, { ...ESHOP_GRAPH.edges[2]!, id: "ghost", target: "gone" }],+ };+ expect(buildLevelView(dirty)).toEqual(buildLevelView(ESHOP_GRAPH));+ const focus = buildLevelView(dirty, { focus: "basket.api" });+ expect(focus.nodes.some((n) => n.type === "service" && n.serviceId === "gone")).toBe(false);+ });++ it("picks the same survivor of a duplicate id whatever the payload order", () => {+ const a = { id: "x", name: "x", repo: "repo-a" };+ const b = { id: "x", name: "x", repo: "repo-b" };+ const heavy = { ...ESHOP_GRAPH.edges[0]!, weight: 9 };+ const g1: LevelsGraph = { nodes: [...ESHOP_GRAPH.nodes, a, b], edges: [...ESHOP_GRAPH.edges, heavy] };+ const g2: LevelsGraph = { nodes: [b, ...ESHOP_GRAPH.nodes, a], edges: [heavy, ...ESHOP_GRAPH.edges] };+ expect(normalizeGraph(g1)).toEqual(normalizeGraph(g2));+ expect(normalizeGraph(g1).nodes.filter((n) => n.id === "x")).toEqual([a]);+ });++ it("normalizes a payload once and reuses it", () => {+ const g: LevelsGraph = { nodes: [...ESHOP_GRAPH.nodes], edges: [...ESHOP_GRAPH.edges] };+ const first = normalizeGraph(g);+ expect(normalizeGraph(g)).toBe(first);+ expect(normalizeGraph(first)).toBe(first);+ });++ it("gives every drawn node and edge a unique id at every level", () => {+ const g = groupedEstate(3, 20);+ for (const view of [+ buildLevelView(flatRing(300)),+ buildLevelView(g, { open: ["g1"] }),+ buildLevelView(ESHOP_GRAPH, { focus: "ordering.api", hops: 2 }),+ buildLevelView(ESHOP_GRAPH, { openTray: true }),+ ]) {+ const ids = [...view.nodes, ...view.edges].map((x) => x.id);+ expect(new Set(ids).size).toBe(ids.length);+ }+ });++ it("counts a direct Data link between two services under the family filter", () => {+ const g: LevelsGraph = {+ nodes: ["a", "b"].map((id) => ({ id, name: id, repo: id })),+ edges: [edge("a", "b", "db", 2)],+ };+ const view = buildLevelView(g, { between: { a: "a", b: "b" } });+ expect(view.between?.aToB?.kinds).toEqual({ db: 2 });+ expect(view.edges.map((e) => e.id)).toEqual(["a->b:db"]);+ });++ it("reports the families drawn", () => {+ expect(buildLevelView(ESHOP_GRAPH).families).toBe(DEFAULT_EDGE_FAMILIES);+ });+});diff --git a/packages/ui/__tests__/workspace/system-map.bench.ts b/packages/ui/__tests__/workspace/system-map.bench.tsindex f631e71ee..6b4219e63 100644--- a/packages/ui/__tests__/workspace/system-map.bench.ts+++ b/packages/ui/__tests__/workspace/system-map.bench.ts@@ -12,6 +12,10 @@ import type { SystemEdgeKind } from "@repowise-dev/types";import { applyView, computeSystemMapPositions, layoutSignature } from "../../src/workspace/system-map/layout";import { collapseToRepos } from "../../src/workspace/system-map/collapse";import { neighbourGroups, serviceResolver } from "../../src/workspace/system-map/system-map-model";+import { buildLevelView } from "../../src/workspace/system-map/levels";+import { allocateSlots } from "../../src/workspace/system-map/draw-budget";+import { servicesBetween } from "../../src/workspace/system-map/between";+import type { LevelsGraph } from "../../src/workspace/system-map/level-types";import { makeSyntheticSystemGraph } from "./fixtures/synthetic-system-graph";const SIZES = [30, 100, 300, 1000] as const;@@ -27,6 +31,12 @@ for (const services of SIZES) {seed: services,});const hub = graph.edges.find((e) => e.kind === "package")?.target ?? graph.nodes[0]!.id;+ // The grouped payload the levels model reads: `group` on nodes plus the `groups` list.+ const groupIds = [...new Set(graph.nodes.map((n) => n.group).filter((g): g is string => Boolean(g)))];+ const levels: LevelsGraph = { ...graph, groups: groupIds.map((id) => ({ id })) };+ const caller = graph.edges.find((e) => e.kind === "http")?.source ?? graph.nodes[0]!.id;+ const callee = graph.edges.find((e) => e.kind === "http")?.target ?? graph.nodes[1]!.id;+ const containers = groupIds.map((_, i) => ({ size: 5 + ((i * 7) % 40) }));describe(`system map, ${services} services / ${graph.edges.length} edges`, () => {bench("applyView (runtime kinds)", () => {@@ -43,6 +53,21 @@ for (const services of SIZES) {neighbourGroups(graph, hub, "in");neighbourGroups(graph, hub, "out");});+ bench("buildLevelView estate (cold payload, normalizes)", () => {+ buildLevelView({ ...levels });+ });+ bench("buildLevelView open group (cached payload)", () => {+ buildLevelView(levels, { open: groupIds.slice(0, 1) });+ });+ bench("buildLevelView focus, two hops (cached payload)", () => {+ buildLevelView(levels, { focus: hub, hops: 2 });+ });+ bench("allocateSlots (one container per group)", () => {+ allocateSlots(containers, 119);+ });+ bench("servicesBetween (runtime pair)", () => {+ servicesBetween(levels, caller, callee);+ });bench("computeSystemMapPositions (ELK, grid past 500)", async () => {await computeSystemMapPositions(graph);}, SLOW);diff --git a/packages/ui/src/workspace/system-map/bands.ts b/packages/ui/src/workspace/system-map/bands.tsnew file mode 100644index 000000000..f7e4aab81--- /dev/null+++ b/packages/ui/src/workspace/system-map/bands.ts@@ -0,0 +1,72 @@+/**+ * Bands: turn system edges into what the map draws, given where each service+ * is drawn. Two service cards keep their own edges (kind and match dash+ * intact); any pair where one end aggregates (a group card, the tray, a+ * "+N more" node) gets one band per ordered pair, carrying the link count and+ * the kind mix. Opposite directions are two bands, so a cycle stays visible.+ * Pure, no React.+ */++import { linkWeight } from "./edge-families";+import type { DrawnBand, DrawnEdge, LevelsEdge, LinkSummary } from "./level-types";++export function emptySummary(): LinkSummary {+ return { links: 0, edges: 0, kinds: {}, gatewayLinks: 0, edgeIds: [] };+}++/** Fold one edge into a summary, in place. */+export function addLink(summary: LinkSummary, edge: LevelsEdge): void {+ const w = linkWeight(edge);+ summary.links += w;+ summary.edges += 1;+ summary.kinds[edge.kind] = (summary.kinds[edge.kind] ?? 0) + w;+ if (edge.strategy === "gateway_route") summary.gatewayLinks += w;+ summary.edgeIds.push(edge.id);+}++export function summarizeLinks(edges: Iterable<LevelsEdge>): LinkSummary {+ const s = emptySummary();+ for (const e of edges) addLink(s, e);+ return s;+}++/** Ascending code-unit order, the one id order every view sorts by. */+export function compareIds(a: string, b: string): number {+ return a < b ? -1 : a > b ? 1 : 0;+}++export function bandId(source: string, target: string): string {+ return `band:${source}>${target}`;+}++/**+ * Connect `edges` between drawn nodes. `drawnAt(serviceId)` names the node a+ * service is drawn as (or inside), null when it is not on the canvas;+ * `isServiceCard(drawnId)` is true when that node is the service's own card.+ * Links whose two ends land on one node are not drawn. Sorted by id.+ */+export function connectEdges(+ edges: Iterable<LevelsEdge>,+ drawnAt: (serviceId: string) => string | null,+ isServiceCard: (drawnId: string) => boolean,+): DrawnEdge[] {+ const singles: DrawnEdge[] = [];+ const bands = new Map<string, DrawnBand>();+ for (const e of edges) {+ const source = drawnAt(e.source);+ const target = drawnAt(e.target);+ if (source === null || target === null) continue;+ if (source === target) continue;+ if (isServiceCard(source) && isServiceCard(target)) {+ singles.push({ type: "edge", id: e.id, source, target, edgeId: e.id });+ continue;+ }+ const id = bandId(source, target);+ let band = bands.get(id);+ if (!band) bands.set(id, (band = { type: "band", id, source, target, summary: emptySummary() }));+ addLink(band.summary, e);+ }+ const out = [...singles, ...bands.values()];+ out.sort((x, y) => compareIds(x.id, y.id));+ return out;+}diff --git a/packages/ui/src/workspace/system-map/between.ts b/packages/ui/src/workspace/system-map/between.tsnew file mode 100644index 000000000..a10b9b0f2--- /dev/null+++ b/packages/ui/src/workspace/system-map/between.ts@@ -0,0 +1,117 @@+/**+ * Between two services: the links that join them directly, in both+ * directions, and when there is no direct link the shortest paths through one+ * other service ("webhookclient reaches catalog.api through webhooks.api").+ * Paths and direct links follow the map's active families (Runtime and Data+ * by default), so what this counts matches what the map draws; a package or+ * co-change edge is a route only when the reader turned its family on. The+ * server's routes-between totals count every kind; this view filters them. Pure, no React; the graph is already loaded.+ */++import { addLink, compareIds, emptySummary } from "./bands";+import { DEFAULT_EDGE_FAMILIES, edgeFamilyOf, type EdgeFamily } from "./edge-families";+import type { LevelsEdge, LevelsGraph, LinkSummary } from "./level-types";++export interface PathHop {+ source: string;+ target: string;+ summary: LinkSummary;+}++/** One route from `nodes[0]` to its last node; `hops[i]` joins `nodes[i]` to `nodes[i + 1]`. */+export interface ServicePath {+ nodes: string[];+ hops: PathHop[];+}++export interface BetweenResult {+ a: string;+ b: string;+ /** Direct links, by direction; null when there is none that way. */+ aToB: LinkSummary | null;+ bToA: LinkSummary | null;+ /** Shortest paths each way: the direct link when there is one, else up to `maxPaths` through one service (strongest first). */+ pathsAToB: ServicePath[];+ pathsBToA: ServicePath[];+}++export interface BetweenOptions {+ /** Families walked for paths and counted as direct links: the map's active families, Runtime and Data by default. */+ families?: ReadonlySet<EdgeFamily>;+ /** 1 = direct only, 2 = also through one other service. Default 2. */+ maxHops?: 1 | 2;+ /** Paths kept per direction. Default 3. */+ maxPaths?: number;+}++type Adjacency = Map<string, Map<string, LinkSummary>>;++/** source -> target -> summary of every edge in the families, self-edges dropped. */+export function buildAdjacency(edges: Iterable<LevelsEdge>, families: ReadonlySet<EdgeFamily>): Adjacency {+ const adj: Adjacency = new Map();+ for (const e of edges) {+ if (e.source === e.target || !families.has(edgeFamilyOf(e))) continue;+ let out = adj.get(e.source);+ if (!out) adj.set(e.source, (out = new Map()));+ let s = out.get(e.target);+ if (!s) out.set(e.target, (s = emptySummary()));+ addLink(s, e);+ }+ return adj;+}++/** Up to `maxPaths` shortest simple paths from `from` to `to`, at most `maxHops` long. */+export function shortestPaths(+ adj: Adjacency,+ from: string,+ to: string,+ maxHops: 1 | 2 = 2,+ maxPaths = 3,+): ServicePath[] {+ const out = from === to || maxPaths <= 0 ? undefined : adj.get(from);+ if (!out) return [];+ const direct = out.get(to);+ if (direct) return [{ nodes: [from, to], hops: [{ source: from, target: to, summary: direct }] }];+ if (maxHops < 2) return [];+ return throughOne(adj, out, from, to).slice(0, maxPaths);+}++/** Paths `from -> via -> to`, strongest first: a path is as strong as its weakest hop, ties by id. */+function throughOne(adj: Adjacency, out: Map<string, LinkSummary>, from: string, to: string): ServicePath[] {+ const twoHop: { via: string; strength: number; first: LinkSummary; second: LinkSummary }[] = [];+ for (const [via, first] of out) {+ const second = via === to ? undefined : adj.get(via)?.get(to);+ if (second) twoHop.push({ via, strength: Math.min(first.links, second.links), first, second });+ }+ twoHop.sort((x, y) => y.strength - x.strength || compareIds(x.via, y.via));+ return twoHop.map(({ via, first, second }) => ({+ nodes: [from, via, to],+ hops: [+ { source: from, target: via, summary: first },+ { source: via, target: to, summary: second },+ ],+ }));+}++/** Links and paths between `a` and `b`. Null when either id is not a service in the graph or they are the same. */+export function servicesBetween(+ graph: LevelsGraph,+ a: string,+ b: string,+ options: BetweenOptions = {},+): BetweenResult | null {+ if (a === b) return null;+ const ids = new Set(graph.nodes.map((n) => n.id));+ if (!ids.has(a) || !ids.has(b)) return null;+ const adj = buildAdjacency(graph.edges, options.families ?? DEFAULT_EDGE_FAMILIES);+ const maxHops = options.maxHops ?? 2;+ const maxPaths = options.maxPaths ?? 3;+ return {+ a,+ b,+ aToB: adj.get(a)?.get(b) ?? null,+ bToA: adj.get(b)?.get(a) ?? null,+ pathsAToB: shortestPaths(adj, a, b, maxHops, maxPaths),+ pathsBToA: shortestPaths(adj, b, a, maxHops, maxPaths),+ };+}diff --git a/packages/ui/src/workspace/system-map/draw-budget.ts b/packages/ui/src/workspace/system-map/draw-budget.tsnew file mode 100644index 000000000..6fef8fd46--- /dev/null+++ b/packages/ui/src/workspace/system-map/draw-budget.ts@@ -0,0 +1,105 @@+/**+ * The draw budget: at most ~120 nodes and ~300 edges on the canvas at once.+ * Past it, the weakest services of each container fold into one "+N more"+ * node and the weakest connectors are not drawn; both are counted in the+ * truncation report so the caption can say so. Pure, no React.+ */++import { linkWeight } from "./edge-families";+import type { DrawBudget, DrawnEdge, LevelsEdge, TruncationReport } from "./level-types";++/** React Flow stays responsive with this much drawn. */+export const DRAW_BUDGET: DrawBudget = { nodes: 120, edges: 300 };++export interface BudgetContainer {+ /** Items the container would draw. */+ size: number;+ /** Most items it may draw before folding, whatever the budget (a large open group). */+ limit?: number;+}++/**+ * Items each container keeps so that kept items plus one "+N more" node per+ * folded container fit `capacity`. Water-filling: every container keeps up to+ * one shared cap, chosen as large as fits, so a small container is never+ * folded to make room for a big one; slots the shared cap leaves over go to+ * the first containers still folding. Deterministic. When even one "+N more"+ * per container does not fit, every container keeps nothing and the view+ * draws more than the budget (only reachable with more open groups than slots).+ */+export function allocateSlots(containers: readonly BudgetContainer[], capacity: number): number[] {+ const keptAt = (cap: number) =>+ containers.map((c) => Math.min(c.size, c.limit ?? c.size, cap));+ const cost = (cap: number) =>+ keptAt(cap).reduce((sum, kept, i) => sum + kept + (kept < containers[i]!.size ? 1 : 0), 0);+ let lo = 0;+ let hi = containers.reduce((m, c) => Math.max(m, c.size), 0);+ // cost() never decreases as the cap grows, so binary-search the largest cap that fits.+ while (lo < hi) {+ const mid = Math.ceil((lo + hi) / 2);+ if (cost(mid) <= capacity) lo = mid;+ else hi = mid - 1;+ }+ const kept = keptAt(lo);+ let spare = Math.max(0, capacity - cost(lo));+ containers.forEach((c, i) => {+ const max = Math.min(c.size, c.limit ?? c.size);+ const room = max - kept[i]!;+ if (room <= 0) return;+ // Filling a container whole also frees its "+N more" slot.+ if (max === c.size && room <= spare + 1) {+ kept[i] = max;+ spare -= room - 1;+ } else {+ const give = Math.min(room, spare);+ kept[i]! += give;+ spare -= give;+ }+ });+ return kept;+}++export interface CappedEdges {+ edges: DrawnEdge[];+ droppedEdges: number;+ droppedLinks: number;+}++/** Links a drawn connector stands for: a band's count, or one edge's weight. */+export function drawnLinks(edge: DrawnEdge, edgesById: ReadonlyMap<string, LevelsEdge>): number {+ if (edge.type === "band") return edge.summary.links;+ const e = edgesById.get(edge.edgeId);+ return e ? linkWeight(e) : 1;+}++/** Keep the `max` strongest connectors (most links, then id), in their original order. */+export function capEdges(+ edges: readonly DrawnEdge[],+ max: number,+ edgesById: ReadonlyMap<string, LevelsEdge>,+): CappedEdges {+ if (edges.length <= max) return { edges: [...edges], droppedEdges: 0, droppedLinks: 0 };+ const ranked = edges+ .map((edge) => ({ edge, links: drawnLinks(edge, edgesById) }))+ .sort((a, b) => b.links - a.links || (a.edge.id < b.edge.id ? -1 : a.edge.id > b.edge.id ? 1 : 0));+ const keep = new Set(ranked.slice(0, Math.max(0, max)).map((r) => r.edge.id));+ let droppedLinks = 0;+ for (const r of ranked.slice(Math.max(0, max))) droppedLinks += r.links;+ return {+ edges: edges.filter((e) => keep.has(e.id)),+ droppedEdges: edges.length - keep.size,+ droppedLinks,+ };+}++/** The report for what a view folded and dropped; null when everything fit. */+export function truncationReport(+ budget: DrawBudget,+ foldedServices: number,+ foldedGroups: number,+ droppedEdges: number,+ droppedLinks: number,+): TruncationReport | null {+ if (foldedServices + foldedGroups + droppedEdges === 0) return null;+ return { budget, foldedServices, foldedGroups, droppedEdges, droppedLinks };+}diff --git a/packages/ui/src/workspace/system-map/edge-families.ts b/packages/ui/src/workspace/system-map/edge-families.tsnew file mode 100644index 000000000..7946aba7a--- /dev/null+++ b/packages/ui/src/workspace/system-map/edge-families.ts@@ -0,0 +1,66 @@+/**+ * Edge families: the four groups the map filters by (Runtime, Data, Build,+ * History). Which kind belongs to which family lives on the kind registry+ * (`SYSTEM_EDGE_KINDS[kind].family`), so a new transport declares its family+ * in the one row it already adds. Pure, no React.+ */++import { edgeKindStyle, type EdgeFamily } from "./edge-kinds";++export type { EdgeFamily };++/** Display order of the family chips. */+export const EDGE_FAMILY_ORDER: readonly EdgeFamily[] = ["runtime", "data", "build", "history"];++/** Drawn on first load: calls, events and shared data. Build and History are opt-in. */+export const DEFAULT_EDGE_FAMILIES: ReadonlySet<EdgeFamily> = new Set<EdgeFamily>(["runtime", "data"]);++/**+ * The families that count as "linked" when the map ranks services and fills+ * the "Not linked at runtime" tray. Fixed on purpose, independent of the+ * filter, so toggling a family never moves a service in or out of the tray+ * and never reorders what the draw budget keeps.+ */+export const LINKED_FAMILIES: ReadonlySet<EdgeFamily> = DEFAULT_EDGE_FAMILIES;++/** The family of an edge kind from the registry; an unknown kind is History, as in core. */+export function edgeFamily(kind: string): EdgeFamily {+ return edgeKindStyle(kind).family;+}++const FAMILIES: ReadonlySet<string> = new Set(EDGE_FAMILY_ORDER);++/**+ * An edge's family: the `family` the server sent when it is one we know,+ * else the kind registry's (payloads written before the field existed).+ */+export function edgeFamilyOf(edge: { kind: string; family?: string | null | undefined }): EdgeFamily {+ const sent = edge.family;+ return sent && FAMILIES.has(sent) ? (sent as EdgeFamily) : edgeFamily(edge.kind);+}++export interface FamilyCount {+ /** System edges of the family. */+ edges: number;+ /** Underlying links (sum of edge weights). */+ links: number;+}++/** Edge and link counts per family, for the chips and the "hidden" caption. Only families present appear. */+export function familyCounts(+ edges: Iterable<{ kind: string; family?: string | null | undefined; weight: number }>,+): Partial<Record<EdgeFamily, FamilyCount>> {+ const out: Partial<Record<EdgeFamily, FamilyCount>> = {};+ for (const e of edges) {+ const family = edgeFamilyOf(e);+ const row = (out[family] ??= { edges: 0, links: 0 });+ row.edges += 1;+ row.links += linkWeight(e);+ }+ return out;+}++/** Links an edge stands for. An edge exists, so it is never fewer than one. */+export function linkWeight(edge: { weight: number }): number {+ return edge.weight > 1 ? edge.weight : 1;+}diff --git a/packages/ui/src/workspace/system-map/edge-kinds.ts b/packages/ui/src/workspace/system-map/edge-kinds.tsindex 9e1609241..207404ac3 100644--- a/packages/ui/src/workspace/system-map/edge-kinds.ts+++ b/packages/ui/src/workspace/system-map/edge-kinds.ts@@ -13,11 +13,19 @@*/import { ArrowRight, Boxes, Database, Link2, Radio, Signal, Zap, type LucideIcon } from "lucide-react";-import type { SystemEdge, SystemEdgeKind, SystemEdgeMatchType } from "@repowise-dev/types";+import type { SystemEdge, SystemEdgeFamily, SystemEdgeKind, SystemEdgeMatchType } from "@repowise-dev/types";/** Whether an edge reflects a structural contract/dependency or behavioral co-change. */export type EdgeCategory = "structural" | "behavioral";+/**+ * The filter family an edge kind belongs to. The map offers families, not+ * kinds, as its first filter row: Runtime and Data are drawn by default, Build+ * (package) and History (co-change) are opt-in. Core sends it on each edge;+ * the registry's `family` answers only for payloads written before that.+ */+export type EdgeFamily = SystemEdgeFamily;+export interface SystemEdgeKindStyle {kind: SystemEdgeKind;/** Short human label for the legend and inspector. */@@ -26,6 +34,7 @@ export interface SystemEdgeKindStyle {color: string;icon: LucideIcon;category: EdgeCategory;+ family: EdgeFamily;}/**@@ -34,13 +43,13 @@ export interface SystemEdgeKindStyle {* theme vars so the map stays consistent with the C4 / knowledge-graph views.*/export const SYSTEM_EDGE_KINDS: Record<SystemEdgeKind, SystemEdgeKindStyle> = {- http: { kind: "http", label: "HTTP", color: "var(--color-accent-secondary)", icon: ArrowRight, category: "structural" },- grpc: { kind: "grpc", label: "gRPC", color: "var(--color-accent-fill)", icon: Zap, category: "structural" },- socket: { kind: "socket", label: "Socket", color: "var(--color-info)", icon: Signal, category: "structural" },- event: { kind: "event", label: "Event", color: "var(--color-warning)", icon: Radio, category: "structural" },- package: { kind: "package", label: "Package", color: "var(--color-accent-primary)", icon: Boxes, category: "structural" },- db: { kind: "db", label: "Database", color: "var(--color-text-tertiary)", icon: Database, category: "structural" },- co_change: { kind: "co_change", label: "Co-change", color: "var(--color-edge-co-change)", icon: Link2, category: "behavioral" },+ http: { kind: "http", label: "HTTP", color: "var(--color-accent-secondary)", icon: ArrowRight, category: "structural", family: "runtime" },+ grpc: { kind: "grpc", label: "gRPC", color: "var(--color-accent-fill)", icon: Zap, category: "structural", family: "runtime" },+ socket: { kind: "socket", label: "Socket", color: "var(--color-info)", icon: Signal, category: "structural", family: "runtime" },+ event: { kind: "event", label: "Event", color: "var(--color-warning)", icon: Radio, category: "structural", family: "runtime" },+ package: { kind: "package", label: "Package", color: "var(--color-accent-primary)", icon: Boxes, category: "structural", family: "build" },+ db: { kind: "db", label: "Database", color: "var(--color-text-tertiary)", icon: Database, category: "structural", family: "data" },+ co_change: { kind: "co_change", label: "Co-change", color: "var(--color-edge-co-change)", icon: Link2, category: "behavioral", family: "history" },};const FALLBACK_KIND: SystemEdgeKindStyle = {@@ -49,6 +58,8 @@ const FALLBACK_KIND: SystemEdgeKindStyle = {color: "var(--color-text-tertiary)",icon: ArrowRight,category: "structural",+ // Matches core: a kind it does not know is History, so it starts hidden.+ family: "history",};/** Resolve the style for an edge kind, tolerant of an unknown future kind. */diff --git a/packages/ui/src/workspace/system-map/estate-view.ts b/packages/ui/src/workspace/system-map/estate-view.tsnew file mode 100644index 000000000..1ccd01a91--- /dev/null+++ b/packages/ui/src/workspace/system-map/estate-view.ts@@ -0,0 +1,342 @@+/**+ * Estate and group-open levels (L0, L1): a card per group, a card per+ * ungrouped service, one tray for services with no Runtime or Data link, and+ * one band per ordered pair where an end aggregates. An opened group becomes+ * the container of its service cards. The server decides whether an estate+ * is grouped (it writes `groups` only when grouping reduces something); a+ * payload without `groups` is drawn flat. Which+ * services are ranked and which go to the tray never depends on the family+ * filter, so a filter toggle changes only the connectors. Pure, no React.+ */++import { compareIds, connectEdges } from "./bands";+import { allocateSlots, capEdges, truncationReport, type BudgetContainer } from "./draw-budget";+import { LINKED_FAMILIES, edgeFamilyOf, linkWeight } from "./edge-families";+import type {+ DrawBudget,+ DrawnEdge,+ DrawnGroupNode,+ DrawnNode,+ LevelViewState,+ LevelsEdge,+ LevelsGraph,+ MapLevel,+ TruncationReport,+} from "./level-types";++/** An opened group over `over` services draws its `keep` most-linked plus "+N more". */+export const OPEN_GROUP_LIMIT = { over: 40, keep: 30 } as const;++export const TRAY_NODE_ID = "tray:";+export const ESTATE_MORE_ID = "more:estate";++export function groupNodeId(groupId: string): string {+ return `group:${groupId}`;+}++function groupMoreId(groupId: string): string {+ return `more:group:${groupId}`;+}++const TRAY_MORE_ID = "more:tray";++function push(map: Map<string, string[]>, key: string, value: string): void {+ const list = map.get(key);+ if (list) list.push(value);+ else map.set(key, [value]);+}++/**+ * Service id -> group id, or null when the payload carries no `groups` (the+ * server groups only estates where it reduces something, so absence means+ * flat). A group with one service in this payload is drawn as that bare+ * service rather than a card around one thing.+ */+export function activeGroups(graph: LevelsGraph): Map<string, string> | null {+ if (!graph.groups || graph.groups.length === 0) return null;+ const members = new Map<string, string[]>();+ for (const n of graph.nodes) if (n.group) push(members, n.group, n.id);+ const out = new Map<string, string>();+ for (const [group, ids] of members) {+ if (ids.length >= 2) for (const id of ids) out.set(id, group);+ }+ return out.size > 0 ? out : null;+}++/** Links per service over the fixed linked families (Runtime and Data), both directions. */+export function linkedWeights(edges: Iterable<LevelsEdge>): Map<string, number> {+ const out = new Map<string, number>();+ for (const e of edges) {+ if (e.source === e.target || !LINKED_FAMILIES.has(edgeFamilyOf(e))) continue;+ const w = linkWeight(e);+ out.set(e.source, (out.get(e.source) ?? 0) + w);+ out.set(e.target, (out.get(e.target) ?? 0) + w);+ }+ return out;+}++export interface EstateView {+ level: Extract<MapLevel, "estate" | "group">;+ grouped: boolean;+ nodes: DrawnNode[];+ edges: DrawnEdge[];+ truncation: TruncationReport | null;+}++type RootItem = { kind: "group"; id: string } | { kind: "tray" } | { kind: "service"; id: string };++/** Services split by where they live before any budget: groups, the root, the tray. */+interface Partition {+ groupOf: Map<string, string> | null;+ /** Group id -> members, most-linked first. */+ members: Map<string, string[]>;+ /** Group ids, most-linked group first. */+ groupIds: string[];+ rootServices: string[];+ trayServices: string[];+}++function partition(graph: LevelsGraph): Partition {+ const groupOf = activeGroups(graph);+ const weights = linkedWeights(graph.edges);+ const weight = (id: string) => weights.get(id) ?? 0;+ const byRank = (a: string, b: string) => weight(b) - weight(a) || compareIds(a, b);+ const members = new Map<string, string[]>();+ const rootServices: string[] = [];+ const trayServices: string[] = [];+ for (const n of graph.nodes) {+ const g = groupOf?.get(n.id);+ if (g !== undefined) push(members, g, n.id);+ else if (weight(n.id) > 0) rootServices.push(n.id);+ else trayServices.push(n.id);+ }+ for (const list of members.values()) list.sort(byRank);+ rootServices.sort(byRank);+ trayServices.sort(byRank);+ const groupIds = [...members]+ .map(([g, ids]) => [g, ids.reduce((sum, id) => sum + weight(id), 0)] as const)+ .sort((a, b) => b[1] - a[1] || compareIds(a[0], b[0]))+ .map(([g]) => g);+ return { groupOf, members, groupIds, rootServices, trayServices };+}++type GroupStats = Map<string, { in: number; out: number; inside: number }>;++/** Links into, out of and inside each group, from the edges rather than the drawing, so open and closed agree. */+function groupLinkStats(visible: readonly LevelsEdge[], groupOf: Map<string, string> | null): GroupStats {+ const stats: GroupStats = new Map();+ if (!groupOf) return stats;+ const stat = (g: string) => {+ let s = stats.get(g);+ if (!s) stats.set(g, (s = { in: 0, out: 0, inside: 0 }));+ return s;+ };+ for (const e of visible) {+ const gs = groupOf.get(e.source);+ const gt = groupOf.get(e.target);+ const w = linkWeight(e);+ if (gs !== undefined && gs === gt) {+ if (e.source !== e.target) stat(gs).inside += w;+ continue;+ }+ if (gs !== undefined) stat(gs).out += w;+ if (gt !== undefined) stat(gt).in += w;+ }+ return stats;+}++/** Where each service is drawn, which ids are their own cards, and what folded. */+interface Placement {+ drawnAt: Map<string, string>;+ cards: Set<string>;+ keptGroups: Set<string>;+ trayCard: boolean;+ rootMore: { services: string[]; groups: string[] };+ /** Open container id -> services folded into its "+N more". */+ openFolded: Map<string, string[]>;+}++function rootItemTarget(item: RootItem): string {+ if (item.kind === "group") return groupNodeId(item.id);+ return item.kind === "tray" ? TRAY_NODE_ID : item.id;+}++function rootItemServices(p: Partition, item: RootItem): readonly string[] {+ if (item.kind === "group") return p.members.get(item.id)!;+ return item.kind === "tray" ? p.trayServices : [item.id];+}++/** The first `keep` root items are drawn; the rest fold into the estate's "+N more". */+function placeRoot(p: Partition, items: readonly RootItem[], keep: number, out: Placement): void {+ items.forEach((item, index) => {+ const isKept = index < keep;+ const services = rootItemServices(p, item);+ const at = isKept ? rootItemTarget(item) : ESTATE_MORE_ID;+ for (const id of services) out.drawnAt.set(id, at);+ if (!isKept) {+ out.rootMore.services.push(...services);+ if (item.kind === "group") out.rootMore.groups.push(item.id);+ } else if (item.kind === "group") out.keptGroups.add(item.id);+ else if (item.kind === "tray") out.trayCard = true;+ else out.cards.add(item.id);+ });+}++/** Kept members become cards inside the container, the rest fold into its "+N more". */+function placeOpen(containerId: string, ids: readonly string[], keep: number, moreId: string, out: Placement): void {+ ids.forEach((id, i) => {+ out.drawnAt.set(id, i < keep ? id : moreId);+ if (i < keep) out.cards.add(id);+ });+ out.openFolded.set(containerId, ids.slice(keep));+}++const limited = (size: number): BudgetContainer =>+ size > OPEN_GROUP_LIMIT.over ? { size, limit: OPEN_GROUP_LIMIT.keep } : { size };++/**+ * Fit the estate to the node budget. Containers: the root (closed group+ * cards, then the tray card, then services, in fold priority), each open+ * group, and the open tray; open containers themselves always draw.+ */+function place(p: Partition, opened: ReadonlySet<string>, trayOpen: boolean, budget: DrawBudget): Placement {+ const openGroups = p.groupIds.filter((g) => opened.has(g));+ const rootItems: RootItem[] = [+ ...p.groupIds.filter((g) => !opened.has(g)).map((id) => ({ kind: "group" as const, id })),+ ...(p.trayServices.length > 0 && !trayOpen ? [{ kind: "tray" as const }] : []),+ ...p.rootServices.map((id) => ({ kind: "service" as const, id })),+ ];+ const containers: BudgetContainer[] = [+ { size: rootItems.length },+ ...openGroups.map((g) => limited(p.members.get(g)!.length)),+ ...(trayOpen ? [limited(p.trayServices.length)] : []),+ ];+ const kept = allocateSlots(containers, budget.nodes - openGroups.length - (trayOpen ? 1 : 0));+ const placed: Placement = {+ drawnAt: new Map(),+ cards: new Set(),+ keptGroups: new Set(),+ trayCard: false,+ rootMore: { services: [], groups: [] },+ openFolded: new Map(),+ };+ placeRoot(p, rootItems, kept[0]!, placed);+ openGroups.forEach((g, i) => placeOpen(groupNodeId(g), p.members.get(g)!, kept[i + 1]!, groupMoreId(g), placed));+ if (trayOpen) placeOpen(TRAY_NODE_ID, p.trayServices, kept[kept.length - 1]!, TRAY_MORE_ID, placed);+ return placed;+}++/** The estate, with any opened groups and the tray, drawing only `visible` edges. */+export function buildEstateView(+ graph: LevelsGraph,+ state: LevelViewState,+ visible: readonly LevelsEdge[],+ edgesById: ReadonlyMap<string, LevelsEdge>,+ budget: DrawBudget,+): EstateView {+ const p = partition(graph);+ const opened = new Set([...(state.open ?? [])].filter((g) => p.members.has(g)));+ const trayOpen = Boolean(state.openTray) && p.trayServices.length > 0;+ const placed = place(p, opened, trayOpen, budget);++ const edges = connectEdges(visible, (id) => placed.drawnAt.get(id) ?? null, (id) => placed.cards.has(id));+ const capped = capEdges(edges, budget.edges, edgesById);+ const stats = groupLinkStats(visible, p.groupOf);+ const nodes = assembleNodes(graph, p, { opened, trayOpen, stats, placed });++ const foldedServices = [...placed.openFolded.values()].reduce((n, f) => n + f.length, placed.rootMore.services.length);+ return {+ level: opened.size > 0 || trayOpen ? "group" : "estate",+ grouped: p.groupOf !== null,+ nodes,+ edges: capped.edges,+ truncation: truncationReport(+ budget,+ foldedServices,+ placed.rootMore.groups.length,+ capped.droppedEdges,+ capped.droppedLinks,+ ),+ };+}++interface AssembleArgs {+ opened: ReadonlySet<string>;+ trayOpen: boolean;+ stats: GroupStats;+ placed: Placement;+}++function groupCard(graph: LevelsGraph, p: Partition, g: string, open: boolean, stats: GroupStats): DrawnGroupNode {+ const meta = graph.groups?.find((m) => m.id === g);+ const ids = p.members.get(g)!;+ const repos = new Set(graph.nodes.filter((n) => p.groupOf?.get(n.id) === g).map((n) => n.repo));+ const s = stats.get(g);+ return {+ type: "group",+ id: groupNodeId(g),+ groupId: g,+ label: meta?.label || g,+ source: meta?.source ?? null,+ open,+ serviceIds: ids,+ repoCount: repos.size,+ linksIn: s?.in ?? 0,+ linksOut: s?.out ?? 0,+ linksInside: s?.inside ?? 0,+ };+}++/**+ * Output order is stable across open/close: groups by weight (an open one+ * followed by its children, as React Flow needs parents first), the tray,+ * ungrouped services, then the estate's "+N more".+ */+function assembleNodes(graph: LevelsGraph, p: Partition, args: AssembleArgs): DrawnNode[] {+ const { trayOpen, placed } = args;+ const tray: DrawnNode[] =+ trayOpen || placed.trayCard+ ? [+ { type: "tray", id: TRAY_NODE_ID, open: trayOpen, serviceIds: p.trayServices },+ ...(trayOpen ? childNodes(p.trayServices, TRAY_NODE_ID, TRAY_MORE_ID, placed) : []),+ ]+ : [];+ return [+ ...p.groupIds.flatMap((g) => groupNodes(graph, p, g, args)),+ ...tray,+ ...cardNodes(p.rootServices, null, placed),+ ...rootMoreNode(placed),+ ];+}++/** A group: nothing when folded, a card when closed, a container followed by its children when open. */+function groupNodes(graph: LevelsGraph, p: Partition, g: string, args: AssembleArgs): DrawnNode[] {+ if (args.opened.has(g)) {+ return [+ groupCard(graph, p, g, true, args.stats),+ ...childNodes(p.members.get(g)!, groupNodeId(g), groupMoreId(g), args.placed),+ ];+ }+ return args.placed.keptGroups.has(g) ? [groupCard(graph, p, g, false, args.stats)] : [];+}++/** Service cards for the ids that kept a card, in the order given. */+function cardNodes(ids: readonly string[], parentId: string | null, placed: Placement): DrawnNode[] {+ return ids+ .filter((id) => placed.cards.has(id))+ .map((id) => ({ type: "service" as const, id, serviceId: id, parentId }));+}++/** An open container's cards, then its "+N more" when the budget folded some. */+function childNodes(ids: readonly string[], parentId: string, moreId: string, placed: Placement): DrawnNode[] {+ const folded = placed.openFolded.get(parentId) ?? [];+ const more: DrawnNode[] =+ folded.length > 0 ? [{ type: "more", id: moreId, parentId, serviceIds: folded, groupIds: [] }] : [];+ return [...cardNodes(ids, parentId, placed), ...more];+}++function rootMoreNode(placed: Placement): DrawnNode[] {+ const { services, groups } = placed.rootMore;+ if (services.length === 0) return [];+ return [{ type: "more", id: ESTATE_MORE_ID, parentId: null, serviceIds: services, groupIds: groups }];+}diff --git a/packages/ui/src/workspace/system-map/focus-columns.ts b/packages/ui/src/workspace/system-map/focus-columns.tsnew file mode 100644index 000000000..a3dc3d289--- /dev/null+++ b/packages/ui/src/workspace/system-map/focus-columns.ts@@ -0,0 +1,205 @@+/**+ * Focus (L2): one service in the middle, what calls it on the left, what it+ * depends on on the right, sorted by link count so each column reads as a+ * list. A service on both sides sits in both columns, marked `bothWays`.+ * Two hops add callers of callers far left and dependencies of dependencies+ * far right. Placement is a fixed column grid, no ELK. Pure, no React.+ */++import type { C4LayoutPosition } from "../../c4/layout/elk-c4-layout";+import { addLink, bandId, compareIds, emptySummary } from "./bands";+import { allocateSlots } from "./draw-budget";+import { edgeFamilyOf, type EdgeFamily } from "./edge-families";+import type { DrawBudget, FocusColumnId, LevelsEdge, LevelsGraph, LinkSummary } from "./level-types";++export interface FocusEntry {+ serviceId: string;+ /** Links between this service and its neighbour column (the focus, for one hop). */+ summary: LinkSummary;+ bothWays: boolean;+}++export interface FocusColumn {+ id: FocusColumnId;+ /** Drawn entries, strongest first. */+ entries: FocusEntry[];+ /** Service ids the draw budget folded into the column's "+N more" node. */+ folded: string[];+}++/** A connector between two drawn ids, every link of the pair in one. */+export interface FocusConnector {+ id: string;+ source: string;+ target: string;+ summary: LinkSummary;+}++export interface FocusLayout {+ focus: string;+ hops: 1 | 2;+ /** Left to right, without the focus: callers2?, callers, dependencies, dependencies2?. */+ columns: FocusColumn[];+ connectors: FocusConnector[];+}++/** Drawn id of a service card in a focus column; the focus card keeps the service id. */+export function focusNodeId(column: FocusColumnId, serviceId: string): string {+ return `${column}:${serviceId}`;+}++export function focusMoreId(column: FocusColumnId): string {+ return `more:${column}`;+}++type Neighbours = Map<string, LinkSummary>;++function collect(into: Neighbours, key: string, edge: LevelsEdge): void {+ let s = into.get(key);+ if (!s) into.set(key, (s = emptySummary()));+ addLink(s, edge);+}++function ranked(neighbours: Neighbours, other: Neighbours): FocusEntry[] {+ return [...neighbours]+ .map(([serviceId, summary]) => ({ serviceId, summary, bothWays: other.has(serviceId) }))+ .sort((x, y) => y.summary.links - x.summary.links || compareIds(x.serviceId, y.serviceId));+}++type PlannedColumn = { id: FocusColumnId; entries: FocusEntry[] };++/** Neighbours of `focus` one way (callers or dependencies), from the edges given. */+function ring(edges: readonly LevelsEdge[], into: (e: LevelsEdge) => string | null): Neighbours {+ const out: Neighbours = new Map();+ for (const e of edges) {+ const key = into(e);+ if (key !== null) collect(out, key, e);+ }+ return out;+}++/** The columns before the budget: one hop each side, plus the outer rings for two hops. */+function planColumns(edges: readonly LevelsEdge[], focus: string, hops: 1 | 2): PlannedColumn[] {+ const callers = ring(edges, (e) => (e.target === focus ? e.source : null));+ const deps = ring(edges, (e) => (e.source === focus ? e.target : null));+ const plan: PlannedColumn[] = [+ { id: "callers", entries: ranked(callers, deps) },+ { id: "dependencies", entries: ranked(deps, callers) },+ ];+ if (hops === 1) return plan;+ const ring1 = new Set([focus, ...callers.keys(), ...deps.keys()]);+ const callers2 = ring(edges, (e) => (callers.has(e.target) && !ring1.has(e.source) ? e.source : null));+ const deps2 = ring(edges, (e) => (deps.has(e.source) && !ring1.has(e.target) ? e.target : null));+ return [+ { id: "callers2", entries: ranked(callers2, deps2) },+ ...plan,+ { id: "dependencies2", entries: ranked(deps2, callers2) },+ ];+}++/** Keep what the node budget allows per column (the focus card takes one slot); fold the rest. */+function foldColumns(plan: readonly PlannedColumn[], budget: DrawBudget): FocusColumn[] {+ const kept = allocateSlots(+ plan.map((c) => ({ size: c.entries.length })),+ budget.nodes - 1,+ );+ return plan.map((c, i) => ({+ id: c.id,+ entries: c.entries.slice(0, kept[i]),+ folded: c.entries.slice(kept[i]).map((e) => e.serviceId),+ }));+}++/** Where a service is drawn in a column: its card, the column's "+N more", or null when not in it. */+function drawnIn(columns: readonly FocusColumn[]): (column: FocusColumnId, id: string) => string | null {+ const at = new Map<FocusColumnId, Map<string, string>>();+ for (const c of columns) {+ const m = new Map<string, string>();+ for (const e of c.entries) m.set(e.serviceId, focusNodeId(c.id, e.serviceId));+ for (const id of c.folded) m.set(id, focusMoreId(c.id));+ at.set(c.id, m);+ }+ return (column, id) => at.get(column)?.get(id) ?? null;+}++/** One connector per pair of drawn ids between neighbouring columns, sorted by id. */+function connectColumns(+ edges: readonly LevelsEdge[],+ focus: string,+ hops: 1 | 2,+ drawn: (column: FocusColumnId, id: string) => string | null,+): FocusConnector[] {+ const connectors = new Map<string, FocusConnector>();+ const connect = (source: string | null, target: string | null, e: LevelsEdge) => {+ if (source === null || target === null) return;+ const id = bandId(source, target);+ let c = connectors.get(id);+ if (!c) connectors.set(id, (c = { id, source, target, summary: emptySummary() }));+ addLink(c.summary, e);+ };+ // Each pair of neighbouring columns, as (source column, target column); null is the focus card.+ const pairs: [FocusColumnId | null, FocusColumnId | null][] = [+ ["callers", null],+ [null, "dependencies"],+ ];+ if (hops === 2) pairs.push(["callers2", "callers"], ["dependencies", "dependencies2"]);+ const at = (column: FocusColumnId | null, id: string) =>+ column === null ? (id === focus ? focus : null) : drawn(column, id);+ for (const e of edges) {+ for (const [from, to] of pairs) connect(at(from, e.source), at(to, e.target), e);+ }+ return [...connectors.values()].sort((x, y) => compareIds(x.id, y.id));+}++/**+ * Columns around `focus` in the families shown, folded to the draw budget.+ * Null when `focus` is not a service in the graph.+ */+export function focusColumns(+ graph: LevelsGraph,+ focus: string,+ options: { families: ReadonlySet<EdgeFamily>; hops?: 1 | 2 | undefined; budget: DrawBudget },+): FocusLayout | null {+ if (!graph.nodes.some((n) => n.id === focus)) return null;+ const hops = options.hops ?? 1;+ const edges = graph.edges.filter((e) => e.source !== e.target && options.families.has(edgeFamilyOf(e)));+ const columns = foldColumns(planColumns(edges, focus, hops), options.budget);+ return { focus, hops, columns, connectors: connectColumns(edges, focus, hops, drawnIn(columns)) };+}++export interface FocusPlacement {+ /** Card footprint, the same for every column. */+ size: { width: number; height: number };+ /** Horizontal gap between columns and vertical gap between cards. */+ gap?: { x: number; y: number };+}++/**+ * Top-left positions for every drawn id: columns left to right, each centred+ * on the focus card's row. Deterministic: same layout in, same positions out.+ */+export function placeFocusColumns(layout: FocusLayout, placement: FocusPlacement): Map<string, C4LayoutPosition> {+ const { width, height } = placement.size;+ const gap = placement.gap ?? { x: 96, y: 16 };+ const left = layout.columns.filter((c) => c.id === "callers2" || c.id === "callers");+ const right = layout.columns.filter((c) => c.id === "dependencies" || c.id === "dependencies2");+ const stacks: string[][] = [+ ...left.map((c) => columnIds(c)),+ [layout.focus],+ ...right.map((c) => columnIds(c)),+ ];+ const positions = new Map<string, C4LayoutPosition>();+ stacks.forEach((ids, col) => {+ const top = -((ids.length * height + (ids.length - 1) * gap.y) / 2);+ ids.forEach((id, row) => {+ positions.set(id, { x: col * (width + gap.x), y: top + row * (height + gap.y), width, height });+ });+ });+ return positions;+}++function columnIds(column: FocusColumn): string[] {+ const ids = column.entries.map((e) => focusNodeId(column.id, e.serviceId));+ if (column.folded.length > 0) ids.push(focusMoreId(column.id));+ return ids;+}diff --git a/packages/ui/src/workspace/system-map/index.ts b/packages/ui/src/workspace/system-map/index.tsindex 8943177b8..bcf63d740 100644--- a/packages/ui/src/workspace/system-map/index.ts+++ b/packages/ui/src/workspace/system-map/index.ts@@ -1,8 +1,10 @@/*** 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.+ * builders and the pure model helpers behind them; the levels model (groups,+ * bands, focus columns, paths between two services, draw budget); layout,+ * registries and overlay types. The rail panels stay exported for hosts that+ * still use them.*/export {@@ -99,6 +101,74 @@ export {type SystemEdgeKindStyle,type EdgeCategory,} from "./edge-kinds";+export {+ buildLevelView,+ normalizeGraph,+ type LevelView,+} from "./levels";+export {+ buildEstateView,+ activeGroups,+ linkedWeights,+ groupNodeId,+ OPEN_GROUP_LIMIT,+ TRAY_NODE_ID,+ ESTATE_MORE_ID,+ type EstateView,+} from "./estate-view";+export {+ focusColumns,+ placeFocusColumns,+ focusNodeId,+ focusMoreId,+ type FocusColumn,+ type FocusConnector,+ type FocusEntry,+ type FocusLayout,+ type FocusPlacement,+} from "./focus-columns";+export {+ servicesBetween,+ shortestPaths,+ buildAdjacency,+ type BetweenOptions,+ type BetweenResult,+ type PathHop,+ type ServicePath,+} from "./between";+export { connectEdges, summarizeLinks, bandId, compareIds } from "./bands";+export { DRAW_BUDGET, allocateSlots, capEdges, truncationReport, type BudgetContainer } from "./draw-budget";+export {+ EDGE_FAMILY_ORDER,+ DEFAULT_EDGE_FAMILIES,+ LINKED_FAMILIES,+ edgeFamily,+ edgeFamilyOf,+ familyCounts,+ linkWeight,+ type EdgeFamily,+ type FamilyCount,+} from "./edge-families";+export type {+ DrawBudget,+ DrawnBand,+ DrawnEdge,+ DrawnGroupNode,+ DrawnMoreNode,+ DrawnNode,+ DrawnServiceNode,+ DrawnSingleEdge,+ DrawnTrayNode,+ FocusColumnId,+ LevelViewState,+ LevelsEdge,+ LevelsGraph,+ LevelsGroupMeta,+ LevelsNode,+ LinkSummary,+ MapLevel,+ TruncationReport,+} from "./level-types";export { SYSTEM_NODE_KINDS, NODE_KIND_ORDER, nodeKindStyle, type SystemNodeKindStyle } from "./node-kinds";export {resolveNodeOverlay,diff --git a/packages/ui/src/workspace/system-map/level-types.ts b/packages/ui/src/workspace/system-map/level-types.tsnew file mode 100644index 000000000..ce67393b5--- /dev/null+++ b/packages/ui/src/workspace/system-map/level-types.ts@@ -0,0 +1,160 @@+/**+ * Shapes for the System Map levels model: the narrow graph it reads, the view+ * state it is driven by, and the drawn graph it returns. Plain data, no React.+ *+ * Input is deliberately narrower than `SystemGraph`: a full `SystemGraph`+ * satisfies it, and so does a lean payload that dropped `contract_refs` and+ * `diagnostics`. `group` / `groups` are optional, and a graph without them is+ * drawn as one flat estate.+ */++import type { SystemEdge, SystemNode } from "@repowise-dev/types";+import type { EdgeFamily } from "./edge-kinds";++/** A service as the levels model reads it. `group` is the id of the system it belongs to, when the server grouped the estate. */+export type LevelsNode = Pick<SystemNode, "id" | "name" | "repo"> & { group?: string | null };++/**+ * An edge as the levels model reads it. `source` depends on / calls `target`.+ * `family` is core's filter family when the payload carries it; the kind+ * registry answers for payloads that do not.+ */+export type LevelsEdge = Pick<SystemEdge, "id" | "source" | "target" | "kind" | "weight" | "strategy" | "family">;++/** Summary of one group, when the graph carries one. Only `id` is required. */+export interface LevelsGroupMeta {+ id: string;+ /** Display name; the id is used when absent. */+ label?: string | null;+ /** Where the group came from (declared tag, name family, linkage). Passed through for the card. */+ source?: string | null;+}++export interface LevelsGraph {+ nodes: readonly LevelsNode[];+ edges: readonly LevelsEdge[];+ /** Present and non-empty only when the server grouped the estate; absent means draw it flat. */+ groups?: readonly LevelsGroupMeta[] | null | undefined;+}++/** At most this much is drawn at once; the rest is aggregated and reported. */+export interface DrawBudget {+ nodes: number;+ edges: number;+}++/** What the reader asked to see. Ids that name nothing in the graph are ignored. */+export interface LevelViewState {+ /** Group ids opened in place (L1). */+ open?: Iterable<string>;+ /** Open the "Not linked at runtime" tray into its service cards. */+ openTray?: boolean;+ /** Service id to focus (L2). */+ focus?: string | null;+ /** Rings of callers and dependencies around the focus. */+ hops?: 1 | 2;+ /** Two service ids to show the links between (L3). Wins over `focus`. */+ between?: { a: string; b: string } | null;+ /** Edge families drawn; defaults to Runtime and Data. */+ families?: ReadonlySet<EdgeFamily>;+}++export type MapLevel = "estate" | "group" | "focus" | "between";++/** The links one drawn connector or one column entry stands for. */+export interface LinkSummary {+ /** Underlying links (sum of edge weights). */+ links: number;+ /** System edges aggregated. */+ edges: number;+ /** Links per edge kind. */+ kinds: Record<string, number>;+ /** Links a gateway's route config made, named "via gateway" on hover. */+ gatewayLinks: number;+ edgeIds: string[];+}++/** A group drawn as a card (closed) or as the container of its service cards (open). */+export interface DrawnGroupNode {+ type: "group";+ id: string;+ groupId: string;+ label: string;+ source: string | null;+ open: boolean;+ serviceIds: string[];+ repoCount: number;+ /** Links drawn into, out of, and inside the group, in the families shown. */+ linksIn: number;+ linksOut: number;+ linksInside: number;+}++/** A service card. `id` is the service id except where one service is drawn twice (focus columns). */+export interface DrawnServiceNode {+ type: "service";+ id: string;+ serviceId: string;+ /** Id of the open group or tray that contains the card. */+ parentId: string | null;+ /** Focus level only: the column the card sits in. */+ column?: FocusColumnId | "focus";+ /** Focus level only: the links between this service and its neighbour column. */+ links?: LinkSummary;+ /** Focus level only: the service both calls and is called by the focus. */+ bothWays?: boolean;+}++/** Services with no Runtime or Data link, as one card (closed) or a container (open). */+export interface DrawnTrayNode {+ type: "tray";+ id: string;+ open: boolean;+ serviceIds: string[];+}++/** "+N more": what the draw budget folded in one container. */+export interface DrawnMoreNode {+ type: "more";+ id: string;+ parentId: string | null;+ serviceIds: string[];+ /** Group cards folded into it (estate level only). */+ groupIds: string[];+}++export type DrawnNode = DrawnGroupNode | DrawnServiceNode | DrawnTrayNode | DrawnMoreNode;++/** One system edge between two drawn service cards. */+export interface DrawnSingleEdge {+ type: "edge";+ id: string;+ source: string;+ target: string;+ edgeId: string;+}++/** Every link between two drawn nodes when at least one of them aggregates (or on focus columns). */+export interface DrawnBand {+ type: "band";+ id: string;+ source: string;+ target: string;+ summary: LinkSummary;+}++export type DrawnEdge = DrawnSingleEdge | DrawnBand;++export type FocusColumnId = "callers2" | "callers" | "dependencies" | "dependencies2";++/** What the draw budget left out. Null on a view that fits. */+export interface TruncationReport {+ budget: DrawBudget;+ /** Services drawn only inside a "+N more" node. */+ foldedServices: number;+ /** Group cards drawn only inside a "+N more" node. */+ foldedGroups: number;+ /** Connectors not drawn because the edge budget was spent, weakest first. */+ droppedEdges: number;+ droppedLinks: number;+}diff --git a/packages/ui/src/workspace/system-map/levels.ts b/packages/ui/src/workspace/system-map/levels.tsnew file mode 100644index 000000000..096428bd1--- /dev/null+++ b/packages/ui/src/workspace/system-map/levels.ts@@ -0,0 +1,190 @@+/**+ * The System Map levels model: view state in, drawn graph out.+ *+ * - Estate (L0) and group open (L1): `estate-view.ts`.+ * - Focus (L2): callers, the service, dependencies (`focus-columns.ts`).+ * - Between (L3): two services, the services on the paths joining them, and+ * every drawn link among them (`between.ts`).+ *+ * Precedence is between, then focus, then the estate; an id that names no+ * service falls through to the next level. Every level is held to the draw+ * budget, and what does not fit is counted in the truncation report.+ * Pure, no React, deterministic.+ */++import { compareIds, connectEdges } from "./bands";+import { servicesBetween, type BetweenResult } from "./between";+import { DRAW_BUDGET, capEdges, truncationReport } from "./draw-budget";+import {+ DEFAULT_EDGE_FAMILIES,+ edgeFamilyOf,+ familyCounts,+ type EdgeFamily,+ type FamilyCount,+} from "./edge-families";+import { buildEstateView } from "./estate-view";+import { focusColumns, focusMoreId, focusNodeId, type FocusColumn, type FocusLayout } from "./focus-columns";+import type {+ DrawBudget,+ DrawnEdge,+ DrawnNode,+ LevelViewState,+ LevelsEdge,+ LevelsGraph,+ MapLevel,+ TruncationReport,+} from "./level-types";++export interface LevelView {+ level: MapLevel;+ /** True when the estate is drawn as groups. */+ grouped: boolean;+ nodes: DrawnNode[];+ edges: DrawnEdge[];+ /** Families drawn. */+ families: ReadonlySet<EdgeFamily>;+ /** Edges and links per family present in the whole graph, for the chips and the hidden-family caption. */+ familyCounts: Partial<Record<EdgeFamily, FamilyCount>>;+ truncation: TruncationReport | null;+ /** Focus level only. */+ focus: FocusLayout | null;+ /** Between level only. */+ between: BetweenResult | null;+}++/**+ * One node per id, edges only between known nodes, both in id order, so a+ * payload with duplicates or dangling edges draws no phantom card and the+ * view is the same whatever order the payload arrived in. Of two records+ * sharing an id, the one whose serialization sorts first wins.+ */+export function normalizeGraph(graph: LevelsGraph): LevelsGraph {+ const cached = normalized.get(graph);+ if (cached) return cached;+ const nodes = dedupeById(graph.nodes);+ const known = new Set(nodes.map((n) => n.id));+ const edges = dedupeById(graph.edges.filter((e) => known.has(e.source) && known.has(e.target)));+ const out = { ...graph, nodes, edges };+ normalized.set(graph, out);+ normalized.set(out, out);+ return out;+}++/** One normalized graph per payload object, so a filter toggle or a focus change never re-sorts the payload. */+const normalized = new WeakMap<LevelsGraph, LevelsGraph>();++/**+ * One record per id, in id order. A duplicate id keeps the copy that+ * serializes first, whatever its position; only colliding records are+ * serialized, so a clean payload costs one pass and a sort.+ */+function dedupeById<T extends { id: string }>(records: readonly T[]): T[] {+ const kept = new Map<string, T>();+ for (const record of records) {+ const prior = kept.get(record.id);+ if (!prior || stableKey(record) < stableKey(prior)) kept.set(record.id, record);+ }+ return [...kept.values()].sort((x, y) => compareIds(x.id, y.id));+}++/** JSON with keys in sorted order, so two equal records always serialize alike. */+function stableKey(record: object): string {+ return JSON.stringify(record, Object.keys(record).sort());+}++/** What every level reads: the normalized graph, the families shown, and the edges they keep. */+interface LevelInput {+ graph: LevelsGraph;+ families: ReadonlySet<EdgeFamily>;+ visible: LevelsEdge[];+ edgesById: Map<string, LevelsEdge>;+ budget: DrawBudget;+}++type LevelResult = Pick<LevelView, "level" | "grouped" | "nodes" | "edges" | "truncation" | "focus" | "between">;++/** Between (L3): the pair and the services on its paths, every drawn link among them. Null when a or b is unknown. */+function betweenLevel(input: LevelInput, pair: { a: string; b: string }): LevelResult | null {+ const between = servicesBetween(input.graph, pair.a, pair.b, { families: input.families });+ if (!between) return null;+ const drawn = new Set([between.a, between.b]);+ for (const p of [...between.pathsAToB, ...between.pathsBToA]) p.nodes.forEach((id) => drawn.add(id));+ const edges = connectEdges(input.visible, (id) => (drawn.has(id) ? id : null), () => true);+ const capped = capEdges(edges, input.budget.edges, input.edgesById);+ return {+ level: "between",+ grouped: false,+ focus: null,+ between,+ nodes: [...drawn].sort().map((id) => ({ type: "service", id, serviceId: id, parentId: null })),+ edges: capped.edges,+ truncation: truncationReport(input.budget, 0, 0, capped.droppedEdges, capped.droppedLinks),+ };+}++/** A focus column's cards, then its "+N more" when the budget folded some. */+function columnNodes(column: FocusColumn): DrawnNode[] {+ const nodes: DrawnNode[] = column.entries.map((e) => ({+ type: "service",+ id: focusNodeId(column.id, e.serviceId),+ serviceId: e.serviceId,+ parentId: null,+ column: column.id,+ links: e.summary,+ bothWays: e.bothWays,+ }));+ if (column.folded.length > 0) {+ nodes.push({ type: "more", id: focusMoreId(column.id), parentId: null, serviceIds: column.folded, groupIds: [] });+ }+ return nodes;+}++/** Focus (L2): left columns, the focus card, right columns. Null when the focus is unknown. */+function focusLevel(input: LevelInput, focusId: string, hops: 1 | 2 | undefined): LevelResult | null {+ const focus = focusColumns(input.graph, focusId, { families: input.families, hops, budget: input.budget });+ if (!focus) return null;+ const isLeft = (c: FocusColumn) => c.id === "callers" || c.id === "callers2";+ const focusCard: DrawnNode = { type: "service", id: focus.focus, serviceId: focus.focus, parentId: null, column: "focus" };+ const nodes = [+ ...focus.columns.filter(isLeft).flatMap(columnNodes),+ focusCard,+ ...focus.columns.filter((c) => !isLeft(c)).flatMap(columnNodes),+ ];+ const folded = new Set(focus.columns.flatMap((c) => c.folded));+ const edges: DrawnEdge[] = focus.connectors.map((c) => ({ type: "band", ...c }));+ const capped = capEdges(edges, input.budget.edges, input.edgesById);+ return {+ level: "focus",+ grouped: false,+ focus,+ between: null,+ nodes,+ edges: capped.edges,+ truncation: truncationReport(input.budget, folded.size, 0, capped.droppedEdges, capped.droppedLinks),+ };+}++/** The drawn graph for a view state. Exported helpers below it expect a normalized graph. */+export function buildLevelView(+ graph: LevelsGraph,+ state: LevelViewState = {},+ budget: DrawBudget = DRAW_BUDGET,+): LevelView {+ const normalized = normalizeGraph(graph);+ const families = state.families ?? DEFAULT_EDGE_FAMILIES;+ const input: LevelInput = {+ graph: normalized,+ families,+ visible: normalized.edges.filter((e) => families.has(edgeFamilyOf(e))),+ edgesById: new Map(normalized.edges.map((e) => [e.id, e])),+ budget,+ };+ const result =+ (state.between ? betweenLevel(input, state.between) : null) ??+ (state.focus ? focusLevel(input, state.focus, state.hops) : null) ?? {+ ...buildEstateView(normalized, state, input.visible, input.edgesById, budget),+ focus: null,+ between: null,+ };+ return { ...result, families, familyCounts: familyCounts(normalized.edges) };+}