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(knowledge-graph): name what the arrows and dots mean, and rebuild the detail panel (#1145)
Raghav Chamadiya157fdfec0044
diff --git a/packages/server/src/repowise/server/services/c4_builder/labels.py b/packages/server/src/repowise/server/services/c4_builder/labels.pyindex 22f238d64..a5a9f9a8e 100644--- a/packages/server/src/repowise/server/services/c4_builder/labels.py+++ b/packages/server/src/repowise/server/services/c4_builder/labels.py@@ -15,12 +15,25 @@ from __future__ import annotationsfrom collections.abc import Iterable# Raw edge-type token -> the verb a reader expects on a C4 arrow.+#+# Every token the extractors actually emit must appear here. A missing one is+# silent: `relation_label` falls through to "depends on", which is the label+# reserved for a *wholly unknown* set, so a real, nameable dependency gets+# reported as the vaguest word we have. That is what happened to `framework`+# and `dynamic_uses`, which between them covered 1,351 of the 13,165 file-level+# edges on a live index (10%) and rendered as "depends on" for their whole life.+# `extends` is the token the extractors emit; `inherits` never was one._EDGE_VERB: dict[str, str] = {"imports": "imports","dynamic_imports": "imports","calls": "calls",+ "extends": "inherits from","inherits": "inherits from","implements": "implements",+ # A lazy/registry import and a framework-convention link (a test file to its+ # conftest) are both real dependencies that no static import expresses.+ "dynamic_uses": "uses",+ "framework": "uses","references": "references","contains": "contains","co_changes": "co-changes",@@ -34,6 +47,9 @@ _VERB_PRIORITY: tuple[str, ...] = ("inherits from","implements","imports",+ # Below "imports": where a pair has both, the static import is the more+ # precise description of the same dependency.+ "uses","references","contains","co-changes",diff --git a/packages/ui/__tests__/zoom/node-signals.test.ts b/packages/ui/__tests__/zoom/node-signals.test.tsnew file mode 100644index 000000000..480ed69a8--- /dev/null+++ b/packages/ui/__tests__/zoom/node-signals.test.ts@@ -0,0 +1,76 @@+import { describe, it, expect } from "vitest";+import { hasRole, healthBandLabel, nodeRoles } from "../../src/zoom/node-signals";+import type { ZoomNode } from "../../src/zoom/types";++function node(over: Partial<ZoomNode> = {}): ZoomNode {+ return {+ id: "n",+ parent_id: null,+ kind: "file",+ name: "n",+ path: "n",+ language: null,+ summary: null,+ children: [],+ rect: { x: 0, y: 0, w: 1, h: 1 },+ metrics: {+ file_count: 0,+ hotspot_count: 0,+ entry_point_count: 0,+ on_flow_count: 0,+ dead_count: 0,+ },+ health_score: null,+ is_entry_point: false,+ is_hotspot: false,+ is_dead: false,+ is_test: false,+ on_flow: false,+ ...over,+ } as ZoomNode;+}++describe("nodeRoles", () => {+ it("is empty when the node carries no role, so no dot is drawn", () => {+ expect(nodeRoles(node())).toEqual([]);+ expect(hasRole(node())).toBe(false);+ });++ it("names every applicable role, not just the priority winner", () => {+ // The old dot ran entry > hotspot > dead > on-flow and drew one colour, so+ // a box that was both reported only "entry".+ const both = node({ is_entry_point: true, is_hotspot: true });+ expect(nodeRoles(both)).toEqual(["Entry point", "Hotspot"]);+ });++ it("inherits a role from the subtree, matching what the card's dot tests", () => {+ const container = node({+ kind: "folder",+ metrics: {+ file_count: 9,+ hotspot_count: 2,+ entry_point_count: 0,+ on_flow_count: 0,+ dead_count: 0,+ },+ });+ expect(nodeRoles(container)).toEqual(["Hotspot"]);+ expect(hasRole(container)).toBe(true);+ });+});++describe("healthBandLabel", () => {+ it("stays quiet for an unscored node, since health is sparse", () => {+ expect(healthBandLabel(null)).toBeNull();+ });++ it("uses the canonical 3-band scale the card's dot paints on", () => {+ expect(healthBandLabel(8.0)).toBe("Healthy");+ expect(healthBandLabel(4.0)).toBe("Warning");+ expect(healthBandLabel(3.9)).toBe("Alert");+ });++ it("does not report a 6.9 as 'Good' while the dot beside it paints amber", () => {+ expect(healthBandLabel(6.9)).toBe("Warning");+ });+});diff --git a/packages/ui/__tests__/zoom/relation-summary.test.ts b/packages/ui/__tests__/zoom/relation-summary.test.tsnew file mode 100644index 000000000..213f9d472--- /dev/null+++ b/packages/ui/__tests__/zoom/relation-summary.test.ts@@ -0,0 +1,113 @@+import { describe, it, expect } from "vitest";+import {+ CO_CHANGES,+ describeCap,+ describeRelations,+ indexRelationsByNode,+ summarizeRelations,+} from "../../src/zoom/relation-summary";+import { EDGE_MAX_PER_PARENT } from "../../src/zoom/constants";+import type { ZoomMap, ZoomRelation } from "../../src/zoom/types";++function rel(source: string, target: string, label: string, count = 1): ZoomRelation {+ return {+ parent_id: "p",+ source_id: source,+ target_id: target,+ label,+ edge_count: count,+ coupling: "loose",+ };+}++function map(relations: ZoomRelation[]): ZoomMap {+ return {+ root_id: "p",+ project_name: "t",+ total_files: 0,+ max_depth: 1,+ truncated: false,+ nodes: [],+ relations,+ };+}++describe("indexRelationsByNode", () => {+ it("indexes a relation under both endpoints", () => {+ const byNode = indexRelationsByNode(map([rel("a", "b", "imports")]));+ expect(byNode.get("a")).toHaveLength(1);+ expect(byNode.get("b")).toHaveLength(1);+ });++ it("drops self-loops, which the canvas never draws either", () => {+ const byNode = indexRelationsByNode(map([rel("a", "a", "imports")]));+ expect(byNode.get("a")).toBeUndefined();+ });+});++describe("summarizeRelations", () => {+ it("orders verbs by count so the dominant one reads first", () => {+ const s = summarizeRelations([+ rel("a", "b", "imports"),+ rel("a", "c", CO_CHANGES),+ rel("a", "d", "imports"),+ ]);+ expect(s.total).toBe(3);+ expect(s.verbs.map((v) => v.verb)).toEqual(["imports", CO_CHANGES]);+ expect(s.verbs[0]!.count).toBe(2);+ expect(s.coChanges).toBe(1);+ });++ it("reports `shown` as the per-parent cap once the total exceeds it", () => {+ const many = Array.from({ length: EDGE_MAX_PER_PARENT + 5 }, (_, i) =>+ rel("a", `b${i}`, "imports"),+ );+ expect(summarizeRelations(many).shown).toBe(EDGE_MAX_PER_PARENT);+ expect(summarizeRelations([rel("a", "b", "imports")]).shown).toBe(1);+ });+});++describe("describeRelations", () => {+ it("collapses the single-verb case, which is 89% of boxes on a real index", () => {+ const s = summarizeRelations([+ rel("a", "b", "imports"),+ rel("a", "c", "imports"),+ rel("a", "d", "imports"),+ ]);+ expect(describeRelations(s)).toBe("3 relations, all imports");+ });++ it("enumerates only when the verbs actually differ", () => {+ const s = summarizeRelations([+ rel("a", "b", "imports"),+ rel("a", "c", "imports"),+ rel("a", "d", CO_CHANGES),+ ]);+ expect(describeRelations(s)).toBe("3 relations: 2 imports, 1 co-changes");+ });++ it("keeps the singular readable rather than saying '1 relations, all imports'", () => {+ expect(describeRelations(summarizeRelations([rel("a", "b", "imports")]))).toBe(+ "1 imports relation",+ );+ });++ it("says so when there is nothing to show", () => {+ expect(describeRelations(summarizeRelations([]))).toBe("No relations at this level");+ });+});++describe("describeCap", () => {+ it("is silent when the view is complete", () => {+ expect(describeCap(summarizeRelations([rel("a", "b", "imports")]))).toBeNull();+ });++ it("names the bound when the cap hides relations, since a silent cap is a lie", () => {+ const many = Array.from({ length: EDGE_MAX_PER_PARENT + 1 }, (_, i) =>+ rel("a", `b${i}`, "imports"),+ );+ expect(describeCap(summarizeRelations(many))).toBe(+ `Showing the ${EDGE_MAX_PER_PARENT} strongest`,+ );+ });+});diff --git a/packages/ui/src/zoom/ZoomCanvas.tsx b/packages/ui/src/zoom/ZoomCanvas.tsxindex 9a6a68c7f..a6b690232 100644--- a/packages/ui/src/zoom/ZoomCanvas.tsx+++ b/packages/ui/src/zoom/ZoomCanvas.tsx@@ -22,7 +22,9 @@ import { type Camera, clampCamera, fitRoot, panByScreen, zoomAbout } from "./camimport { type FlyOptions, ZoomRenderer, type FrameStats } from "./renderer";import { buildScene } from "./scene";import { resolveZoomPalette } from "./theme";-import type { ZoomMap, ZoomNode } from "./types";+import type { ZoomMap, ZoomNode, ZoomRelation } from "./types";+import { describeRelations, summarizeRelations } from "./relation-summary";+import { healthBandLabel, nodeRoles } from "./node-signals";import { useThemeVersion } from "../shared/use-theme-tokens";export interface ZoomCanvasHandle {@@ -42,6 +44,17 @@ export interface ZoomCanvasProps {initialFocusId?: string;/** Show a small live frame-stat overlay (drawn/culled/fps). Dev aid. */showStats?: boolean;+ /**+ * Draw only relations carrying this verb, or every relation when unset.+ * See `DrawOptions.relationVerb` for why this is one verb and not a set.+ */+ relationVerb?: string | null;+ /**+ * Relations incident to a node, for the hover card's one-line summary. The+ * host already indexes these for its detail panel, so it passes the lookup in+ * rather than the canvas walking the relation list a second time.+ */+ relationsByNode?: Map<string, ZoomRelation[]>;}const WHEEL_ZOOM_RATE = 0.0015;@@ -69,7 +82,16 @@ function usePrefersReducedMotion(): boolean {}export const ZoomCanvas = forwardRef<ZoomCanvasHandle, ZoomCanvasProps>(function ZoomCanvas(- { data, className, onSelect, onFocusChange, initialFocusId, showStats },+ {+ data,+ className,+ onSelect,+ onFocusChange,+ initialFocusId,+ showStats,+ relationVerb = null,+ relationsByNode,+ },ref,) {const canvasRef = useRef<HTMLCanvasElement | null>(null);@@ -141,6 +163,10 @@ export const ZoomCanvas = forwardRef<ZoomCanvasHandle, ZoomCanvasProps>(functionrendererRef.current?.setScene(scene);}, [scene]);+ useEffect(() => {+ rendererRef.current?.setRelationVerb(relationVerb);+ }, [relationVerb]);+// One-shot: jump to the URL-provided focus node once the canvas has done its// initial fit (it needs a real viewport size before a node rect can be framed).const initialAppliedRef = useRef(false);@@ -332,7 +358,13 @@ export const ZoomCanvas = forwardRef<ZoomCanvasHandle, ZoomCanvasProps>(functionclassName="h-full w-full touch-none outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"style={{ cursor: "grab" }}/>- {hover && <HoverCard hover={hover} canvas={canvasRef.current} />}+ {hover && (+ <HoverCard+ hover={hover}+ canvas={canvasRef.current}+ relations={relationsByNode?.get(hover.node.id)}+ />+ )}{showStats && stats && <StatsOverlay stats={stats} laidOut={scene.laidOutCount} />}</div>);@@ -347,12 +379,26 @@ const HOVER_KIND_LABEL: Record<ZoomNode["kind"], string> = {};/**- * A deliberately light tooltip: kind, name, path and a one-line summary. The- * full metric breakdown lives in the side panel (open on click), so the hover- * stays calm and premium instead of dumping numbers.+ * A deliberately light tooltip: kind, name, path, a one-line summary and, when+ * the host supplies the index, what this box's arrows mean. The full metric+ * breakdown lives in the side panel (open on click), so the hover stays calm+ * and premium instead of dumping numbers.+ *+ * The relation line is here because the arrows appear on hover: naming them+ * anywhere else would explain a thing the reader is no longer looking at.*/-function HoverCard({ hover, canvas }: { hover: HoverState; canvas: HTMLCanvasElement | null }) {+function HoverCard({+ hover,+ canvas,+ relations,+}: {+ hover: HoverState;+ canvas: HTMLCanvasElement | null;+ relations: ZoomRelation[] | undefined;+}) {const { node } = hover;+ const roles = nodeRoles(node);+ const band = healthBandLabel(node.health_score);// Flip the card toward the interior when the cursor is near the right/bottom// edge, so it never spills off-canvas (N2).const w = canvas?.clientWidth ?? 0;@@ -366,7 +412,7 @@ function HoverCard({ hover, canvas }: { hover: HoverState; canvas: HTMLCanvasEleclassName="pointer-events-none absolute z-10 max-w-[16rem] rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-3 py-2 text-xs shadow-xl"style={{ left: hover.sx, top: hover.sy, transform: `translate(${tx}, ${ty})` }}>- <div className="text-[10px] font-medium uppercase tracking-wide text-[var(--color-text-tertiary)]">+ <div className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">{HOVER_KIND_LABEL[node.kind]}</div><div className="mt-0.5 font-semibold text-[var(--color-text-primary)]">{node.name}</div>@@ -376,6 +422,26 @@ function HoverCard({ hover, canvas }: { hover: HoverState; canvas: HTMLCanvasEle{node.summary && (<div className="mt-1 line-clamp-2 text-[var(--color-text-secondary)]">{node.summary}</div>)}+ {/* The two dots on the card, in words. They are drawn in the corners with+ no key of their own, so the moment the pointer is on the card is the+ cheapest place to say what they mean. */}+ {(roles.length > 0 || band) && (+ <div className="mt-1.5 flex flex-wrap items-center gap-x-2 gap-y-0.5 text-[var(--color-text-secondary)]">+ {roles.length > 0 && (+ <span className="text-[var(--color-accent-primary)]">{roles.join(" · ")}</span>+ )}+ {band && (+ <span className="tabular-nums">+ Health {node.health_score!.toFixed(1)} {band}+ </span>+ )}+ </div>+ )}+ {relations && relations.length > 0 && (+ <div className="mt-1.5 border-t border-[var(--color-border-default)] pt-1.5 text-[var(--color-text-tertiary)] tabular-nums">+ {describeRelations(summarizeRelations(relations))}+ </div>+ )}</div>);}diff --git a/packages/ui/src/zoom/draw-tree.ts b/packages/ui/src/zoom/draw-tree.tsindex 6cf98a8b4..de5b7022a 100644--- a/packages/ui/src/zoom/draw-tree.ts+++ b/packages/ui/src/zoom/draw-tree.ts@@ -41,6 +41,18 @@ export interface DrawOptions {lowDetail: boolean;/** Shared ruled-paper card texture; null until the asset loads (or on SSR). */paper?: PaperTexture | null;+ /**+ * Draw only relations carrying this verb (`ZoomRelation.label`), or every+ * relation when null.+ *+ * Deliberately one verb and not a set. Measured on a live index, 80.5% of+ * relations are `imports` and 89% of boxes carry a single verb across all+ * their relations, so a general multi-verb filter would be a no-op on nine+ * boxes in ten. The one subset that earns a control is `co-changes` (5.3%):+ * files that change together without importing each other, which no other+ * view surfaces.+ */+ relationVerb?: string | null;}/**@@ -193,7 +205,17 @@ export function drawScene(const r = worldRectToScreen(cam, vp, wr);if (isOnScreen(r, vp) && r.w >= EDGE_MIN_BOX_PX) childRects.set(kid.id, r);}- drawEdges(ctx, scene, node, childRects, palette, child, opts.lowDetail, focusId);+ drawEdges(+ ctx,+ scene,+ node,+ childRects,+ palette,+ child,+ opts.lowDetail,+ focusId,+ opts.relationVerb ?? null,+ );for (const kid of visible) drawNode(kid, child, depth + 1);@@ -221,6 +243,7 @@ function drawEdges(alpha: number,lowDetail: boolean,focusId: string | null,+ relationVerb: string | null,): void {// Relations are revealed only for the box the user is pointing at / has// selected, so the canvas is not a thicket of arrows. No focus -> no edges.@@ -232,6 +255,7 @@ function drawEdges((r) =>r.source_id !== r.target_id &&(r.source_id === focusId || r.target_id === focusId) &&+ (relationVerb === null || r.label === relationVerb) &&childRects.has(r.source_id) &&childRects.has(r.target_id),);diff --git a/packages/ui/src/zoom/index.ts b/packages/ui/src/zoom/index.tsindex 9678b101b..080b04083 100644--- a/packages/ui/src/zoom/index.ts+++ b/packages/ui/src/zoom/index.ts@@ -20,6 +20,17 @@ export { focusChain, focusId } from "./focus-path";export { buildScene, childNodes } from "./scene";export type { ZoomScene } from "./scene";+export {+ CO_CHANGES,+ describeCap,+ describeRelations,+ indexRelationsByNode,+ summarizeRelations,+} from "./relation-summary";+export type { RelationSummary, VerbCount } from "./relation-summary";++export { hasRole, healthBandLabel, nodeRoles } from "./node-signals";+export { drawScene, pickNode } from "./draw-tree";export type { DrawOptions, DrawStats, PickEntry } from "./draw-tree";diff --git a/packages/ui/src/zoom/node-signals.ts b/packages/ui/src/zoom/node-signals.tsnew file mode 100644index 000000000..8c3abbdd3--- /dev/null+++ b/packages/ui/src/zoom/node-signals.ts@@ -0,0 +1,51 @@+/**+ * What a card's two dots mean, in words. Pure, browser-free.+ *+ * A card carries two dots and nothing on the surface named either. Worse, they+ * shared a palette: the role dot painted `--color-success` for "has an entry+ * point" while the health dot painted the same token for "healthy", so a reader+ * who worked out one dot would misread the other. Colour bands belong to health+ * (one accent, two semantics), so the role dot is now a single accent dot+ * meaning "there is something here" and this module supplies the words that say+ * what.+ *+ * Naming all applicable roles also fixes a silent drop: the old dot ran a+ * priority cascade (entry > hotspot > dead > on-flow) and drew only the winner,+ * so a box that was both an entry point and a hotspot reported only "entry".+ */++import { bandForScore, HEALTH_BAND_LABEL } from "@repowise-dev/types/health";+import type { ZoomNode } from "./types";++/**+ * Every role that applies to a node, most notable first. Empty when the node+ * carries none, which is when the card draws no role dot at all.+ *+ * A container inherits a role from its subtree (`metrics.*_count`), matching+ * what the card's dot tests, so the words and the dot can never disagree.+ */+export function nodeRoles(node: ZoomNode): string[] {+ const roles: string[] = [];+ if (node.is_entry_point || node.metrics.entry_point_count > 0) roles.push("Entry point");+ if (node.is_hotspot || node.metrics.hotspot_count > 0) roles.push("Hotspot");+ if (node.is_dead || node.metrics.dead_count > 0) roles.push("Dead code");+ if (node.on_flow || node.metrics.on_flow_count > 0) roles.push("On an execution flow");+ return roles;+}++/** True when the card should draw its role dot. */+export function hasRole(node: ZoomNode): boolean {+ return nodeRoles(node).length > 0;+}++/**+ * The health dot's band as a word, from the canonical 3-band scale in+ * `@repowise-dev/types/health` — the same `bandForScore` the dot itself paints+ * on. Not the 5-step Excellent/Good/Fair ladder the scan surfaces use: a 6.9+ * reads "Good" there and paints amber here, and a label that contradicts the+ * dot it sits beside is worse than no label.+ */+export function healthBandLabel(score: number | null): string | null {+ if (score === null) return null;+ return HEALTH_BAND_LABEL[bandForScore(score)];+}diff --git a/packages/ui/src/zoom/nodes.ts b/packages/ui/src/zoom/nodes.tsindex 634619d53..4cd9490fc 100644--- a/packages/ui/src/zoom/nodes.ts+++ b/packages/ui/src/zoom/nodes.ts@@ -17,6 +17,7 @@import { ALERT_MAX, HEALTHY_MIN } from "@repowise-dev/types/health";import type { Rect } from "./camera";+import { hasRole } from "./node-signals";import { ARROW_SIZE_PX, EDGE_LINE_PX } from "./constants";import type { EdgeRoute } from "./edges";import type { ZoomPalette } from "./theme";@@ -173,13 +174,22 @@ function drawPaperTexture(ctx.restore();}-/** The single most salient role color for a node's status dot, or null. */+/**+ * The role dot's colour, or null when a node carries no role.+ *+ * One hue, deliberately. This used to return a different colour per role from+ * `palette.entry` / `.hotspot` / `.dead` / `.flow`, which collided head-on with+ * the health dot in the footer: `palette.entry` and `palette.healthHealthy` are+ * both `--color-success`, so a green dot meant "has an entry point" in the+ * top-right corner and "healthy" in the bottom-left one, forty pixels apart on+ * the same card. Green/amber/red carry a band and belong to health.+ *+ * The role dot now says only "there is something here"; `nodeRoles` in+ * `node-signals.ts` says what, in words, on hover and in the detail panel —+ * where it can name every applicable role rather than a cascade's winner.+ */function roleColor(node: ZoomNode, palette: ZoomPalette): string | null {- if (node.is_entry_point || node.metrics.entry_point_count > 0) return palette.entry;- if (node.is_hotspot || node.metrics.hotspot_count > 0) return palette.hotspot;- if (node.is_dead || node.metrics.dead_count > 0) return palette.dead;- if (node.on_flow || node.metrics.on_flow_count > 0) return palette.flow;- return null;+ return hasRole(node) ? palette.accent : null;}function roundRectPath(ctx: CanvasRenderingContext2D, r: Rect, radius: number): void {diff --git a/packages/ui/src/zoom/relation-summary.ts b/packages/ui/src/zoom/relation-summary.tsnew file mode 100644index 000000000..3f4cdf866--- /dev/null+++ b/packages/ui/src/zoom/relation-summary.ts@@ -0,0 +1,105 @@+/**+ * What one box's arrows actually say, in words. Pure, browser-free.+ *+ * The canvas draws a relation as a routed line whose only encoding is a+ * coupling-derived weight; the verb (`ZoomRelation.label`) was carried on the+ * wire and never rendered anywhere, so nothing on the surface said whether an+ * arrow meant "imports" or "changes at the same time as". This module turns the+ * relations incident to a node into the sentence the detail panel prints and+ * the caption the canvas key uses.+ *+ * It also reports what the per-parent cap hides. `drawEdges` shows only the+ * strongest `EDGE_MAX_PER_PARENT`, and on a real index that bites hard: 99 of+ * 218 containers have more relations than the cap, the worst holding 133. A+ * bounded view that does not say it is bounded reads as a complete one.+ */++import { EDGE_MAX_PER_PARENT } from "./constants";+import type { ZoomMap, ZoomRelation } from "./types";++/** The co-changes verb, as `c4_builder/labels.py` spells it. */+export const CO_CHANGES = "co-changes";++export interface VerbCount {+ verb: string;+ count: number;+}++export interface RelationSummary {+ /** Relations incident to the node, in either direction. */+ total: number;+ /** How many the canvas will actually draw, given the per-parent cap. */+ shown: number;+ /** Descending by count, so the dominant verb reads first. */+ verbs: VerbCount[];+ /** Incident relations whose verb is `co-changes`. */+ coChanges: number;+}++/**+ * Index relations by each endpoint once, so a panel that re-renders per+ * selection does not rescan the whole relation list (3,694 on this repo).+ */+export function indexRelationsByNode(map: ZoomMap): Map<string, ZoomRelation[]> {+ const byNode = new Map<string, ZoomRelation[]>();+ const add = (id: string, r: ZoomRelation): void => {+ const bucket = byNode.get(id);+ if (bucket) bucket.push(r);+ else byNode.set(id, [r]);+ };+ for (const r of map.relations) {+ if (r.source_id === r.target_id) continue;+ add(r.source_id, r);+ add(r.target_id, r);+ }+ return byNode;+}++/** Summarise the relations incident to one node. */+export function summarizeRelations(relations: readonly ZoomRelation[]): RelationSummary {+ const counts = new Map<string, number>();+ let coChanges = 0;+ for (const r of relations) {+ counts.set(r.label, (counts.get(r.label) ?? 0) + 1);+ if (r.label === CO_CHANGES) coChanges += 1;+ }+ const verbs = [...counts.entries()]+ .map(([verb, count]) => ({ verb, count }))+ .sort((a, b) => b.count - a.count || a.verb.localeCompare(b.verb));++ return {+ total: relations.length,+ shown: Math.min(relations.length, EDGE_MAX_PER_PARENT),+ verbs,+ coChanges,+ };+}++/**+ * The summary as one readable line.+ *+ * On a live index 89% of boxes have a single verb across all their relations,+ * so the common case is "9 relations, all imports" and the enumerated form is+ * the exception rather than the default.+ */+export function describeRelations(summary: RelationSummary): string {+ const { total, verbs } = summary;+ if (total === 0) return "No relations at this level";+ const noun = total === 1 ? "relation" : "relations";+ if (verbs.length === 1) {+ const only = verbs[0]!.verb;+ return total === 1 ? `1 ${only} relation` : `${total} ${noun}, all ${only}`;+ }+ const parts = verbs.map((v) => `${v.count} ${v.verb}`);+ return `${total} ${noun}: ${parts.join(", ")}`;+}++/**+ * What the cap is hiding, or null when nothing is. Kept separate from+ * `describeRelations` so a caller can style the caveat differently from the+ * fact, and so the honest-cap copy exists in exactly one place.+ */+export function describeCap(summary: RelationSummary): string | null {+ if (summary.total <= summary.shown) return null;+ return `Showing the ${summary.shown} strongest`;+}diff --git a/packages/ui/src/zoom/renderer.ts b/packages/ui/src/zoom/renderer.tsindex 474dede24..ed3c98073 100644--- a/packages/ui/src/zoom/renderer.ts+++ b/packages/ui/src/zoom/renderer.ts@@ -75,6 +75,7 @@ export class ZoomRenderer {private selectedId: string | null = null;private hoveredId: string | null = null;+ private relationVerb: string | null = null;private lowDetailFrames = 0;private tween: Tween | null = null;private lastFocusId: string | null = null;@@ -128,6 +129,13 @@ export class ZoomRenderer {this.invalidate();}+ /** Restrict drawn relations to one verb, or null for all of them. */+ setRelationVerb(verb: string | null): void {+ if (verb === this.relationVerb) return;+ this.relationVerb = verb;+ this.invalidate();+ }+setScene(scene: ZoomScene): void {this.scene = scene;// Only frame once we have a real layout size; otherwise the first resize@@ -252,6 +260,7 @@ export class ZoomRenderer {hoveredId: this.hoveredId,lowDetail,paper: this.paper,+ relationVerb: this.relationVerb,});if (this.onStats) {this.onStats({diff --git a/packages/web/src/app/repos/[id]/knowledge-graph/page.tsx b/packages/web/src/app/repos/[id]/knowledge-graph/page.tsxindex 11a6bfdd6..6af6e23e1 100644--- a/packages/web/src/app/repos/[id]/knowledge-graph/page.tsx+++ b/packages/web/src/app/repos/[id]/knowledge-graph/page.tsx@@ -9,6 +9,15 @@* navigation chrome (breadcrumb, search-to-zoom, detail panel, first-visit hint)* and keeps the focused node in the URL so a zoom state is shareable.*+ * The chrome sits *around* the canvas, not on it. It used to be four floating+ * panels — breadcrumb, search, detail panel, hint — over the one thing on the+ * page that cannot be read past, and two of them shared the top-right corner,+ * so selecting a node dropped the detail panel on top of the search box.+ * Breadcrumb and search are now a header row, the detail panel is a rail, and+ * the canvas keeps the hover card (which tracks the pointer) plus the one-time+ * gesture hint, which teaches the canvas itself and never returns once+ * dismissed. Anything permanent goes around the map, not on it.+ ** This replaced the earlier node-link / layered-C4 Knowledge Graph. The reusable* C4 machinery it used to render still lives on (backend `c4_builder`, the zoom* map's own `/zoom-map` endpoint, and `@repowise-dev/ui/c4` for the VS Code@@ -20,14 +29,20 @@ import { parseAsString, useQueryState } from "nuqs";import { ScanSearch } from "lucide-react";import { PageShell } from "@repowise-dev/ui/shared/page-shell";import { ZoomCanvas } from "@repowise-dev/ui/zoom";-import type { ZoomCanvasHandle, ZoomNode } from "@repowise-dev/ui/zoom";+import { CO_CHANGES, indexRelationsByNode } from "@repowise-dev/ui/zoom";+import type { ZoomCanvasHandle, ZoomNode, ZoomRelation } from "@repowise-dev/ui/zoom";import { useZoomMap } from "@/lib/hooks/use-graph";import { ZoomBreadcrumb } from "@/components/zoom/zoom-breadcrumb";import { ZoomSearch } from "@/components/zoom/zoom-search";import { ZoomDetailPanel } from "@/components/zoom/zoom-detail-panel";+import { ZoomMapKey } from "@/components/zoom/zoom-map-key";import { ZoomHint } from "@/components/zoom/zoom-hint";import { ZoomExportButton } from "@/components/zoom/zoom-export-button";+/** Stable identities, so an unselected / unloaded render does not churn props. */+const EMPTY_RELATIONS: ZoomRelation[] = [];+const NO_RELATIONS: Map<string, ZoomRelation[]> = new Map();+export default function KnowledgeGraphPage({ params }: { params: Promise<{ id: string }> }) {const { id: repoId } = use(params);@@ -40,6 +55,7 @@ export default function KnowledgeGraphPage({ params }: { params: Promise<{ id: s);const [chain, setChain] = useState<ZoomNode[]>([]);const [selected, setSelected] = useState<ZoomNode | null>(null);+ const [relationVerb, setRelationVerb] = useState<string | null>(null);// Snapshot the initial URL focus once so later URL writes don't re-trigger a jump.const initialFocus = useRef(focusParam ?? undefined).current;@@ -60,6 +76,16 @@ export default function KnowledgeGraphPage({ params }: { params: Promise<{ id: sconst allNodes = useMemo(() => zoomMap?.nodes ?? [], [zoomMap]);const nodeById = useMemo(() => new Map(allNodes.map((n) => [n.id, n])), [allNodes]);+ // Indexed once per map rather than per selection: this repo ships 3,694+ // relations and both the rail and the hover card read them.+ const relationsByNode = useMemo(+ () => (zoomMap ? indexRelationsByNode(zoomMap) : NO_RELATIONS),+ [zoomMap],+ );+ const coChangeCount = useMemo(+ () => (zoomMap?.relations ?? []).filter((r) => r.label === CO_CHANGES).length,+ [zoomMap],+ );const showStats = process.env.NODE_ENV === "development";return (@@ -73,57 +99,76 @@ export default function KnowledgeGraphPage({ params }: { params: Promise<{ id: sactions={<ZoomExportButton repoId={repoId} disabled={isLoading || !!error} />}maxWidth="wide">- {/* Full-bleed canvas (no framing border): the map blends into the page.- Breadcrumb + search float over the canvas as an overlay rather than a- chrome bar, and a first-visit hint teaches the zoom gestures, so the map- gets the whole area. */}- <div className="relative h-[calc(100vh-12rem)] min-h-[520px] overflow-hidden rounded-lg">- {isLoading && (- <div className="flex h-full items-center justify-center text-sm text-[var(--color-text-secondary)]">- Building the knowledge graph…- </div>- )}- {error && !isLoading && (- <div className="flex h-full items-center justify-center text-sm text-[var(--color-error)]">- Could not load the knowledge graph for this repository.- </div>- )}- {zoomMap && !isLoading && (- <>- <ZoomCanvas- ref={canvasRef}- data={zoomMap}- initialFocusId={initialFocus}- onSelect={setSelected}- onFocusChange={onFocusChange}- showStats={showStats}+ {isLoading && (+ <div className="flex h-[520px] items-center justify-center text-sm text-[var(--color-text-secondary)]">+ Building the knowledge graph…+ </div>+ )}+ {error && !isLoading && (+ <div className="flex h-[520px] items-center justify-center text-sm text-[var(--color-error)]">+ Could not load the knowledge graph for this repository.+ </div>+ )}+ {zoomMap && !isLoading && (+ <>+ {/* The one chrome row: where you are, and how to get somewhere. */}+ <div className="mb-3 flex items-start justify-between gap-3 border-b border-[var(--color-border-default)] pb-3">+ <ZoomBreadcrumb chain={chain} onCrumb={flyTo} />+ <ZoomSearch+ nodes={allNodes}+ onPick={(id) => {+ flyTo(id);+ setSelected(nodeById.get(id) ?? null);+ }}/>- <div className="pointer-events-none absolute inset-x-0 top-0 z-10 flex items-start justify-between gap-3 p-3">- <div className="pointer-events-auto rounded-lg border border-[var(--color-border-subtle)] bg-[var(--color-bg-glass)] px-2 py-1 shadow-sm backdrop-blur">- <ZoomBreadcrumb chain={chain} onCrumb={flyTo} />- </div>- <div className="pointer-events-auto">- <ZoomSearch- nodes={allNodes}- onPick={(id) => {- flyTo(id);- setSelected(nodeById.get(id) ?? null);- }}- />- </div>+ </div>++ {/* Canvas and rail are peers in a grid, so the panel can never land+ on the map. Below xl the rail relocates under the canvas rather+ than covering it or disappearing. */}+ {/* Sized so the canvas and the key row below it both fit one screen.+ The key row explains the arrows, and the canvas swallows the wheel+ to zoom, so a reader whose pointer is over the map cannot scroll+ down to find it. */}+ <div+ className={`grid h-[calc(100vh-21.5rem)] min-h-[400px] gap-4 ${+ selected ? "xl:grid-cols-[minmax(0,1fr)_320px]" : "grid-cols-1"+ }`}+ >+ <div className="relative min-h-0 overflow-hidden rounded-lg">+ <ZoomCanvas+ ref={canvasRef}+ data={zoomMap}+ initialFocusId={initialFocus}+ onSelect={setSelected}+ onFocusChange={onFocusChange}+ showStats={showStats}+ relationVerb={relationVerb}+ relationsByNode={relationsByNode}+ />+ <ZoomHint /></div>{selected && (- <ZoomDetailPanel- node={selected}- repoId={repoId}- onClose={() => setSelected(null)}- onZoom={(id) => flyTo(id)}- />+ <div className="min-h-0 self-start xl:max-h-full">+ <ZoomDetailPanel+ node={selected}+ repoId={repoId}+ relations={relationsByNode.get(selected.id) ?? EMPTY_RELATIONS}+ relationVerb={relationVerb}+ onClose={() => setSelected(null)}+ onZoom={(id) => flyTo(id)}+ />+ </div>)}- <ZoomHint />- </>- )}- </div>+ </div>++ <ZoomMapKey+ verb={relationVerb}+ onVerbChange={setRelationVerb}+ coChangeCount={coChangeCount}+ />+ </>+ )}</PageShell>);}diff --git a/packages/web/src/components/zoom/zoom-detail-panel.tsx b/packages/web/src/components/zoom/zoom-detail-panel.tsxindex 5c19dc59c..a5488f4c2 100644--- a/packages/web/src/components/zoom/zoom-detail-panel.tsx+++ b/packages/web/src/components/zoom/zoom-detail-panel.tsx@@ -1,20 +1,42 @@"use client";/**- * Detail panel for the selected zoom node. A self-contained inspector (metadata,- * rolled-up metrics, summary) plus a "zoom here" action that flies the camera- * into the node. Kept lightweight and decoupled from the architecture-view- * selection store so the zoom canvas owns its own selection lifecycle.+ * Detail panel for the selected zoom node: what this box is, how healthy it is,+ * what it holds, and what its arrows mean.+ *+ * It is a *rail beside the canvas*, not a floating card on it. Chrome goes+ * around a canvas, never on it: a diagram is the one thing on its page that+ * cannot be read past, so anything on top of it competes with the subject. The+ * old panel was pinned `absolute right-3 top-3` and landed on top of the search+ * box, which shares that corner.+ *+ * Inside, figures are hairline rows rather than a grid of bordered mini-cards.+ * A card means "a discrete object you can act on" and a file count is not that;+ * at 288px wide, eight bordered boxes read as box soup with no lead. Every+ * number is `tabular-nums` because a column of figures that reflows as digits+ * change fails to line up.*/import Link from "next/link";import { FileCode, ScanSearch, X } from "lucide-react";-import type { ZoomNode } from "@repowise-dev/ui/zoom";-import { scoreTextColor } from "@repowise-dev/ui/health";+import type { ZoomNode, ZoomRelation } from "@repowise-dev/ui/zoom";+import {+ describeCap,+ describeRelations,+ healthBandLabel,+ nodeRoles,+ summarizeRelations,+} from "@repowise-dev/ui/zoom";+import { bandForScore } from "@repowise-dev/types/health";+import { healthBandTextColor } from "@repowise-dev/ui/health";interface ZoomDetailPanelProps {node: ZoomNode;repoId: string;+ /** Relations incident to this node, in either direction. */+ relations: ZoomRelation[];+ /** The verb the map is currently filtered to, or null for all of them. */+ relationVerb: string | null;onClose: () => void;onZoom: (id: string) => void;}@@ -34,43 +56,102 @@ const KIND_LABEL: Record<ZoomNode["kind"], string> = {file: "File",};-function Stat({ label, value, tone }: { label: string; value: number; tone?: string }) {+/** A micro-label: mono, because it labels something a machine produced. */+function Micro({ children }: { children: React.ReactNode }) {return (- <div className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-canvas)] px-2.5 py-1.5">- <div className={`text-sm font-semibold ${tone ?? "text-[var(--color-text-primary)]"}`}>- {value}- </div>- <div className="text-[10px] uppercase tracking-wide text-[var(--color-text-muted)]">{label}</div>+ <span className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">+ {children}+ </span>+ );+}++/** One figure as a hairline row, not a card. */+function Row({ label, value, tone }: { label: string; value: number; tone?: string }) {+ return (+ <div className="flex items-baseline justify-between border-t border-[var(--color-border-default)] py-1.5">+ <Micro>{label}</Micro>+ <span+ className={`text-[15px] font-medium tabular-nums ${tone ?? "text-[var(--color-text-primary)]"}`}+ >+ {value.toLocaleString()}+ </span></div>);}-export function ZoomDetailPanel({ node, repoId, onClose, onZoom }: ZoomDetailPanelProps) {+/**+ * A role as the accent dot plus the word. The dot matches the one on the card,+ * so the panel reads as the card's caption; the word is what the card cannot+ * say. A filled pill would spend a ground, a border and coloured text on one+ * token that repeats down a panel.+ */+function Mark({ children }: { children: React.ReactNode }) {+ return (+ <span className="flex items-center gap-1 text-[11px] font-medium text-[var(--color-text-secondary)]">+ <span+ aria-hidden+ className="h-1.5 w-1.5 rounded-full bg-[var(--color-accent-primary)]"+ />+ {children}+ </span>+ );+}++export function ZoomDetailPanel({+ node,+ repoId,+ relations,+ relationVerb,+ onClose,+ onZoom,+}: ZoomDetailPanelProps) {const m = node.metrics;const isFile = node.kind === "file";+ // The canonical 3-band scale, so the panel agrees with the dot on the card+ // beside it. The 5-step Excellent/Good ladder the scan surfaces use would+ // call a 6.9 "Good" while the card paints it amber.+ const band = healthBandLabel(node.health_score);+ const bandClass =+ node.health_score === null ? "" : healthBandTextColor(bandForScore(node.health_score));+ const roles = nodeRoles(node);+ // The description covers the whole box; the cap has to be measured against+ // what the map is *drawing*, or a filtered view still claims to be showing+ // "the 10 strongest" while two arrows are on screen.+ const summary = summarizeRelations(relations);+ const drawn = summarizeRelations(+ relationVerb === null ? relations : relations.filter((r) => r.label === relationVerb),+ );+ const cap = describeCap(drawn);+return (- <aside className="absolute right-3 top-3 z-20 flex max-h-[calc(100%-1.5rem)] w-72 flex-col overflow-hidden rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] shadow-xl">- <header className="flex items-start justify-between gap-2 border-b border-[var(--color-border-default)] px-3 py-2.5">+ /* Height follows content, capped at the canvas: a panel stretched to a+ full-height rail leaves a dead gutter under a short node's figures, and+ pins its actions a long way from the thing they act on. */+ <aside className="flex max-h-full min-h-0 flex-col overflow-hidden rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)]">+ <header className="flex items-start justify-between gap-2 px-4 pb-3 pt-3.5"><div className="min-w-0">- <div className="flex items-center gap-1.5">- <span className="rounded bg-[var(--color-bg-canvas)] px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-[var(--color-text-tertiary)]">- {KIND_LABEL[node.kind]}- </span>- {node.is_entry_point && (- <span className="text-[10px] font-medium text-[var(--color-success)]">entry</span>- )}- {node.on_flow && !node.is_entry_point && (- <span className="text-[10px] font-medium text-[var(--color-accent-secondary)]">on flow</span>- )}- </div>- <h2 className="mt-1 truncate text-sm font-semibold text-[var(--color-text-primary)]" title={node.name}>+ <Micro>{KIND_LABEL[node.kind]}</Micro>+ {/* A real size step, so hierarchy comes from the type scale rather+ than from another border. */}+ <h2 className="mt-1 text-[18px] font-semibold leading-tight text-[var(--color-text-primary)]">{node.name}</h2>{node.path && node.path !== node.name && (- <p className="truncate text-xs text-[var(--color-text-tertiary)]" title={node.path}>+ /* Scrolls, never truncates: an ellipsis in the primary column+ reports a layout decision to the reader as missing content. */+ <p className="mt-1 overflow-x-auto whitespace-nowrap font-mono text-[11px] text-[var(--color-text-tertiary)]">{node.path}</p>)}+ {/* Every role the card's accent dot stands for, not just the one a+ priority cascade would have picked. */}+ {roles.length > 0 && (+ <div className="mt-2 flex flex-wrap items-center gap-x-3 gap-y-1">+ {roles.map((role) => (+ <Mark key={role}>{role}</Mark>+ ))}+ </div>+ )}</div><buttontype="button"@@ -82,45 +163,76 @@ export function ZoomDetailPanel({ node, repoId, onClose, onZoom }: ZoomDetailPan</button></header>- <div className="flex-1 overflow-auto px-3 py-3">- {node.summary && (- <p className="mb-3 text-xs leading-relaxed text-[var(--color-text-secondary)]">{node.summary}</p>- )}- <div className="grid grid-cols-2 gap-2">- {node.health_score !== null && (- <div className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-canvas)] px-2.5 py-1.5">- <div className={`text-sm font-semibold ${scoreTextColor(node.health_score)}`}>+ <div className="min-h-0 shrink overflow-auto px-4 pb-4">+ {band && node.health_score !== null && (+ <div className="border-t border-[var(--color-border-default)] pt-3">+ <div className={`flex items-baseline gap-2 ${bandClass}`}>+ <span className="text-[32px] font-bold leading-none tabular-nums">{node.health_score.toFixed(1)}- </div>- <div className="text-[10px] uppercase tracking-wide text-[var(--color-text-muted)]">- {isFile ? "health" : "health (avg)"}- </div>+ </span>+ <span className="text-[15px] font-medium">{band}</span></div>- )}- {!isFile && <Stat label="files" value={m.file_count} />}+ {/* A figure alone is not readable. Say what it measures. */}+ <p className="mt-1.5 text-[13px] leading-relaxed text-[var(--color-text-secondary)]">+ Code health out of 10+ {isFile ? "" : ", averaged across this subtree weighted by size"}.+ </p>+ </div>+ )}++ {node.summary && (+ <p className="mt-3 border-t border-[var(--color-border-default)] pt-3 text-[13px] leading-relaxed text-[var(--color-text-secondary)]">+ {node.summary}+ </p>+ )}++ <div className="mt-3">+ {!isFile && <Row label="Files" value={m.file_count} />}{m.hotspot_count > 0 && (- <Stat label="hotspots" value={m.hotspot_count} tone="text-[var(--color-risk-high)]" />+ <Row label="Hotspots" value={m.hotspot_count} tone="text-[var(--color-risk-high)]" />)}{m.entry_point_count > 0 && (- <Stat label="entry points" value={m.entry_point_count} tone="text-[var(--color-success)]" />+ <Row+ label="Entry points"+ value={m.entry_point_count}+ tone="text-[var(--color-success)]"+ />)}- {m.on_flow_count > 0 && <Stat label="on flow" value={m.on_flow_count} />}- {m.dead_count > 0 && <Stat label="dead" value={m.dead_count} />}+ {m.on_flow_count > 0 && <Row label="On flow" value={m.on_flow_count} />}+ {m.dead_count > 0 && <Row label="Dead" value={m.dead_count} />}</div>++ {/* What the arrows mean. The verb was on the wire and drawn nowhere,+ so nothing on this surface said whether a line meant "imports" or+ "changes at the same time as". */}+ <div className="mt-3 border-t border-[var(--color-border-default)] pt-3">+ <Micro>Relations</Micro>+ <p className="mt-1.5 text-[13px] leading-relaxed text-[var(--color-text-secondary)] tabular-nums">+ {describeRelations(summary)}+ </p>+ {cap && (+ /* A surface that bounds its own coverage has to say so, or the+ partial view reads as the whole one. */+ <p className="mt-1 text-[12px] text-[var(--color-text-tertiary)] tabular-nums">+ {cap} on the map.+ </p>+ )}+ </div>+{node.language && (- <div className="mt-3 text-xs text-[var(--color-text-tertiary)]">- Language: <span className="text-[var(--color-text-secondary)]">{node.language}</span>+ <div className="mt-3 border-t border-[var(--color-border-default)] pt-3 text-[13px] text-[var(--color-text-secondary)]">+ <Micro>Language</Micro> <span className="ml-1">{node.language}</span></div>)}</div>{(node.children.length > 0 || isFile) && (- <footer className="flex flex-col gap-2 border-t border-[var(--color-border-default)] p-2">+ <footer className="flex flex-col gap-2 border-t border-[var(--color-border-default)] p-3">{node.children.length > 0 && (<buttontype="button"onClick={() => onZoom(node.id)}- className="flex w-full items-center justify-center gap-1.5 rounded-md bg-[var(--color-accent-primary)] px-3 py-1.5 text-xs font-medium text-[var(--color-text-on-accent)] hover:opacity-90"+ className="flex w-full items-center justify-center gap-1.5 rounded-md bg-[var(--color-accent-primary)] px-3 py-2 text-[13px] font-medium text-[var(--color-text-on-accent)] hover:opacity-90"><ScanSearch className="h-3.5 w-3.5" />Zoom in@@ -129,7 +241,7 @@ export function ZoomDetailPanel({ node, repoId, onClose, onZoom }: ZoomDetailPan{isFile && node.path && (<Linkhref={fileHref(repoId, node.path)}- className="flex w-full items-center justify-center gap-1.5 rounded-md border border-[var(--color-border-default)] px-3 py-1.5 text-xs font-medium text-[var(--color-text-primary)] hover:bg-[var(--color-bg-wash-hover)]"+ className="flex w-full items-center justify-center gap-1.5 rounded-md border border-[var(--color-border-default)] px-3 py-2 text-[13px] font-medium text-[var(--color-text-primary)] hover:bg-[var(--color-bg-wash-hover)]"><FileCode className="h-3.5 w-3.5" />Open file pagediff --git a/packages/web/src/components/zoom/zoom-map-key.tsx b/packages/web/src/components/zoom/zoom-map-key.tsxnew file mode 100644index 000000000..31a2e516d--- /dev/null+++ b/packages/web/src/components/zoom/zoom-map-key.tsx@@ -0,0 +1,104 @@+"use client";++/**+ * The row that says what the map's marks mean, plus the one control over them.+ *+ * Chrome goes *around* a canvas, never on it, so this is a hairline row under+ * the map rather than another floating panel. It carries the two things a card+ * shows without naming: the accent dot in its top-right corner and the health+ * dot in its footer. Before this, a reader had no way to learn either one, and+ * the two dots shared a palette, so working out one taught you the wrong thing+ * about the other.+ *+ * Why one toggle and not a verb filter. Measured on a live index, the arrows+ * carry three verbs, not the seven the label vocabulary allows: `imports`+ * 80.5%, `uses` 14.3%, `co-changes` 5.3%. `calls`, `inherits from`,+ * `implements` and `references` cannot occur at all, because the zoom map is+ * fed file-level edges and those four are symbol-level. On top of that, 89% of+ * boxes carry a single verb across every one of their relations, so a general+ * filter would do nothing on nine boxes in ten and its main visible effect+ * would be arrows vanishing.+ *+ * Co-changes is the exception worth a control: files that change together+ * without importing each other, which is coupling no other view on the site+ * surfaces, and which is invisible here by default because it is drowned by+ * the imports it shares a canvas with.+ */++import { CO_CHANGES } from "@repowise-dev/ui/zoom";+import { HEALTH_BAND_LABEL } from "@repowise-dev/types/health";++interface ZoomMapKeyProps {+ /** Null = every relation draws; CO_CHANGES = only co-change relations. */+ verb: string | null;+ onVerbChange: (verb: string | null) => void;+ /** Co-change relations in the whole map, so the toggle can carry its figure. */+ coChangeCount: number;+}++function Dot({ className }: { className: string }) {+ return <span aria-hidden className={`inline-block h-2 w-2 shrink-0 rounded-full ${className}`} />;+}++export function ZoomMapKey({ verb, onVerbChange, coChangeCount }: ZoomMapKeyProps) {+ const only = verb === CO_CHANGES;++ return (+ <div className="mt-3 border-t border-[var(--color-border-default)] pt-3">+ <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">+ <p className="min-w-0 text-[13px] leading-relaxed text-[var(--color-text-secondary)]">+ {only ? (+ <>+ Showing <span className="text-[var(--color-text-primary)]">co-changes only</span>:+ files that change in the same commits without importing each other.+ </>+ ) : (+ <>+ Hover a card to see what it depends on. Arrow weight is how many file pairs the+ dependency covers.+ </>+ )}+ </p>+ {/* A count on the control tells you whether it is worth a click before+ you spend one. Only shown because it is already in the loaded map. */}+ <button+ type="button"+ onClick={() => onVerbChange(only ? null : CO_CHANGES)}+ aria-pressed={only}+ disabled={coChangeCount === 0}+ className={`shrink-0 self-start rounded-md border px-2.5 py-1 text-[12px] font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50 sm:self-auto ${+ only+ ? "border-[var(--color-accent-primary)] text-[var(--color-accent-primary)]"+ : "border-[var(--color-border-default)] text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-wash-hover)] hover:text-[var(--color-text-primary)]"+ }`}+ >+ Co-changes only{" "}+ <span className="font-mono tabular-nums text-[var(--color-text-tertiary)]">+ {coChangeCount.toLocaleString()}+ </span>+ </button>+ </div>++ {/* The dots. Health keeps the traffic light because the colours carry a+ band; the role dot is one accent hue meaning "there is something+ here", and the hover card names which. */}+ <dl className="mt-2 flex flex-wrap items-center gap-x-5 gap-y-1 text-[12px] text-[var(--color-text-tertiary)]">+ <div className="flex items-center gap-1.5">+ <Dot className="bg-[var(--color-accent-primary)]" />+ <dt className="sr-only">Top-right dot</dt>+ <dd>Entry point, hotspot, dead code or on an execution flow. Hover for which.</dd>+ </div>+ <div className="flex items-center gap-1.5">+ <Dot className="bg-[var(--color-success)]" />+ <Dot className="bg-[var(--color-warning)]" />+ <Dot className="bg-[var(--color-error)]" />+ <dt className="sr-only">Footer dot</dt>+ <dd>+ Code health: {HEALTH_BAND_LABEL.healthy} 8+, {HEALTH_BAND_LABEL.warning} 4 to 8,{" "}+ {HEALTH_BAND_LABEL.alert} under 4.+ </dd>+ </div>+ </dl>+ </div>+ );+}diff --git a/tests/unit/server/services/test_c4_labels.py b/tests/unit/server/services/test_c4_labels.pyindex ec0a5278d..a7d6151be 100644--- a/tests/unit/server/services/test_c4_labels.py+++ b/tests/unit/server/services/test_c4_labels.py@@ -18,6 +18,16 @@ from repowise.server.services.c4_builder.labels import coupling_strength, relati(("dynamic_imports", "imports"), "imports"),(("dynamic_imports",), "imports"),(("calls", "imports"), "calls"),+ # Tokens the extractors really emit must all be named. These three were+ # missing, so a lazy import, a conftest link and a subclass all reported+ # as "depends on" — the label reserved for a wholly-unknown set.+ (("dynamic_uses",), "uses"),+ (("framework",), "uses"),+ (("extends",), "inherits from"),+ # A static import describes the same dependency more precisely.+ (("framework", "imports"), "imports"),+ # ...but a subclass relationship outranks it, as `calls` does.+ (("extends", "imports"), "inherits from"),# Empty / unknown never yields a bare token or empty string.((), "depends on"),(("totally_unknown",), "depends on"),