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(architecture): make the Map a place you can drill into (#2104)
Raghav Chamadiyacdbb68e70ac4
diff --git a/packages/api-client/src/types/intelligence.ts b/packages/api-client/src/types/intelligence.tsindex 8fbcfb2cb..d7771a83a 100644--- a/packages/api-client/src/types/intelligence.ts+++ b/packages/api-client/src/types/intelligence.ts@@ -47,6 +47,10 @@ export interface CommunityMember {path: string;pagerank: number;is_entry_point: boolean;+ /** Cross-link signals, so a count can name the files behind it. Optional: an+ * older server omits them, which reads as "no signal", not as "not flagged". */+ is_hotspot?: boolean;+ is_dead?: boolean;}export interface NeighboringCommunity {@@ -63,6 +67,24 @@ export interface CommunityDetailResponse {members: CommunityMember[];truncated: boolean;neighboring_communities: NeighboringCommunity[];+ /** State of the area rather than its shape. Every field below is optional:+ * additive on the wire, and absent from an older server.+ *+ * LOC-weighted mean health over the members that carry a score, 0-10, higher+ * is better. `null` when none do — which is not zero and must not render as+ * a score. */+ health_score?: number | null;+ /** How many members contributed to `health_score`. */+ scored_member_count?: number;+ /** Members flagged hot / dead / decision-anchored, over every member — not+ * only the page returned in `members`. */+ hot_count?: number;+ dead_count?: number;+ decision_count?: number;+ /** Who is primary owner on the most members, and how many. "Most files+ * owned", not "most commits" — see the router comment. */+ primary_owner?: string | null;+ primary_owner_file_count?: number;}export interface CommunitySummaryItem {diff --git a/packages/server/src/repowise/server/routers/graph/community.py b/packages/server/src/repowise/server/routers/graph/community.pyindex 80923dfea..7833e685f 100644--- a/packages/server/src/repowise/server/routers/graph/community.py+++ b/packages/server/src/repowise/server/routers/graph/community.py@@ -28,6 +28,19 @@ from repowise.server.services.graph_views import (build_architecture_graph,build_community_slice,)+from repowise.server.services.node_signals import EMPTY_SIGNALS, collect_node_signals++# How many members the detail endpoint reads to compute the community's shape+# and state. It used to be 200, which silently disagreed with the community+# *list* — a 587-file community reported 587 there and 200 here, and every+# rollup below covered a third of it.+#+# Ceiling: a community larger than this still reports this number, and its+# counts still cover only the top slice by PageRank. The largest community in+# any repo indexed so far is under 600, so nothing reaches it. If one does, the+# upgrade is a `SELECT COUNT(*)` for the true `member_count` plus an explicit+# "counted over the top N" field, not a bigger constant.+_MEMBER_READ_CAP = 2000router = APIRouter()@@ -111,7 +124,7 @@ async def get_community_detail() -> CommunityDetailResponse:"""Return detailed info for a single community."""all_members = await crud.get_community_members(- session, repo_id, community_id, node_type="file", limit=200+ session, repo_id, community_id, node_type="file", limit=_MEMBER_READ_CAP)if not all_members:raise HTTPException(status_code=404, detail="Community not found or empty")@@ -120,20 +133,73 @@ async def get_community_detail(label = community_label(top)cohesion = community_cohesion(top)+ # State of the area, in two path-scoped reads over the same member list the+ # shape figures above are computed from. `collect_node_signals` is the same+ # join `build_architecture_graph` uses for the hub discs, so a community's+ # hot/dead counts here and its disc on the canvas can never disagree.+ member_paths = [m.node_id for m in all_members]+ signals = await collect_node_signals(session, repo_id, member_paths)+ hot_count = sum(1 for p in member_paths if signals.get(p, EMPTY_SIGNALS).is_hotspot)+ dead_count = sum(1 for p in member_paths if signals.get(p, EMPTY_SIGNALS).is_dead)+ decision_count = sum(+ 1 for p in member_paths if signals.get(p, EMPTY_SIGNALS).has_decision+ )++ # Most files owned, not most commits: ownership is denormalised onto+ # GitMetadata.primary_owner_name and there is no per-(file, author) table to+ # tally properly. The field name and the panel copy both say "owns".+ owner_files: dict[str, int] = {}+ for p in member_paths:+ owner = signals.get(p, EMPTY_SIGNALS).primary_owner+ if owner:+ owner_files[owner] = owner_files.get(owner, 0) + 1+ primary_owner: str | None = None+ primary_owner_file_count = 0+ if owner_files:+ primary_owner, primary_owner_file_count = max(+ owner_files.items(), key=lambda kv: (kv[1], kv[0])+ )++ # LOC-weighted mean over the members that carry a score, matching+ # `rollup_health`: effective score prefers the split defect_score and falls+ # back to the overall score, weight is max(nloc, 1), and a community where+ # nothing is scored gets None rather than a zero it never measured.+ health_metrics = await crud.get_health_metrics(+ session, repo_id, file_paths=member_paths+ )+ weighted_sum = 0.0+ weight = 0.0+ scored_member_count = 0+ for hm in health_metrics:+ score = hm.defect_score if hm.defect_score is not None else hm.score+ if score is None:+ continue+ w = float(max(hm.nloc or 1, 1))+ weighted_sum += score * w+ weight += w+ scored_member_count += 1+ health_score = round(weighted_sum / weight, 2) if weight > 0 else None+members_out: list[CommunityMember] = []if include_members:for m in all_members[:member_limit]:+ sig = signals.get(m.node_id, EMPTY_SIGNALS)members_out.append(CommunityMember(path=m.node_id,pagerank=round(m.pagerank or 0.0, 6),is_entry_point=m.is_entry_point,+ is_hotspot=sig.is_hotspot,+ is_dead=sig.is_dead,))- # Neighboring communities- cross_edges = await crud.get_cross_community_edges(session, repo_id, community_id)- # Resolve labels for neighbors+ # Neighboring communities. `get_cross_community_edges` orders by edge count+ # descending, so the top slice is taken *before* the label loop: it used to+ # resolve a label for every neighbour in the repo and then keep ten.+ cross_edges = (await crud.get_cross_community_edges(session, repo_id, community_id))[+ :10+ ]neighbor_cids = [ce["target_community_id"] for ce in cross_edges]neighbor_labels: dict[int, str] = {}for ncid in neighbor_cids:@@ -151,7 +217,7 @@ async def get_community_detail(label=neighbor_labels.get(ce["target_community_id"], ""),cross_edge_count=ce["edge_count"],)- for ce in cross_edges[:10]+ for ce in cross_edges]return CommunityDetailResponse(@@ -162,4 +228,11 @@ async def get_community_detail(members=members_out,truncated=len(all_members) > member_limit,neighboring_communities=neighbors,+ health_score=health_score,+ scored_member_count=scored_member_count,+ hot_count=hot_count,+ dead_count=dead_count,+ decision_count=decision_count,+ primary_owner=primary_owner,+ primary_owner_file_count=primary_owner_file_count,)diff --git a/packages/server/src/repowise/server/schemas/intelligence.py b/packages/server/src/repowise/server/schemas/intelligence.pyindex 7d36afef5..4623fa6a0 100644--- a/packages/server/src/repowise/server/schemas/intelligence.py+++ b/packages/server/src/repowise/server/schemas/intelligence.py@@ -138,6 +138,11 @@ class CommunityMember(BaseModel):path: strpagerank: floatis_entry_point: bool+ #: Cross-link signals, so the panel can name *which* members are in trouble+ #: rather than only counting them. Defaulted: an older server omits them and+ #: the client reads "no signal", which is what an older server means.+ is_hotspot: bool = False+ is_dead: bool = Falseclass NeighboringCommunity(BaseModel):@@ -154,6 +159,28 @@ class CommunityDetailResponse(BaseModel):members: list[CommunityMember]truncated: boolneighboring_communities: list[NeighboringCommunity]+ #: State of the area, not its shape. All additive and defaulted so a client+ #: pinned to an older server keeps its current payload shape.+ #:+ #: LOC-weighted mean of the members' effective health score (0-10, higher is+ #: better), over the members that have one. ``None`` when none do — which is+ #: not the same as zero and must not render as a score.+ health_score: float | None = None+ #: How many members contributed to ``health_score``. The panel needs this to+ #: say "over 12 of 30 files" rather than implying the whole community was+ #: measured.+ scored_member_count: int = 0+ #: Members flagged by the git hotspot, dead-code and decision joins. Counted+ #: over every member, not only the ``member_limit`` page returned above.+ hot_count: int = 0+ dead_count: int = 0+ decision_count: int = 0+ #: The person who is primary owner on the most members, and how many. Read+ #: off the denormalised ``GitMetadata.primary_owner_name``; there is no+ #: per-(file, author) table, so this is "most files owned", not "most+ #: commits".+ primary_owner: str | None = None+ primary_owner_file_count: int = 0class CommunitySummaryItem(BaseModel):diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.tsindex 2eb01d823..43d2f225a 100644--- a/packages/types/src/generated/http.ts+++ b/packages/types/src/generated/http.ts@@ -504,12 +504,21 @@ export interface CommunityDetailResponse {members: CommunityMember[];truncated: boolean;neighboring_communities: NeighboringCommunity[];+ health_score?: number | null;+ scored_member_count?: number;+ hot_count?: number;+ dead_count?: number;+ decision_count?: number;+ primary_owner?: string | null;+ primary_owner_file_count?: number;}export interface CommunityMember {path: string;pagerank: number;is_entry_point: boolean;+ is_hotspot?: boolean;+ is_dead?: boolean;}export interface CommunitySliceNodeResponse {diff --git a/packages/types/src/graph.ts b/packages/types/src/graph.tsindex 45365fb12..afe8d31bc 100644--- a/packages/types/src/graph.ts+++ b/packages/types/src/graph.ts@@ -339,6 +339,10 @@ export interface CommunityMember {path: string;pagerank: number;is_entry_point: boolean;+ /** Cross-link signals, so a count can name the files behind it. Optional: an+ * older server omits them, which reads as "no signal", not as "not flagged". */+ is_hotspot?: boolean;+ is_dead?: boolean;}export interface NeighboringCommunity {@@ -355,6 +359,24 @@ export interface CommunityDetail {members: CommunityMember[];truncated: boolean;neighboring_communities: NeighboringCommunity[];+ /** State of the area rather than its shape. Every field below is optional:+ * additive on the wire, and absent from an older server.+ *+ * LOC-weighted mean health over the members that carry a score, 0-10, higher+ * is better. `null` when none do — which is not zero and must not render as+ * a score. */+ health_score?: number | null;+ /** How many members contributed to `health_score`. */+ scored_member_count?: number;+ /** Members flagged hot / dead / decision-anchored, over every member — not+ * only the page returned in `members`. */+ hot_count?: number;+ dead_count?: number;+ decision_count?: number;+ /** Who is primary owner on the most members, and how many. "Most files+ * owned", not "most commits" — see the router comment. */+ primary_owner?: string | null;+ primary_owner_file_count?: number;}export interface CommunitySummaryItem {diff --git a/packages/ui/__tests__/graph/constants.test.ts b/packages/ui/__tests__/graph/constants.test.tsindex 3e3473004..647129618 100644--- a/packages/ui/__tests__/graph/constants.test.ts+++ b/packages/ui/__tests__/graph/constants.test.ts@@ -66,7 +66,7 @@ describe("label density", () => {});describe("EDGE_COLORS", () => {- const expectedTypes = ["import", "crossCommunity", "internal", "dynamic", "lowConfidence"];+ const expectedTypes = ["crossCommunity", "internal", "dynamic", "lowConfidence"];it("has valid hex colors for all edge types in both themes", () => {for (const theme of ["light", "dark"] as const) {@@ -85,10 +85,12 @@ describe("EDGE_COLORS", () => {expect(EDGE_COLORS).toBe(EDGE_COLORS_BY_THEME.dark);});- it("uses the warm semantic scheme: orange imports, plum cross-community", () => {- // import = brand orange in both themes- expect(EDGE_COLORS_BY_THEME.light.import).toBe("#f59520");- expect(EDGE_COLORS_BY_THEME.dark.import).toBe("#f59520");+ it("uses the warm semantic scheme, and keys no kind that is never drawn", () => {+ // No "import" kind. classifyEdge returned it only for an edge with an+ // endpoint missing from the graph, and the adapter drops those before+ // drawing, so the swatch keyed zero marks in every state.+ expect("import" in EDGE_COLORS_BY_THEME.light).toBe(false);+ expect("import" in EDGE_COLORS_BY_THEME.dark).toBe(false);// cross-community = plum (accent-secondary), different per themeexpect(EDGE_COLORS_BY_THEME.light.crossCommunity).toBe("#58436c");expect(EDGE_COLORS_BY_THEME.dark.crossCommunity).toBe("#a98fc4");diff --git a/packages/ui/__tests__/graph/graph-community-panel.test.tsx b/packages/ui/__tests__/graph/graph-community-panel.test.tsxindex bd7733c9f..abf8ec1a4 100644--- a/packages/ui/__tests__/graph/graph-community-panel.test.tsx+++ b/packages/ui/__tests__/graph/graph-community-panel.test.tsx@@ -1,5 +1,5 @@import { describe, it, expect, vi } from "vitest";-import { render, screen } from "@testing-library/react";+import { render, screen, fireEvent } from "@testing-library/react";import { GraphCommunityPanel } from "../../src/graph/graph-community-panel.js";import type { CommunityDetail } from "@repowise-dev/types/graph";@@ -19,8 +19,29 @@ const sampleCommunity: CommunityDetail = {],};+const withState: CommunityDetail = {+ ...sampleCommunity,+ health_score: 5.2,+ scored_member_count: 2,+ hot_count: 1,+ dead_count: 1,+ decision_count: 1,+ primary_owner: "Ada",+ primary_owner_file_count: 2,+ members: [+ { path: "src/auth/login.ts", pagerank: 0.05, is_entry_point: true, is_hotspot: true },+ { path: "src/auth/session.ts", pagerank: 0.03, is_entry_point: false, is_dead: true },+ { path: "src/auth/utils.ts", pagerank: 0.01, is_entry_point: false },+ ],+};++/** Open a `CollapsibleSection` by its toggle label. */+function expand(title: string) {+ fireEvent.click(screen.getByRole("button", { name: new RegExp(title) }));+}+describe("GraphCommunityPanel", () => {- it("renders community label, members, and neighbors", () => {+ it("names the community and says the grouping was automatic", () => {render(<GraphCommunityPanelcommunityId={7}@@ -30,12 +51,11 @@ describe("GraphCommunityPanel", () => {/>,);expect(screen.getByText("auth-cluster")).toBeTruthy();- expect(screen.getByText("Members (3)")).toBeTruthy();- expect(screen.getByText("db-cluster")).toBeTruthy();+ expect(screen.getByText("3 files, grouped automatically")).toBeTruthy();});- it("shows the expand-on-canvas affordance only when the callback is provided", () => {- const onExpand = vi.fn();+ it("shows the enter affordance only when the callback is provided", () => {+ const onEnter = vi.fn();const { rerender } = render(<GraphCommunityPanelcommunityId={7}@@ -44,7 +64,7 @@ describe("GraphCommunityPanel", () => {onClose={vi.fn()}/>,);- expect(screen.queryByText("Expand on canvas")).toBeNull();+ expect(screen.queryByText("Enter this community")).toBeNull();rerender(<GraphCommunityPanel@@ -52,12 +72,11 @@ describe("GraphCommunityPanel", () => {community={sampleCommunity}isLoading={false}onClose={vi.fn()}- onExpandOnCanvas={onExpand}+ onEnterCommunity={onEnter}/>,);- const btn = screen.getByText("Expand on canvas");- btn.click();- expect(onExpand).toHaveBeenCalledTimes(1);+ screen.getByText("Enter this community").click();+ expect(onEnter).toHaveBeenCalledTimes(1);});it("falls back to a numeric label when community is null", () => {@@ -73,3 +92,224 @@ describe("GraphCommunityPanel", () => {expect(screen.getByText("Community not found")).toBeTruthy();});});++describe("GraphCommunityPanel reading order", () => {+ it("opens with the state above the fold and the long lists collapsed", () => {+ // The complaint this structure answers: everything used to be expanded, so+ // the figure that says whether the area is in trouble sat one screen above+ // thirty member rows and ten neighbour rows.+ render(+ <GraphCommunityPanel+ communityId={7}+ community={withState}+ isLoading={false}+ onClose={vi.fn()}+ />,+ );+ // Lede and facts are rendered.+ expect(screen.getByText("5.2")).toBeTruthy();+ expect(screen.getByText("Changes often")).toBeTruthy();+ // The lists are behind a disclosure, so no member or neighbour is drawn.+ expect(screen.queryByText("src/auth/login.ts")).toBeNull();+ expect(screen.queryByText("db-cluster")).toBeNull();+ });++ it("counts each collapsed list on its own toggle", () => {+ render(+ <GraphCommunityPanel+ communityId={7}+ community={withState}+ isLoading={false}+ onClose={vi.fn()}+ />,+ );+ // A closed section still has to say how much is inside it, or collapsing is+ // just hiding.+ expect(screen.getByRole("button", { name: /Members/ }).textContent).toContain("3");+ expect(screen.getByRole("button", { name: /Talks to/ }).textContent).toContain("1");+ });++ it("reveals the members on demand", () => {+ render(+ <GraphCommunityPanel+ communityId={7}+ community={withState}+ isLoading={false}+ onClose={vi.fn()}+ memberHref={(p) => `/files/${p}`}+ />,+ );+ expand("Members");+ expect(screen.getByText("src/auth/login.ts")).toBeTruthy();+ expect(screen.getByText("src/auth/utils.ts")).toBeTruthy();+ });+});++describe("GraphCommunityPanel state", () => {+ it("leads with the health figure, its band, and how much of the group it covers", () => {+ render(+ <GraphCommunityPanel+ communityId={7}+ community={withState}+ isLoading={false}+ onClose={vi.fn()}+ />,+ );+ expect(screen.getByText("5.2")).toBeTruthy();+ // Five-band vocabulary, shared with the Code Health lede and the file+ // health drawer, so one score never gets two sets of words.+ expect(screen.getByText("Fair")).toBeTruthy();+ // The mean is over the scored members, and says so rather than implying it+ // measured all three.+ expect(screen.getByText(/2 of 3 files that are\s+scored/)).toBeTruthy();+ });++ it("never renders a missing health score as a number", () => {+ render(+ <GraphCommunityPanel+ communityId={7}+ community={{ ...sampleCommunity, health_score: null }}+ isLoading={false}+ onClose={vi.fn()}+ />,+ );+ expect(screen.getByText("Not scored")).toBeTruthy();+ expect(screen.queryByText("0.0")).toBeNull();+ });++ it("puts the signal counts in the fact grid, greying the zeroes", () => {+ render(+ <GraphCommunityPanel+ communityId={7}+ community={{ ...withState, hot_count: 4, dead_count: 0 }}+ isLoading={false}+ onClose={vi.fn()}+ />,+ );+ expect(screen.getByText("4 files")).toBeTruthy();+ // A zero is still news, so it is stated rather than dropped.+ expect(screen.getByText("none")).toBeTruthy();+ });++ it("expands the entry-point badge instead of abbreviating it", () => {+ render(+ <GraphCommunityPanel+ communityId={7}+ community={withState}+ isLoading={false}+ onClose={vi.fn()}+ />,+ );+ expand("Members");+ expect(screen.getByText("Entry")).toBeTruthy();+ expect(screen.queryByText("EP")).toBeNull();+ });++ it("makes a neighbour row navigable when the host can navigate", () => {+ const onNeighborSelect = vi.fn();+ const { rerender } = render(+ <GraphCommunityPanel+ communityId={7}+ community={withState}+ isLoading={false}+ onClose={vi.fn()}+ />,+ );+ expand("Talks to");+ // Without a handler the row is text, not a button that does nothing — the+ // bug this replaced.+ expect(screen.queryByRole("button", { name: /db-cluster/ })).toBeNull();++ rerender(+ <GraphCommunityPanel+ communityId={7}+ community={withState}+ isLoading={false}+ onClose={vi.fn()}+ onNeighborSelect={onNeighborSelect}+ />,+ );+ // No second expand: the section keeps its own open state across a+ // rerender, and toggling again would close it.+ screen.getByRole("button", { name: /db-cluster/ }).click();+ expect(onNeighborSelect).toHaveBeenCalledWith(4);+ });++ it("sends a flagged member to the page that explains the flag", () => {+ render(+ <GraphCommunityPanel+ communityId={7}+ community={withState}+ isLoading={false}+ onClose={vi.fn()}+ healthHrefFor={(p) => `/health?file=${p}`}+ deadCodeHref="/dead"+ />,+ );+ expand("Members");+ const hot = screen.getByLabelText(+ "src/auth/login.ts is a churn hotspot; open it in Code Health",+ );+ expect(hot.getAttribute("href")).toBe("/health?file=src/auth/login.ts");+ const dead = screen.getByLabelText(+ "src/auth/session.ts is flagged unreachable; open the dead-code findings",+ );+ expect(dead.getAttribute("href")).toBe("/dead");+ });+});++describe("GraphCommunityPanel truthfulness", () => {+ it("reconciles a count over every member with a list showing only a page", () => {+ render(+ <GraphCommunityPanel+ communityId={7}+ community={{+ ...withState,+ member_count: 500,+ truncated: true,+ hot_count: 12,+ }}+ isLoading={false}+ onClose={vi.fn()}+ />,+ );+ // The toggle carries the ratio while closed...+ expect(screen.getByRole("button", { name: /Members/ }).textContent).toContain(+ "3 of 500",+ );+ // ...and the opened list says which figure covers what, because counting+ // four flames under a headline of twelve is otherwise unexplained.+ expand("Members");+ expect(+ screen.getByText("The 3 most connected. The counts above cover all 500."),+ ).toBeTruthy();+ });++ it("does not render a cohesion figure for a community that has no pairs", () => {+ // `_cohesion_score` returns 1.0 for n <= 1 by definition, so the raw value+ // would read as a perfect score beside a tooltip about file pairs.+ render(+ <GraphCommunityPanel+ communityId={7}+ community={{ ...sampleCommunity, member_count: 1, cohesion: 1 }}+ isLoading={false}+ onClose={vi.fn()}+ />,+ );+ expect(screen.queryByText("Cohesion")).toBeNull();+ expect(screen.queryByText("100.0%")).toBeNull();+ });++ it("states cohesion as a labelled figure for a community that has pairs", () => {+ render(+ <GraphCommunityPanel+ communityId={7}+ community={sampleCommunity}+ isLoading={false}+ onClose={vi.fn()}+ />,+ );+ expect(screen.getByText("Cohesion")).toBeTruthy();+ expect(screen.getByText("82.0%")).toBeTruthy();+ });+});diff --git a/packages/ui/__tests__/graph/graph-doc-panel.test.tsx b/packages/ui/__tests__/graph/graph-doc-panel.test.tsxindex 27465e2b4..3e8c57847 100644--- a/packages/ui/__tests__/graph/graph-doc-panel.test.tsx+++ b/packages/ui/__tests__/graph/graph-doc-panel.test.tsx@@ -40,7 +40,7 @@ describe("GraphDocPanel", () => {expect(screen.getByText("claude-haiku-4-5")).toBeTruthy();});- it("renders the empty state when an error is supplied", () => {+ it("falls back to browsing when the host offers no file page", () => {render(<GraphDocPanelnodeId="src/missing.ts"@@ -51,7 +51,31 @@ describe("GraphDocPanel", () => {onClose={vi.fn()}/>,);- expect(screen.getByText("No documentation found for this file.")).toBeTruthy();+ // Same words as the file page's own empty state. A file with no extracted+ // symbols that is neither an entry point nor a hotspot is deliberately not+ // given a page, so "not found" described it as a failure.+ expect(screen.getByText("No documentation page for this file")).toBeTruthy();expect(screen.getByText("Browse all docs").getAttribute("href")).toBe("/repos/r/docs");});++ it("sends the reader to the file's own page, which works without a doc page", () => {+ render(+ <GraphDocPanel+ nodeId="src/missing.ts"+ page={null}+ isLoading={false}+ error={new Error("404")}+ fullPageHref="/repos/r/files/src/missing.ts"+ browseDocsHref="/repos/r/docs"+ onClose={vi.fn()}+ />,+ );+ // A real destination — history, health, symbols and graph position are all+ // there for an undocumented file — rather than a consolation link to the+ // whole docs tree.+ expect(screen.getByText("Open the file page").getAttribute("href")).toBe(+ "/repos/r/files/src/missing.ts",+ );+ expect(screen.queryByText("Browse all docs")).toBeNull();+ });});diff --git a/packages/ui/__tests__/graph/graph-flow.test.tsx b/packages/ui/__tests__/graph/graph-flow.test.tsxindex 5755bff18..5a9e05446 100644--- a/packages/ui/__tests__/graph/graph-flow.test.tsx+++ b/packages/ui/__tests__/graph/graph-flow.test.tsx@@ -6,7 +6,11 @@ import { GraphFlow } from "../../src/graph/graph-flow.js";// Stub the Sigma canvas: it dynamically imports "sigma", which needs WebGL2// and rejects under jsdom. These tests assert toolbar / notice / picker// behavior, none of which lives inside the canvas.-const { focusNodeSpy } = vi.hoisted(() => ({ focusNodeSpy: vi.fn() }));+const { focusNodeSpy, nodeCameraSpy, setEntryCameraSpy } = vi.hoisted(() => ({+ focusNodeSpy: vi.fn(),+ nodeCameraSpy: vi.fn(() => ({ x: 0.4, y: 0.6, ratio: 0.08 })),+ setEntryCameraSpy: vi.fn(),+}));vi.mock("../../src/graph/sigma/sigma-canvas.js", () => ({SigmaCanvas: forwardRef(function MockSigmaCanvas(_props, ref) {useImperativeHandle(ref, () => ({@@ -14,6 +18,8 @@ vi.mock("../../src/graph/sigma/sigma-canvas.js", () => ({fitView: () => {},zoomIn: () => {},zoomOut: () => {},+ nodeCamera: nodeCameraSpy,+ setEntryCamera: setEntryCameraSpy,}));return <div data-testid="sigma-canvas" />;}),@@ -22,6 +28,8 @@ vi.mock("../../src/graph/sigma/sigma-canvas.js", () => ({afterEach(() => {vi.useRealTimers();focusNodeSpy.mockClear();+ nodeCameraSpy.mockClear();+ setEntryCameraSpy.mockClear();});// Fixture file node carrying every required GraphNode field.@@ -127,7 +135,9 @@ describe("GraphFlow shell", () => {fullGraph={{ nodes: [], links: [], truncated: true, dead_total: 3 }}/>,);- fireEvent.click(screen.getByRole("radio", { name: "Dead" }));+ // The segment carries its own total now, so the accessible name is+ // "Dead 3" rather than "Dead".+ fireEvent.click(screen.getByRole("radio", { name: /^Dead/ }));expect(screen.getByText("Dead files are outside the loaded view")).toBeTruthy();});@@ -139,7 +149,7 @@ describe("GraphFlow shell", () => {fullGraph={{ nodes: [], links: [], dead_total: 0 }}/>,);- fireEvent.click(screen.getByRole("radio", { name: "Dead" }));+ fireEvent.click(screen.getByRole("radio", { name: /^Dead/ }));expect(screen.getByText("No dead files in this repo")).toBeTruthy();});@@ -174,6 +184,7 @@ describe("GraphFlow shell", () => {/>,);+ fireEvent.click(screen.getByRole("button", { name: "Trace" }));fireEvent.click(screen.getByRole("button", { name: "Execution flows" }));expect(screen.getByText("Execution Flows")).toBeTruthy();@@ -204,6 +215,7 @@ describe("GraphFlow shell", () => {<GraphFlow {...baseProps} initialViewMode="full" executionFlows={flows} />,);+ fireEvent.click(screen.getByRole("button", { name: "Trace" }));fireEvent.click(screen.getByRole("button", { name: "Execution flows" }));fireEvent.click(screen.getByText("main"));@@ -297,3 +309,286 @@ describe("GraphFlow shell", () => {expect(button.getAttribute("aria-pressed")).toBe("true");});});++describe("GraphFlow drill-down", () => {+ const sliceNode = (id: string, isBoundary = false) => ({+ ...fileNode(id, "typescript"),+ community_id: 3,+ ...(isBoundary ? { is_boundary: true } : {}),+ });++ const slice = {+ community_id: 3,+ member_count: 2,+ nodes: [sliceNode("src/a.ts"), sliceNode("src/b.ts"), sliceNode("vendor/z.ts", true)],+ links: [{ source: "src/a.ts", target: "src/b.ts", imported_names: ["x"] }],+ };++ const communities = [+ { community_id: 3, label: "auth-cluster", cohesion: 0.4, member_count: 2, top_file: "src/a.ts" },+ ];++ it("draws the entered community's own slice instead of the capped full graph", () => {+ render(+ <GraphFlow+ {...baseProps}+ viewMode="full"+ activeCommunity={3}+ communitySlice={slice as never}+ communities={communities as never}+ fullGraph={{ nodes: [fileNode("other/far.ts", "python")], links: [] } as never}+ />,+ );+ // The slice rendered, so the canvas is not the empty state and the+ // breadcrumb names where we are.+ expect(screen.getByTestId("sigma-canvas")).toBeTruthy();+ const crumbs = screen.getByLabelText("Graph location");+ expect(crumbs.textContent).toContain("auth-cluster");+ });++ it("reports leaving the community when the breadcrumb root is clicked", () => {+ const onActiveCommunityChange = vi.fn();+ const onViewModeChange = vi.fn();+ render(+ <GraphFlow+ {...baseProps}+ viewMode="full"+ activeCommunity={3}+ communitySlice={slice as never}+ communities={communities as never}+ repoName="repowise"+ onActiveCommunityChange={onActiveCommunityChange}+ onViewModeChange={onViewModeChange}+ />,+ );+ fireEvent.click(screen.getByTitle("Back to repowise"));+ expect(onActiveCommunityChange).toHaveBeenCalledWith(null);+ // Up from a community is the constellation it came from, not "all files".+ expect(onViewModeChange).toHaveBeenCalledWith("architecture");+ });++ it("shows no breadcrumb when nothing has been drilled into", () => {+ render(+ <GraphFlow+ {...baseProps}+ viewMode="full"+ activeCommunity={null}+ communities={communities as never}+ fullGraph={{ nodes: [fileNode("src/a.ts", "typescript")], links: [] } as never}+ />,+ );+ expect(screen.queryByLabelText("Graph location")).toBeNull();+ });++ it("ignores a community carried into the constellation scope", () => {+ // `?community=` only means something on a file-level scope; half-applying+ // it would draw a slice under a "Communities" switcher.+ render(+ <GraphFlow+ {...baseProps}+ viewMode="architecture"+ activeCommunity={3}+ communitySlice={slice as never}+ communities={communities as never}+ />,+ );+ expect(screen.queryByLabelText("Graph location")).toBeNull();+ });+});++describe("GraphFlow module filter", () => {+ const nodes = [+ fileNode("packages/ui/src/a.ts", "typescript"),+ fileNode("packages/ui/src/b.ts", "typescript"),+ fileNode("packages/core/src/c.py", "python"),+ ];++ it("reports every module group, not only the selected one", () => {+ const onModuleGroupsChange = vi.fn();+ render(+ <GraphFlow+ {...baseProps}+ viewMode="full"+ activeModule="packages/ui"+ onModuleGroupsChange={onModuleGroupsChange}+ fullGraph={{ nodes, links: [] } as never}+ />,+ );+ // Derived from the unfiltered payload: selecting a module must not collapse+ // the menu you selected it from.+ const groups = onModuleGroupsChange.mock.calls.at(-1)?.[0] as { id: string }[];+ expect(groups.map((g) => g.id).sort()).toEqual(["packages/core", "packages/ui"]);+ });+});++describe("GraphFlow drill-down honesty", () => {+ const member = (id: string) => ({ ...fileNode(id, "typescript"), community_id: 3 });+ const stub = (id: string) => ({ ...member(id), is_boundary: true });++ const communities = [+ { community_id: 3, label: "auth-cluster", cohesion: 0.4, member_count: 500, top_file: "src/a.ts" },+ ];++ it("says so when the slice is capped, and counts the stubs separately", () => {+ render(+ <GraphFlow+ {...baseProps}+ viewMode="full"+ activeCommunity={3}+ communities={communities as never}+ communitySlice={{+ community_id: 3,+ member_count: 500,+ truncated: true,+ nodes: [member("src/a.ts"), member("src/b.ts"), stub("vendor/z.ts")],+ links: [],+ } as never}+ />,+ );+ // "The files in auth-cluster" over 2 of 500 would be the lie; the repo-wide+ // truncation banner is deliberately off in this scope.+ expect(+ screen.getByText(+ "Showing the 2 most connected of 500 files in this group, plus 1 faded file outside it that they reach.",+ ),+ ).toBeTruthy();+ });++ it("withdraws the All / Hot / Dead filter, which could not reach a slice", () => {+ // The slice endpoint returns the whole community whatever the signal says,+ // so inside one the pill lit, the URL changed, an overlay fetch fired and+ // the canvas did not move.+ render(+ <GraphFlow+ {...baseProps}+ viewMode="full"+ activeCommunity={3}+ communities={communities as never}+ communitySlice={{+ community_id: 3,+ member_count: 2,+ truncated: false,+ nodes: [member("src/a.ts"), member("src/b.ts")],+ links: [],+ } as never}+ />,+ );+ expect(screen.queryByRole("radio", { name: /^Dead/ })).toBeNull();+ expect(screen.queryByRole("radio", { name: /^Hot/ })).toBeNull();+ });++ it("names the community once in prose, not three times on one screen", () => {+ render(+ <GraphFlow+ {...baseProps}+ viewMode="full"+ activeCommunity={3}+ communities={communities as never}+ communitySlice={{+ community_id: 3,+ member_count: 2,+ truncated: false,+ nodes: [member("src/a.ts"), member("src/b.ts")],+ links: [],+ } as never}+ />,+ );+ // The breadcrumb names it and carries the way out; the description used to+ // repeat the name and then explain the faded ring a second time, beside a+ // banner already counting it. The double-click instruction is withheld+ // because this host wired no `onNodeViewDocs` for it to reach.+ expect(+ screen.getByText("How the files in this group depend on each other."),+ ).toBeTruthy();+ });++ it("only promises the double-click when the host wired somewhere to go", () => {+ render(+ <GraphFlow+ {...baseProps}+ viewMode="full"+ activeCommunity={3}+ communities={communities as never}+ onNodeViewDocs={vi.fn()}+ communitySlice={{+ community_id: 3,+ member_count: 2,+ truncated: false,+ nodes: [member("src/a.ts"), member("src/b.ts")],+ links: [],+ } as never}+ />,+ );+ expect(+ screen.getByText(+ "How the files in this group depend on each other. Double-click a file to open it.",+ ),+ ).toBeTruthy();+ });++ it("does not claim truncation when the whole community is drawn", () => {+ render(+ <GraphFlow+ {...baseProps}+ viewMode="full"+ activeCommunity={3}+ communities={communities as never}+ communitySlice={{+ community_id: 3,+ member_count: 2,+ truncated: false,+ nodes: [member("src/a.ts"), member("src/b.ts")],+ links: [],+ } as never}+ />,+ );+ expect(screen.getByText("Showing all 2 files in this group.")).toBeTruthy();+ });++ it("drops the held frame when the slice fetch fails instead of pinning it", () => {+ // SWR leaves `data` undefined and `isLoading` false between retries. Holding+ // on "no slice yet" alone left the constellation drawn under a breadcrumb+ // asserting a scoped file graph, with no error and no empty state.+ const { rerender } = render(+ <GraphFlow+ {...baseProps}+ viewMode="architecture"+ constellationGraph={+ { nodes: [{ community_id: 3, label: "auth-cluster", member_count: 2, avg_pagerank: 0.1 }], edges: [] } as never+ }+ communities={communities as never}+ />,+ );+ rerender(+ <GraphFlow+ {...baseProps}+ viewMode="full"+ activeCommunity={3}+ communitySlice={undefined}+ isLoadingCommunitySlice={false}+ communities={communities as never}+ />,+ );+ expect(screen.getByText("No graph data")).toBeTruthy();+ });++ it("drops the dead/hot captions inside a community the signal never filtered", () => {+ render(+ <GraphFlow+ {...baseProps}+ viewMode="dead"+ activeCommunity={3}+ communities={communities as never}+ deadCodeGraph={{ nodes: [], links: [], dead_total: 9 } as never}+ communitySlice={{+ community_id: 3,+ member_count: 2,+ truncated: false,+ nodes: [member("src/a.ts"), member("src/b.ts")],+ links: [],+ } as never}+ />,+ );+ expect(screen.queryByText(/dead files/)).toBeNull();+ });+});diff --git a/packages/ui/__tests__/graph/graph-legend.test.tsx b/packages/ui/__tests__/graph/graph-legend.test.tsxnew file mode 100644index 000000000..3be939fd8--- /dev/null+++ b/packages/ui/__tests__/graph/graph-legend.test.tsx@@ -0,0 +1,137 @@+import { describe, it, expect, vi } from "vitest";+import { render, screen } from "@testing-library/react";+import { GraphLegend } from "../../src/graph/graph-legend";++const base = {+ nodeCount: 94,+ edgeCount: 553,+ colorMode: "community" as const,+ viewMode: "full" as const,+};++describe("GraphLegend inside a community", () => {+ const scoped = {+ ...base,+ scopeLabel: "repowise/extractors",+ scopeCommunityId: 4,+ sliceCounts: { members: 54, boundary: 40 },+ visibleEdgeCount: 312,+ visibleEdgeTypes: new Set(["crossCommunity", "internal"]),+ onEdgeTypeToggle: vi.fn(),+ };++ it("keys the community that is drawn, not eight the API happened to list first", () => {+ // The whole-repo key sourced its swatches from `useCommunities`, in API+ // order, so the community you drilled into was usually absent from its own+ // view.+ render(+ <GraphLegend+ {...scoped}+ communityLabels={new Map([[1, "packages/web"], [2, "packages/cli"]])}+ />,+ );+ expect(screen.getByText("repowise/extractors")).toBeTruthy();+ expect(screen.queryByText("packages/web")).toBeNull();+ });++ it("drops the whole-repo community filter, which dimmed the slice you came to read", () => {+ // `Deselect all` ran over every drawn node, so one click blanked the+ // subject; and toggling a community that is not on the canvas changed+ // nothing while leaving its swatch filled.+ render(+ <GraphLegend+ {...scoped}+ onToggleAllCommunities={vi.fn()}+ onCommunityToggle={vi.fn()}+ communityLabels={new Map([[1, "packages/web"]])}+ />,+ );+ expect(screen.queryByText("Deselect all")).toBeNull();+ expect(screen.queryByText("Select all")).toBeNull();+ });++ it("counts the members, the ring and the edges actually drawn", () => {+ render(<GraphLegend {...scoped} />);+ // Not "94 nodes · 553 edges": that count folded the boundary stubs into+ // the file count and included the edges the filter was hiding.+ expect(+ screen.getByText(/54 files · 40 outside · 312 edges shown/),+ ).toBeTruthy();+ });++ it("gives the faded ring a row, instead of explaining it only in prose", () => {+ render(<GraphLegend {...scoped} />);+ expect(screen.getByText("Outside this group")).toBeTruthy();+ });++ it("words the edge kinds for the scope it is describing", () => {+ render(<GraphLegend {...scoped} />);+ expect(screen.getByText("Within this group")).toBeTruthy();+ expect(screen.getByText("Leaving this group")).toBeTruthy();+ expect(screen.queryByText("Cross-community")).toBeNull();+ });+});++describe("GraphLegend at repo scope", () => {+ it("keys no edge kind that is never drawn", () => {+ // `classifyEdge` returned "import" only for an edge whose endpoint was+ // missing from the graph, and the adapter drops those before drawing.+ render(+ <GraphLegend+ {...base}+ visibleEdgeTypes={new Set(["crossCommunity", "internal"])}+ onEdgeTypeToggle={vi.fn()}+ />,+ );+ expect(screen.queryByText("Imports")).toBeNull();+ expect(screen.getByText("Cross-community")).toBeTruthy();+ });++ it("carries the node filter beside the count that filter changes", () => {+ render(+ <GraphLegend {...base} nodeFilter={<button type="button">All</button>} />,+ );+ expect(screen.getByRole("button", { name: "All" })).toBeTruthy();+ });++ it("reports the edges it can see rather than the ones it holds", () => {+ render(<GraphLegend {...base} visibleEdgeCount={312} />);+ expect(screen.getByText(/94 nodes · 312 edges/)).toBeTruthy();+ });+});++describe("GraphLegend before the canvas has anything to key", () => {+ it("offers no Deselect all when no listed community is drawn", () => {+ // `communityLabels` is the repo-wide summary and resolves before an async+ // graph build finishes. Filtering rows by what is drawn made the list+ // empty — and `[]` is truthy, so the group rendered its label and a lone+ // "Deselect all" over zero swatches. Clicking it dimmed every node while+ // `[].every(...)` kept the label reading "Deselect all".+ render(+ <GraphLegend+ {...base}+ communityLabels={new Map([[1, "packages/web"]])}+ drawnCommunityIds={new Set()}+ onToggleAllCommunities={vi.fn()}+ onCommunityToggle={vi.fn()}+ />,+ );+ expect(screen.queryByText("Deselect all")).toBeNull();+ expect(screen.queryByText("packages/web")).toBeNull();+ expect(screen.queryByText("Community")).toBeNull();+ });++ it("keys only the communities the canvas is drawing", () => {+ render(+ <GraphLegend+ {...base}+ communityLabels={new Map([[1, "packages/web"], [2, "packages/cli"]])}+ drawnCommunityIds={new Set([2])}+ onCommunityToggle={vi.fn()}+ />,+ );+ expect(screen.getByText("packages/cli")).toBeTruthy();+ expect(screen.queryByText("packages/web")).toBeNull();+ });+});+diff --git a/packages/ui/__tests__/graph/graphology-adapter.test.ts b/packages/ui/__tests__/graph/graphology-adapter.test.tsindex 5bc5bf580..c769dbb32 100644--- a/packages/ui/__tests__/graph/graphology-adapter.test.ts+++ b/packages/ui/__tests__/graph/graphology-adapter.test.ts@@ -148,3 +148,181 @@ describe("moduleGraphToGraphology", () => {expect(attrs.communityId).toBe(3);});});++describe("fileGraphToGraphology on a community slice", () => {+ // A slice is one community by definition, so the whole-repo seed — which+ // partitions by `community_id` and rings the centroids — degenerates: the+ // members all share one id and land in a single small disc while the+ // boundary stubs, which carry their own real ids, are strewn across the rest+ // of the ring. On the 94-node slice this was reported from, the members+ // occupied 3.4% of the drawn area.+ const members = Array.from({ length: 12 }, (_, i) =>+ makeNode({ node_id: `src/auth/f${i}.ts`, community_id: 4 }),+ );+ const stubs = [+ makeNode({ node_id: "src/db/pool.ts", community_id: 9 }),+ makeNode({ node_id: "src/http/router.ts", community_id: 17 }),+ ];+ const boundaryNodeIds = new Set(stubs.map((n) => n.node_id));+ const links: GraphLink[] = [+ { source: "src/auth/f0.ts", target: "src/db/pool.ts", imported_names: ["pool"] },+ { source: "src/auth/f1.ts", target: "src/http/router.ts", imported_names: ["router"] },+ ];++ const radius = (g: ReturnType<typeof fileGraphToGraphology>, id: string) => {+ const a = g.getNodeAttributes(id);+ return Math.hypot(a.x, a.y);+ };++ it("gives the members most of the field instead of a dot in the corner", () => {+ const g = fileGraphToGraphology(makeFileGraph([...members, ...stubs], links), {+ boundaryNodeIds,+ });+ const memberRadii = members.map((n) => radius(g, n.node_id));+ const stubRadii = stubs.map((n) => radius(g, n.node_id));+ const widest = Math.max(...memberRadii, ...stubRadii);++ // Members reach out to roughly 60% of the drawn radius, so their own+ // structure is the subject rather than a speck at the centre.+ expect(Math.max(...memberRadii) / widest).toBeGreaterThan(0.5);+ // Every stub sits outside every member, so the ring reads as the edge of+ // the world rather than as more of the same graph.+ expect(Math.min(...stubRadii)).toBeGreaterThan(Math.max(...memberRadii));+ });++ it("puts a stub on the bearing of the member it attaches to", () => {+ const g = fileGraphToGraphology(makeFileGraph([...members, ...stubs], links), {+ boundaryNodeIds,+ });+ const bearing = (id: string) => {+ const a = g.getNodeAttributes(id);+ return Math.atan2(a.y, a.x);+ };+ const delta = (a: number, b: number) =>+ Math.abs(Math.atan2(Math.sin(a - b), Math.cos(a - b)));+ // Within the ring's own jitter band of the member that pulls it, so an+ // edge leaving the group is a short spoke rather than a chord across it.+ expect(delta(bearing("src/db/pool.ts"), bearing("src/auth/f0.ts"))).toBeLessThan(0.2);+ expect(delta(bearing("src/http/router.ts"), bearing("src/auth/f1.ts"))).toBeLessThan(0.2);+ });++ it("leaves the whole-repo seed alone when no boundary set is given", () => {+ const withSlice = fileGraphToGraphology(makeFileGraph([...members, ...stubs], links), {+ boundaryNodeIds,+ });+ const withoutSlice = fileGraphToGraphology(makeFileGraph([...members, ...stubs], links));+ // The community partition still runs for every other caller — the slice+ // branch is gated on `boundaryNodeIds` and nothing else.+ expect(withoutSlice.getNodeAttributes("src/auth/f0.ts").x).not.toBe(+ withSlice.getNodeAttributes("src/auth/f0.ts").x,+ );+ });++ it("classifies no edge as the unreachable import kind", () => {+ const g = fileGraphToGraphology(makeFileGraph([...members, ...stubs], links), {+ boundaryNodeIds,+ });+ const kinds = new Set<string>();+ g.forEachEdge((_, attrs) => kinds.add(attrs.edgeKind));+ expect(kinds.has("import" as never)).toBe(false);+ // Member-to-stub edges cross communities; that is what the ring encodes.+ expect(kinds.has("crossCommunity")).toBe(true);+ });+});++describe("fileGraphToGraphology slice seed degenerate cases", () => {+ const boundary = (ids: string[]) => new Set(ids);+ const at = (g: ReturnType<typeof fileGraphToGraphology>, id: string) => {+ const a = g.getNodeAttributes(id);+ return { r: Math.hypot(a.x, a.y), t: Math.atan2(a.y, a.x) };+ };++ it("puts a lone member at the centre, not two thirds of the way to the rim", () => {+ // `sqrt((i + 1) / n)` gave member 0 the full radius, so a one-file+ // community drew its one file out on the 3 o'clock ray with every stub+ // stacked on that same bearing and the rest of the field empty.+ const nodes = [+ makeNode({ node_id: "src/only.ts", community_id: 4 }),+ makeNode({ node_id: "vendor/a.ts", community_id: 9 }),+ makeNode({ node_id: "vendor/b.ts", community_id: 9 }),+ ];+ const links: GraphLink[] = [+ { source: "src/only.ts", target: "vendor/a.ts", imported_names: ["a"] },+ { source: "src/only.ts", target: "vendor/b.ts", imported_names: ["b"] },+ ];+ const g = fileGraphToGraphology(makeFileGraph(nodes, links), {+ boundaryNodeIds: boundary(["vendor/a.ts", "vendor/b.ts"]),+ });+ const member = at(g, "src/only.ts");+ const rim = Math.max(at(g, "vendor/a.ts").r, at(g, "vendor/b.ts").r);+ expect(member.r / rim).toBeLessThan(0.05);+ });++ it("fans stubs that all hang off one member instead of stacking them", () => {+ // The seed IS the layout — FA2 and noverlap are both off for a file graph+ // — so nothing separates two stubs that resolve to the same bearing later.+ const members = Array.from({ length: 6 }, (_, i) =>+ makeNode({ node_id: `src/m${i}.ts`, community_id: 4 }),+ );+ const stubs = Array.from({ length: 20 }, (_, i) =>+ makeNode({ node_id: `vendor/s${i}.ts`, community_id: 9 }),+ );+ // Every stub attaches to the same high-degree member.+ const links: GraphLink[] = stubs.map((s) => ({+ source: "src/m0.ts",+ target: s.node_id,+ imported_names: ["x"],+ }));+ const g = fileGraphToGraphology(makeFileGraph([...members, ...stubs], links), {+ boundaryNodeIds: boundary(stubs.map((s) => s.node_id)),+ });+ const angles = stubs.map((s) => at(g, s.node_id).t).sort((a, b) => a - b);+ const spans = angles.at(-1)! - angles[0]!;+ // A band wide enough to seat twenty, not the old fixed ±0.1 rad box.+ expect(spans).toBeGreaterThan(1);+ // And no two of them land on the same bearing.+ expect(new Set(angles.map((a) => a.toFixed(4))).size).toBe(stubs.length);+ });++ it("never emits a non-finite coordinate", () => {+ const nodes = [+ makeNode({ node_id: "src/a.ts", community_id: 4 }),+ makeNode({ node_id: "src/b.ts", community_id: 4 }),+ makeNode({ node_id: "vendor/x.ts", community_id: 9 }),+ makeNode({ node_id: "vendor/y.ts", community_id: 9 }),+ ];+ const links: GraphLink[] = [+ // A stub pulled in exactly opposite directions, which sums to a float+ // residue rather than to zero.+ { source: "src/a.ts", target: "vendor/x.ts", imported_names: ["x"] },+ { source: "src/b.ts", target: "vendor/x.ts", imported_names: ["x"] },+ // A self-link, and a link naming a node the graph does not carry.+ { source: "vendor/y.ts", target: "vendor/y.ts", imported_names: ["y"] },+ { source: "src/a.ts", target: "src/gone.ts", imported_names: ["g"] },+ ];+ const g = fileGraphToGraphology(makeFileGraph(nodes, links), {+ boundaryNodeIds: boundary(["vendor/x.ts", "vendor/y.ts"]),+ });+ g.forEachNode((_, a) => {+ expect(Number.isFinite(a.x)).toBe(true);+ expect(Number.isFinite(a.y)).toBe(true);+ });+ });++ it("does not seed a slice when the node count makes the field zero-sized", () => {+ // `nodeCount` is a public option. At 0 the spread is 0 and every seeded+ // coordinate would collapse onto the origin, with no FA2 to rescue it.+ const nodes = [+ makeNode({ node_id: "src/a.ts", community_id: 4 }),+ makeNode({ node_id: "vendor/x.ts", community_id: 9 }),+ ];+ const g = fileGraphToGraphology(makeFileGraph(nodes, []), {+ boundaryNodeIds: boundary(["vendor/x.ts"]),+ nodeCount: 0,+ });+ g.forEachNode((_, a) => {+ expect(Number.isFinite(a.x)).toBe(true);+ expect(Number.isFinite(a.y)).toBe(true);+ });+ });+});diff --git a/packages/ui/__tests__/graph/use-community-filter.test.ts b/packages/ui/__tests__/graph/use-community-filter.test.tsnew file mode 100644index 000000000..3f7e26607--- /dev/null+++ b/packages/ui/__tests__/graph/use-community-filter.test.ts@@ -0,0 +1,64 @@+import { describe, it, expect } from "vitest";+import { renderHook, act } from "@testing-library/react";+import Graph from "graphology";+import { useCommunityFilter } from "../../src/graph/use-community-filter";+import type { SigmaNodeAttributes, SigmaEdgeAttributes } from "../../src/graph/sigma/types";++/** A graph of file nodes, one per community id given. */+function graphOf(communityIds: number[]) {+ const g = new Graph<SigmaNodeAttributes, SigmaEdgeAttributes>();+ communityIds.forEach((cid, i) => {+ g.addNode(`f${i}.ts`, {+ x: 0,+ y: 0,+ size: 1,+ color: "#000",+ label: `f${i}.ts`,+ nodeType: "file",+ communityId: cid,+ } as SigmaNodeAttributes);+ });+ return g;+}++describe("useCommunityFilter", () => {+ it("ignores a community with nothing on the canvas", () => {+ // The key used to list communities from the repo-wide summary, so clicking+ // one that was not drawn added a phantom id: nothing dimmed and the swatch+ // stayed filled.+ const { result } = renderHook(() => useCommunityFilter(graphOf([0, 1, 2])));+ act(() => result.current.handleCommunityToggle(99));+ expect(result.current.activeCommunities).toBeNull();+ expect(result.current.communityDimmedNodes).toBeNull();+ });++ it("does not let an id from a graph that is gone un-filter the canvas", () => {+ // The drawn set changes on a signal toggle, a module filter, an ego depth+ // and a load-more. A leftover id made `next.size` match `allCommunityIds`+ // and reset the filter to "show all" — on a click whose label said hide.+ const { result, rerender } = renderHook(+ ({ ids }: { ids: number[] }) => useCommunityFilter(graphOf(ids)),+ { initialProps: { ids: [0, 1, 2, 3] } },+ );+ act(() => result.current.handleCommunityToggle(0));+ expect(result.current.activeCommunities).toEqual(new Set([1, 2, 3]));++ // Community 3 leaves the canvas; the stale id stays in state, invisibly.+ rerender({ ids: [1, 2] });+ act(() => result.current.handleCommunityToggle(1));+ expect(result.current.activeCommunities).toEqual(new Set([2]));+ });++ it("still collapses to no filter once every drawn community is back on", () => {+ const { result } = renderHook(() => useCommunityFilter(graphOf([0, 1])));+ act(() => result.current.handleCommunityToggle(0));+ expect(result.current.activeCommunities).toEqual(new Set([1]));+ act(() => result.current.handleCommunityToggle(0));+ expect(result.current.activeCommunities).toBeNull();+ });++ it("reports the communities that are actually drawn", () => {+ const { result } = renderHook(() => useCommunityFilter(graphOf([4, 4, 7])));+ expect(result.current.drawnCommunityIds).toEqual(new Set([4, 7]));+ });+});diff --git a/packages/ui/src/dashboard/community-summary-grid.tsx b/packages/ui/src/dashboard/community-summary-grid.tsxindex 9015cf4ab..633c2018c 100644--- a/packages/ui/src/dashboard/community-summary-grid.tsx+++ b/packages/ui/src/dashboard/community-summary-grid.tsx@@ -170,7 +170,7 @@ export function CommunitySummaryGrid({Architecture Communities ({communities.length})</CardTitle>{prefix && (- <a href={`${prefix}/architecture?view=graph&colorMode=community`} className="text-[10px] text-[var(--color-accent-primary)] hover:underline">+ <a href={`${prefix}/architecture?view=communities`} className="text-[10px] text-[var(--color-accent-primary)] hover:underline">View in Graph →</a>)}diff --git a/packages/ui/src/dashboard/execution-flows-panel.tsx b/packages/ui/src/dashboard/execution-flows-panel.tsxindex 07a996e14..007eecf1a 100644--- a/packages/ui/src/dashboard/execution-flows-panel.tsx+++ b/packages/ui/src/dashboard/execution-flows-panel.tsx@@ -168,7 +168,7 @@ export function ExecutionFlowsPanel({ flows, repoId, linkPrefix }: ExecutionFlow<CardHeader className="pb-2"><div className="flex items-center justify-between"><CardTitle className="text-sm font-medium">Execution Flows</CardTitle>- <a href={`${prefix}/architecture?view=graph&viewMode=architecture`} className="text-[10px] text-[var(--color-accent-primary)] hover:underline">+ <a href={`${prefix}/architecture?view=communities`} className="text-[10px] text-[var(--color-accent-primary)] hover:underline">View in Graph →</a></div>diff --git a/packages/ui/src/dashboard/module-minimap.tsx b/packages/ui/src/dashboard/module-minimap.tsxindex 23f14104f..0fc098a0f 100644--- a/packages/ui/src/dashboard/module-minimap.tsx+++ b/packages/ui/src/dashboard/module-minimap.tsx@@ -118,7 +118,7 @@ export function ModuleMinimap({ nodes, edges, repoId, linkPrefix }: ModuleMinimaArchitecture</span><a- href={`${prefix}/architecture?view=graph`}+ href={`${prefix}/architecture?view=communities`}className="text-[10px] text-[var(--color-accent-primary)] hover:underline font-normal">Full graphdiff --git a/packages/ui/src/dashboard/module-overview-grid.tsx b/packages/ui/src/dashboard/module-overview-grid.tsxindex 74f725c90..9c2cd89bc 100644--- a/packages/ui/src/dashboard/module-overview-grid.tsx+++ b/packages/ui/src/dashboard/module-overview-grid.tsx@@ -52,7 +52,7 @@ export function ModuleOverviewGrid({ nodes, edges, repoId, linkPrefix, initialVi</span></span><a- href={`${prefix}/architecture?view=graph`}+ href={`${prefix}/architecture?view=communities`}className="text-[10px] text-[var(--color-accent-primary)] hover:underline font-normal">Full graph →@@ -72,7 +72,7 @@ export function ModuleOverviewGrid({ nodes, edges, repoId, linkPrefix, initialVireturn (<akey={m.module_id}- href={`${prefix}/architecture?view=graph&node=${encodeURIComponent(m.module_id)}`}+ href={`${prefix}/architecture?view=files&node=${encodeURIComponent(m.module_id)}`}className="group rounded-lg border border-[var(--color-border-default)] p-3 hover:border-[var(--color-border-hover)] hover:bg-[var(--color-bg-elevated)] transition-colors"><p className="text-xs font-medium text-[var(--color-text-primary)] truncate mb-2" title={m.module_id}>diff --git a/packages/ui/src/files/file-graph-tab.tsx b/packages/ui/src/files/file-graph-tab.tsxindex 651c7fb3e..47971869f 100644--- a/packages/ui/src/files/file-graph-tab.tsx+++ b/packages/ui/src/files/file-graph-tab.tsx@@ -156,7 +156,7 @@ export function FileGraphTab({}action={<A- href={`${linkPrefix}/architecture?view=graph&node=${encodeURIComponent(filePath)}`}+ href={`${linkPrefix}/architecture?view=files&node=${encodeURIComponent(filePath)}`}className="text-sm font-medium text-[var(--color-accent-primary)] hover:underline">Show in the dependency graph <span aria-hidden>→</span>diff --git a/packages/ui/src/git/hotspot-table.tsx b/packages/ui/src/git/hotspot-table.tsxindex f74565090..40e9c25a8 100644--- a/packages/ui/src/git/hotspot-table.tsx+++ b/packages/ui/src/git/hotspot-table.tsx@@ -473,7 +473,7 @@ export function HotspotTable({{prefix && (<RowActionsactions={[- { icon: GitBranch, label: "Graph", href: `${prefix}/architecture?view=graph&node=${encodeURIComponent(h.file_path)}` },+ { icon: GitBranch, label: "Graph", href: `${prefix}/architecture?view=files&node=${encodeURIComponent(h.file_path)}` },// `?file=` is read by nothing in the docs// surface, so this used to open the repo// overview while looking like it had worked.diff --git a/packages/ui/src/git/ownership-table.tsx b/packages/ui/src/git/ownership-table.tsxindex 55cff923a..be84abca1 100644--- a/packages/ui/src/git/ownership-table.tsx+++ b/packages/ui/src/git/ownership-table.tsx@@ -131,7 +131,7 @@ export function OwnershipTable({ entries, repoId, linkPrefix }: OwnershipTablePr{prefix && (<RowActionsactions={[- { icon: GitBranch, label: "Graph", href: `${prefix}/architecture?view=graph&node=${encodeURIComponent(entry.module_path)}` },+ { icon: GitBranch, label: "Graph", href: `${prefix}/architecture?view=files&node=${encodeURIComponent(entry.module_path)}` },{ icon: Flame, label: "Hotspots", href: `${prefix}/code-health?tab=triage` },]}/>diff --git a/packages/ui/src/graph/elk-layout.ts b/packages/ui/src/graph/elk-layout.tsindex e47a95c9d..a4081003d 100644--- a/packages/ui/src/graph/elk-layout.ts+++ b/packages/ui/src/graph/elk-layout.ts@@ -39,6 +39,9 @@ export interface FileNodeData {hasDoc: boolean;isHotspot?: boolean | undefined;isDead?: boolean | undefined;+ /** Named by a recorded architectural decision. Already on the node payload;+ * the inspector uses it to offer the decision as a destination. */+ hasDecision?: boolean | undefined;[key: string]: unknown;}diff --git a/packages/ui/src/graph/graph-canvas-shell.tsx b/packages/ui/src/graph/graph-canvas-shell.tsxindex 595a86763..4d7973a0b 100644--- a/packages/ui/src/graph/graph-canvas-shell.tsx+++ b/packages/ui/src/graph/graph-canvas-shell.tsx@@ -4,6 +4,9 @@ import * as React from "react";import { cn } from "../lib/cn";export interface GraphCanvasShellProps {+ /** "You are here", above the title. Present only once the canvas is showing+ * something narrower than the whole scope, so it never adds a permanent row. */+ breadcrumb?: React.ReactNode | undefined;/** Optional one-line title rendered above the canvas (no second header band). */title?: string | undefined;/** Optional one-line description under the title. */@@ -42,6 +45,7 @@ export interface GraphCanvasShellProps {* same arrangement.*/export function GraphCanvasShell({+ breadcrumb,title,description,titleActions,@@ -54,9 +58,10 @@ export function GraphCanvasShell({}: GraphCanvasShellProps) {return (<div className={cn("flex h-full flex-col", className)}>- {(title || description || titleActions) && (+ {(breadcrumb || title || description || titleActions) && (<div className="flex shrink-0 flex-wrap items-start justify-between gap-2 px-4 pt-3 sm:px-6"><div className="min-w-0 max-w-2xl">+ {breadcrumb && <div className="mb-1 min-w-0">{breadcrumb}</div>}{title && (<h2 className="text-sm font-semibold text-[var(--color-text-primary)]">{title}@@ -84,8 +89,20 @@ export function GraphCanvasShell({)}>{/* A floor, so a tall header or key row cannot squeeze the subject to- nothing; the page scrolls instead. */}- <div className="relative min-h-0 overflow-hidden max-lg:min-h-[22rem]">+ nothing; the page scrolls instead.++ Below `lg` the rail is a sheet over the bottom 70% of this cell, and+ the canvas parks its own zoom/fit controls at `bottom-3`. Opening a+ panel therefore buried them. This publishes the sheet's extent as a+ variable the canvas chrome reads for its own offset, so the controls+ step above the sheet instead of under it. Above `lg` the rail is a+ grid peer and there is nothing to clear. */}+ <div+ className={cn(+ "relative min-h-0 overflow-hidden max-lg:min-h-[22rem]",+ rail && "max-lg:[--canvas-chrome-bottom:calc(70%+0.75rem)]",+ )}+ >{children}{overlay}</div>@@ -94,7 +111,14 @@ export function GraphCanvasShell({className={cn(// Bottom sheet under lg so the canvas keeps its height on a// phone; a real grid column from lg up.- "absolute inset-x-0 bottom-0 z-20 flex max-h-[70%] flex-col overflow-hidden",+ // `--z-dropdown`, which is the raw `z-20` this used to carry+ // spelled as the token. Deliberately NOT `--z-sidebar`: Radix+ // tooltips and popovers portal to `body` at `--z-dropdown`, so a+ // rail that outranked them would render its own tooltips behind+ // itself. Equal, and later in the DOM, is what makes them land on+ // top. It still clears the canvas chrome at `--z-elevated`, and+ // still yields to the context menu and the help modal.+ "absolute inset-x-0 bottom-0 z-[var(--z-dropdown)] flex max-h-[70%] flex-col overflow-hidden","rounded-t-xl border-t border-[var(--color-border-default)] bg-[var(--color-bg-surface)] shadow-xl shadow-black/20","lg:static lg:max-h-none lg:rounded-none lg:border-t-0 lg:border-l lg:shadow-none",)}diff --git a/packages/ui/src/graph/graph-community-panel.tsx b/packages/ui/src/graph/graph-community-panel.tsxindex db768934e..7cf07f912 100644--- a/packages/ui/src/graph/graph-community-panel.tsx+++ b/packages/ui/src/graph/graph-community-panel.tsx@@ -1,12 +1,44 @@"use client";-import { X, ArrowRight, Sparkles } from "lucide-react";+import type { ReactNode } from "react";+import { X, ArrowRight, CornerDownRight, Flame, Skull } from "lucide-react";import { Badge } from "../ui/badge";import { ScrollArea } from "../ui/scroll-area";import { Skeleton } from "../ui/skeleton";+import { CollapsibleSection } from "../shared/collapsible-section";+import { InfoTip } from "../shared/info-tip";import { truncatePath } from "../lib/format";+// Shared band function, never a local threshold: two surfaces disagreeing+// about where "Good" starts is worse than the import.+import { healthBand } from "../overview/health-lede";import type { CommunityDetail } from "@repowise-dev/types/graph";+/**+ * What the rolled-up health score means for an *area* rather than a file.+ *+ * The number alone is not actionable: 6.2 is a fine file and a group of files+ * averaging 6.2 is a different claim. These sentences say what the reader+ * should do about it, per the design language's "lead with one figure and a+ * plain-language interpretation".+ *+ * Every one is phrased as a claim about the *average*, because that is all a+ * LOC-weighted mean supports. "Nothing here is risky" would be the natural+ * reading of a healthy score and it is not one this figure can make: a single+ * bad file inside a healthy group is exactly the file such a sentence would+ * tell the reader to skip.+ *+ * Keyed on `healthBand`'s label, the same five bands the Code Health lede and+ * the file health drawer show, so one score never gets two vocabularies.+ */+const HEALTH_READING: Record<string, string> = {+ Excellent:+ "On average this area scores well. A mean hides its worst file, so check the flags below.",+ Good: "On average this area scores well. A mean hides its worst file, so check the flags below.",+ Fair: "This area averages into the middle; some files here carry real defect risk.",+ "Needs work": "This area averages low. Read it before you change it.",+ Critical: "This area averages into the worst band. Read it before you change it.",+};+export interface GraphCommunityPanelProps {/** Community id surfaced in the empty/loading title fallback. */communityId: number;@@ -15,12 +47,22 @@ export interface GraphCommunityPanelProps {/** Loading flag from the consumer's data hook. */isLoading: boolean;onClose: () => void;- /** Optional: blossom this community's files on the canvas. When provided, an- * "Expand on canvas" affordance is shown (the constellation single-click now- * opens this panel instead of expanding, so the panel offers the expand). */- onExpandOnCanvas?: (() => void) | undefined;+ /** Optional: draw this community's own scoped file graph. The primary action,+ * and the same thing double-clicking the hub does. */+ onEnterCommunity?: (() => void) | undefined;+ /** Optional: open a neighbouring community's panel and select its hub. Makes+ * the neighbour list navigable; without it the rows render as plain text+ * rather than as buttons that do nothing. */+ onNeighborSelect?: ((communityId: number) => void) | undefined;/** Build a member href (typically the canonical file page). */memberHref?: ((path: string) => string) | undefined;+ /** Where a *hot* member goes: its row in the Code Health triage map. */+ healthHrefFor?: ((path: string) => string) | undefined;+ /** Where a *dead* member goes: the dead-code findings list. Repo-scoped,+ * because there is no per-file dead-code route. */+ deadCodeHref?: string | undefined;+ /** Repo-wide Code Health, for the panel's "leave for the right page" link. */+ codeHealthHref?: string | undefined;}export function GraphCommunityPanel({@@ -28,142 +70,490 @@ export function GraphCommunityPanel({community,isLoading,onClose,- onExpandOnCanvas,+ onEnterCommunity,+ onNeighborSelect,memberHref,+ healthHrefFor,+ deadCodeHref,+ codeHealthHref,}: GraphCommunityPanelProps) {return (<div className="flex h-full min-h-0 flex-col">- {/* Header */}- <div className="flex items-center justify-between px-4 py-3 border-b border-[var(--color-border-default)]">+ {/* Header and the primary action sit OUTSIDE the scroll container, so+ "Enter this community" stays reachable however far down the reader+ has scrolled. */}+ <div className="flex shrink-0 items-start justify-between gap-2 border-b border-[var(--color-border-default)] px-4 py-3"><div className="min-w-0">- <p className="text-sm font-medium text-[var(--color-text-primary)] truncate">+ <p className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">+ Community+ </p>+ <p className="mt-0.5 truncate text-sm font-medium text-[var(--color-text-primary)]">{community?.label ?? `Community ${communityId}`}</p>{community && (- <p className="text-[10px] text-[var(--color-text-tertiary)]">- {community.member_count} files · cohesion {(community.cohesion * 100).toFixed(0)}%+ // The label and the grouping are both algorithmic. Saying so is the+ // difference between a name the reader trusts too much and one they+ // read as a summary.+ <p className="text-[11px] text-[var(--color-text-secondary)]">+ {community.member_count} files, grouped automatically</p>)}</div><buttononClick={onClose}aria-label="Close community details"- className="p-1 rounded hover:bg-[var(--color-bg-elevated)] transition-colors"+ className="shrink-0 rounded p-1 transition-colors hover:bg-[var(--color-bg-elevated)]"><X className="h-4 w-4 text-[var(--color-text-tertiary)]" /></button></div>- {/* Expand-on-canvas affordance — mirrors the double-click blossom. */}- {onExpandOnCanvas && (- <div className="px-4 py-2 border-b border-[var(--color-border-default)]">+ {onEnterCommunity && (+ <div className="shrink-0 border-b border-[var(--color-border-default)] px-4 py-2"><button- onClick={onExpandOnCanvas}- className="flex w-full items-center justify-center gap-1.5 rounded-md border border-[var(--color-border-default)] px-2 py-1.5 text-xs text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)] transition-colors"+ onClick={onEnterCommunity}+ className="flex w-full items-center justify-center gap-1.5 rounded-md border border-[var(--color-accent-primary)]/30 bg-[var(--color-accent-primary)]/10 px-2 py-1.5 text-xs font-medium text-[var(--color-accent-primary)] transition-colors hover:bg-[var(--color-accent-primary)]/20">- <Sparkles className="h-3 w-3" />- Expand on canvas+ <CornerDownRight className="h-3 w-3" />+ Enter this community</button></div>)}- {/* Content */}{isLoading ? (- <div className="p-4 space-y-2">+ <div className="space-y-2 p-4"><Skeleton className="h-4 w-full" /><Skeleton className="h-4 w-3/4" /><Skeleton className="h-4 w-full" /><Skeleton className="h-4 w-2/3" /></div>) : community ? (- <ScrollArea className="flex-1">- <div className="p-4 space-y-4">- {/* Members */}- <div>- <p className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-2">- Members ({community.member_count})- </p>+ <ScrollArea className="min-h-0 flex-1">+ {/*+ Reading order, and only the first two are open on arrival.++ This used to be five undifferentiated blocks of 11px prose followed+ by thirty member rows and ten neighbour rows, all expanded, so the+ figure that answers "is this area in trouble" scrolled away and the+ rest was noise. The lede and the fact grid answer the question; the+ member list is the audit trail behind those numbers and the+ neighbours are a navigation aid, so both are demoted behind a+ disclosure. Same call `CollapsibleSection` exists for on the file+ health drawer, and the same component.+ */}+ <div className="flex flex-col gap-4 px-4 py-4">+ <HealthLede community={community} codeHealthHref={codeHealthHref} />+ <FactGrid community={community} deadCodeHref={deadCodeHref} />++ <CollapsibleSection+ title="Members"+ hint={+ community.truncated+ ? `${community.members.length} of ${community.member_count}`+ : `${community.members.length}`+ }+ >+ {/* The counts in the grid above are over every member; this is a+ ranked page of them. Without this line a reader counts four+ flames under a headline of twelve. */}+ {community.truncated && (+ <p className="text-[11px] text-[var(--color-text-secondary)]">+ The {community.members.length} most connected. The counts above+ cover all {community.member_count}.+ </p>+ )}<div className="space-y-1">- {community.members.map((m) => {- const maxPr = community.members[0]?.pagerank || 1;- const barWidth = maxPr > 0 ? Math.round((m.pagerank / maxPr) * 100) : 0;-- return (- <div- key={m.path}- className="flex items-center gap-2 py-1 px-1.5 rounded hover:bg-[var(--color-bg-elevated)] transition-colors"- >- <div className="min-w-0 flex-1">- {memberHref ? (- <a- href={memberHref(m.path)}- className="block text-xs font-mono text-[var(--color-text-primary)] truncate hover:text-[var(--color-accent-primary)] hover:underline"- title={m.path}- >- {truncatePath(m.path)}- </a>- ) : (- <p className="text-xs font-mono text-[var(--color-text-primary)] truncate" title={m.path}>- {truncatePath(m.path)}- </p>- )}- </div>- {/* PageRank bar */}- <div className="w-16 h-1.5 rounded-full bg-[var(--color-bg-elevated)] overflow-hidden shrink-0">- <div- className="h-full rounded-full bg-[var(--color-accent)]"- style={{ width: `${barWidth}%` }}- />- </div>- {m.is_entry_point && (- <Badge variant="accent" className="text-[8px] h-3.5 shrink-0">- EP- </Badge>- )}- </div>- );- })}- {community.truncated && (- <p className="text-[10px] text-[var(--color-text-tertiary)] px-1.5 pt-1">- +{community.member_count - community.members.length} more files- </p>- )}+ {community.members.map((m) => (+ <MemberRow+ key={m.path}+ path={m.path}+ pagerank={m.pagerank}+ maxPagerank={community.members[0]?.pagerank || 1}+ isEntryPoint={m.is_entry_point}+ isHotspot={m.is_hotspot}+ isDead={m.is_dead}+ memberHref={memberHref}+ healthHrefFor={healthHrefFor}+ deadCodeHref={deadCodeHref}+ />+ ))}</div>- </div>+ </CollapsibleSection>- {/* Neighboring Communities */}{community.neighboring_communities.length > 0 && (- <div>- <p className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-2">- Neighboring Communities+ <CollapsibleSection+ title="Talks to"+ hint={`${community.neighboring_communities.length}`}+ >+ <p className="text-[11px] text-[var(--color-text-secondary)]">+ Groups this one depends on or is depended on by, most-connected+ first.</p><div className="space-y-1">{community.neighboring_communities.map((n) => (- <div+ <NeighborRowkey={n.community_id}- className="flex items-center justify-between gap-2 py-1 px-1.5 rounded hover:bg-[var(--color-bg-elevated)] transition-colors"- >- <div className="flex items-center gap-1.5 min-w-0">- <ArrowRight className="h-3 w-3 shrink-0 text-[var(--color-text-tertiary)]" />- <span className="text-xs text-[var(--color-text-primary)] truncate">- {n.label}- </span>- </div>- <Badge variant="outline" className="text-[10px] shrink-0 h-4">- {n.cross_edge_count} edges- </Badge>- </div>+ label={n.label}+ crossEdgeCount={n.cross_edge_count}+ onSelect={+ onNeighborSelect+ ? () => onNeighborSelect(n.community_id)+ : undefined+ }+ />))}</div>- </div>+ </CollapsibleSection>)}</div></ScrollArea>) : (<div className="p-4">- <p className="text-xs text-[var(--color-text-tertiary)]">Community not found</p>+ <p className="text-xs text-[var(--color-text-secondary)]">Community not found</p></div>)}</div>);}++/** The lead figure: is this area in trouble? */+function HealthLede({+ community,+ codeHealthHref,+}: {+ community: CommunityDetail;+ codeHealthHref?: string | undefined;+}) {+ const score = community.health_score;+ const scored = community.scored_member_count ?? 0;++ if (score == null) {+ return (+ <div>+ <p className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">+ Health+ </p>+ <p className="mt-1 text-sm text-[var(--color-text-primary)]">Not scored</p>+ <p className="mt-0.5 text-[11px] text-[var(--color-text-secondary)]">+ None of these files carry a health score yet, so this area has no+ reading. That is missing evidence, not a clean bill.+ </p>+ </div>+ );+ }++ const band = healthBand(score);+ return (+ <div>+ <p className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">+ Health+ </p>+ <div className="mt-1 flex flex-wrap items-baseline gap-x-2 gap-y-1">+ <span+ className="text-[32px] font-semibold leading-none tracking-tight tabular-nums"+ style={{ color: band.color }}+ >+ {score.toFixed(1)}+ </span>+ <span className="text-xs text-[var(--color-text-tertiary)]">out of 10</span>+ <span+ className="w-fit rounded-full border px-2 py-0.5 text-[11px] font-medium"+ style={{+ color: band.color,+ borderColor: `color-mix(in srgb, ${band.color} 40%, transparent)`,+ background: `color-mix(in srgb, ${band.color} 9%, transparent)`,+ }}+ >+ {band.label}+ </span>+ </div>+ <p className="mt-1.5 text-[11px] leading-relaxed text-[var(--color-text-secondary)]">+ {HEALTH_READING[band.label]}{" "}+ {/* The mean is over the files that have a score, which is rarely all of+ them. Saying how many stops the figure from claiming more coverage+ than it has. */}+ Averaged over the {scored} of {community.member_count} files that are+ scored, weighted by size.+ {codeHealthHref && (+ <>+ {" "}+ <a+ href={codeHealthHref}+ className="text-[var(--color-accent-primary)] hover:underline"+ >+ Code Health+ </a>+ </>+ )}+ </p>+ </div>+ );+}++/**+ * The state of the area as a hairline fact grid, copying `MetricGrid` on the+ * file health drawer.+ *+ * These were four prose blocks and an icon row. A grid makes "12 files" and+ * "1.4%" scannable as the same kind of news and gives each figure a label,+ * which is what stops the panel reading as a wall of sentences. Explanations+ * that were paragraphs are tooltips: the cohesion figure is unreadable without+ * one and equally unreadable with three lines of prose taking the space above+ * the member list.+ */+function FactGrid({+ community,+ deadCodeHref,+}: {+ community: CommunityDetail;+ deadCodeHref?: string | undefined;+}) {+ const hot = community.hot_count ?? 0;+ const dead = community.dead_count ?? 0;+ const decisions = community.decision_count ?? 0;+ const owner = community.primary_owner;+ const ownerFiles = community.primary_owner_file_count ?? 0;++ const fileWord = (n: number) => (n === 1 ? "file" : "files");++ const cells: { label: string; value: ReactNode; tip?: string }[] = [+ {+ label: "Changes often",+ value: (+ <FactValue muted={hot === 0}>+ {hot === 0 ? "none" : `${hot} ${fileWord(hot)}`}+ </FactValue>+ ),+ tip: "Members git says are churn hotspots. The flames in the member list mark which ones.",+ },+ {+ label: "Unreachable",+ value:+ dead > 0 && deadCodeHref ? (+ <a+ href={deadCodeHref}+ className="text-sm font-semibold tabular-nums text-[var(--color-accent-primary)] hover:underline"+ >+ {dead} {fileWord(dead)}+ </a>+ ) : (+ <FactValue muted={dead === 0}>+ {dead === 0 ? "none" : `${dead} ${fileWord(dead)}`}+ </FactValue>+ ),+ tip: "Members with an open dead-code finding.",+ },+ {+ label: "Under a decision",+ value: (+ <FactValue muted={decisions === 0}>+ {decisions === 0 ? "none" : `${decisions} ${fileWord(decisions)}`}+ </FactValue>+ ),+ tip: "Members named by a recorded architectural decision.",+ },+ {+ label: "Cohesion",+ value: <FactValue>{(community.cohesion * 100).toFixed(1)}%</FactValue>,+ // "depend on", not "import": the edge set behind this is every file+ // dependency kind, so "import" would understate what counted.+ tip: "The share of possible file pairs in this group that actually depend on each other. It drops as a group grows, so it compares groups of similar size rather than a group against the repo.",+ },+ ];++ if (owner) {+ cells.push({+ label: "Mostly owned by",+ value: (+ <span+ className="block truncate text-sm text-[var(--color-text-primary)]"+ title={owner}+ >+ {owner}+ </span>+ ),+ tip: `Primary owner on ${ownerFiles} of these files, from git blame. Most files owned, not most commits.`,+ });+ }++ // Cohesion is 1.0 for a single-file community by definition, so a one-file+ // group would show a perfect score beside a tooltip about pairs.+ const visible =+ community.member_count <= 1 ? cells.filter((c) => c.label !== "Cohesion") : cells;++ return (+ <dl className="grid grid-cols-2 border-y border-[var(--color-border-default)]">+ {visible.map((c, i) => (+ <div+ key={c.label}+ className={[+ "min-w-0 px-3 py-2.5 border-[var(--color-border-default)]",+ // Hairlines between cells only; the outer edges come from border-y+ // on the wrapper, so cells never double up on a boundary.+ i % 2 === 1 ? "border-l" : "",+ i >= 2 ? "border-t" : "",+ ]+ .filter(Boolean)+ .join(" ")}+ >+ <dt className="flex items-center gap-1 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">+ <span className="truncate">{c.label}</span>+ {c.tip && <InfoTip content={c.tip} label={`About ${c.label}`} />}+ </dt>+ <dd className="mt-1">{c.value}</dd>+ </div>+ ))}+ </dl>+ );+}++/** A fact value, greyed when it is a zero: "none" is news too, quieter news. */+function FactValue({ children, muted }: { children: ReactNode; muted?: boolean }) {+ return (+ <span+ className={+ muted+ ? "text-sm tabular-nums text-[var(--color-text-tertiary)]"+ : "text-sm font-semibold tabular-nums text-[var(--color-text-primary)]"+ }+ >+ {children}+ </span>+ );+}++function MemberRow({+ path,+ pagerank,+ maxPagerank,+ isEntryPoint,+ isHotspot,+ isDead,+ memberHref,+ healthHrefFor,+ deadCodeHref,+}: {+ path: string;+ pagerank: number;+ maxPagerank: number;+ isEntryPoint: boolean;+ isHotspot?: boolean | undefined;+ isDead?: boolean | undefined;+ memberHref?: ((path: string) => string) | undefined;+ healthHrefFor?: ((path: string) => string) | undefined;+ deadCodeHref?: string | undefined;+}) {+ const barWidth = maxPagerank > 0 ? Math.round((pagerank / maxPagerank) * 100) : 0;+ const healthHref = isHotspot ? healthHrefFor?.(path) : undefined;++ return (+ <div className="flex items-center gap-2 rounded px-1.5 py-1 transition-colors hover:bg-[var(--color-bg-elevated)]">+ <div className="min-w-0 flex-1">+ {memberHref ? (+ <a+ href={memberHref(path)}+ className="block truncate font-mono text-xs text-[var(--color-text-primary)] hover:text-[var(--color-accent-primary)] hover:underline"+ title={path}+ >+ {truncatePath(path)}+ </a>+ ) : (+ <p+ className="truncate font-mono text-xs text-[var(--color-text-primary)]"+ title={path}+ >+ {truncatePath(path)}+ </p>+ )}+ </div>+ {/* A flagged member links where the flag is explained, which is the only+ per-file scoped exit this panel can offer honestly. */}+ {isHotspot &&+ (healthHref ? (+ <a+ href={healthHref}+ title="Changes often. Open it in Code Health."+ aria-label={`${path} is a churn hotspot; open it in Code Health`}+ className="shrink-0 text-[var(--color-warning)] hover:opacity-80"+ >+ <Flame className="h-3 w-3" />+ </a>+ ) : (+ <Flame+ className="h-3 w-3 shrink-0 text-[var(--color-warning)]"+ aria-label="Churn hotspot"+ />+ ))}+ {isDead &&+ (deadCodeHref ? (+ <a+ href={deadCodeHref}+ title="Flagged unreachable. Open the dead-code findings."+ aria-label={`${path} is flagged unreachable; open the dead-code findings`}+ className="shrink-0 text-[var(--color-text-tertiary)] hover:opacity-80"+ >+ <Skull className="h-3 w-3" />+ </a>+ ) : (+ <Skull+ className="h-3 w-3 shrink-0 text-[var(--color-text-tertiary)]"+ aria-label="Flagged unreachable"+ />+ ))}+ <div className="h-1.5 w-12 shrink-0 overflow-hidden rounded-full bg-[var(--color-bg-elevated)]">+ <div+ className="h-full rounded-full bg-[var(--color-accent)]"+ style={{ width: `${barWidth}%` }}+ />+ </div>+ {isEntryPoint && (+ // Was "EP" at 8px. An abbreviation nothing on screen expands is not a+ // label; the title carries the rest, because a 340px rail cannot.+ <Badge+ variant="accent"+ className="h-4 shrink-0 text-[10px]"+ title="Entry point: something outside this repo calls into this file"+ >+ Entry+ </Badge>+ )}+ </div>+ );+}++function NeighborRow({+ label,+ crossEdgeCount,+ onSelect,+}: {+ label: string;+ crossEdgeCount: number;+ onSelect?: (() => void) | undefined;+}) {+ const body = (+ <>+ <div className="flex min-w-0 items-center gap-1.5">+ <ArrowRight className="h-3 w-3 shrink-0 text-[var(--color-text-tertiary)]" />+ <span className="truncate text-xs text-[var(--color-text-primary)]">{label}</span>+ </div>+ <Badge variant="outline" className="h-4 shrink-0 text-[10px]">+ {crossEdgeCount} edges+ </Badge>+ </>+ );++ // These rows looked clickable and were not: plain divs with a hover tint and+ // no handler. They are buttons when the host can navigate, and plain rows+ // when it cannot.+ return onSelect ? (+ <button+ type="button"+ onClick={onSelect}+ className="flex w-full items-center justify-between gap-2 rounded px-1.5 py-1 text-left transition-colors hover:bg-[var(--color-bg-elevated)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"+ >+ {body}+ </button>+ ) : (+ <div className="flex items-center justify-between gap-2 rounded px-1.5 py-1">{body}</div>+ );+}diff --git a/packages/ui/src/graph/graph-context-menu.tsx b/packages/ui/src/graph/graph-context-menu.tsxindex 4f8dc7991..9e0f6fa2b 100644--- a/packages/ui/src/graph/graph-context-menu.tsx+++ b/packages/ui/src/graph/graph-context-menu.tsx@@ -28,7 +28,10 @@ export const GraphContextMenu = memo(function GraphContextMenu({return (<div- className="fixed z-50 min-w-[200px] rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)] shadow-xl shadow-black/40 backdrop-blur-md py-1 text-xs"+ // `--z-modal`, because this is `fixed` and has to clear the rail+ // (`--z-sidebar`); `--z-dropdown` sits below it and would put the menu+ // behind an open panel.+ className="fixed z-[var(--z-modal)] min-w-[200px] rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)] shadow-xl shadow-black/40 backdrop-blur-md py-1 text-xs"style={{ left: x, top: y }}><div className="px-3 py-1.5 text-[10px] text-[var(--color-text-tertiary)] font-mono truncate border-b border-[var(--color-border-default)] mb-1">diff --git a/packages/ui/src/graph/graph-doc-panel.tsx b/packages/ui/src/graph/graph-doc-panel.tsxindex a4a582635..c1eafc934 100644--- a/packages/ui/src/graph/graph-doc-panel.tsx+++ b/packages/ui/src/graph/graph-doc-panel.tsx@@ -26,9 +26,12 @@ export interface GraphDocPanelProps {isLoading: boolean;/** Truthy when no doc page exists for this node. */error?: unknown;- /** Href for the "open full page" external-link icon. Provided by consumer. */+ /** Href for the file's own page. Also the empty state's way out: that page+ * renders history, health, symbols and graph position for a file with no+ * written documentation, so it is a real destination rather than a+ * consolation link. */fullPageHref?: string;- /** Href for the "browse all docs" fallback link inside the empty state. */+ /** Href for the docs reading surface, offered when there is no file page. */browseDocsHref?: string;onClose: () => void;}@@ -113,16 +116,35 @@ export function GraphDocPanel({{Boolean(error) && !isLoading && (<div className="flex flex-col items-center justify-center h-32 gap-2 px-6 text-center"><AlertCircle className="h-5 w-5 text-[var(--color-text-tertiary)]" />- <p className="text-xs text-[var(--color-text-tertiary)]">- No documentation found for this file.+ {/* Same words as the file page's own empty state+ (`files/file-doc-tab.tsx`), because one absence should not have+ two vocabularies. "Not found" also read as a failure; a file+ with no extracted symbols that is neither an entry point nor a+ hotspot is deliberately not given a page. */}+ <p className="text-xs font-medium text-[var(--color-text-secondary)]">+ No documentation page for this file</p>- {browseDocsHref && (+ <p className="text-[11px] text-[var(--color-text-tertiary)]">+ Repowise writes pages for the files that carry a repository's+ shape. Everything else it knows about this one is still on the+ file's own page.+ </p>+ {fullPageHref ? (<a- href={browseDocsHref}+ href={fullPageHref}className="text-xs text-[var(--color-accent-primary)] hover:underline">- Browse all docs+ Open the file page</a>+ ) : (+ browseDocsHref && (+ <a+ href={browseDocsHref}+ className="text-xs text-[var(--color-accent-primary)] hover:underline"+ >+ Browse all docs+ </a>+ ))}</div>)}diff --git a/packages/ui/src/graph/graph-flow.tsx b/packages/ui/src/graph/graph-flow.tsxindex cf28f78be..80ccdd0b1 100644--- a/packages/ui/src/graph/graph-flow.tsx+++ b/packages/ui/src/graph/graph-flow.tsx@@ -23,15 +23,17 @@ const HUB_FOCUS_RATIO = 0.45;// build in chunks off the critical path (see sigmaGraph below).const ASYNC_BUILD_THRESHOLD = 1000;-import { useExpandedHubs } from "./use-expanded-hubs";+import { usePrefersReducedMotion } from "../hooks/use-prefers-reduced-motion";+import { GraphScopeBreadcrumb } from "./graph-scope-breadcrumb";import { traceToEdgeKeys, traceToFileTrace } from "./graph-flow-helpers";import { useGraphContextMenu } from "./use-graph-context-menu";import { useGraphSearch } from "./use-graph-search";import { useCommunityFilter } from "./use-community-filter";-import { useModuleFilter } from "./use-module-filter";+import { useModuleFilter, filterGraphToModule } from "./use-module-filter";import { useGraphKeyboardShortcuts } from "./use-graph-keyboard-shortcuts";import { GraphToolbar, type ColorMode, type ViewMode, type LayoutMode, type GraphTheme } from "./graph-toolbar";import { GraphLegend } from "./graph-legend";+import { GraphNodeFilter } from "./graph-toolbar";import { GraphCanvasShell } from "./graph-canvas-shell";import { GraphContextMenu } from "./graph-context-menu";import { GraphInspectionPanel } from "./graph-inspection-panel";@@ -49,11 +51,7 @@ import {fileGraphToGraphology,fileGraphToGraphologyAsync,} from "./sigma/graphology-adapter";-import {- architectureToGraphology,- hubNodeId,- mergeCommunitySlice,-} from "./sigma/constellation-adapter";+import { architectureToGraphology, hubNodeId } from "./sigma/constellation-adapter";import { computeRadialLayout } from "./sigma/radial-layout";import { ELK_MAX_NODES, elkSkipReason } from "./sigma/use-elk-sigma-layout";import type { SigmaNodeAttributes, SigmaEdgeAttributes } from "./sigma/types";@@ -72,12 +70,23 @@ export interface GraphFlowProps {/** Community super-graph for the constellation (radial Knowledge Graph) scope. */constellationGraph?: ArchitectureGraph | undefined;isLoadingConstellationGraph?: boolean;- /** Member slices for currently-expanded hubs, keyed by community_id. The host- * fetches these in response to {@link onExpandedHubsChange}. */+ /** @deprecated Unread. Hubs no longer blossom satellites in place: a+ * double-click *enters* the community and draws its own file graph. See+ * {@link communitySlice}. Kept optional so a host compiles while it drops it. */constellationSlices?: Map<number, CommunitySlice> | undefined;- /** Fired when the set of expanded constellation hubs changes, so the host can- * fetch the corresponding slices. */+ /** @deprecated Unread. See {@link onActiveCommunityChange}. */onExpandedHubsChange?: (expanded: number[]) => void;+ /** The community currently being drilled into, or null for the whole scope.+ * Controlled by the host, which URL-syncs it as `?community=`. */+ activeCommunity?: number | null | undefined;+ /** Fired when the reader enters or leaves a community (hub double-click, the+ * panel's Enter action, the breadcrumb, Escape). The host writes `?community=`+ * and, on entry, switches the scope to files. */+ onActiveCommunityChange?: ((communityId: number | null) => void) | undefined;+ /** The entered community's own sub-graph: its members plus one-hop boundary+ * stubs. Fetched by the host in response to {@link onActiveCommunityChange}. */+ communitySlice?: CommunitySlice | undefined;+ isLoadingCommunitySlice?: boolean | undefined;/** Repo name for the constellation core label. */repoName?: string;deadCodeGraph: GraphExport | undefined;@@ -125,6 +134,14 @@ export interface GraphFlowProps {/** Canonical file-page href for a file node — renders an "Open file page"* action in the inspection panel. */fileHrefFor?: (nodeId: string) => string;+ /** Per-file destinations for the inspector's outbound actions: where this+ * file's health, git history and decisions live. Optional; each action is+ * hidden when the host does not supply it. */+ fileHealthHrefFor?: ((nodeId: string) => string) | undefined;+ fileHistoryHrefFor?: ((nodeId: string) => string) | undefined;+ fileDecisionsHrefFor?: ((nodeId: string) => string) | undefined;+ /** The repo's dead-code findings. Offered only on a node flagged dead. */+ deadCodeHref?: string | undefined;renderPathFinder?: (props: {initialFrom: string;initialTo: string;@@ -135,8 +152,10 @@ export interface GraphFlowProps {renderCommunityPanel?: (props: {communityId: number;onClose: () => void;- /** Blossom this community's files on the canvas (expand affordance). */- onExpandOnCanvas: () => void;+ /** Draw this community's own scoped file graph (the drill-down). */+ onEnterCommunity: () => void;+ /** Open a neighbouring community's panel, without leaving the canvas. */+ onNeighborSelect: (communityId: number) => void;}) => ReactNode;/** Fired when the community detail panel transitions to open. */onCommunityPanelOpen?: (communityId: number) => void;@@ -146,7 +165,8 @@ export interface GraphFlowProps {onSelectedNodeChange?: ((nodeId: string | null) => void) | undefined;/** One-line explanation of the current scope, shown in the header row. */description?: string;- /** Host controls placed left of the toolbar (scope switcher, module filter). */+ /** Host controls placed left of the toolbar (scope switcher, narrowing+ * control). */headerActions?: ReactNode;/** Full-width notice above the canvas (e.g. the truncation banner). */banner?: ReactNode;@@ -161,8 +181,10 @@ export function GraphFlow(props: GraphFlowProps) {isLoadingFullGraph,constellationGraph,isLoadingConstellationGraph,- constellationSlices,- onExpandedHubsChange,+ activeCommunity: controlledActiveCommunity,+ onActiveCommunityChange,+ communitySlice,+ isLoadingCommunitySlice,repoName,deadCodeGraph,isLoadingDeadCodeGraph,@@ -184,6 +206,10 @@ export function GraphFlow(props: GraphFlowProps) {onNodeViewDocs,onNodeViewSymbols,fileHrefFor,+ fileHealthHrefFor,+ fileHistoryHrefFor,+ fileDecisionsHrefFor,+ deadCodeHref,renderPathFinder,renderCommunityPanel,onCommunityPanelOpen,@@ -241,28 +267,52 @@ export function GraphFlow(props: GraphFlowProps) {const [egoDepth, setEgoDepth] = useState(0);+ // How much of a found path this view cannot draw. See `handlePathFound`.+ const [pathNotice, setPathNotice] = useState<string | null>(null);++ // Both structural kinds, because the description under every file-scope+ // reading promises "how they depend on each other". The old default was+ // `["import", "crossCommunity"]`, and `"import"` was an unreachable+ // classification — `classifyEdge` returned it only for an edge whose+ // endpoint was missing from the graph, and those are dropped before they are+ // drawn. So the default meant "cross-community only", and inside a community+ // that hid the entire internal structure and drew only the exits.+ //+ // This raises the whole-repo default too, deliberately: measured on this+ // repo's own 1,500-node graph it goes from 1,052 to 5,027 drawn edges, an+ // average degree of 3.35, well short of a hairball and the difference+ // between drawing 21% of the structure and all of it.const [visibleEdgeTypes, setVisibleEdgeTypes] = useState<Set<string>>(- () => new Set(["import", "crossCommunity"]),+ () => new Set(["crossCommunity", "internal"]),);// Signal overlays (replaces separate view modes for dead/hot/arch).// Derived from the host-provided initial view mode — no URL reads here.- const [activeSignals, setActiveSignals] = useState<Set<Signal>>(() => {+ const activeSignals = useMemo<Set<Signal>>(() => {if (initialViewMode === "dead") return new Set<Signal>(["dead"]);if (initialViewMode === "hotfiles") return new Set<Signal>(["hot"]);if (initialViewMode === "unified") return new Set<Signal>(["dead", "hot"]);return new Set<Signal>();- });+ }, [initialViewMode]);const hideTests = activeSignals.has("hideTests");- // Expand/collapse constellation hubs (radial blossom). Esc collapses the most- // recently expanded hub; multiple hubs may be open at once.- const { expandedHubs, toggleHub, collapseLast, collapseAll: collapseAllHubs } =- useExpandedHubs();+ // Drill-down: the community whose own file graph is drawn.+ // (reconciliation effect lives below, once the panel state exists) The host owns it+ // (`?community=`); the local fallback keeps an uncontrolled host working.+ const [activeCommunityState, setActiveCommunityState] = useState<number | null>(null);+ const activeCommunity =+ controlledActiveCommunity !== undefined+ ? controlledActiveCommunity+ : activeCommunityState;+ const setActiveCommunity = useCallback(+ (next: number | null) => {+ if (onActiveCommunityChange) onActiveCommunityChange(next);+ else setActiveCommunityState(next);+ },+ [onActiveCommunityChange],+ );- useEffect(() => {- onExpandedHubsChange?.(expandedHubs);- }, [expandedHubs, onExpandedHubsChange]);+ const prefersReducedMotion = usePrefersReducedMotion();// Context menu (state + dismiss-on-click/Escape lifecycle)const { ctxMenu, setCtxMenu } = useGraphContextMenu();@@ -325,64 +375,87 @@ export function GraphFlow(props: GraphFlowProps) {[openCommunityPanel],);- // Hub double-click toggles the blossom: expand eases the camera to frame the- // cluster (and opens the panel); collapse just folds it back.- const handleConstellationHubToggle = useCallback(+ // Scope changes arrive from the toolbar, the host's switcher, and the+ // drill-down below, so it lives above all three.+ const handleViewChange = useCallback((v: ViewMode) => {+ setViewModeState(v);+ onViewModeChange?.(v);+ }, [onViewModeChange]);++ // Hub double-click ENTERS the community: the canvas swaps to that community's+ // own file graph, scoped, with its one-hop neighbours as the edge of the+ // world. The hub used to blossom satellites in place, which showed you the+ // files without ever letting you work on them.+ //+ // Camera continuity is what makes this read as one movement. The hub's+ // position is handed to the renderer as the point the *next* graph opens+ // from, so the scoped layout eases outward from where the disc was rather+ // than cutting to a fresh frame. `prefers-reduced-motion` skips the travel.+ const enterCommunity = useCallback((cid: number) => {- const willExpand = !expandedHubs.includes(cid);- toggleHub(cid);- if (willExpand) {- const nodeId = hubNodeId(cid);- setSelectedNodeId(nodeId);- sigmaRef.current?.focusNode(nodeId, HUB_FOCUS_RATIO);- openCommunityPanel(cid);+ const nodeId = hubNodeId(cid);+ if (!prefersReducedMotion) {+ // Tighter than HUB_FOCUS_RATIO: the movement opens *out* of the hub.+ sigmaRef.current?.setEntryCamera(sigmaRef.current.nodeCamera(nodeId, 0.08));}+ setSelectedNodeId(null);+ setPathNotice(null);+ setActiveCommunity(cid);+ openCommunityPanel(cid);+ // Files scope, since a community's members are files. A controlled host+ // reflects this back through `viewMode`.+ handleViewChange("full");},- [expandedHubs, toggleHub, openCommunityPanel],+ [prefersReducedMotion, setActiveCommunity, openCommunityPanel, handleViewChange],);+ /** Back out of a community to the constellation it came from. */+ const leaveCommunity = useCallback(() => {+ // Drop any entry camera that was armed but never consumed (an entry whose+ // slice failed to arrive), so it cannot seed an unrelated later swap.+ sigmaRef.current?.setEntryCamera(null);+ setSelectedNodeId(null);+ setCommunityPanelId(null);+ setActiveCommunity(null);+ handleViewChange("architecture");+ }, [setActiveCommunity, handleViewChange]);++ // The community can also change from outside this component: the narrowing+ // control writes `?community=` directly, the scope switcher clears it, and a+ // shared link arrives with one already set. Those routes never run+ // `enterCommunity`/`leaveCommunity`, so a panel describing the community you+ // just left would stay in the rail, and an armed entry camera would survive+ // to seed an unrelated later graph swap.+ const appliedCommunityRef = useRef(activeCommunity);+ useEffect(() => {+ const previous = appliedCommunityRef.current;+ if (previous === activeCommunity) return;+ appliedCommunityRef.current = activeCommunity;+ // Only the panel for the community being left; `enterCommunity` has already+ // pointed it at the new one by the time this runs.+ setCommunityPanelId((open) => (open !== null && open === previous ? null : open));+ if (activeCommunity === null) sigmaRef.current?.setEntryCamera(null);+ }, [activeCommunity]);+// ---- Derived state ----const isUnified = viewMode === "unified";// The "architecture" scope renders the radial community constellation.const isConstellation = viewMode === "architecture";// Constellation graph: one hub per community + repo-core, radial positions.- // When hubs are expanded, blossom each one's member slice as satellites- // (deterministic radial math, no FA2). Rebuilt fresh each time (the adapter- // is pure + the merge mutates only the new instance), so the memo stays pure.const constellationSigmaGraph = useMemo(() => {if (!isConstellation || !constellationGraph) return null;- const graph = architectureToGraphology(+ return architectureToGraphology(constellationGraph,repoName ? { repoName } : {},);- if (constellationSlices) {- for (const cid of expandedHubs) {- const slice = constellationSlices.get(cid);- if (slice) mergeCommunitySlice(graph, cid, slice);- }- }- return graph;- }, [isConstellation, constellationGraph, repoName, expandedHubs, constellationSlices]);-- // Nodes to dim while any hub is expanded: every hub disc NOT in the expanded- // set (and the repo-core), so the open cluster(s) read as foreground. Reuses- // the dimColor machinery via the dedicated expand-dim channel.- const expandDimmedNodes = useMemo(() => {- if (!isConstellation || expandedHubs.length === 0 || !constellationGraph) {- return null;- }- const expandedSet = new Set(expandedHubs);- const dimmed = new Set<string>();- for (const n of constellationGraph.nodes) {- if (!expandedSet.has(n.community_id)) dimmed.add(hubNodeId(n.community_id));- }- return dimmed;- }, [isConstellation, expandedHubs, constellationGraph]);+ }, [isConstellation, constellationGraph, repoName]);// Ring radii for the depth-ring underlay (graph coordinates).const constellationRingRadii = useMemo(() => {- if (!isConstellation || !constellationGraph) return null;+ // Not gated on the scope: the held frame during a drill-down is still the+ // constellation, and rings that vanish out from under it read as a glitch.+ if (!constellationGraph) return null;return computeRadialLayout(constellationGraph.nodes.map((n) => ({community_id: n.community_id,@@ -390,7 +463,7 @@ export function GraphFlow(props: GraphFlowProps) {avg_pagerank: n.avg_pagerank,})),).ringRadii;- }, [isConstellation, constellationGraph]);+ }, [constellationGraph]);const communityLabels = useMemo(() => {if (!communities) return undefined;@@ -412,13 +485,31 @@ export function GraphFlow(props: GraphFlowProps) {}));}, [constellationGraph]);- // File-level graph data for each scope- const fileGraphData = useMemo(() => {+ // Whether a community is actually being drawn: `?community=` only means+ // anything on a file-level scope, so a stale one carried into the+ // constellation is ignored rather than half-applied.+ const isInsideCommunity = !isConstellation && activeCommunity !== null;++ // "This community talks to that one; take me there." From the constellation+ // that means selecting the neighbour hub and framing it; from inside a+ // community it means entering the neighbour, because that is the altitude+ // the reader is already at.+ const handleNeighborSelect = useCallback(+ (cid: number) => {+ if (isInsideCommunity) enterCommunity(cid);+ else handleConstellationHubClick(cid);+ },+ [isInsideCommunity, enterCommunity, handleConstellationHubClick],+ );++ // The file-level payload *before* narrowing. The module group list is derived+ // from this, so choosing a module never empties the menu it came from.+ const scopeGraphData = useMemo(() => {switch (viewMode) {case "full":case "unified":return fullGraph ? { nodes: fullGraph.nodes, links: fullGraph.links } : undefined;- // "architecture" now renders the radial constellation, not a file graph.+ // "architecture" renders the radial constellation, not a file graph.case "dead":return deadCodeGraph? { nodes: deadCodeGraph.nodes, links: deadCodeGraph.links }@@ -432,8 +523,32 @@ export function GraphFlow(props: GraphFlowProps) {}}, [viewMode, fullGraph, deadCodeGraph, hotFilesGraph]);+ // Boundary stubs of the entered community: one-hop neighbours the slice+ // carries as context. Drawn smaller and desaturated, so the scoped graph has+ // an edge instead of trailing off into nothing.+ const sliceBoundaryIds = useMemo(() => {+ if (!isInsideCommunity || !communitySlice) return undefined;+ const ids = new Set<string>();+ for (const n of communitySlice.nodes) if (n.is_boundary) ids.add(n.node_id);+ return ids.size > 0 ? ids : undefined;+ }, [isInsideCommunity, communitySlice]);++ // What actually gets built and drawn. A community replaces the payload+ // outright (it is its own graph, not a view of the capped one); a module+ // narrows it. They are one axis and never both apply.+ const fileGraphData = useMemo(() => {+ if (isInsideCommunity) {+ return communitySlice+ ? { nodes: communitySlice.nodes, links: communitySlice.links }+ : undefined;+ }+ if (!scopeGraphData) return undefined;+ return filterGraphToModule(scopeGraphData, controlledActiveModule ?? null);+ }, [isInsideCommunity, communitySlice, scopeGraphData, controlledActiveModule]);+// Loading stateconst isLoading =+ isInsideCommunity ? !!isLoadingCommunitySlice :viewMode === "full" || viewMode === "unified" ? isLoadingFullGraph :viewMode === "architecture" ? !!isLoadingConstellationGraph :viewMode === "dead" ? isLoadingDeadCodeGraph :@@ -479,9 +594,9 @@ export function GraphFlow(props: GraphFlowProps) {return fileGraphToGraphology({ nodes: graphData.nodes, links: graphData.links },- { signals },+ { signals, ...(sliceBoundaryIds ? { boundaryNodeIds: sliceBoundaryIds } : {}) },);- }, [fileGraphData, hasHotSignal, hasDeadSignal, isUnified, hotNodeIds, deadNodeIds]);+ }, [fileGraphData, hasHotSignal, hasDeadSignal, isUnified, hotNodeIds, deadNodeIds, sliceBoundaryIds]);// Async-built file graph for large graphs (built in chunks off the main// thread critical path). Null while building / when the sync path applies.@@ -519,7 +634,7 @@ export function GraphFlow(props: GraphFlowProps) {void fileGraphToGraphologyAsync({ nodes: fileGraphData.nodes, links: fileGraphData.links },- { signals },+ { signals, ...(sliceBoundaryIds ? { boundaryNodeIds: sliceBoundaryIds } : {}) },).then((graph) => {if (cancelled) return;setAsyncSigmaGraph(graph);@@ -529,26 +644,46 @@ export function GraphFlow(props: GraphFlowProps) {return () => {cancelled = true;};- }, [needsAsyncBuild, fileGraphData, hasHotSignal, hasDeadSignal, isUnified, hotNodeIds, deadNodeIds]);+ }, [needsAsyncBuild, fileGraphData, hasHotSignal, hasDeadSignal, isUnified, hotNodeIds, deadNodeIds, sliceBoundaryIds]);const sigmaGraph = isConstellation? constellationSigmaGraph: (syncSigmaGraph ?? asyncSigmaGraph);+ // Entering a community swaps the payload, and the slice is a round trip.+ // Blanking to a skeleton in between would unmount the renderer, and with it+ // the camera that makes the drill-down read as one movement rather than two+ // pages. So the last frame is held until the slice lands, and only for that+ // transition — every other empty graph still reports itself honestly.+ const heldGraphRef = useRef<GraphologyGraph<+ SigmaNodeAttributes,+ SigmaEdgeAttributes+ > | null>(null);+ if (sigmaGraph) heldGraphRef.current = sigmaGraph;+ // Gated on the fetch actually being in flight. Holding on `!communitySlice`+ // alone meant a *failed* slice pinned the previous frame forever: SWR leaves+ // `data` undefined and `isLoading` false between retries, so the constellation+ // stayed drawn under a breadcrumb and a description both asserting a scoped+ // file graph, with no error and no empty state anywhere.+ const isEnteringCommunity =+ isInsideCommunity && !communitySlice && !!isLoadingCommunitySlice;+ const displayGraph =+ sigmaGraph ?? (isEnteringCommunity ? heldGraphRef.current : null);+const { hiddenNodes, isActive: isEgoActive, visibleCount: egoVisibleCount } = useEgoFilter({- graph: sigmaGraph,+ graph: displayGraph,selectedNodeId,depth: egoDepth,});// Node data maps (sorted metrics moved into GraphInspectionPanel)const sigmaNodeMaps = useMemo(() => {- if (!sigmaGraph) return null;+ if (!displayGraph) return null;const fileMap = new Map<string, FileNodeData>();const modMap = new Map<string, ModuleNodeData>();- sigmaGraph.forEachNode((nodeId, attrs) => {+ displayGraph.forEachNode((nodeId, attrs) => {if (attrs.nodeType === "file") {const fileData: FileNodeData = {nodeType: "file",@@ -565,6 +700,7 @@ export function GraphFlow(props: GraphFlowProps) {};if (attrs.isHotspot) fileData.isHotspot = true;if (attrs.isDead) fileData.isDead = true;+ if (attrs.hasDecision) fileData.hasDecision = true;fileMap.set(nodeId, fileData);} else if (attrs.nodeType === "module") {modMap.set(nodeId, {@@ -585,7 +721,7 @@ export function GraphFlow(props: GraphFlowProps) {});return { fileMap, modMap };- }, [sigmaGraph]);+ }, [displayGraph]);const effectiveNodeDataMap = sigmaNodeMaps?.fileMap ?? new Map<string, FileNodeData>();const effectiveModuleDataMap = sigmaNodeMaps?.modMap ?? new Map<string, ModuleNodeData>();@@ -593,27 +729,32 @@ export function GraphFlow(props: GraphFlowProps) {// How many flagged nodes actually made it into the rendered graph — paired// with the repo-wide totals to caption the dead/hot views honestly.const overlayStats = useMemo(() => {- if (!sigmaGraph) return null;+ if (!displayGraph) return null;let deadInView = 0;let hotInView = 0;- sigmaGraph.forEachNode((_, attrs) => {+ displayGraph.forEachNode((_, attrs) => {if (attrs.isDead) deadInView++;if (attrs.isHotspot) hotInView++;});return { deadInView, hotInView };- }, [sigmaGraph]);+ }, [displayGraph]);- const isDeadView = viewMode === "dead" || viewMode === "unified";- const isHotView = viewMode === "hotfiles" || viewMode === "unified";+ // A community slice is its own payload and was never filtered to dead or hot+ // files, so the signal captions must not describe it. Reachable from+ // `?view=files&signal=dead` plus a community pick.+ const isDeadView =+ !isInsideCommunity && (viewMode === "dead" || viewMode === "unified");+ const isHotView =+ !isInsideCommunity && (viewMode === "hotfiles" || viewMode === "unified");// Trace nodes of the selected execution flow that fell outside the loaded// node set — highlighting/focus silently no-op for them, so tell the user.const activeFlowMissingCount = useMemo(() => {- if (activeFlowIdx === null || !executionFlows || !sigmaGraph) return 0;+ if (activeFlowIdx === null || !executionFlows || !displayGraph) return 0;const flow = executionFlows.flows[activeFlowIdx];if (!flow) return 0;- return traceToFileTrace(flow.trace).filter((id) => !sigmaGraph.hasNode(id)).length;- }, [activeFlowIdx, executionFlows, sigmaGraph]);+ return traceToFileTrace(flow.trace).filter((id) => !displayGraph.hasNode(id)).length;+ }, [activeFlowIdx, executionFlows, displayGraph]);// Empty-state copy for a dead/hot view that resolved to zero nodes. Two// different failure modes deserve two different messages: the repo really@@ -651,43 +792,37 @@ export function GraphFlow(props: GraphFlowProps) {// Search (Fuse index + debounced query + result navigation)const { searchQuery, setSearchQuery, searchResults, searchDimmedNodes, handleSearchKeyDown } =- useGraphSearch({ sigmaGraph, hideTests, panToNode, setSelectedNodeId });+ useGraphSearch({ sigmaGraph: displayGraph, hideTests, panToNode, setSelectedNodeId });// Community filter (active communities + dimming + legend toggles)- const { activeCommunities, communityDimmedNodes, handleCommunityToggle, handleToggleAllCommunities } =- useCommunityFilter(sigmaGraph);-- // Module filter (path-prefix dimming). Replaces the old Modules *scope*: the- // control lives in the section header and the host owns the selection, so- // only the dimming derivation happens here.- const { moduleGroups, moduleDimmedNodes, handleModuleChange } = useModuleFilter(sigmaGraph);- useEffect(() => {- handleModuleChange(controlledActiveModule ?? null);- }, [controlledActiveModule, handleModuleChange]);+ const {+ activeCommunities,+ communityDimmedNodes,+ drawnCommunityIds,+ handleCommunityToggle,+ handleToggleAllCommunities,+ } = useCommunityFilter(displayGraph);++ // Module groups, offered to the host's narrowing control. Derived from the+ // scope's *unfiltered* payload: the filter now removes nodes rather than+ // dimming them, so deriving the menu from the drawn graph would leave one+ // option in it the moment you used it.+ const { moduleGroups } = useModuleFilter(+ isInsideCommunity ? undefined : scopeGraphData?.nodes,+ controlledActiveModule ?? null,+ );useEffect(() => {onModuleGroupsChange?.(moduleGroups);}, [moduleGroups, onModuleGroupsChange]);- // The module filter and the community filter answer the same question — "is- // this node outside what I asked for?" — so they share the one dim channel- // and compose as an AND. Two independent dim levels would just muddy the- // canvas with three shades of "not this".- const filterDimmedNodes = useMemo(() => {- if (!communityDimmedNodes) return moduleDimmedNodes;- if (!moduleDimmedNodes) return communityDimmedNodes;- const union = new Set(communityDimmedNodes);- for (const id of moduleDimmedNodes) union.add(id);- return union;- }, [communityDimmedNodes, moduleDimmedNodes]);-// Flow index whose trace head has already been focused, so the deferred// re-focus below fires at most once per selection and never re-steers the// camera on later graph changes while the same flow stays active.const flowFocusedRef = useRef<number | null>(null);// Live graph handle for the focus timer (the effect below deliberately- // keeps sigmaGraph out of its deps).- const sigmaGraphRef = useRef(sigmaGraph);- sigmaGraphRef.current = sigmaGraph;+ // keeps displayGraph out of its deps).+ const drawnGraphRef = useRef(displayGraph);+ drawnGraphRef.current = displayGraph;// Execution flow highlightinguseEffect(() => {@@ -709,7 +844,7 @@ export function GraphFlow(props: GraphFlowProps) {focusTimerRef.current = undefined;const firstNode = fileTrace[0];if (!firstNode) return;- if (sigmaGraphRef.current?.hasNode(firstNode)) {+ if (drawnGraphRef.current?.hasNode(firstNode)) {flowFocusedRef.current = activeFlowIdx;sigmaRef.current?.focusNode(firstNode);}@@ -733,10 +868,10 @@ export function GraphFlow(props: GraphFlowProps) {if (focusTimerRef.current !== undefined) return;const trace = executionFlows?.flows[activeFlowIdx]?.trace;const firstNode = trace ? traceToFileTrace(trace)[0] : undefined;- if (!firstNode || !sigmaGraph?.hasNode(firstNode)) return;+ if (!firstNode || !displayGraph?.hasNode(firstNode)) return;flowFocusedRef.current = activeFlowIdx;sigmaRef.current?.focusNode(firstNode);- }, [activeFlowIdx, executionFlows, sigmaGraph]);+ }, [activeFlowIdx, executionFlows, displayGraph]);// ---- Handlers ----@@ -748,10 +883,10 @@ export function GraphFlow(props: GraphFlowProps) {// double-click zoom; core returns void so the zoom-jump is kept.const handleSigmaDoubleClick = useCallback((nodeId: string, nodeType: string): boolean | void => {- if (nodeType === "hub" && sigmaGraph?.hasNode(nodeId)) {- const cid = sigmaGraph.getNodeAttribute(nodeId, "communityId");+ if (nodeType === "hub" && displayGraph?.hasNode(nodeId)) {+ const cid = displayGraph.getNodeAttribute(nodeId, "communityId");if (typeof cid === "number" && cid >= 0) {- handleConstellationHubToggle(cid);+ enterCommunity(cid);return true;}return;@@ -760,7 +895,7 @@ export function GraphFlow(props: GraphFlowProps) {onNodeViewDocs?.(nodeId);return true;},- [onNodeViewDocs, sigmaGraph, handleConstellationHubToggle],+ [onNodeViewDocs, displayGraph, enterCommunity],);// Unified grammar — SINGLE CLICK = select + inspect (never structural):@@ -774,8 +909,8 @@ export function GraphFlow(props: GraphFlowProps) {(nodeId: string, nodeType: string) => {if (nodeType === "core") return;if (selectedNodeId === nodeId) return;- if (nodeType === "hub" && sigmaGraph?.hasNode(nodeId)) {- const cid = sigmaGraph.getNodeAttribute(nodeId, "communityId");+ if (nodeType === "hub" && displayGraph?.hasNode(nodeId)) {+ const cid = displayGraph.getNodeAttribute(nodeId, "communityId");if (typeof cid === "number" && cid >= 0) {setSelectedNodeId(nodeId);sigmaRef.current?.focusNode(nodeId, HUB_FOCUS_RATIO);@@ -788,7 +923,7 @@ export function GraphFlow(props: GraphFlowProps) {// the rail rather than outranking the inspector forever.setCommunityPanelId(null);},- [selectedNodeId, sigmaGraph, openCommunityPanel],+ [selectedNodeId, displayGraph, openCommunityPanel],);const handleSigmaNodeContextMenu = useCallback(@@ -825,12 +960,12 @@ export function GraphFlow(props: GraphFlowProps) {setEgoDepth(0);return true;}- if (isConstellation && expandedHubs.length > 0) {- collapseLast();+ if (isInsideCommunity) {+ leaveCommunity();return true;}return false;- }, [showShortcutHelp, selectedNodeId, communityPanelId, isConstellation, expandedHubs.length, collapseLast]);+ }, [showShortcutHelp, selectedNodeId, communityPanelId, isInsideCommunity, leaveCommunity]);const handleToggleShortcutHelp = useCallback(() => {setShowShortcutHelp((s) => !s);@@ -853,10 +988,23 @@ export function GraphFlow(props: GraphFlowProps) {(pathNodes: string[]) => {setHighlightedPath(new Set(pathNodes));setHighlightedEdges(traceToEdgeKeys(pathNodes));+ // The path endpoint is repo-wide while the canvas may be a module filter+ // or one community, so a path can legitimately run through files this+ // view does not draw. `focusNode` no-ops on those, which read as the+ // control doing nothing. Focus the first file that IS here, and say how+ // many are not — the same courtesy the flows panel already extends.+ const graph = drawnGraphRef.current;+ const drawn = graph ? pathNodes.filter((id) => graph.hasNode(id)) : pathNodes;+ const missing = pathNodes.length - drawn.length;+ setPathNotice(+ missing > 0+ ? `${missing} of ${pathNodes.length} files on this path are outside the current view.`+ : null,+ );clearTimeout(focusTimerRef.current);focusTimerRef.current = setTimeout(() => {- if (pathNodes.length > 0) {- sigmaRef.current?.focusNode(pathNodes[0]!);+ if (drawn.length > 0) {+ sigmaRef.current?.focusNode(drawn[0]!);}}, 800);},@@ -866,17 +1014,13 @@ export function GraphFlow(props: GraphFlowProps) {const handlePathClear = useCallback(() => {setHighlightedPath(new Set());setHighlightedEdges(new Set());+ setPathNotice(null);}, []);const handleFitView = useCallback(() => {sigmaRef.current?.fitView();}, []);- const handleViewChange = useCallback((v: ViewMode) => {- setViewModeState(v);- onViewModeChange?.(v);- }, [onViewModeChange]);-// Everything a scope change has to clear, in one place. Scope can now arrive// from the host (the section-header switcher, URL-synced) as well as from the// toolbar's overlay buttons, so this reacts to the resolved value rather than@@ -892,32 +1036,26 @@ export function GraphFlow(props: GraphFlowProps) {setLayoutNotice(null);setHighlightedPath(new Set());setHighlightedEdges(new Set());+ // Measured against the graph being replaced, so it retires with it.+ setPathNotice(null);setSelectedNodeId(null);- // Leaving the constellation collapses any open blossoms.- if (viewMode !== "architecture") collapseAllHubs();- }, [viewMode, collapseAllHubs]);+ // Back to the constellation by any route (the switcher, a legacy link):+ // the drill-down is a file-scope state and does not survive leaving it.+ if (viewMode === "architecture") setActiveCommunity(null);+ }, [viewMode, setActiveCommunity]);const handleLayoutModeChange = useCallback((mode: LayoutMode) => {// Refuse right at the click when ELK can't run: switching the mode anyway// would stop the force layout and leave an active-looking toggle doing// nothing (the canvas-side notice covers graphs that grow past the cap// after the mode is already active).- if (mode === "hierarchical" && sigmaGraph && sigmaGraph.order > ELK_MAX_NODES) {- setLayoutNotice(elkSkipReason(sigmaGraph.order));+ if (mode === "hierarchical" && displayGraph && displayGraph.order > ELK_MAX_NODES) {+ setLayoutNotice(elkSkipReason(displayGraph.order));return;}setLayoutMode(mode);setLayoutNotice(null);- }, [sigmaGraph]);-- const handleSignalToggle = useCallback((signal: Signal) => {- setActiveSignals((prev) => {- const next = new Set(prev);- if (next.has(signal)) next.delete(signal);- else next.add(signal);- return next;- });- }, []);+ }, [displayGraph]);const handleEdgeTypeToggle = useCallback((edgeType: string) => {setVisibleEdgeTypes((prev) => {@@ -934,20 +1072,20 @@ export function GraphFlow(props: GraphFlowProps) {// A rebuild can drop the selected node (module expanded into files) — clear// the selection then, or the reducer dims the whole canvas around a ghost.useEffect(() => {- if (selectedNodeId && sigmaGraph && !sigmaGraph.hasNode(selectedNodeId)) {+ if (selectedNodeId && displayGraph && !displayGraph.hasNode(selectedNodeId)) {setSelectedNodeId(null);}- }, [sigmaGraph, selectedNodeId]);+ }, [displayGraph, selectedNodeId]);const initialNodeApplied = useRef(false);useEffect(() => {- if (initialNodeApplied.current || !initialSelectedNode || !sigmaGraph) return;- if (sigmaGraph.hasNode(initialSelectedNode)) {+ if (initialNodeApplied.current || !initialSelectedNode || !displayGraph) return;+ if (displayGraph.hasNode(initialSelectedNode)) {initialNodeApplied.current = true;setSelectedNodeId(initialSelectedNode);setTimeout(() => panToNode(initialSelectedNode), 300);}- }, [initialSelectedNode, sigmaGraph, panToNode]);+ }, [initialSelectedNode, displayGraph, panToNode]);const handleInspectNavigate = useCallback((nodeId: string) => {setSelectedNodeId(nodeId);@@ -994,11 +1132,14 @@ export function GraphFlow(props: GraphFlowProps) {setCtxMenu(null);}, [ctxMenu, setCtxMenu]);- if (isLoading || isAwaitingAsyncBuild || (isBuildingGraph && !sigmaGraph))+ if (+ (isLoading || isAwaitingAsyncBuild || isBuildingGraph) &&+ !displayGraph+ )return <Skeleton className="h-full w-full rounded-lg" />;const showOverlayCounts =- !!sigmaGraph && sigmaGraph.order > 0 && (isDeadView || isHotView);+ !!displayGraph && displayGraph.order > 0 && (isDeadView || isHotView);const hasCanvasStatus =(isEgoActive && !!selectedNodeId) || (showOverlayCounts && !!overlayStats);@@ -1019,7 +1160,10 @@ export function GraphFlow(props: GraphFlowProps) {initialTo: pathTo,onPathFound: handlePathFound,onClear: handlePathClear,- onClose: () => setShowPathFinder(false),+ onClose: () => {+ setShowPathFinder(false);+ setPathNotice(null);+ },}): showFlows? executionFlows && executionFlows.flows.length > 0@@ -1045,14 +1189,15 @@ export function GraphFlow(props: GraphFlowProps) {? renderCommunityPanel({communityId: communityPanelId,onClose: () => setCommunityPanelId(null),- onExpandOnCanvas: () => handleConstellationHubToggle(communityPanelId),+ onEnterCommunity: () => enterCommunity(communityPanelId),+ onNeighborSelect: handleNeighborSelect,}): selectedNodeId && inspectedNode? (<GraphInspectionPanelnodeId={selectedNodeId}data={inspectedNode}- graph={sigmaGraph}+ graph={displayGraph}allNodes={effectiveNodeDataMap}communityLabel={inspectedFile@@ -1068,6 +1213,12 @@ export function GraphFlow(props: GraphFlowProps) {: undefined}filePageHref={inspectedFile ? fileHrefFor?.(selectedNodeId) : undefined}+ healthHref={inspectedFile ? fileHealthHrefFor?.(selectedNodeId) : undefined}+ historyHref={inspectedFile ? fileHistoryHrefFor?.(selectedNodeId) : undefined}+ decisionsHref={+ inspectedFile ? fileDecisionsHrefFor?.(selectedNodeId) : undefined+ }+ deadCodeHref={deadCodeHref}onFindPath={handleInspectFindPath}isModuleExpanded={false}egoDepth={egoDepth}@@ -1077,26 +1228,90 @@ export function GraphFlow(props: GraphFlowProps) {): undefined;+ // Inside a community the host's own description describes the wrong thing:+ // it was written for "every file in the repo". The scoped one is stated here+ // because only this component knows the drill-down happened.+ // The slice is capped server-side (SLICE_MEMBER_CAP), and the boundary stubs+ // are drawn but are not members. Both make the drawn node count disagree with+ // "the files in X", and the repo-wide truncation banner is deliberately off+ // in this scope, so the honest sentence has to come from here.+ const sliceNotice = (() => {+ if (!isInsideCommunity || !communitySlice) return null;+ const drawn = communitySlice.nodes.filter((n) => !n.is_boundary).length;+ const stubs = communitySlice.nodes.length - drawn;+ const parts: string[] = [];+ if (communitySlice.truncated && communitySlice.member_count > drawn) {+ parts.push(+ `Showing the ${drawn} most connected of ${communitySlice.member_count} files in this group`,+ );+ } else {+ parts.push(`Showing all ${drawn} files in this group`);+ }+ if (stubs > 0) {+ // Where the faded ring is explained. It used to be said twice: here as a+ // count and again in the description as prose about "faded nodes".+ parts.push(+ `plus ${stubs} faded file${stubs === 1 ? "" : "s"} outside it that they reach`,+ );+ }+ return `${parts.join(", ")}.`;+ })();++ // What the key reports. `displayGraph.size` counts every edge in the graph+ // including the kinds the edge filter is hiding, which is how a slice showing+ // only its exits could still claim 553 edges. Reconciles the edge filter+ // only: the ego filter hides nodes at the canvas rather than in the graph,+ // and reports its own count in the status row beside this.+ const visibleEdgeCount = useMemo(() => {+ if (!displayGraph) return 0;+ let n = 0;+ displayGraph.forEachEdge((_, attrs) => {+ if (visibleEdgeTypes.has(attrs.edgeKind)) n++;+ });+ return n;+ }, [displayGraph, visibleEdgeTypes]);++ // Members vs the one-hop stubs around them, from the same payload the banner+ // counts, so the two figures on screen cannot disagree.+ const sliceCounts = useMemo(() => {+ if (!communitySlice) return undefined;+ const members = communitySlice.nodes.filter((n) => !n.is_boundary).length;+ return { members, boundary: communitySlice.nodes.length - members };+ }, [communitySlice]);++ const activeCommunityLabel =+ activeCommunity !== null+ ? (communityLabels?.get(activeCommunity) ?? `Community ${activeCommunity}`)+ : null;+return (<GraphCanvasShell- description={description}+ breadcrumb={+ isInsideCommunity && activeCommunityLabel ? (+ <GraphScopeBreadcrumb+ rootLabel={repoName ?? "All communities"}+ leafLabel={activeCommunityLabel}+ onRoot={leaveCommunity}+ />+ ) : undefined+ }+ description={+ // The breadcrumb above already names the community and carries the way+ // out, and the narrowing select names it a third time. Prose repeating+ // it is noise, so this says what the picture is, not what it is called.+ isInsideCommunity+ ? `How the files in this group depend on each other.${+ onNodeViewDocs ? " Double-click a file to open it." : ""+ }`+ : description+ }titleActions={<div className="flex flex-wrap items-center justify-end gap-2">{headerActions}<GraphToolbarviewMode={viewMode}- onViewChange={handleViewChange}colorMode={colorMode}onColorModeChange={setColorMode}- hideTests={hideTests}- onHideTestsChange={(v) => {- setActiveSignals(prev => {- const next = new Set(prev);- if (v) next.add("hideTests");- else next.delete("hideTests");- return next;- });- }}onFitView={handleFitView}showPathFinder={showPathFinder}pathFinderAvailable={Boolean(renderPathFinder)}@@ -1114,23 +1329,32 @@ export function GraphFlow(props: GraphFlowProps) {searchQuery={searchQuery}onSearchChange={setSearchQuery}searchMatchCount={searchResults.length}- searchTotalCount={sigmaGraph?.order ?? 0}+ searchTotalCount={displayGraph?.order ?? 0}onSearchKeyDown={handleSearchKeyDown}- layoutMode={layoutMode}+ layoutMode={isEnteringCommunity ? "radial" : layoutMode}onLayoutModeChange={handleLayoutModeChange}onToggleHelp={handleToggleShortcutHelp}hierarchicalDisabledReason={- sigmaGraph && sigmaGraph.order > ELK_MAX_NODES- ? elkSkipReason(sigmaGraph.order)+ displayGraph && displayGraph.order > ELK_MAX_NODES+ ? elkSkipReason(displayGraph.order): undefined}/></div>}banner={- banner || layoutNotice ? (+ banner || layoutNotice || sliceNotice || pathNotice ? (<div className="space-y-2">{banner}+ {(sliceNotice || pathNotice) && (+ <p+ role="status"+ aria-live="polite"+ className="text-[11px] text-[var(--color-text-secondary)]"+ >+ {[sliceNotice, pathNotice].filter(Boolean).join(" ")}+ </p>+ )}{layoutNotice && (<divrole="status"@@ -1154,13 +1378,33 @@ export function GraphFlow(props: GraphFlowProps) {footer={<div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2"><GraphLegend- nodeCount={sigmaGraph?.order ?? 0}- edgeCount={sigmaGraph?.size ?? 0}+ nodeCount={displayGraph?.order ?? 0}+ edgeCount={displayGraph?.size ?? 0}+ visibleEdgeCount={visibleEdgeCount}colorMode={colorMode}viewMode={viewMode}+ {...(isInsideCommunity && activeCommunityLabel+ ? {+ scopeLabel: activeCommunityLabel,+ scopeCommunityId: activeCommunity ?? undefined,+ sliceCounts,+ }+ : {})}+ nodeFilter={+ // Withdrawn inside a community: the slice endpoint returns the+ // whole community whatever the signal says, so the pill lit, the+ // URL changed and the canvas did not.+ isConstellation || isInsideCommunity ? undefined : (+ <GraphNodeFilter+ viewMode={viewMode}+ onViewChange={handleViewChange}+ />+ )+ }{...(communityLabels ? { communityLabels } : {})}onCommunityClick={openCommunityPanel}activeCommunities={activeCommunities ?? undefined}+ drawnCommunityIds={drawnCommunityIds}onCommunityToggle={handleCommunityToggle}onToggleAllCommunities={handleToggleAllCommunities}visibleEdgeTypes={isConstellation ? undefined : visibleEdgeTypes}@@ -1224,18 +1468,17 @@ export function GraphFlow(props: GraphFlowProps) {style={{ touchAction: "none", ...(graphTheme === "dark" ? { background: "var(--color-bg-root)" } : {}) }}aria-label="Dependency graph">- {sigmaGraph && sigmaGraph.order > 0 ? (+ {displayGraph && displayGraph.order > 0 ? (<SigmaCanvasref={sigmaRef}- graph={sigmaGraph}- layoutMode={layoutMode}+ graph={displayGraph}+ layoutMode={isEnteringCommunity ? "radial" : layoutMode}viewMode={viewMode}selectedNodeId={selectedNodeId}highlightedPath={highlightedPath}highlightedEdges={highlightedEdges}searchDimmedNodes={searchDimmedNodes}- communityDimmedNodes={filterDimmedNodes}- expandDimmedNodes={isConstellation ? expandDimmedNodes : null}+ communityDimmedNodes={communityDimmedNodes}colorMode={colorMode}activeSignals={activeSignals}graphTheme={graphTheme}@@ -1246,9 +1489,12 @@ export function GraphFlow(props: GraphFlowProps) {onNodeContextMenu={handleSigmaNodeContextMenu}onStageClick={() => setSelectedNodeId(null)}onLayoutSkipped={setLayoutNotice}+ reducedMotion={prefersReducedMotion}hiddenNodes={isEgoActive ? hiddenNodes : undefined}visibleEdgeTypes={visibleEdgeTypes}- depthRingRadii={isConstellation ? constellationRingRadii : null}+ depthRingRadii={+ isConstellation || isEnteringCommunity ? constellationRingRadii : null+ }/>) : !isLoading ? (<div className="flex items-center justify-center h-full">diff --git a/packages/ui/src/graph/graph-inspection-panel.tsx b/packages/ui/src/graph/graph-inspection-panel.tsxindex c831c1fcb..4cb6f6061 100644--- a/packages/ui/src/graph/graph-inspection-panel.tsx+++ b/packages/ui/src/graph/graph-inspection-panel.tsx@@ -16,6 +16,8 @@ import {Flame,Skull,Lightbulb,+ Activity,+ GitCommitHorizontal,} from "lucide-react";import { ScrollArea } from "../ui/scroll-area";import { languageColor } from "../lib/confidence";@@ -46,6 +48,25 @@ export interface GraphInspectionPanelProps {onViewSymbols?: (() => void) | undefined;/** Canonical file-page href — renders the primary "Open file page" action. */filePageHref?: string | undefined;+ /**+ * Where this file's evidence lives, so the graph stops being a cul-de-sac.+ * A dependency graph is exactly where "what breaks if I change this" gets+ * asked, and the answer is on other pages.+ *+ * All optional; an action is hidden when the host supplies no href. The two+ * that describe a *finding* are gated on the node carrying it as well+ * (`decisionsHref` on `hasDecision`, `deadCodeHref` on `isDead`) so they+ * cannot advertise a finding that is not there. `healthHref` and+ * `historyHref` are not gated: every file has a history tab and a health tab,+ * which state their own emptiness. One known near-miss: `hasDecision` counts+ * `proposed` decisions and the file page only renders its Decisions tab for+ * *governing* ones, so a proposed-only file lands on the page without it.+ */+ healthHref?: string | undefined;+ historyHref?: string | undefined;+ decisionsHref?: string | undefined;+ /** The dead-code findings list. Offered only for a node flagged dead. */+ deadCodeHref?: string | undefined;onFindPath?: (() => void) | undefined;onShowEgoGraph?: (() => void) | undefined;onExpandModule?: (() => void) | undefined;@@ -81,6 +102,10 @@ export const GraphInspectionPanel = memo(function GraphInspectionPanel({onViewDocs,onViewSymbols,filePageHref,+ healthHref,+ historyHref,+ decisionsHref,+ deadCodeHref,onFindPath,onShowEgoGraph,onExpandModule,@@ -308,6 +333,38 @@ export const GraphInspectionPanel = memo(function GraphInspectionPanel({<Code2 className="w-3 h-3" /> Symbols</button>)}+ {!isMod && healthHref && (+ <a+ href={healthHref}+ className="flex items-center justify-center gap-1.5 rounded-lg bg-[var(--color-bg-inset)] hover:bg-[var(--color-bg-surface)] border border-[var(--color-border-default)] px-2 py-1.5 text-caption font-medium text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] transition-colors"+ >+ <Activity className="w-3 h-3" /> Health+ </a>+ )}+ {!isMod && historyHref && (+ <a+ href={historyHref}+ className="flex items-center justify-center gap-1.5 rounded-lg bg-[var(--color-bg-inset)] hover:bg-[var(--color-bg-surface)] border border-[var(--color-border-default)] px-2 py-1.5 text-caption font-medium text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] transition-colors"+ >+ <GitCommitHorizontal className="w-3 h-3" /> History+ </a>+ )}+ {!isMod && decisionsHref && data.hasDecision && (+ <a+ href={decisionsHref}+ className="flex items-center justify-center gap-1.5 rounded-lg bg-[var(--color-bg-inset)] hover:bg-[var(--color-bg-surface)] border border-[var(--color-border-default)] px-2 py-1.5 text-caption font-medium text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] transition-colors"+ >+ <Lightbulb className="w-3 h-3" /> Decisions+ </a>+ )}+ {!isMod && deadCodeHref && data.isDead && (+ <a+ href={deadCodeHref}+ className="flex items-center justify-center gap-1.5 rounded-lg bg-[var(--color-bg-inset)] hover:bg-[var(--color-bg-surface)] border border-[var(--color-border-default)] px-2 py-1.5 text-caption font-medium text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] transition-colors"+ >+ <Skull className="w-3 h-3" /> Dead code+ </a>+ )}{onFindPath && (<buttononClick={onFindPath}diff --git a/packages/ui/src/graph/graph-legend.tsx b/packages/ui/src/graph/graph-legend.tsxindex 44bae78af..db950be9b 100644--- a/packages/ui/src/graph/graph-legend.tsx+++ b/packages/ui/src/graph/graph-legend.tsx@@ -1,6 +1,7 @@"use client";import { useState, memo } from "react";+import type { ReactNode } from "react";import { ChevronDown, ChevronUp } from "lucide-react";import { LANGUAGE_COLORS } from "../lib/confidence";import { edgeColorsForTheme } from "./sigma/constants";@@ -10,6 +11,30 @@ import type { ColorMode, ViewMode } from "./graph-toolbar";/** Community rows shown before the key folds into a "+N" line. */const COMMUNITY_ROWS = 8;+/**+ * Edge kinds, in the order they are keyed.+ *+ * There is no "Imports" row any more. `classifyEdge` returned that kind only+ * for an edge with an endpoint missing from the graph, and those are dropped+ * before they are drawn — so the swatch keyed zero marks in every state, and+ * because it was also in the default visible set, "cross-community only" read+ * as a two-kind default.+ */+const EDGE_KINDS = [+ { type: "crossCommunity", label: "Cross-community" },+ { type: "internal", label: "Internal" },+ { type: "dynamic", label: "Dynamic" },+ { type: "lowConfidence", label: "Low confidence" },+] as const;++/** The same kinds, worded for a canvas holding one community. */+const SCOPED_EDGE_KINDS = [+ { type: "internal", label: "Within this group" },+ { type: "crossCommunity", label: "Leaving this group" },+ { type: "dynamic", label: "Dynamic" },+ { type: "lowConfidence", label: "Low confidence" },+] as const;+const LANGUAGE_LEGEND = [{ lang: "python", color: LANGUAGE_COLORS.python, label: "Python" },{ lang: "typescript", color: LANGUAGE_COLORS.typescript, label: "TypeScript" },@@ -109,6 +134,25 @@ interface GraphLegendProps {| undefined;/** Click a constellation row → focus that hub's camera. */onConstellationHubClick?: ((communityId: number) => void) | undefined;+ /**+ * Name of the one community being drawn, when the canvas has been drilled+ * into. Its presence selects the scoped reading of this key.+ */+ scopeLabel?: string | undefined;+ /** Members vs one-hop boundary stubs in the drawn slice. */+ sliceCounts?: { members: number; boundary: number } | undefined;+ /** Community id of the drawn slice, for the swatch hue. */+ scopeCommunityId?: number | undefined;+ /** Edges actually drawn under the current edge-type filter. Falls back to+ * `edgeCount`, which counts hidden ones too. */+ visibleEdgeCount?: number | undefined;+ /** Rendered beside the node count, so the control that changes how many+ * nodes are drawn sits next to the figure reporting it. */+ nodeFilter?: ReactNode | undefined;+ /** Communities actually on the canvas. `communityLabels` is the repo-wide+ * summary list, which on a capped file graph names groups no node here+ * belongs to; keying those offered a toggle that could not do anything. */+ drawnCommunityIds?: Set<number> | undefined;}export const GraphLegend = memo(function GraphLegend({@@ -126,6 +170,12 @@ export const GraphLegend = memo(function GraphLegend({graphTheme = "dark",constellationEntries,onConstellationHubClick,+ scopeLabel,+ sliceCounts,+ scopeCommunityId,+ visibleEdgeCount,+ nodeFilter,+ drawnCommunityIds,}: GraphLegendProps) {// Open by default: every node is painted from this key, so a collapsed one// ships a field of coloured circles with no way to read them.@@ -181,20 +231,111 @@ export const GraphLegend = memo(function GraphLegend({);}+ const drawnEdgeCount = visibleEdgeCount ?? edgeCount;++ // Communities worth a row: the repo-wide summary, narrowed to what is on the+ // canvas. `communityLabels` resolves before an async graph build finishes, so+ // `drawnCommunityIds` is legitimately empty for those frames — and a key with+ // no rows must not still offer a control that dims everything.+ const keyedCommunities =+ communityLabels && communityLabels.size > 0+ ? Array.from(communityLabels.entries()).filter(+ ([cid]) => !drawnCommunityIds || drawnCommunityIds.has(cid),+ )+ : null;+ const hasCommunityRows = keyedCommunities === null || keyedCommunities.length > 0;++ // Inside a community the whole-repo key describes the wrong thing. Its eight+ // community swatches come from the repo-wide summary list in API order, so+ // the community you drilled into is usually not even among them; its+ // Deselect-all dims every node on the canvas including the ones you came to+ // read; and toggling a community that is not drawn changes nothing while+ // leaving its swatch filled. Community filtering is a whole-repo grammar, so+ // the scoped key drops it and keys what is on the canvas — following+ // `health/map/legend.tsx` and `system-map-legend.tsx`, where the key reads+ // the same source the marks do.+ if (scopeLabel) {+ const members = sliceCounts?.members ?? nodeCount;+ const boundary = sliceCounts?.boundary ?? 0;+ return (+ <div className={shellClass}>+ <button onClick={() => setExpanded((s) => !s)} className={headerClass}>+ <span className={countClass}>+ {members} file{members === 1 ? "" : "s"}+ {boundary > 0 ? ` · ${boundary} outside` : ""} ·{" "}+ {drawnEdgeCount} edge{drawnEdgeCount === 1 ? "" : "s"} shown+ </span>+ <Chevron expanded={expanded} />+ </button>+ {expanded && (+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1">+ <div className={rowClass}>+ <Swatch+ color={+ colorMode === "community" && scopeCommunityId !== undefined+ ? communityFamily(scopeCommunityId).satellite+ : undefined+ }+ />+ <span className="max-w-[14rem] truncate">{scopeLabel}</span>+ <span className="shrink-0 tabular-nums text-[10px] text-[var(--color-text-tertiary)]">+ {members}+ </span>+ </div>+ {boundary > 0 && (+ <div className={rowClass}>+ {/* The faded ring was explained in prose and keyed nowhere. */}+ <span className="h-2 w-2 shrink-0 rounded-full border border-[var(--color-text-tertiary)]" />+ <span>Outside this group</span>+ <span className="shrink-0 tabular-nums text-[10px] text-[var(--color-text-tertiary)]">+ {boundary}+ </span>+ </div>+ )}+ {onEdgeTypeToggle && visibleEdgeTypes && (+ <>+ <p className={groupClass}>Edges</p>+ {SCOPED_EDGE_KINDS.map((et) => {+ const checked = visibleEdgeTypes.has(et.type);+ return (+ <div key={et.type} className={rowClass}>+ <SwatchToggle+ color={edgeColors[et.type]}+ checked={checked}+ label={`Toggle ${et.label} edges`}+ onToggle={() => onEdgeTypeToggle(et.type)}+ />+ <span className={`truncate ${checked ? "" : "opacity-45"}`}>+ {et.label}+ </span>+ </div>+ );+ })}+ </>+ )}+ </div>+ )}+ </div>+ );+ }+return (<div className={shellClass}><button onClick={() => setExpanded((s) => !s)} className={headerClass}><span className={countClass}>- {nodeCount} nodes · {edgeCount} edges+ {nodeCount} nodes · {drawnEdgeCount} edges</span><Chevron expanded={expanded} /></button>+ {nodeFilter}{expanded && (<div className="flex flex-wrap items-center gap-x-3 gap-y-1">- <p className={groupClass}>- {colorMode === "language" ? "Language" : "Community"}- </p>+ {(colorMode === "language" || hasCommunityRows) && (+ <p className={groupClass}>+ {colorMode === "language" ? "Language" : "Community"}+ </p>+ )}{colorMode === "language" &&LANGUAGE_LEGEND.map((l) => (@@ -207,14 +348,14 @@ export const GraphLegend = memo(function GraphLegend({</div>))}- {colorMode === "community" && (() => {- const all = communityLabels && communityLabels.size > 0- ? Array.from(communityLabels.entries())- : null;+ {colorMode === "community" && hasCommunityRows && (() => {+ const all = keyedCommunities;const entries = all ? all.slice(0, COMMUNITY_ROWS) : null;const overflow = all ? all.length - entries!.length : 0;- const allSelected = !activeCommunities || (entries- ? entries.every(([cid]) => activeCommunities.has(cid))+ // Over every row, not the eight shown: the label read "Deselect+ // all" while communities nine and beyond were already off.+ const allSelected = !activeCommunities || (all+ ? all.every(([cid]) => activeCommunities.has(cid)): true);return (<>@@ -228,7 +369,10 @@ export const GraphLegend = memo(function GraphLegend({)}{entries? entries.map(([cid, label]) => {- const color = communityFamily(cid).hub;+ // Satellite, not hub: file nodes are painted+ // `family.satellite` by use-sigma's colour pass, so the+ // hub hue keyed a mark this canvas never draws.+ const color = communityFamily(cid).satellite;const checked = !activeCommunities || activeCommunities.has(cid);return (<div key={cid} className={rowClass}>@@ -277,18 +421,12 @@ export const GraphLegend = memo(function GraphLegend({{onEdgeTypeToggle && visibleEdgeTypes && (<><p className={groupClass}>Edges</p>- {([- { type: "import", label: "Imports", color: edgeColors.import },- { type: "crossCommunity", label: "Cross-community", color: edgeColors.crossCommunity },- { type: "internal", label: "Internal", color: edgeColors.internal },- { type: "dynamic", label: "Dynamic", color: edgeColors.dynamic },- { type: "lowConfidence", label: "Low confidence", color: edgeColors.lowConfidence },- ] as const).map((et) => {+ {EDGE_KINDS.map((et) => {const checked = visibleEdgeTypes.has(et.type);return (<div key={et.type} className={rowClass}><SwatchToggle- color={et.color}+ color={edgeColors[et.type]}checked={checked}label={`Toggle ${et.label} edges`}onToggle={() => onEdgeTypeToggle(et.type)}diff --git a/packages/ui/src/graph/graph-scope-breadcrumb.tsx b/packages/ui/src/graph/graph-scope-breadcrumb.tsxnew file mode 100644index 000000000..6fd9776d7--- /dev/null+++ b/packages/ui/src/graph/graph-scope-breadcrumb.tsx@@ -0,0 +1,47 @@+"use client";++import { ChevronRight, Home } from "lucide-react";++/**+ * "You are here" for the graph, shown only once you have gone somewhere.+ *+ * Entering a community swaps what the canvas draws, so without this the reader+ * has no way to tell a scoped graph from the whole repo and no way back except+ * a keyboard shortcut nothing documents. Follows `ZoomBreadcrumb` on the+ * Knowledge Graph: a home crumb that returns to the overview, then the trail.+ *+ * Two levels is the whole depth the Map has, so this takes a single leaf rather+ * than a chain it would never fill.+ */+export function GraphScopeBreadcrumb({+ rootLabel,+ leafLabel,+ onRoot,+}: {+ /** The whole-repo crumb, e.g. the repo name. */+ rootLabel: string;+ /** Where you are now. */+ leafLabel: string;+ onRoot: () => void;+}) {+ return (+ <nav+ aria-label="Graph location"+ className="flex min-w-0 items-center gap-1 text-xs text-[var(--color-text-secondary)]"+ >+ <button+ type="button"+ onClick={onRoot}+ title={`Back to ${rootLabel}`}+ className="flex shrink-0 items-center gap-1 rounded px-1.5 py-1 hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"+ >+ <Home className="h-3.5 w-3.5" />+ <span className="max-w-[10rem] truncate">{rootLabel}</span>+ </button>+ <ChevronRight className="h-3.5 w-3.5 shrink-0 text-[var(--color-text-tertiary)]" />+ <span className="max-w-[16rem] truncate px-1 py-1 font-medium text-[var(--color-text-primary)]">+ {leafLabel}+ </span>+ </nav>+ );+}diff --git a/packages/ui/src/graph/graph-scope-controls.tsx b/packages/ui/src/graph/graph-scope-controls.tsxindex f7bcd313e..593b340de 100644--- a/packages/ui/src/graph/graph-scope-controls.tsx+++ b/packages/ui/src/graph/graph-scope-controls.tsx@@ -3,6 +3,7 @@import type { KeyboardEvent as ReactKeyboardEvent } from "react";import { formatNumber } from "../lib/format";import type { ModuleGroup } from "./use-module-filter";+import type { CommunitySummaryItem } from "@repowise-dev/types/graph";/*** How zoomed out the graph is. Exactly one axis, in exactly one control.@@ -91,13 +92,9 @@ export function GraphScopeSwitcher({const PROMINENT_MODULES = 8;/**- * Module filter for the Files scope: pick a path prefix, everything else dims.- *- * Deliberately absent from the Communities scope. The constellation payload- * carries a community's label, size and one representative file — not its- * members' paths — so "does this community contain `packages/ui`?" is a- * question that view cannot answer. A control that could only guess is worse- * than no control.+ * @deprecated Superseded by {@link GraphNarrowingSelect}, which puts the module+ * and community filters in one control because they are one axis. Kept+ * exported and working so an out-of-tree host compiles while it ports.*/export function ModuleFilterSelect({groups,@@ -146,3 +143,107 @@ export function ModuleFilterSelect({</label>);}+++/**+ * The one narrowing control: "Showing all files / community X / module Y".+ *+ * `?module=` and `?community=` are the same axis — both answer "which part of+ * the repo am I looking at?" — so they get one control and are mutually+ * exclusive. Two selects side by side would let a reader ask for a community+ * *and* a module and get an intersection nobody meant.+ *+ * Deliberately absent from the Communities scope. The constellation is the+ * whole repo at one circle per group; narrowing it to one group is the+ * drill-down, not a filter.+ */+export function GraphNarrowingSelect({+ modules,+ communities,+ activeModule,+ activeCommunity,+ onChange,+ className,+}: {+ modules: ModuleGroup[];+ /** Communities offered as narrowing targets. Empty hides that group. */+ communities?: readonly CommunitySummaryItem[] | undefined;+ activeModule: string | null;+ activeCommunity: number | null;+ /** Exactly one of the two is ever non-null. */+ onChange: (next: { module: string | null; community: number | null }) => void;+ className?: string | undefined;+}) {+ const hasCommunities = (communities?.length ?? 0) > 0;+ if (modules.length < 2 && !hasCommunities) return null;++ const prominent = modules.slice(0, PROMINENT_MODULES);+ const rest = modules.slice(PROMINENT_MODULES);+ // A `?module=` from an old link can name a prefix this graph no longer has.+ // The filter removes rather than dims, so the canvas is legitimately empty —+ // but a controlled <select> whose value matches no option renders *blank*,+ // which reads as a broken control rather than as a filter that matched+ // nothing. Give the stale value an option that says so.+ const staleModule =+ activeModule && !modules.some((g) => g.id === activeModule) ? activeModule : null;++ // Encoded rather than two parallel values, because a <select> has one value+ // and the two kinds share a namespace ("external" is a module id, 3 is a+ // community id).+ const value =+ activeCommunity !== null+ ? `c:${activeCommunity}`+ : activeModule+ ? `m:${activeModule}`+ : "";++ return (+ <label+ className={`inline-flex items-center gap-1.5 text-xs text-[var(--color-text-secondary)] ${className ?? ""}`}+ >+ <span className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-secondary)]">+ Showing+ </span>+ <select+ value={value}+ onChange={(e) => {+ const v = e.target.value;+ if (v.startsWith("c:")) onChange({ module: null, community: Number(v.slice(2)) });+ else if (v.startsWith("m:")) onChange({ module: v.slice(2), community: null });+ else onChange({ module: null, community: null });+ }}+ className="max-w-[15rem] rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2 py-1 text-xs text-[var(--color-text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"+ >+ <option value="">All files</option>+ {staleModule && <option value={`m:${staleModule}`}>{staleModule} · 0</option>}+ {hasCommunities && (+ <optgroup label="Community">+ {communities!.map((c) => (+ <option key={c.community_id} value={`c:${c.community_id}`}>+ {c.label} · {formatNumber(c.member_count)}+ </option>+ ))}+ </optgroup>+ )}+ {modules.length > 0 && (+ <optgroup label="Module">+ {prominent.map((g) => (+ <option key={g.id} value={`m:${g.id}`}>+ {g.id} · {formatNumber(g.fileCount)}+ </option>+ ))}+ </optgroup>+ )}+ {rest.length > 0 && (+ <optgroup label="Smaller modules">+ {rest.map((g) => (+ <option key={g.id} value={`m:${g.id}`}>+ {g.id} · {formatNumber(g.fileCount)}+ </option>+ ))}+ </optgroup>+ )}+ </select>+ </label>+ );+}diff --git a/packages/ui/src/graph/graph-shortcut-help.tsx b/packages/ui/src/graph/graph-shortcut-help.tsxindex bb93cce03..ef48e0221 100644--- a/packages/ui/src/graph/graph-shortcut-help.tsx+++ b/packages/ui/src/graph/graph-shortcut-help.tsx@@ -23,7 +23,7 @@ const GESTURES: { gesture: string; action: string }[] = [/** Keyboard + gesture cheatsheet, toggled with `?`. */export function GraphShortcutHelp({ onClose }: { onClose: () => void }) {return (- <div className="absolute inset-0 z-30 flex items-center justify-center bg-black/40 p-4" onClick={onClose}>+ <div className="absolute inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/40 p-4" onClick={onClose}><divclassName="w-full max-w-sm rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-4 shadow-xl shadow-black/30"onClick={(e) => e.stopPropagation()}diff --git a/packages/ui/src/graph/graph-toolbar.tsx b/packages/ui/src/graph/graph-toolbar.tsxindex a669832b0..be42bfbe6 100644--- a/packages/ui/src/graph/graph-toolbar.tsx+++ b/packages/ui/src/graph/graph-toolbar.tsx@@ -3,7 +3,6 @@import {Palette,Network,- EyeOff,Maximize,Route,Skull,@@ -15,9 +14,11 @@ import {Waypoints,SlidersHorizontal,HelpCircle,+ ChevronDown,} from "lucide-react";import { memo, useState } from "react";import { Button } from "../ui/button";+import { Popover, PopoverTrigger, PopoverContent } from "../ui/popover";/*** No "risk" member. There was one, and it painted `pagerank * 3` through@@ -86,11 +87,23 @@ export function viewModeToScopeOverlays(view: ViewMode): { scope: Scope; overlayinterface GraphToolbarProps {viewMode: ViewMode;- onViewChange: (mode: ViewMode) => void;+ /**+ * @deprecated The All/Hot/Dead filter moved to {@link GraphNodeFilter}, which+ * renders beside the node count it changes. Accepted and ignored here so an+ * out-of-tree host compiles while it ports.+ */+ onViewChange?: ((mode: ViewMode) => void) | undefined;colorMode: ColorMode;onColorModeChange: (mode: ColorMode) => void;- hideTests: boolean;- onHideTestsChange: (v: boolean) => void;+ /**+ * @deprecated Removed. The control was titled "Hide test files" and filtered+ * *search results* only — `activeSignals` never reached the renderer, so+ * every test file stayed drawn. Accepted and ignored rather than shipping a+ * button that does not do what it says.+ */+ hideTests?: boolean | undefined;+ /** @deprecated See {@link GraphToolbarProps.hideTests}. */+ onHideTestsChange?: ((v: boolean) => void) | undefined;onFitView: () => void;showPathFinder: boolean;onTogglePathFinder: () => void;@@ -142,16 +155,21 @@ const LAYOUT_MODES: { id: LayoutMode; icon: typeof GitBranch; label: string }[]];/**- * One control surface in the section header. Translucency, blur and a shadow- * are how chrome sits over a diagram; this lives on the page plane now, so it- * takes a plain hairline frame instead.+ * Groups inside the one header cluster.+ *+ * A hairline *between* groups, not a box *around* them. This was a bordered+ * panel whose three groups stacked as blocks, so beside the scope controls it+ * read as a second toolbar. Every peer canvas puts exactly one cluster in the+ * header band: `health/triage-view` (lens switcher only), the Knowledge Graph+ * page (one hairline row), `workspace/system-map` (filters only) and+ * `coupling/coupling-explorer` (hairline rows, no box). DESIGN_LANGUAGE.md+ * reserves bordered containers for objects that can be selected, opened or+ * acted on; a cluster of loose toggles is not one.*/-const panelClass =- "overflow-hidden rounded-lg border border-[var(--color-border-default)]";+const groupClass = "flex items-center gap-0.5";-/** A divider row inside the panel. The first group omits the top hairline. */-const groupClass =- "flex flex-wrap items-center gap-0.5 p-1 border-t border-[var(--color-border-default)] first:border-t-0";+const dividerClass =+ "ml-0.5 border-l border-[var(--color-border-default)] pl-1.5";const itemActiveClass ="bg-[var(--color-accent-primary)]/15 text-[var(--color-accent-primary)]";@@ -160,13 +178,87 @@ const itemIdleClass =const itemClass ="flex items-center gap-1.5 rounded-md px-2 py-2 text-[10px] font-medium transition-colors sm:py-1";-export const GraphToolbar = memo(function GraphToolbar({+/** Segmented control, matching `coupling-explorer`'s: counts live inside the+ * segments rather than in a caption beside them. */+const segmentGroupClass =+ "inline-flex overflow-hidden rounded-md border border-[var(--color-border-default)]";+const segmentClass =+ "shrink-0 whitespace-nowrap border-r border-[var(--color-border-default)] px-2 py-1.5 text-[10px] font-medium transition-colors last:border-r-0 sm:py-1";++/**+ * Exclusive All / Hot / Dead node filter, rendered beside the node count it+ * changes rather than in the header.+ *+ * A control whose entire effect is "how many nodes are drawn" belongs next to+ * the figure reporting that number — DESIGN_LANGUAGE.md's rule that a control+ * must change the same dataset its caption counts.+ *+ * No totals inside the segments. They would be repo-wide, sitting a few pixels+ * from a node count that is view-scoped, with nothing saying the two figures+ * count different sets. `OverlayCountChip` already reconciles them as+ * "380 of 412" in the canvas status row, where there is room to say so.+ */+export function GraphNodeFilter({viewMode,onViewChange,+ className,+}: {+ viewMode: ViewMode;+ onViewChange: (mode: ViewMode) => void;+ className?: string | undefined;+}) {+ const { scope, overlays } = viewModeToScopeOverlays(viewMode);+ const active: Overlay | "all" = overlays.has("dead")+ ? "dead"+ : overlays.has("hot")+ ? "hot"+ : "all";++ return (+ <div+ role="radiogroup"+ aria-label="Node filter"+ className={`${segmentGroupClass} ${className ?? ""}`}+ >+ {NODE_FILTERS.map((f) => {+ const Icon = f.icon;+ const isActive = active === f.id;+ return (+ <button+ key={f.id}+ type="button"+ role="radio"+ aria-checked={isActive}+ title={f.hint}+ onClick={() =>+ onViewChange(+ scopeOverlaysToViewMode(+ scope,+ new Set<Overlay>(f.id === "all" ? [] : [f.id]),+ ),+ )+ }+ className={`${segmentClass} ${+ isActive+ ? "bg-[var(--color-accent-primary)]/15 text-[var(--color-accent-primary)]"+ : "text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-wash-hover)] hover:text-[var(--color-text-primary)]"+ }`}+ >+ <span className="inline-flex items-center gap-1">+ {Icon && <Icon className="h-3 w-3" />}+ {f.label}+ </span>+ </button>+ );+ })}+ </div>+ );+}++export const GraphToolbar = memo(function GraphToolbar({+ viewMode,colorMode,onColorModeChange,- hideTests,- onHideTestsChange,onFitView,showPathFinder,onTogglePathFinder,@@ -183,84 +275,29 @@ export const GraphToolbar = memo(function GraphToolbar({onToggleHelp,hierarchicalDisabledReason,}: GraphToolbarProps) {- // Below sm the full control cluster is too much chrome over the canvas —- // collapse it behind a single toggle, keeping search always reachable.+ // Below sm the full control cluster is too much chrome — collapse it behind+ // a single toggle, keeping search always reachable.const [mobileOpen, setMobileOpen] = useState(false);+ const [traceOpen, setTraceOpen] = useState(false);const clusterVisibility = mobileOpen ? "flex" : "hidden sm:flex";- // Derive scope + overlays from the legacy ViewMode so this component remains- // the single source of truth — callers can continue to round-trip the- // wire-format ``viewMode`` value through query params without translation.- const { scope: activeScope, overlays: activeOverlays } = viewModeToScopeOverlays(viewMode);+ // Derive scope from the legacy ViewMode so this component remains the single+ // source of truth — callers can continue to round-trip the wire-format+ // `viewMode` value through query params without translation.+ const { scope: activeScope } = viewModeToScopeOverlays(viewMode);// The Knowledge Graph (constellation) scope is a fixed radial composition:// overlays / FA2 / hierarchical layout don't apply, so those controls are// hidden here rather than shown in a half-working state.const isConstellation = activeScope === "architecture";- // Exclusive node filter. Legacy "unified" URLs parse to both overlays and- // render as Dead here; any click normalizes back to a single filter.- const activeFilter: Overlay | "all" = activeOverlays.has("dead")- ? "dead"- : activeOverlays.has("hot")- ? "hot"- : "all";-- const setNodeFilter = (id: Overlay | "all") => {- const next = new Set<Overlay>(id === "all" ? [] : [id]);- onViewChange(scopeOverlaysToViewMode(activeScope, next));- };+ const traceActive = showPathFinder || showFlows;return (- <div className="flex flex-col gap-1.5 items-end">- {/* Mobile: single toggle for the control cluster */}- <button- onClick={() => setMobileOpen((s) => !s)}- className={`flex items-center gap-1.5 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]/90 backdrop-blur-sm px-2 py-1.5 text-[10px] font-medium shadow-sm sm:hidden ${- mobileOpen- ? "text-[var(--color-accent-primary)]"- : "text-[var(--color-text-secondary)]"- }`}- aria-expanded={mobileOpen}- aria-label="Graph controls"- >- <SlidersHorizontal className="w-3 h-3" />- Controls- </button>-- <div className={panelClass}>- {/* Node filter (exclusive All / Hot / Dead) — not applicable in the constellation */}- {!isConstellation && (- <div- role="radiogroup"- aria-label="Node filter"- className={`${clusterVisibility} ${groupClass}`}- >- {NODE_FILTERS.map((f) => {- const Icon = f.icon;- const isActive = activeFilter === f.id;- return (- <button- key={f.id}- onClick={() => setNodeFilter(f.id)}- className={`${itemClass} ${isActive ? itemActiveClass : itemIdleClass}`}- title={f.hint}- aria-label={f.label}- role="radio"- aria-checked={isActive}- >- {Icon && <Icon className="w-3 h-3" />}- <span className={Icon ? "hidden lg:inline" : undefined}>{f.label}</span>- </button>- );- })}- </div>- )}-- {/* Layout · colour · actions. */}- <div className={`${clusterVisibility} ${groupClass}`}>+ <div className="flex flex-wrap items-center justify-end gap-1.5">+ <div className={`${clusterVisibility} flex-wrap items-center gap-y-1`}>{!isConstellation && (- <div className="flex gap-0.5">- {LAYOUT_MODES.map((m) => {+ <div className={groupClass}>+ {LAYOUT_MODES.map((m) => {const Icon = m.icon;const isActive = layoutMode === m.id;const disabledReason =@@ -281,8 +318,8 @@ export const GraphToolbar = memo(function GraphToolbar({<Icon className="w-3 h-3" /></button>);- })}- </div>+ })}+ </div>)}{/* Colour-by. The active mode always carries its word: unlabelled@@ -290,75 +327,105 @@ export const GraphToolbar = memo(function GraphToolbar({Hidden in the constellation, where hubs are family-colouredregardless of this setting. */}{!isConstellation && (- <div className="flex items-center gap-0.5 border-l border-[var(--color-border-default)] pl-1">- <span className="hidden pl-1 pr-0.5 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)] lg:inline">- Colour- </span>- {COLOR_MODES.map((m) => {- const Icon = m.icon;- const isActive = colorMode === m.id;- return (- <button- key={m.id}- onClick={() => onColorModeChange(m.id)}- className={`${itemClass} ${isActive ? itemActiveClass : itemIdleClass}`}- title={m.label}- aria-label={m.label}- aria-pressed={isActive}- >- <Icon className="w-3 h-3" />- {isActive && <span>{m.label}</span>}- </button>- );- })}- </div>+ <div className={`${groupClass} ${dividerClass}`}>+ <span className="hidden pr-0.5 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)] lg:inline">+ Colour+ </span>+ {COLOR_MODES.map((m) => {+ const Icon = m.icon;+ const isActive = colorMode === m.id;+ return (+ <button+ key={m.id}+ onClick={() => onColorModeChange(m.id)}+ className={`${itemClass} ${isActive ? itemActiveClass : itemIdleClass}`}+ title={m.label}+ aria-label={m.label}+ aria-pressed={isActive}+ >+ <Icon className="w-3 h-3" />+ {isActive && <span>{m.label}</span>}+ </button>+ );+ })}+ </div>)}{/* No theme control here. It set the *global* theme, so it did exactlywhat the app's own toggle in the header does, a few hundred pixelsaway — two controls, one effect, and this one buried in a row of a- dozen unlabelled icons. */}- <div className="flex gap-0.5 border-l border-[var(--color-border-default)] pl-1">- {/* Path finder / execution flows operate on file-level nodes and- don't apply to the community constellation — hidden there. */}- {!isConstellation && pathFinderAvailable && (- <Button- size="sm"- variant="ghost"- onClick={onTogglePathFinder}- className={`h-8 w-8 sm:h-7 sm:w-7 p-0 ${showPathFinder ? "text-[var(--color-accent-primary)]" : "text-[var(--color-text-tertiary)]"}`}- title="Find dependency path"- aria-label="Find dependency path"- aria-pressed={showPathFinder}- >- <Route className="w-3.5 h-3.5" />- </Button>- )}- {!isConstellation && (- <Button- size="sm"- variant="ghost"- onClick={onToggleFlows}- className={`h-8 w-8 sm:h-7 sm:w-7 p-0 ${showFlows ? "text-[var(--color-accent-primary)]" : "text-[var(--color-text-tertiary)]"}`}- title="Execution flows"- aria-label="Execution flows"- aria-pressed={showFlows}- >- <Workflow className="w-3.5 h-3.5" />- </Button>- )}+ dozen unlabelled icons.++ Path finding and execution flows are two uncommon actions that were+ two unlabelled glyphs. DESIGN_LANGUAGE.md: do not abbreviate an+ uncommon action to make it fit. One named control, opened on+ demand, carries both with their words. */}+ <div className={`${groupClass} ${isConstellation ? "" : dividerClass}`}>{!isConstellation && (- <Button- size="sm"- variant="ghost"- onClick={() => onHideTestsChange(!hideTests)}- className={`h-8 w-8 sm:h-7 sm:w-7 p-0 ${hideTests ? "text-[var(--color-accent-primary)]" : "text-[var(--color-text-tertiary)]"}`}- title={hideTests ? "Show test files" : "Hide test files"}- aria-label={hideTests ? "Show test files" : "Hide test files"}- aria-pressed={hideTests}- >- <EyeOff className="w-3.5 h-3.5" />- </Button>+ <Popover open={traceOpen} onOpenChange={setTraceOpen}>+ <PopoverTrigger asChild>+ <button+ type="button"+ className={`${itemClass} ${traceActive ? itemActiveClass : itemIdleClass}`}+ title={+ pathFinderAvailable+ ? "Trace a dependency path or an execution flow"+ : "Trace an execution flow"+ }+ // Not colour alone. The two buttons this replaced each+ // carried their own `aria-pressed`; without this a reader who+ // cannot see the accent has to open the menu to learn a trace+ // panel is already open.+ aria-label={+ showPathFinder+ ? "Trace — dependency path open"+ : showFlows+ ? "Trace — execution flows open"+ : "Trace"+ }+ >+ <Route className="w-3 h-3" />+ <span>Trace</span>+ <ChevronDown className="w-3 h-3" />+ </button>+ </PopoverTrigger>+ <PopoverContent align="end" className="w-56 p-1">+ {pathFinderAvailable && (+ <button+ type="button"+ onClick={() => {+ setTraceOpen(false);+ onTogglePathFinder();+ }}+ aria-pressed={showPathFinder}+ className={`flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-xs transition-colors hover:bg-[var(--color-bg-wash-hover)] ${+ showPathFinder+ ? "text-[var(--color-accent-primary)]"+ : "text-[var(--color-text-primary)]"+ }`}+ >+ <Route className="h-3.5 w-3.5 shrink-0" />+ Find dependency path+ </button>+ )}+ <button+ type="button"+ onClick={() => {+ setTraceOpen(false);+ onToggleFlows();+ }}+ aria-pressed={showFlows}+ className={`flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-xs transition-colors hover:bg-[var(--color-bg-wash-hover)] ${+ showFlows+ ? "text-[var(--color-accent-primary)]"+ : "text-[var(--color-text-primary)]"+ }`}+ >+ <Workflow className="h-3.5 w-3.5 shrink-0" />+ Execution flows+ </button>+ </PopoverContent>+ </Popover>)}<Buttonsize="sm"@@ -386,9 +453,11 @@ export const GraphToolbar = memo(function GraphToolbar({</div>{/* Search stays visible at every width — it is the one control that- still works when the rest of the cluster is collapsed on a phone. */}- <div className="flex items-center gap-1.5 border-t border-[var(--color-border-default)] px-2 py-1.5">- <Search className="h-3 w-3 shrink-0 text-[var(--color-text-tertiary)]" />+ still works when the rest of the cluster is collapsed on a phone. A+ bordered field of its own width, rather than a row of the old panel,+ so it stops stretching to whatever the widest stacked group needed. */}+ <div className="relative">+ <Search className="pointer-events-none absolute left-2 top-1/2 h-3 w-3 -translate-y-1/2 text-[var(--color-text-tertiary)]" /><inputtype="text"value={searchQuery}@@ -396,24 +465,40 @@ export const GraphToolbar = memo(function GraphToolbar({onKeyDown={onSearchKeyDown}placeholder="Search nodes…"aria-label="Search graph nodes"- className="w-full min-w-0 sm:w-28 bg-transparent text-xs text-[var(--color-text-primary)] outline-none placeholder:text-[var(--color-text-tertiary)] lg:w-40"+ className="w-40 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] py-1.5 pl-7 pr-14 text-xs text-[var(--color-text-primary)] outline-none placeholder:text-[var(--color-text-tertiary)] focus:border-[var(--color-border-hover)] sm:w-36 lg:w-48"/>- {searchQuery && searchMatchCount != null && searchTotalCount != null && (- <span className="whitespace-nowrap font-mono text-[10px] tabular-nums text-[var(--color-text-tertiary)]">- {searchMatchCount}/{searchTotalCount}- </span>- )}- {searchQuery && (- <button- onClick={() => onSearchChange("")}- aria-label="Clear search"- className="text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)]"- >- <X className="h-3 w-3" />- </button>- )}- </div>+ <span className="absolute right-2 top-1/2 flex -translate-y-1/2 items-center gap-1">+ {searchQuery && searchMatchCount != null && searchTotalCount != null && (+ <span className="whitespace-nowrap font-mono text-[10px] tabular-nums text-[var(--color-text-tertiary)]">+ {searchMatchCount}/{searchTotalCount}+ </span>+ )}+ {searchQuery && (+ <button+ onClick={() => onSearchChange("")}+ aria-label="Clear search"+ className="text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)]"+ >+ <X className="h-3 w-3" />+ </button>+ )}+ </span></div>++ {/* Mobile: single toggle for the control cluster */}+ <button+ onClick={() => setMobileOpen((s) => !s)}+ className={`flex items-center gap-1.5 rounded-md border border-[var(--color-border-default)] px-2 py-1.5 text-[10px] font-medium sm:hidden ${+ mobileOpen+ ? "text-[var(--color-accent-primary)]"+ : "text-[var(--color-text-secondary)]"+ }`}+ aria-expanded={mobileOpen}+ aria-label="Graph controls"+ >+ <SlidersHorizontal className="w-3 h-3" />+ Controls+ </button></div>);});diff --git a/packages/ui/src/graph/index.ts b/packages/ui/src/graph/index.tsindex d81aa2827..50380b03a 100644--- a/packages/ui/src/graph/index.ts+++ b/packages/ui/src/graph/index.ts@@ -10,6 +10,7 @@ export * from "./node-badges";export * from "./graph-context-drawer";export * from "./graph-truncation-banner";export * from "./graph-canvas-shell";+export * from "./graph-scope-breadcrumb";export * from "./graph-flow";export * from "./graph-flow-panel";export * from "./edge-provenance";diff --git a/packages/ui/src/graph/path-finder-panel.tsx b/packages/ui/src/graph/path-finder-panel.tsxindex 41b833dbc..0091a34e4 100644--- a/packages/ui/src/graph/path-finder-panel.tsx+++ b/packages/ui/src/graph/path-finder-panel.tsx@@ -97,7 +97,7 @@ function NodeAutocomplete({/><ChevronDown className="absolute right-2.5 top-1/2 -translate-y-1/2 w-3 h-3 text-[var(--color-text-tertiary)]" />{showDropdown && displayResults.length > 0 && (- <div className="absolute top-full left-0 mt-1 w-full max-h-52 overflow-auto z-50 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)] shadow-xl shadow-black/30 py-1">+ <div className="absolute top-full left-0 mt-1 w-full max-h-52 overflow-auto z-[var(--z-dropdown)] rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)] shadow-xl shadow-black/30 py-1">{results.length === 0 && topNodes.length > 0 && (<div className="px-3 py-1 text-[10px] text-[var(--color-text-tertiary)] uppercase tracking-wider">Top files by importancediff --git a/packages/ui/src/graph/sigma/constants.ts b/packages/ui/src/graph/sigma/constants.tsindex 248f3a155..d2706c0f4 100644--- a/packages/ui/src/graph/sigma/constants.ts+++ b/packages/ui/src/graph/sigma/constants.ts@@ -44,13 +44,14 @@ export function getNodeMass(// ---- Edge colors by semantic type (warm theme palette) ----//// Per-theme literal hex (canvas can't resolve var()); mirrors the semantic-// edge palette in lib/confidence.ts EDGE_COLORS — import = brand orange,+// edge palette in lib/confidence.ts EDGE_COLORS. No "import" key: that kind+// was only ever returned for an edge with an endpoint missing from the graph,+// and the adapter drops those before drawing.// crossCommunity = plum (--color-accent-secondary), internal = sage/green// (--color-success family). Dark variants are lifted to read on the near-black// plum canvas. Resolve via edgeColorsForTheme(); kept literal + allowlisted.export type EdgeKind =- | "import"| "crossCommunity"| "internal"| "dynamic"@@ -61,14 +62,12 @@ export const EDGE_COLORS_BY_THEME: Record<Record<EdgeKind, string>> = {light: {- import: "#f59520", // brand orangecrossCommunity: "#58436c", // plum (accent-secondary)internal: "#1d8155", // sage/green (success)dynamic: "#8c7f88", // muted text-tertiarylowConfidence: "#b8aeb3", // faint plum-gray},dark: {- import: "#f59520", // brand orangecrossCommunity: "#a98fc4", // plum-300 (accent-secondary dark)internal: "#34d399", // green (success dark)dynamic: "#786f84", // muted text-tertiary dark@@ -89,7 +88,6 @@ export function edgeColorsForTheme(export const EDGE_COLORS = EDGE_COLORS_BY_THEME.dark;export const EDGE_SIZE_MULTIPLIERS = {- import: 0.6,crossCommunity: 0.8,internal: 0.4,dynamic: 0.3,diff --git a/packages/ui/src/graph/sigma/constellation-adapter.ts b/packages/ui/src/graph/sigma/constellation-adapter.tsindex 4919ae24f..caf9ea2d2 100644--- a/packages/ui/src/graph/sigma/constellation-adapter.ts+++ b/packages/ui/src/graph/sigma/constellation-adapter.ts@@ -199,6 +199,11 @@ export interface SliceMergeResult {* `nodeType:"file"` so the community-mode recolor paints them the family SOFT* variant automatically.*/+/**+ * @deprecated No longer called. A hub double-click enters the community and+ * hands its slice to the file-graph renderer instead of blossoming satellites+ * on the radial layout. Kept exported for out-of-tree hosts mid-port.+ */export function mergeCommunitySlice(graph: Graph<SigmaNodeAttributes, SigmaEdgeAttributes>,communityId: number,diff --git a/packages/ui/src/graph/sigma/graphology-adapter.ts b/packages/ui/src/graph/sigma/graphology-adapter.tsindex 6ee5ba753..77832b9d4 100644--- a/packages/ui/src/graph/sigma/graphology-adapter.ts+++ b/packages/ui/src/graph/sigma/graphology-adapter.ts@@ -55,13 +55,118 @@ function classifyEdge(sourceNode.community_id === targetNode.community_id)return "internal";- if (- sourceNode &&- targetNode &&- sourceNode.community_id !== targetNode.community_id- )- return "crossCommunity";- return "import";+ // One endpoint is missing from `nodeMap`, which is built from exactly+ // `graph.nodes` — so the edge loop below drops this link before it is ever+ // drawn. It still needs a kind to be bucketed by; "crossCommunity" is the+ // honest reading of an edge leaving the known set.+ return "crossCommunity";+}++/**+ * Positions for a community slice, which the whole-repo seed lays out badly.+ *+ * That seed partitions by `community_id` and puts each community's centroid on+ * a golden-angle ring. A slice is one community by definition, so the partition+ * degenerates: every member shares an id and lands in a single small disc,+ * while the boundary stubs carry their own real community ids and get strewn+ * across the rest of the ring. Measured on a 94-node slice the members occupied+ * 3.4% of the drawn area and every member-to-stub edge was a chord longer than+ * the members' own diameter.+ *+ * So lay a slice out on its own terms: members fill the middle, stubs ring the+ * edge on the bearing of whatever they attach to.+ */+function seedSlicePositions(+ graph: GraphExport,+ boundaryNodeIds: Set<string>,+ spread: number,+): Map<string, { x: number; y: number }> {+ const goldenAngle = Math.PI * (3 - Math.sqrt(5));+ const positions = new Map<string, { x: number; y: number }>();+ const members = graph.nodes.filter((n) => !boundaryNodeIds.has(n.node_id));+ const stubs = graph.nodes.filter((n) => boundaryNodeIds.has(n.node_id));+ if (members.length === 0) return positions;++ // Sunflower over the inner 60% of the field. sqrt on the radius keeps the+ // distribution uniform over area rather than bunched at the centre.+ const memberRadius = spread * 0.6;+ const memberAngle = new Map<string, number>();+ members.forEach((node, i) => {+ const angle = i * goldenAngle;+ // `i / n`, so member 0 sits at the centre and member n-1 near the rim.+ // With `(i + 1) / n` the first member took the full radius, which drew a+ // one-file community out on the 3 o'clock ray with every stub stacked on+ // that same bearing and the rest of the field empty.+ const r = memberRadius * Math.sqrt(i / members.length);+ memberAngle.set(node.node_id, angle);+ positions.set(node.node_id, {+ x: r * Math.cos(angle),+ y: r * Math.sin(angle),+ });+ });++ // Vector mean of the bearings a stub is pulled toward, not a mean of the+ // angles: averaging 0.1 and 6.2 radians numerically would put the stub on the+ // opposite side of the graph from both of its neighbours.+ const pull = new Map<string, { x: number; y: number; n: number }>();+ for (const link of graph.links) {+ const sourceIsStub = boundaryNodeIds.has(link.source);+ const targetIsStub = boundaryNodeIds.has(link.target);+ if (sourceIsStub === targetIsStub) continue;+ const stub = sourceIsStub ? link.source : link.target;+ const angle = memberAngle.get(sourceIsStub ? link.target : link.source);+ if (angle === undefined) continue;+ const acc = pull.get(stub) ?? { x: 0, y: 0, n: 0 };+ acc.x += Math.cos(angle);+ acc.y += Math.sin(angle);+ acc.n += 1;+ pull.set(stub, acc);+ }++ // Resolve every bearing first, then fan. Cancellation is judged against a+ // residue scaled by the number of contributing links, because two exactly+ // opposite bearings sum to ~1e-17 rather than to 0.+ const bearings = stubs.map((node, i) => {+ const acc = pull.get(node.node_id);+ const cancelled =+ !acc || Math.hypot(acc.x, acc.y) < acc.n * 1e-9;+ // Nothing to point at, or pulls that cancel: spread the unanchored stubs+ // evenly instead of stacking them on one bearing.+ return cancelled ? i * goldenAngle : Math.atan2(acc.y, acc.x);+ });++ // Stubs that share a bearing get a band wide enough to hold them all. A+ // community whose boundary hangs off one high-degree member would otherwise+ // put every stub in one small box, and since the seed IS the layout — FA2+ // and noverlap are both off for a file graph — nothing separates them later.+ const perBearing = new Map<number, number>();+ const bucketOf = (a: number) => Math.round(a / 0.15);+ for (const a of bearings) {+ const b = bucketOf(a);+ perBearing.set(b, (perBearing.get(b) ?? 0) + 1);+ }+ const placedInBucket = new Map<number, number>();++ stubs.forEach((node, i) => {+ const angle = bearings[i]!;+ const bucket = bucketOf(angle);+ const crowd = perBearing.get(bucket) ?? 1;+ const seat = placedInBucket.get(bucket) ?? 0;+ placedInBucket.set(bucket, seat + 1);+ // The ring is a band, not a circle. The arc grows with the crowd so 40+ // stubs on one bearing occupy 40 seats rather than 40 overlapping discs;+ // the radial jitter is deterministic, like the rest of the seed.+ const arc = Math.min(0.2 * crowd, Math.PI / 2);+ const offset = crowd === 1 ? 0 : (seat / (crowd - 1) - 0.5) * arc;+ const hash = simpleHash(node.node_id);+ const ring = spread * (0.92 + (((hash >> 10) % 1000) / 1000) * 0.16);+ positions.set(node.node_id, {+ x: ring * Math.cos(angle + offset),+ y: ring * Math.sin(angle + offset),+ });+ });++ return positions;}function computeEdgeSize(@@ -113,6 +218,9 @@ const CHUNK_SIZE = 500;export type FileGraphAdapterOptions = {signals?: { hotNodeIds?: Set<string>; deadNodeIds?: Set<string> };nodeCount?: number;+ /** Nodes that are context rather than content — the one-hop stubs a community+ * slice carries. Drawn as the boundary of the scoped view. */+ boundaryNodeIds?: Set<string>;};export function fileGraphToGraphology(@@ -173,6 +281,13 @@ function* buildFileGraph();const communityCount = sortedCommunities.length;+ // A slice gets its own seed; see seedSlicePositions for why the partition+ // above degenerates when every member shares one community id.+ const slicePositions =+ options?.boundaryNodeIds?.size && spread > 0+ ? seedSlicePositions(graph, options.boundaryNodeIds, spread)+ : null;+let processed = 0;for (let i = 0; i < sortedCommunities.length; i++) {const communityId = sortedCommunities[i]!;@@ -192,8 +307,9 @@ function* buildFileGraph(const hash = simpleHash(node.node_id);const r = (jitter / 2) * Math.sqrt((hash % 1000) / 1000);const theta = (((hash >> 10) % 1000) / 1000) * 2 * Math.PI;- const x = centroidX + r * Math.cos(theta);- const y = centroidY + r * Math.sin(theta);+ const seeded = slicePositions?.get(node.node_id);+ const x = seeded ? seeded.x : centroidX + r * Math.cos(theta);+ const y = seeded ? seeded.y : centroidY + r * Math.sin(theta);let baseSize: number;if (node.is_entry_point) {@@ -206,6 +322,12 @@ function* buildFileGraph(let size = getScaledNodeSize(baseSize, nodeCount);size *= Math.min(1 + node.pagerank * 2, 2);+ const isBoundary = options?.boundaryNodeIds?.has(node.node_id) ?? false;+ // Two thirds, so a stub reads as smaller than every member without+ // vanishing. Colour is handled in use-sigma's colour pass, which runs+ // after this and would otherwise overwrite anything set here.+ if (isBoundary) size *= 0.65;+const color = languageColor(node.language);const attrs: SigmaNodeAttributes = {@@ -227,6 +349,7 @@ function* buildFileGraph(mass: getNodeMass("file", nodeCount),originalColor: color,};+ if (isBoundary) attrs.isBoundary = true;// Signal data may come from two sources: explicit overlay sets// (legacy unified-graph flow) or enriched node payloads from Phase A.@@ -256,7 +379,6 @@ function* buildFileGraph(// Classify edges in one O(E) pass, then bucket by kind (avoids O(E log E) sort)const kindBuckets: Record<SigmaEdgeAttributes["edgeKind"], GraphLink[]> = {crossCommunity: [],- import: [],internal: [],dynamic: [],lowConfidence: [],@@ -269,7 +391,6 @@ function* buildFileGraph(}const orderedLinks = (kindBuckets.crossCommunity- .concat(kindBuckets.import).concat(kindBuckets.internal).concat(kindBuckets.dynamic).concat(kindBuckets.lowConfidence)diff --git a/packages/ui/src/graph/sigma/sigma-canvas.tsx b/packages/ui/src/graph/sigma/sigma-canvas.tsxindex 0291ec321..66481cf54 100644--- a/packages/ui/src/graph/sigma/sigma-canvas.tsx+++ b/packages/ui/src/graph/sigma/sigma-canvas.tsx@@ -17,7 +17,7 @@ import type {GraphNode as GraphNodeResponse,GraphLink as GraphEdgeResponse,} from "@repowise-dev/types/graph";-import { useSigmaRenderer } from "./use-sigma";+import { useSigmaRenderer, type CameraPosition } from "./use-sigma";import { useFA2Layout } from "./use-fa2-layout";import { useElkSigmaLayout } from "./use-elk-sigma-layout";import { SigmaControls } from "./sigma-controls";@@ -59,6 +59,9 @@ export interface SigmaCanvasProps {visibleEdgeTypes?: Set<string> | undefined;/** Concentric depth-ring radii (graph coords) for the constellation underlay. */depthRingRadii?: readonly [number, number, number] | null | undefined;+ /** Suppress the camera easings. Honour `prefers-reduced-motion` here rather+ * than reading the media query inside the renderer. */+ reducedMotion?: boolean | undefined;}export interface SigmaCanvasHandle {@@ -66,6 +69,11 @@ export interface SigmaCanvasHandle {fitView: () => void;zoomIn: () => void;zoomOut: () => void;+ /** Where the camera would sit to frame `nodeId` in the graph drawn *now*. */+ nodeCamera: (nodeId: string, ratio?: number) => CameraPosition | null;+ /** Seed the camera's starting point for the next graph swap (consumed once),+ * so a drill-down reads as one movement instead of a hard cut. */+ setEntryCamera: (state: CameraPosition | null) => void;}export const SigmaCanvas = forwardRef<SigmaCanvasHandle, SigmaCanvasProps>(@@ -75,7 +83,8 @@ export const SigmaCanvas = forwardRef<SigmaCanvasHandle, SigmaCanvasProps>(setContainer(node);}, []);- const { sigma, focusNode, fitView, zoomIn, zoomOut } = useSigmaRenderer({+ const { sigma, focusNode, fitView, zoomIn, zoomOut, nodeCamera, setEntryCamera } =+ useSigmaRenderer({container,graph: props.graph,selectedNodeId: props.selectedNodeId,@@ -89,6 +98,7 @@ export const SigmaCanvas = forwardRef<SigmaCanvasHandle, SigmaCanvasProps>(graphTheme: props.graphTheme,hiddenNodes: props.hiddenNodes,visibleEdgeTypes: props.visibleEdgeTypes,+ reducedMotion: props.reducedMotion,});const { isRunning: isLayoutRunning } = useFA2Layout({@@ -204,6 +214,8 @@ export const SigmaCanvas = forwardRef<SigmaCanvasHandle, SigmaCanvasProps>(fitView,zoomIn,zoomOut,+ nodeCamera,+ setEntryCamera,}));const hasDepthRings = !!props.depthRingRadii;diff --git a/packages/ui/src/graph/sigma/sigma-controls.tsx b/packages/ui/src/graph/sigma/sigma-controls.tsxindex 281e3afe1..d8e11e5b2 100644--- a/packages/ui/src/graph/sigma/sigma-controls.tsx+++ b/packages/ui/src/graph/sigma/sigma-controls.tsx@@ -29,7 +29,10 @@ export function SigmaControls({"flex h-9 w-9 sm:h-7 sm:w-7 items-center justify-center rounded-md text-[var(--color-text-tertiary)] transition-colors hover:bg-[var(--color-bg-wash-hover)] hover:text-[var(--color-text-primary)]";return (- <div className="absolute bottom-3 right-3 z-10 flex flex-col items-end gap-1.5">+ // `--canvas-chrome-bottom` is published by `GraphCanvasShell` when a rail+ // is open as a bottom sheet, so these controls clear it instead of sitting+ // underneath. Falls back to the plain inset when nothing sets it.+ <div className="absolute bottom-[var(--canvas-chrome-bottom,0.75rem)] right-3 z-[var(--z-elevated)] flex flex-col items-end gap-1.5 transition-[bottom] duration-200 motion-reduce:transition-none">{isLayoutRunning && (<div className="flex items-center gap-1.5 whitespace-nowrap rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]/85 px-2 py-1 text-[10px] text-[var(--color-accent-primary)] shadow-sm backdrop-blur-sm"><ActivityDot className="h-1.5 w-1.5" />diff --git a/packages/ui/src/graph/sigma/types.ts b/packages/ui/src/graph/sigma/types.tsindex f0050ab9a..4741c50fc 100644--- a/packages/ui/src/graph/sigma/types.ts+++ b/packages/ui/src/graph/sigma/types.ts@@ -52,6 +52,11 @@ export interface SigmaNodeAttributes {/** Render the label even when density culling would hide it (hubs/core). */forceLabel?: boolean | undefined;+ /** A one-hop neighbour drawn *outside* the community slice on screen: the+ * edge of the world, not a member. Drawn smaller and desaturated so the+ * scoped graph has a visible boundary instead of trailing off. */+ isBoundary?: boolean | undefined;+// Signal overlays (set by adapter based on signal data)isHotspot?: boolean | undefined;isDead?: boolean | undefined;@@ -89,7 +94,6 @@ export interface SigmaEdgeAttributes {// Semantic classification of the edgeedgeKind:- | "import"| "crossCommunity"| "internal"| "dynamic"diff --git a/packages/ui/src/graph/sigma/use-sigma.ts b/packages/ui/src/graph/sigma/use-sigma.tsindex 3acaed3f9..23ec06c42 100644--- a/packages/ui/src/graph/sigma/use-sigma.ts+++ b/packages/ui/src/graph/sigma/use-sigma.ts@@ -428,6 +428,17 @@ export interface UseSigmaOptions {graphTheme: "light" | "dark";hiddenNodes?: Set<string> | undefined;visibleEdgeTypes?: Set<string> | undefined;+ /** Suppress the camera easings this hook drives. Read live, so a change to+ * the OS setting takes effect without a remount. */+ reducedMotion?: boolean | undefined;+}++/** A camera position in Sigma's *framed* coordinate space (what+ * `getNodeDisplayData` returns), not raw graph coordinates. */+export interface CameraPosition {+ x: number;+ y: number;+ ratio: number;}export interface UseSigmaReturn {@@ -439,6 +450,18 @@ export interface UseSigmaReturn {fitView: () => void;zoomIn: () => void;zoomOut: () => void;+ /** A camera position framing `nodeId` as it sits *right now*, for handing to+ * {@link UseSigmaReturn.setEntryCamera} across a graph swap. */+ nodeCamera: (nodeId: string, ratio?: number) => CameraPosition | null;+ /**+ * Seed where the camera *starts* on the next graph swap, consumed once.+ *+ * A graph swap otherwise resets the camera from wherever it happens to be,+ * which throws away the reader's place. Drilling into a community sets this+ * to the hub's own position, so the new scoped graph opens at the point the+ * hub occupied and eases out to frame itself: one movement, not two pages.+ */+ setEntryCamera: (state: CameraPosition | null) => void;}export function useSigmaRenderer(options: UseSigmaOptions): UseSigmaReturn {@@ -572,6 +595,9 @@ export function useSigmaRenderer(options: UseSigmaOptions): UseSigmaReturn {const family = communityFamilies(attrs.communityId);color = attrs.nodeType === "module" ? family.hub : family.satellite;}+ // Boundary stubs are context, not content: they sit outside the+ // community being drawn, so they recede before any signal tint.+ if (attrs.isBoundary) color = desaturateColor(color, 0.8);if (attrs.isDead) color = desaturateColor(color, 0.6);if (attrs.isHotspot) color = tintColor(color, viz.hotspot, 0.4);// Decision-anchored files get a subtle warm tint so they're@@ -592,7 +618,7 @@ export function useSigmaRenderer(options: UseSigmaOptions): UseSigmaReturn {const edge = viz.edge;graph.updateEachEdgeAttributes((_edgeKey, attrs) => {- const color = edge[attrs.edgeKind] ?? edge.import;+ const color = edge[attrs.edgeKind] ?? edge.internal;if (attrs.color === color) return attrs;return { ...attrs, color };},@@ -802,13 +828,34 @@ export function useSigmaRenderer(options: UseSigmaOptions): UseSigmaReturn {};}, [options.container]);+ // Where the camera should *start* on the next graph swap, consumed once.+ const entryCameraRef = useRef<CameraPosition | null>(null);+ const setEntryCamera = useCallback((state: CameraPosition | null) => {+ entryCameraRef.current = state;+ }, []);+ // Read at swap time rather than closed over, so the deps below stay `[graph]`+ // and a settings change never re-swaps the graph.+ const reducedMotionRef = useRef(!!options.reducedMotion);+ reducedMotionRef.current = !!options.reducedMotion;+// Update graph when it changesuseEffect(() => {const sigma = sigmaRef.current;if (!sigma || !options.graph) return;graphRef.current = options.graph;sigma.setGraph(options.graph);- sigma.getCamera().animatedReset({ duration: 500 });+ const camera = sigma.getCamera();+ const entry = entryCameraRef.current;+ entryCameraRef.current = null;+ // Reduced motion still resets — it is the *travel* that is suppressed, not+ // the destination, and skipping the reset would leave the new graph framed+ // by the old one's camera.+ if (reducedMotionRef.current) {+ camera.animatedReset({ duration: 0 });+ return;+ }+ if (entry) camera.setState({ x: entry.x, y: entry.y, ratio: entry.ratio, angle: 0 });+ camera.animatedReset({ duration: 500 });}, [options.graph]);// Label culling is a function of graph size, but the init effect above depends@@ -842,10 +889,22 @@ export function useSigmaRenderer(options: UseSigmaOptions): UseSigmaReturn {if (!display) return;sigma.getCamera().animate({ x: display.x, y: display.y, ratio },- { duration: 400 },+ { duration: reducedMotionRef.current ? 0 : 400 },);}, []);+ const nodeCamera = useCallback(+ (nodeId: string, ratio = 0.15): CameraPosition | null => {+ const sigma = sigmaRef.current;+ const graph = graphRef.current;+ if (!sigma || !graph || !graph.hasNode(nodeId)) return null;+ const display = sigma.getNodeDisplayData(nodeId);+ if (!display) return null;+ return { x: display.x, y: display.y, ratio };+ },+ [],+ );+const fitView = useCallback(() => {sigmaRef.current?.getCamera().animatedReset({ duration: 300 });}, []);@@ -864,5 +923,7 @@ export function useSigmaRenderer(options: UseSigmaOptions): UseSigmaReturn {fitView,zoomIn,zoomOut,+ nodeCamera,+ setEntryCamera,};}diff --git a/packages/ui/src/graph/use-community-filter.ts b/packages/ui/src/graph/use-community-filter.tsindex 5cdb54540..9b8db2adf 100644--- a/packages/ui/src/graph/use-community-filter.ts+++ b/packages/ui/src/graph/use-community-filter.ts@@ -39,9 +39,20 @@ export function useCommunityFilter(sigmaGraph: SigmaGraph | null) {const handleCommunityToggle = useCallback((cid: number) => {+ // A community with nothing on this canvas has nothing to toggle. The+ // key used to list communities from the repo-wide summary, so clicking+ // one that was not drawn added a phantom id: nothing dimmed, the swatch+ // stayed filled, and the phantom then made `next.size` match and reset+ // the filter to "show all" — the opposite of the label.+ if (!allCommunityIds.has(cid)) return;setActiveCommunities((prev) => {- const current = prev ?? new Set(allCommunityIds);- const next = new Set(current);+ // Re-intersected every time: the drawn set changes on a signal toggle,+ // a module filter, an ego depth and a load-more, and an id left over+ // from a graph that is gone made the size check below fire on the+ // wrong click.+ const next = new Set(+ prev ? [...prev].filter((id) => allCommunityIds.has(id)) : allCommunityIds,+ );if (next.has(cid)) next.delete(cid);else next.add(cid);if (next.size === allCommunityIds.size) return null;@@ -58,6 +69,9 @@ export function useCommunityFilter(sigmaGraph: SigmaGraph | null) {return {activeCommunities,communityDimmedNodes,+ /** Communities with at least one node on the canvas. The key filters its+ * rows by this so it cannot offer a toggle that does nothing. */+ drawnCommunityIds: allCommunityIds,handleCommunityToggle,handleToggleAllCommunities,};diff --git a/packages/ui/src/graph/use-expanded-hubs.ts b/packages/ui/src/graph/use-expanded-hubs.tsindex fceffe2e7..97509332f 100644--- a/packages/ui/src/graph/use-expanded-hubs.ts+++ b/packages/ui/src/graph/use-expanded-hubs.ts@@ -8,8 +8,14 @@ import { useState, useCallback } from "react";* most-recent-LAST so Esc / {@link collapseLast} closes the most recently* opened cluster (documented behavior). {@link collapseAll} closes everything.*- * Pure client state — the actual member slices are fetched separately- * (see useCommunitySlices) and merged into the sigma graph by the shell.+ * Pure client state — the actual member slices were fetched separately and+ * merged into the sigma graph by the shell.+ *+ * @deprecated No longer wired up. A hub double-click now *enters* the+ * community and draws its own scoped file graph (`GraphFlow`'s+ * `activeCommunity` / `communitySlice`), rather than blossoming its members as+ * satellites on the radial layout. Kept exported, and untouched, only so an+ * out-of-tree host compiles while it ports; delete once none does.*/export function useExpandedHubs() {// Insertion-ordered list of expanded community ids (oldest → newest).diff --git a/packages/ui/src/graph/use-module-filter.ts b/packages/ui/src/graph/use-module-filter.tsindex 8f20a2828..3e6856291 100644--- a/packages/ui/src/graph/use-module-filter.ts+++ b/packages/ui/src/graph/use-module-filter.ts@@ -1,8 +1,5 @@-import { useCallback, useMemo, useState } from "react";-import type Graph from "graphology";-import type { SigmaEdgeAttributes, SigmaNodeAttributes } from "./sigma/types";--type SigmaGraph = Graph<SigmaNodeAttributes, SigmaEdgeAttributes>;+import { useMemo } from "react";+import type { GraphNode } from "@repowise-dev/types/graph";/** Bucket every path outside the repo's own tree, however it is spelled. */const EXTERNAL_GROUP = "external";@@ -38,43 +35,38 @@ export interface ModuleGroup {}/**- * Filter the file graph by module, by dimming everything outside the selected- * module rather than removing it — the surrounding structure is the context- * that makes "this module" mean anything, and it is the same grammar the- * community filter, the ego filter and search already use.+ * Filter the file graph by module: a path prefix, everything outside it+ * **removed** from the graph that gets built.+ *+ * It used to dim instead. Dimming 1,500 nodes means reading the answer through+ * fog while still paying to lay out, colour and draw every node you asked to+ * hide — the worst of both. Removing them is the honest reading of "filter" and+ * it is also strictly cheaper: the graphology build, the layout and the render+ * all shrink to what you selected.*- * `activeModule === null` means no filter.+ * The group list is derived from the **unfiltered** nodes, so choosing a module+ * never collapses the menu you chose it from.** This replaces a whole separate "Modules" scope, which drew one circle per* top-level directory: a 9-item list where one item held 69% of the files,* with its own endpoint, breadcrumb trail, drill-down state and* expand-on-double-click. A skewed list is a bad canvas and a fine filter.*/-export function useModuleFilter(sigmaGraph: SigmaGraph | null) {- const [activeModule, setActiveModule] = useState<string | null>(null);-+export function useModuleFilter(+ nodes: readonly GraphNode[] | undefined,+ activeModule: string | null,+) {const moduleGroups = useMemo<ModuleGroup[]>(() => {- if (!sigmaGraph) return [];+ if (!nodes) return [];const counts = new Map<string, number>();- sigmaGraph.forEachNode((_nodeId, attrs) => {- if (attrs.nodeType !== "file") return;- const group = moduleGroupFor(attrs.fullPath);+ for (const node of nodes) {+ const group = moduleGroupFor(node.node_id);counts.set(group, (counts.get(group) ?? 0) + 1);- });+ }return [...counts].map(([id, fileCount]) => ({ id, fileCount })).sort((a, b) => b.fileCount - a.fileCount || a.id.localeCompare(b.id));- }, [sigmaGraph]);-- const moduleDimmedNodes = useMemo(() => {- if (!activeModule || !sigmaGraph) return null;- const dimmed = new Set<string>();- sigmaGraph.forEachNode((nodeId, attrs) => {- if (attrs.nodeType !== "file") return;- if (moduleGroupFor(attrs.fullPath) !== activeModule) dimmed.add(nodeId);- });- return dimmed.size > 0 ? dimmed : null;- }, [activeModule, sigmaGraph]);+ }, [nodes]);/** How many nodes the active module actually matches — the control reports* this, so it can never claim a filter that selected nothing. */@@ -83,15 +75,27 @@ export function useModuleFilter(sigmaGraph: SigmaGraph | null) {return moduleGroups.find((g) => g.id === activeModule)?.fileCount ?? 0;}, [activeModule, moduleGroups]);- const handleModuleChange = useCallback((next: string | null) => {- setActiveModule(next);- }, []);+ return { moduleGroups, activeModuleCount };+}- return {- activeModule,- activeModuleCount,- moduleGroups,- moduleDimmedNodes,- handleModuleChange,- };+/**+ * Narrow a file-graph payload to one module, dropping any link that lost an+ * endpoint. Pure, so the caller can memo it beside the rest of its graph data.+ * Returns the input unchanged when nothing is selected.+ */+export function filterGraphToModule<+ N extends { node_id: string },+ L extends { source: string; target: string },+>(+ data: { nodes: N[]; links: L[] },+ activeModule: string | null,+): { nodes: N[]; links: L[] } {+ if (!activeModule) return data;+ // No escape hatch when this matches nothing: a stale `?module=` from an old+ // link would otherwise render the whole graph under a control claiming one+ // module. The empty canvas plus the control's own count is the honest pair.+ const nodes = data.nodes.filter((n) => moduleGroupFor(n.node_id) === activeModule);+ const kept = new Set(nodes.map((n) => n.node_id));+ const links = data.links.filter((l) => kept.has(l.source) && kept.has(l.target));+ return { nodes, links };}diff --git a/packages/ui/src/symbols/symbol-table.tsx b/packages/ui/src/symbols/symbol-table.tsxindex b75644b05..97a8fc34a 100644--- a/packages/ui/src/symbols/symbol-table.tsx+++ b/packages/ui/src/symbols/symbol-table.tsx@@ -384,7 +384,7 @@ export function SymbolTable({{icon: GitBranch,label: "Graph",- href: `${prefix}/architecture?view=graph&node=${encodeURIComponent(sym.file_path)}`,+ href: `${prefix}/architecture?view=files&node=${encodeURIComponent(sym.file_path)}`,},{icon: BookOpen,diff --git a/packages/vscode/webview/src/views/graph/App.tsx b/packages/vscode/webview/src/views/graph/App.tsxindex 0e05fd8d9..3345c1676 100644--- a/packages/vscode/webview/src/views/graph/App.tsx+++ b/packages/vscode/webview/src/views/graph/App.tsx@@ -109,7 +109,8 @@ export function App({ host, params, repo, refreshToken }: ViewProps<"graph">) {host={host}communityId={p.communityId}onClose={p.onClose}- onExpandOnCanvas={p.onExpandOnCanvas}+ onEnterCommunity={p.onEnterCommunity}+ onNeighborSelect={p.onNeighborSelect}/>)}/>@@ -129,12 +130,14 @@ function CommunityPanel({host,communityId,onClose,- onExpandOnCanvas,+ onEnterCommunity,+ onNeighborSelect,}: {host: WebviewHost;communityId: number;onClose: () => void;- onExpandOnCanvas: () => void;+ onEnterCommunity: () => void;+ onNeighborSelect: (communityId: number) => void;}) {const [community, setCommunity] = useState<CommunityDetail | null>(null);const [isLoading, setIsLoading] = useState(true);@@ -165,7 +168,8 @@ function CommunityPanel({community={community}isLoading={isLoading}onClose={onClose}- onExpandOnCanvas={onExpandOnCanvas}+ onEnterCommunity={onEnterCommunity}+ onNeighborSelect={onNeighborSelect}/>);}diff --git a/packages/web/src/app/repos/[id]/architecture/page.tsx b/packages/web/src/app/repos/[id]/architecture/page.tsxindex 73bcb4f91..802ce22bf 100644--- a/packages/web/src/app/repos/[id]/architecture/page.tsx+++ b/packages/web/src/app/repos/[id]/architecture/page.tsx@@ -26,6 +26,8 @@* - `?view=` communities | files | coupling | packages | symbols* - `?signal=` dead | hot — which overlay is lit on the graph* - `?module=` a path prefix the file scope is filtered to+ * - `?community=` the community the file scope is drilled into. One axis with+ * `?module=`: both narrow the file graph, so at most one is ever set.** `?view=` and `?viewMode=` used to encode the same axis twice — `view=explore`* and `viewMode=full` both meant "the file graph", and they could disagree.@@ -125,6 +127,7 @@ export default function ArchitecturePage({const [viewModeParam, setViewModeParam] = useQueryState("viewMode");const [, setSignal] = useQueryState("signal");const [, setModule] = useQueryState("module");+ const [, setCommunity] = useQueryState("community");const [, setFocus] = useQueryState("focus");const [, setNode] = useQueryState("node");@@ -165,10 +168,11 @@ export default function ArchitecturePage({if (id !== "map") {void setSignal(null);void setModule(null);+ void setCommunity(null);void setNode(null);}},- [setView, setFocus, setSignal, setModule, setNode],+ [setView, setFocus, setSignal, setModule, setCommunity, setNode],);const handleScopeChange = useCallback(diff --git a/packages/web/src/app/repos/[id]/graph/page.tsx b/packages/web/src/app/repos/[id]/graph/page.tsxindex 4c5af468a..0c47d1e99 100644--- a/packages/web/src/app/repos/[id]/graph/page.tsx+++ b/packages/web/src/app/repos/[id]/graph/page.tsx@@ -10,7 +10,7 @@ export default async function LegacyGraphRedirect({}) {const { id } = await params;const sp = await searchParams;- const qs = new URLSearchParams({ view: "graph" });+ const qs = new URLSearchParams({ view: "communities" });for (const [key, value] of Object.entries(sp)) {if (typeof value === "string" && key !== "view") qs.set(key, value);}diff --git a/packages/web/src/app/repos/[id]/overview/page.tsx b/packages/web/src/app/repos/[id]/overview/page.tsxindex 6397cf212..e3e1e3751 100644--- a/packages/web/src/app/repos/[id]/overview/page.tsx+++ b/packages/web/src/app/repos/[id]/overview/page.tsx@@ -271,7 +271,7 @@ export default async function OverviewPage({ params }: Props) {{label: "Languages",value: formatNumber(summary.languages.length),- href: `${base}/architecture?view=graph&colorMode=language`,+ href: `${base}/architecture?view=files&colorMode=language`,},);@@ -441,7 +441,7 @@ export default async function OverviewPage({ params }: Props) {title="Composition"action={<SectionLink- href={`${base}/architecture?view=graph&colorMode=language`}+ href={`${base}/architecture?view=files&colorMode=language`}LinkComponent={Link}>Open the graphdiff --git a/packages/web/src/components/architecture/graph-view.tsx b/packages/web/src/components/architecture/graph-view.tsxindex a31846dff..b8b9bc2bd 100644--- a/packages/web/src/components/architecture/graph-view.tsx+++ b/packages/web/src/components/architecture/graph-view.tsx@@ -9,10 +9,11 @@ import { GraphDocPanel } from "@/components/graph/graph-doc-panel";import { GraphTruncationBanner } from "@repowise-dev/ui/graph/graph-truncation-banner";import {GraphScopeSwitcher,- ModuleFilterSelect,+ GraphNarrowingSelect,} from "@repowise-dev/ui/graph/graph-scope-controls";import type { ModuleGroup } from "@repowise-dev/ui/graph/use-module-filter";import { getGraph } from "@/lib/api/graph";+import { useCommunities } from "@/lib/hooks/use-graph";import type { GraphExportResponse } from "@/lib/api/types";type ViewMode = "full" | "architecture" | "dead" | "hotfiles" | "unified";@@ -54,6 +55,11 @@ export function GraphView({const [, setColorModeParam] = useQueryState("colorMode");const [signal, setSignal] = useQueryState("signal");const [activeModule, setActiveModule] = useQueryState("module");+ // The drill-down, as URL state, so "inside this community" is a link you can+ // share and restore. Written with nuqs' default `history: "replace"`, like+ // every other param on this page, so Back leaves the page rather than+ // stepping out of the community — the breadcrumb and Escape are the way up.+ const [communityParam, setCommunityParam] = useQueryState("community");const [docNodeId, setDocNodeId] = useState<string | null>(null);const [graphLimit, setGraphLimit] = useState<number | undefined>(undefined);const [moduleGroups, setModuleGroups] = useState<ModuleGroup[]>([]);@@ -63,12 +69,24 @@ export function GraphView({const effectiveScope: Scope = initialNode ? "files" : scope;const viewMode = toViewMode(effectiveScope, signal);+ // A non-numeric or absent `?community=` is simply "not drilled in", the same+ // as a bad `?colorMode=`: an old link degrades, it does not error.+ // Matched rather than coerced: `Number("")` and `Number(" ")` are both 0, so+ // a bare `?community=` would resolve to community zero, which is a real one.+ const activeCommunity =+ effectiveScope === "files" && communityParam !== null && /^\d+$/.test(communityParam)+ ? Number(communityParam)+ : null;++ const { communities } = useCommunities(repoId);+// Only the unfiltered file scope renders the capped `/api/graph` payload.// The constellation, and each of the dead/hot signals, has its own endpoint —// so neither the fetch nor the truncation banner belongs to them. The banner// used to show under the signals too, announcing "1,500 of 3,194 files" over- // a canvas drawing 734 nodes that came from somewhere else entirely.- const usesFullGraph = effectiveScope === "files" && !signal;+ // a canvas drawing 734 nodes that came from somewhere else entirely. An+ // entered community brings its own payload for the same reason.+ const usesFullGraph = effectiveScope === "files" && !signal && activeCommunity === null;const { data: graphData } = useSWR<GraphExportResponse>(usesFullGraph ? `graph:${repoId}:${graphLimit ?? "default"}` : null,@@ -133,12 +151,61 @@ export function GraphView({const handleScopeChange = useCallback((next: Scope) => {- // The module filter is a file-scope concept; carrying it into the- // communities view would leave a control set to something invisible.- if (next === "communities") void setActiveModule(null);+ // Narrowing is a file-scope concept, so it does not survive a trip to the+ // constellation. It does not survive a trip *back* either: a+ // `?view=communities&community=3` link (hand-edited, or an old share)+ // renders the constellation with the param still set, and without this+ // clicking "Files" would drop the reader inside community 3 rather than+ // in the file graph they asked for.+ void setActiveModule(null);+ void setCommunityParam(null);+ // `?node=` forces the file scope for as long as it is set, so leaving it+ // behind makes every later scope change a no-op. Asking for a scope is+ // asking to stop looking at one pinned node.+ void setSelectedNode(null);onScopeChange(next);},- [onScopeChange, setActiveModule],+ [onScopeChange, setActiveModule, setCommunityParam, setSelectedNode],+ );++ // Entering or leaving a community, from the canvas (hub double-click, the+ // panel, Escape, the breadcrumb) or from the narrowing control. Entering+ // implies the file scope; leaving returns to the constellation the community+ // came from, which is where a community is a thing you can see.+ const handleActiveCommunityChange = useCallback(+ (next: number | null) => {+ void setCommunityParam(next === null ? null : String(next));+ // Same reason as the scope switcher: a `?node=` left over from opening a+ // file's docs inside the community would pin the file scope, so leaving+ // would land on the whole-repo file graph under a "Communities" URL.+ void setSelectedNode(null);+ if (next !== null) {+ void setActiveModule(null);+ // A slice is its own payload and was never filtered to dead or hot+ // files, so a `?signal=` carried in would caption it with counts that+ // describe a graph nobody is looking at.+ void setSignal(null);+ onScopeChange("files");+ } else {+ onScopeChange("communities");+ }+ },+ [setCommunityParam, setActiveModule, setSelectedNode, setSignal, onScopeChange],+ );++ const handleNarrowingChange = useCallback(+ ({ module, community }: { module: string | null; community: number | null }) => {+ // Community picks route through the same handler the canvas uses, so one+ // door does the reconciling (drop the `?node=` pin, drop `?signal=`, keep+ // the scope honest) however the reader asked.+ if (community !== null) {+ handleActiveCommunityChange(community);+ return;+ }+ void setCommunityParam(null);+ void setActiveModule(module);+ },+ [handleActiveCommunityChange, setCommunityParam, setActiveModule],);const isCommunities = effectiveScope === "communities";@@ -147,16 +214,27 @@ export function GraphView({() => (<div className="flex flex-wrap items-center gap-2">{!isCommunities && (- <ModuleFilterSelect- groups={moduleGroups}+ <GraphNarrowingSelect+ modules={moduleGroups}+ communities={communities}activeModule={activeModule}- onModuleChange={(next) => void setActiveModule(next)}+ activeCommunity={activeCommunity}+ onChange={handleNarrowingChange}/>)}<GraphScopeSwitcher scope={effectiveScope} onScopeChange={handleScopeChange} /></div>),- [isCommunities, moduleGroups, activeModule, setActiveModule, effectiveScope, handleScopeChange],+ [+ isCommunities,+ moduleGroups,+ communities,+ activeModule,+ activeCommunity,+ handleNarrowingChange,+ effectiveScope,+ handleScopeChange,+ ],);return (@@ -195,6 +273,8 @@ export function GraphView({// back/forward and shared links restore it without a remount.viewMode={viewMode}activeModule={activeModule}+ activeCommunity={activeCommunity}+ onActiveCommunityChange={handleActiveCommunityChange}// Same value the banner reports, so the caption and the canvas can// never disagree about how many files are drawn.graphLimit={graphLimit}diff --git a/packages/web/src/components/docs/docs-viewer.tsx b/packages/web/src/components/docs/docs-viewer.tsxindex 1c7982636..af4e3bcb2 100644--- a/packages/web/src/components/docs/docs-viewer.tsx+++ b/packages/web/src/components/docs/docs-viewer.tsx@@ -100,7 +100,7 @@ function DocsSidebar({ repoId, targetPath }: { repoId: string; targetPath: strin<div className="flex items-center justify-between gap-2"><span className="text-xs text-[var(--color-text-tertiary)]">Community</span><Link- href={`/repos/${repoId}/architecture?view=graph&colorMode=community`}+ href={`/repos/${repoId}/architecture?view=communities`}className="inline-flex items-center gap-1 truncate text-xs text-[var(--color-accent)] hover:underline">{metrics.community_label}diff --git a/packages/web/src/components/graph/graph-community-panel.tsx b/packages/web/src/components/graph/graph-community-panel.tsxindex 5f2ead366..6fb964466 100644--- a/packages/web/src/components/graph/graph-community-panel.tsx+++ b/packages/web/src/components/graph/graph-community-panel.tsx@@ -9,14 +9,16 @@ interface GraphCommunityPanelWrapperProps {repoId: string;communityId: number;onClose: () => void;- onExpandOnCanvas?: (() => void) | undefined;+ onEnterCommunity?: (() => void) | undefined;+ onNeighborSelect?: ((communityId: number) => void) | undefined;}export function GraphCommunityPanel({repoId,communityId,onClose,- onExpandOnCanvas,+ onEnterCommunity,+ onNeighborSelect,}: GraphCommunityPanelWrapperProps) {const { community, isLoading } = useCommunityDetail(repoId, communityId);@@ -26,8 +28,16 @@ export function GraphCommunityPanel({community={community as CommunityDetail | null | undefined}isLoading={isLoading}onClose={onClose}- onExpandOnCanvas={onExpandOnCanvas}+ onEnterCommunity={onEnterCommunity}+ onNeighborSelect={onNeighborSelect}memberHref={(path) => fileEntityPath(`/repos/${repoId}`, path)}+ // Code Health's triage map takes `?file=` and opens on that row, so a hot+ // member gets an exact destination rather than a repo-wide page.+ healthHrefFor={(path) =>+ `/repos/${repoId}/code-health?tab=triage&file=${encodeURIComponent(path)}`+ }+ deadCodeHref={`/repos/${repoId}/code-health?tab=dead-code`}+ codeHealthHref={`/repos/${repoId}/code-health`}/>);}diff --git a/packages/web/src/components/graph/graph-doc-panel.tsx b/packages/web/src/components/graph/graph-doc-panel.tsxindex 07f078f9b..d9f0e0e57 100644--- a/packages/web/src/components/graph/graph-doc-panel.tsx+++ b/packages/web/src/components/graph/graph-doc-panel.tsx@@ -21,7 +21,9 @@ export function GraphDocPanel({ repoId, nodeId, onClose }: GraphDocPanelWrapperPpage={page as DocPage | null | undefined}isLoading={isLoading}error={error}- fullPageHref={page ? fileEntityPath(`/repos/${repoId}`, nodeId) : undefined}+ // Unconditional: the file page is a valid route whether or not a wiki+ // page was written for the file, and it is the empty state's way out.+ fullPageHref={fileEntityPath(`/repos/${repoId}`, nodeId)}browseDocsHref={`/repos/${repoId}/docs`}onClose={onClose}/>diff --git a/packages/web/src/components/graph/graph-flow.tsx b/packages/web/src/components/graph/graph-flow.tsxindex 2e701d1af..295ecdc9d 100644--- a/packages/web/src/components/graph/graph-flow.tsx+++ b/packages/web/src/components/graph/graph-flow.tsx@@ -13,7 +13,7 @@ import {useDeadCodeGraph,useHotFilesGraph,useCommunities,- useCommunitySlices,+ useCommunitySlice,useExecutionFlows,} from "@/lib/hooks/use-graph";import { useRepo } from "@/lib/hooks/use-repo";@@ -37,6 +37,9 @@ export interface GraphFlowProps {viewMode?: ViewMode;/** Controlled module filter — the page owns it via `?module=`. */activeModule?: string | null;+ /** Controlled drill-down — the page owns it via `?community=`. */+ activeCommunity?: number | null;+ onActiveCommunityChange?: (communityId: number | null) => void;/** Node cap for the full-graph fetch, stepped up by the truncation banner.* Must be the SAME value the banner is reporting: this and the banner's own* fetch share an SWR key, so a mismatch means the caption describes a@@ -75,6 +78,8 @@ export function GraphFlow({initialViewMode,viewMode: controlledViewMode,activeModule,+ activeCommunity,+ onActiveCommunityChange,graphLimit,onModuleGroupsChange,initialColorMode,@@ -97,9 +102,6 @@ export function GraphFlow({initialViewMode ?? "architecture",);const viewMode = controlledViewMode ?? viewModeState;- // Currently-expanded constellation hubs (community ids). Drives the slice- // fetch; the shell owns the actual expand/collapse interaction state.- const [expandedHubs, setExpandedHubs] = useState<number[]>([]);// Latched on first open of the flows panel. It starts closed, so this keeps a// trace fetch nobody asked for off every file-scope render.const [flowsRequested, setFlowsRequested] = useState(false);@@ -121,11 +123,11 @@ export function GraphFlow({const { graph: hotGraph, isLoading: hotLoading } = useHotFilesGraph(viewMode === "hotfiles" ? repoId : null,);- // Member slices for expanded hubs — only fetched in the constellation scope- // and only while at least one hub is open (conditional SWR inside the hook).- const { slices: constellationSlices } = useCommunitySlices(- viewMode === "architecture" ? repoId : null,- expandedHubs,+ // The entered community's own sub-graph. Conditional inside the hook, so no+ // fetch happens until somebody drills in, and none survives leaving.+ const { slice: communitySlice, isLoading: sliceLoading } = useCommunitySlice(+ viewMode !== "architecture" && activeCommunity != null ? repoId : null,+ activeCommunity ?? null,);const { repo } = useRepo(repoId);const resolvedRepoName = repoName ?? repo?.name;@@ -150,8 +152,10 @@ export function GraphFlow({isLoadingFullGraph={fullLoading}constellationGraph={constellationGraph as ArchitectureGraph | undefined}isLoadingConstellationGraph={constellationLoading}- constellationSlices={constellationSlices as Map<number, CommunitySlice> | undefined}- onExpandedHubsChange={setExpandedHubs}+ communitySlice={communitySlice as CommunitySlice | undefined}+ isLoadingCommunitySlice={sliceLoading}+ activeCommunity={activeCommunity}+ onActiveCommunityChange={onActiveCommunityChange}{...(resolvedRepoName ? { repoName: resolvedRepoName } : {})}deadCodeGraph={deadGraph as GraphExport | undefined}isLoadingDeadCodeGraph={deadLoading}@@ -180,6 +184,19 @@ export function GraphFlow({)}fileHrefFor={(nodeId) => fileEntityPath(`/repos/${repoId}`, nodeId)}+ // The file page already carries a Health, a History and a Decisions tab+ // for exactly this file, so the graph hands off to them rather than to a+ // repo-wide page the reader then has to search.+ fileHealthHrefFor={(nodeId) =>+ `${fileEntityPath(`/repos/${repoId}`, nodeId)}?tab=health`+ }+ fileHistoryHrefFor={(nodeId) =>+ `${fileEntityPath(`/repos/${repoId}`, nodeId)}?tab=history`+ }+ fileDecisionsHrefFor={(nodeId) =>+ `${fileEntityPath(`/repos/${repoId}`, nodeId)}?tab=decisions`+ }+ deadCodeHref={`/repos/${repoId}/code-health?tab=dead-code`}onCommunityPanelOpen={onCommunityPanelOpen}onSelectedNodeChange={onSelectedNodeChange}renderPathFinder={(props) => (@@ -197,7 +214,8 @@ export function GraphFlow({repoId={repoId}communityId={props.communityId}onClose={props.onClose}- onExpandOnCanvas={props.onExpandOnCanvas}+ onEnterCommunity={props.onEnterCommunity}+ onNeighborSelect={props.onNeighborSelect}/>)}/>diff --git a/packages/web/src/components/risk/dead-code-tab.tsx b/packages/web/src/components/risk/dead-code-tab.tsxindex 0e28f660d..628b2a710 100644--- a/packages/web/src/components/risk/dead-code-tab.tsx+++ b/packages/web/src/components/risk/dead-code-tab.tsx@@ -57,7 +57,7 @@ export function DeadCodeTab({ repoId }: { repoId: string }) {patchFinding: (findingId, patch) => patchDeadCodeFinding(findingId, patch),fileHref: (path) => fileEntityPath(prefix, path),graphHref: (path) =>- `${prefix}/architecture?view=graph&node=${encodeURIComponent(path)}`,+ `${prefix}/architecture?view=files&node=${encodeURIComponent(path)}`,navigate: (href) => router.push(href),};diff --git a/packages/web/src/components/shared/file-card-host.tsx b/packages/web/src/components/shared/file-card-host.tsxindex c1dd505bc..2409a485e 100644--- a/packages/web/src/components/shared/file-card-host.tsx+++ b/packages/web/src/components/shared/file-card-host.tsx@@ -28,7 +28,7 @@ export function useFileCardHost(repoId?: string) {(repoId? {file: fileEntityPath(`/repos/${repoId}`, next.file_path),- graph: `/repos/${repoId}/architecture?view=graph&node=${encodeURIComponent(next.file_path)}`,+ graph: `/repos/${repoId}/architecture?view=files&node=${encodeURIComponent(next.file_path)}`,// `?file=` was read by nothing in the docs surface, so this// button silently opened the repo overview — a different file's// prose, looking exactly like the link had worked. The reader isdiff --git a/packages/web/src/lib/hooks/use-graph.ts b/packages/web/src/lib/hooks/use-graph.tsindex 9d6100f00..b6517c76d 100644--- a/packages/web/src/lib/hooks/use-graph.ts+++ b/packages/web/src/lib/hooks/use-graph.ts@@ -119,32 +119,16 @@ export function useCommunityDetail(repoId: string | null, communityId: number |}/**- * Constellation blossom: fetch the slices for the currently expanded hubs.- * Conditional — the key is null (no request) until at least one hub is- * expanded. We fetch all expanded ids in one SWR keyed on the sorted id list- * (deterministic key, no duplicate requests on re-render); each id resolves to- * its own slice via `getCommunitySlice`. Returns a map keyed by community_id.+ * The drill-down payload: one community's members plus the one-hop stubs that+ * bound them. Conditional — no request until somebody enters a community.*/-export function useCommunitySlices(- repoId: string | null,- expandedIds: readonly number[],-) {- const sorted = [...expandedIds].sort((a, b) => a - b);- const key =- repoId && sorted.length > 0- ? `community-slices:${repoId}:${sorted.join(",")}`- : null;- const { data, error, isLoading } = useSWR<Map<number, CommunitySliceResponse>>(- key,- async () => {- const slices = await Promise.all(- sorted.map((id) => getCommunitySlice(repoId!, id)),- );- return new Map(sorted.map((id, i) => [id, slices[i]!]));- },+export function useCommunitySlice(repoId: string | null, communityId: number | null) {+ const { data, error, isLoading } = useSWR<CommunitySliceResponse>(+ repoId && communityId != null ? `community-slice:${repoId}:${communityId}` : null,+ () => getCommunitySlice(repoId!, communityId!),SWR_OPTS,);- return { slices: data, error, isLoading };+ return { slice: data, error, isLoading };}export function useGraphMetrics(repoId: string | null, nodeId: string | null) {diff --git a/tests/unit/server/test_graph.py b/tests/unit/server/test_graph.pyindex 7072699f8..2f2f94111 100644--- a/tests/unit/server/test_graph.py+++ b/tests/unit/server/test_graph.py@@ -707,3 +707,113 @@ async def test_module_graph_aggregates_signals(client: AsyncClient, app) -> Noneassert src["dead_count"] == 1assert src["has_decision"] is Trueassert src["primary_owner"] == "Alice"+++# ---------------------------------------------------------------------------+# Community detail: state, not just shape (Phase 2)+# ---------------------------------------------------------------------------+++def _health_metric(path: str, *, score: float, nloc: int) -> dict:+ return {+ "file_path": path,+ "score": score,+ "max_ccn": 3,+ "max_nesting": 2,+ "nloc": nloc,+ "duplication_pct": 0.0,+ "has_test_file": False,+ "line_coverage_pct": None,+ "branch_coverage_pct": None,+ "module": "src",+ }+++async def test_community_detail_rolls_up_health_hot_dead_and_owner(+ client: AsyncClient, app+) -> None:+ repo = await create_test_repo(client)+ await _populate_two_communities(app.state.session_factory, repo["id"])++ async with get_session(app.state.session_factory) as session:+ # a.py: 100 lines at 9.0. b.py: 300 lines at 5.0. LOC-weighted mean is+ # (900 + 1500) / 400 = 6.0, which a plain mean would put at 7.0.+ await crud.save_health_metrics(+ session,+ repo["id"],+ [+ _health_metric("src/a.py", score=9.0, nloc=100),+ _health_metric("src/b.py", score=5.0, nloc=300),+ ],+ )+ await crud.upsert_git_metadata(+ session,+ repository_id=repo["id"],+ file_path="src/a.py",+ is_hotspot=True,+ primary_owner_name="Ada",+ )+ await crud.upsert_git_metadata(+ session,+ repository_id=repo["id"],+ file_path="src/b.py",+ is_hotspot=False,+ primary_owner_name="Ada",+ )+ session.add(+ DeadCodeFinding(+ repository_id=repo["id"],+ file_path="src/b.py",+ kind="unreachable_file",+ status="open",+ confidence=0.9,+ )+ )+ session.add(+ DecisionRecord(+ repository_id=repo["id"],+ title="Adopt FastAPI",+ status="active",+ source="cli",+ affected_files_json=json.dumps(["src/a.py"]),+ )+ )+ await session.flush()++ resp = await client.get(f"/api/graph/{repo['id']}/communities/0")+ assert resp.status_code == 200+ data = resp.json()++ assert data["health_score"] == 6.0+ assert data["scored_member_count"] == 2+ assert data["hot_count"] == 1+ assert data["dead_count"] == 1+ assert data["decision_count"] == 1+ assert data["primary_owner"] == "Ada"+ assert data["primary_owner_file_count"] == 2++ # The flags are on the members too, so the panel can name the files behind+ # each count rather than only reporting a number.+ by_path = {m["path"]: m for m in data["members"]}+ assert by_path["src/a.py"]["is_hotspot"] is True+ assert by_path["src/a.py"]["is_dead"] is False+ assert by_path["src/b.py"]["is_dead"] is True+++async def test_community_detail_health_is_null_when_nothing_is_scored(+ client: AsyncClient, app+) -> None:+ # Not zero. An unscored area has no reading, and a 0.0 would render as the+ # worst possible score on a surface whose whole job is "is this in trouble".+ repo = await create_test_repo(client)+ await _populate_two_communities(app.state.session_factory, repo["id"])++ resp = await client.get(f"/api/graph/{repo['id']}/communities/0")+ assert resp.status_code == 200+ data = resp.json()+ assert data["health_score"] is None+ assert data["scored_member_count"] == 0+ assert data["hot_count"] == 0+ assert data["primary_owner"] is None