Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(coupling): filter by what the graph explains, and open a pair (#1973)

Raghav Chamadiya0356771a19c5
diff --git a/packages/ui/__tests__/coupling/coupling-explorer.test.tsx b/packages/ui/__tests__/coupling/coupling-explorer.test.tsx
index 94a5cc185..bc5d1c88f 100644
--- a/packages/ui/__tests__/coupling/coupling-explorer.test.tsx
+++ b/packages/ui/__tests__/coupling/coupling-explorer.test.tsx
@@ -1,5 +1,5 @@
import { describe, it, expect, vi } from "vitest";
-import { render, waitFor, screen } from "@testing-library/react";
+import { render, waitFor, screen, fireEvent, within } from "@testing-library/react";
import type {
CouplingEdge,
CouplingNode,
@@ -78,4 +78,142 @@ describe("CouplingExplorer", () => {
const guidance = screen.getByText(/Tracing/i);
expect(guidance).toHaveTextContent("Tracing hub.py");
});
+});
+
+// The arcs live in the diagram's dedicated `fill="none"` group; the module
+// bands are separate paths outside it.
+const arcs = (container: HTMLElement) =>
+ container.querySelectorAll('g[fill="none"] > path').length;
+const inTable = () => within(screen.getByRole("table"));
+
+function labelled(
+ s: string,
+ t: string,
+ structural: CouplingEdge["structural"],
+ strength = 3,
+): CouplingEdge {
+ return { ...edge(s, t, strength), structural };
+}
+
+describe("CouplingExplorer structural segments", () => {
+ // A lockfile pair that outranks everything on strength, and the real finding.
+ const plumbing = labelled("pyproject.toml", "uv.lock", "not_applicable", 90);
+ const explained = labelled("core/a.py", "core/b.py", "corroborated", 50);
+ const finding = labelled("core/c.py", "server/d.py", "unexplained", 10);
+ const data = graph(
+ [
+ node("pyproject.toml"),
+ node("uv.lock"),
+ node("core/a.py"),
+ node("core/b.py"),
+ node("core/c.py"),
+ node("server/d.py"),
+ ],
+ [plumbing, explained, finding],
+ );
+
+ it("opens on the unexplained segment, so release plumbing is not the headline", () => {
+ render(<CouplingExplorer data={data} />);
+ expect(inTable().getByText("c.py")).toBeInTheDocument();
+ expect(inTable().queryByText("↔ uv.lock")).not.toBeInTheDocument();
+ expect(inTable().queryByText("↔ b.py")).not.toBeInTheDocument();
+ });
+
+ it("drives the diagram with the same filter as the table", () => {
+ const { container } = render(<CouplingExplorer data={data} />);
+ // One unexplained pair → one arc, not all three.
+ expect(arcs(container)).toBe(1);
+ fireEvent.click(screen.getByRole("button", { name: /^All/ }));
+ expect(arcs(container)).toBe(3);
+ });
+
+ it("narrows the diagram when the search box narrows the table", () => {
+ const { container } = render(<CouplingExplorer data={data} />);
+ fireEvent.click(screen.getByRole("button", { name: /^All/ }));
+ expect(arcs(container)).toBe(3);
+ fireEvent.change(screen.getByLabelText(/filter the couplings by file path/i), {
+ target: { value: "uv.lock" },
+ });
+ expect(arcs(container)).toBe(1);
+ });
+
+ it("opens on All when nothing is unexplained, rather than on an empty list", () => {
+ const noFinding = graph(
+ [node("pyproject.toml"), node("uv.lock"), node("core/a.py"), node("core/b.py")],
+ [plumbing, explained],
+ );
+ render(<CouplingExplorer data={noFinding} />);
+ expect(inTable().getByText("↔ uv.lock")).toBeInTheDocument();
+ });
+
+ it("hides the segments on an index written before the structural check", () => {
+ const data = graph([node("a.py"), node("b.py")], [edge("a.py", "b.py")]);
+ render(<CouplingExplorer data={data} />);
+ expect(screen.queryByRole("group", { name: /dependency graph/i })).not.toBeInTheDocument();
+ });
+});
+
+describe("CouplingExplorer pair selection", () => {
+ const data = graph(
+ [node("core/a.py"), node("core/b.py"), node("core/c.py")],
+ [edge("core/a.py", "core/b.py", 5), edge("core/a.py", "core/c.py", 2)],
+ );
+
+ it("pins both ends of the row's pair and serializes them to the focus", () => {
+ const onFocusChange = vi.fn();
+ render(<CouplingExplorer data={data} onFocusChange={onFocusChange} />);
+ fireEvent.click(inTable().getByText("↔ c.py"));
+ expect(onFocusChange).toHaveBeenCalledWith("core/a.py|core/c.py");
+ expect(screen.getByText(/Tracing/i)).toHaveTextContent("core/a.py ↔ core/c.py");
+ });
+
+ it("reopens a serialized pair from the initial focus", () => {
+ render(<CouplingExplorer data={data} initialFocus="core/a.py|core/b.py" />);
+ expect(screen.getByText(/Tracing/i)).toHaveTextContent("core/a.py ↔ core/b.py");
+ });
+
+ it("opens the pair's detail panel on the same click that pins it", () => {
+ render(<CouplingExplorer data={data} repoLinkPrefix="/repos/r" />);
+ // Not the file name: those are links and stop propagation so they can
+ // navigate. The rest of the row opens the panel.
+ fireEvent.click(inTable().getByText("↔ c.py").closest("tr")!);
+ const panel = screen.getByRole("dialog");
+ // The claim, the labelled AI action, and a route onward to each file.
+ expect(within(panel).getByRole("button", { name: /ai decouple prompt/i })).toBeInTheDocument();
+ const links = within(panel).getAllByRole("link", { name: /open file page/i });
+ expect(links).toHaveLength(2);
+ expect(links[0]).toHaveAttribute("href", "/repos/r/files/core/a.py");
+ });
+
+ it("names both directions separately in the panel", () => {
+ const asymmetric = graph(
+ [node("core/a.py"), node("core/b.py")],
+ [
+ {
+ ...edge("core/a.py", "core/b.py", 5),
+ support: 27,
+ confidence_ab: 0.47,
+ confidence_ba: 1.0,
+ structural: "unexplained",
+ },
+ ],
+ );
+ render(<CouplingExplorer data={asymmetric} />);
+ fireEvent.click(inTable().getAllByRole("row")[1]!);
+ const panel = within(screen.getByRole("dialog"));
+ // A single "up to 100%" hides which side owns it; both shares are stated.
+ expect(panel.getByText("47%")).toBeInTheDocument();
+ expect(panel.getByText("100%")).toBeInTheDocument();
+ expect(panel.getByText(/47% of its commits also touched b\.py/)).toBeInTheDocument();
+ expect(panel.getByText("Unexplained")).toBeInTheDocument();
+ });
+
+ it("treats an unrecognized pipe path as one file, not a pair", () => {
+ const odd = graph(
+ [node("weird|name.py"), node("core/b.py")],
+ [edge("core/b.py", "weird|name.py")],
+ );
+ render(<CouplingExplorer data={odd} initialFocus="weird|name.py" />);
+ expect(screen.getByText(/Tracing/i)).toHaveTextContent("Tracing weird|name.py");
+ });
});
\ No newline at end of file
diff --git a/packages/ui/__tests__/coupling/coupling-graph.test.tsx b/packages/ui/__tests__/coupling/coupling-graph.test.tsx
index 66f1c4242..8b6cec691 100644
--- a/packages/ui/__tests__/coupling/coupling-graph.test.tsx
+++ b/packages/ui/__tests__/coupling/coupling-graph.test.tsx
@@ -49,6 +49,54 @@ describe("CouplingGraph", () => {
expect(onHover).toHaveBeenCalledWith(expect.any(String));
});
+ it("is decorative and names the table as its accessible equivalent", () => {
+ const nodes = [node("api/a.py"), node("core/b.py")];
+ const edges = [edge("api/a.py", "core/b.py")];
+ const { container } = render(
+ <CouplingGraph nodes={nodes} edges={edges} tableId="pairs" />,
+ );
+ // No tab stop and no operable role, so it must not announce itself as one.
+ const svg = container.querySelector("svg")!;
+ expect(svg).toHaveAttribute("aria-hidden", "true");
+ expect(svg.getAttribute("role")).toBeNull();
+ expect(screen.getByRole("link", { name: /the table below/i })).toHaveAttribute(
+ "href",
+ "#pairs",
+ );
+ });
+
+ it("lights only the focused pair's arc, and rings both of its ends", () => {
+ const nodes = [node("api/a.py"), node("core/b.py"), node("ui/c.py")];
+ const edges = [edge("api/a.py", "core/b.py"), edge("api/a.py", "ui/c.py")];
+ const { container } = render(
+ <CouplingGraph
+ nodes={nodes}
+ edges={edges}
+ focusedPair={{ source: "api/a.py", target: "ui/c.py" }}
+ pinnedPair={{ source: "api/a.py", target: "ui/c.py" }}
+ />,
+ );
+ const arcs = [...container.querySelectorAll('g[fill="none"] > path')];
+ const lit = arcs.filter((p) => Number(p.getAttribute("stroke-opacity")) > 0.5);
+ // One arc: focusing a.py alone would light both of its couplings.
+ expect(lit).toHaveLength(1);
+ // A persistent ring on each end.
+ expect(container.querySelectorAll('circle[stroke="var(--color-accent-primary)"]')).toHaveLength(
+ 2,
+ );
+ });
+
+ it("keeps hub labels when a file is focused instead of swapping them out", () => {
+ const nodes = [node("api/a.py"), node("core/b.py"), node("ui/c.py")];
+ const edges = [edge("api/a.py", "core/b.py"), edge("core/b.py", "ui/c.py")];
+ const { container, rerender } = render(
+ <CouplingGraph nodes={nodes} edges={edges} focusedPath={null} />,
+ );
+ const unfocused = container.querySelectorAll("svg text").length;
+ rerender(<CouplingGraph nodes={nodes} edges={edges} focusedPath="api/a.py" />);
+ expect(container.querySelectorAll("svg text").length).toBeGreaterThanOrEqual(unfocused);
+ });
+
it("pins a file on click (onPinToggle fires with the path)", () => {
const nodes = [node("api/a.py"), node("core/b.py")];
const edges = [edge("api/a.py", "core/b.py")];
diff --git a/packages/ui/__tests__/coupling/coupling-prompt.test.ts b/packages/ui/__tests__/coupling/coupling-prompt.test.ts
new file mode 100644
index 000000000..03448e8f4
--- /dev/null
+++ b/packages/ui/__tests__/coupling/coupling-prompt.test.ts
@@ -0,0 +1,42 @@
+import { describe, it, expect } from "vitest";
+import { buildCouplingAiPrompt } from "../../src/health/ai-prompt-builder.js";
+
+const edge = {
+ source: "core/answer.py",
+ target: "core/config.py",
+ strength: 4.16,
+ last_co_change: "2026-06-01",
+ support: 27,
+ confidence_ab: 0.47,
+ confidence_ba: 1.0,
+ structural: "unexplained",
+};
+
+describe("buildCouplingAiPrompt", () => {
+ it("hands the model the evidence it is asked to judge", () => {
+ const prompt = buildCouplingAiPrompt({
+ edge,
+ repoName: "repowise",
+ nodes: {
+ "core/answer.py": { module: "core", score: 3.2, nloc: 900 },
+ "core/config.py": { module: "core", score: 8.1, nloc: 40 },
+ },
+ });
+ // The graph's verdict decides the question the prompt asks.
+ expect(prompt).toContain("nothing connects them");
+ expect(prompt).toContain("Shared commits: **27**");
+ expect(prompt).toContain("47% of A's own commits also touched B");
+ expect(prompt).toContain("100% of B's also touched A");
+ expect(prompt).toContain("module `core`, health 3.2/10, 900 lines");
+ // Only renders when the call site threads `repoName`.
+ expect(prompt).toContain("(`repowise`)");
+ });
+
+ it("says nothing about the graph when the index carries no verdict", () => {
+ const prompt = buildCouplingAiPrompt({
+ edge: { source: "a.py", target: "b.py", strength: 2, last_co_change: null },
+ });
+ expect(prompt).not.toContain("Dependency graph:");
+ expect(prompt).toContain("File A: `a.py`");
+ });
+});
diff --git a/packages/ui/__tests__/coupling/coupling-table.test.tsx b/packages/ui/__tests__/coupling/coupling-table.test.tsx
index ed92956d8..5f719bcc5 100644
--- a/packages/ui/__tests__/coupling/coupling-table.test.tsx
+++ b/packages/ui/__tests__/coupling/coupling-table.test.tsx
@@ -62,11 +62,14 @@ describe("CouplingTable (virtualized)", () => {
expect(link).toHaveAttribute("href", "/repos/r/files/api/a.py");
});
- it("sorts by strength ascending when the Strength header is toggled", () => {
+ it("sorts by strength ascending when the Strength header is toggled twice", () => {
const edges = [edge("a.py", "b.py", 9), edge("c.py", "d.py", 1)];
render(<CouplingTable edges={edges} />);
- // Default is strength desc → strongest (9) first. Toggle to ascending.
- fireEvent.click(inTable().getByRole("button", { name: /strength/i }));
+ // Default is confidence, not strength: the first click switches key and
+ // lands on desc (strongest first), the second flips it.
+ const strength = inTable().getByRole("button", { name: /strength/i });
+ fireEvent.click(strength);
+ fireEvent.click(strength);
const rows = screen.getAllByRole("row").filter((r) => r.querySelector("td"));
// First data row should now be the weakest pair (c.py ↔ d.py).
expect(rows[0]).toHaveTextContent("c.py");
@@ -77,12 +80,21 @@ describe("CouplingTable (virtualized)", () => {
expect(screen.getByText(/no couplings detected/i)).toBeInTheDocument();
});
- it("renders the AI decouple action when onGeneratePrompt is provided", () => {
- const onGenerate = vi.fn();
- render(<CouplingTable edges={[edge("a.py", "b.py")]} onGeneratePrompt={onGenerate} />);
- const btn = inTable().getByRole("button", { name: /ai decouple prompt/i });
- fireEvent.click(btn);
- expect(onGenerate).toHaveBeenCalledTimes(1);
+ it("keeps per-row actions out of the table", () => {
+ // The AI prompt lives in the pair panel, where it can carry a label.
+ render(<CouplingTable edges={[edge("a.py", "b.py")]} hasDetails />);
+ expect(inTable().queryByRole("button", { name: /ai decouple prompt/i })).not.toBeInTheDocument();
+ });
+
+ it("names each side's module so a cross-boundary pair is visible", () => {
+ const moduleFor = (p: string) => (p.startsWith("ui/") ? "ui" : "server");
+ render(<CouplingTable edges={[edge("ui/a.py", "server/b.py")]} moduleFor={moduleFor} />);
+ expect(inTable().getByText(/ui/)).toBeInTheDocument();
+ });
+
+ it("says so when both files sit in the same module", () => {
+ render(<CouplingTable edges={[edge("ui/a.py", "ui/b.py")]} moduleFor={() => "ui"} />);
+ expect(inTable().getByText("within ui")).toBeInTheDocument();
});
});
@@ -118,15 +130,56 @@ describe("CouplingTable together column", () => {
expect(inTable().queryByText(/of one side/)).not.toBeInTheDocument();
});
- it("sorts by shared commits, not by date", () => {
+ it("opens ordered by the stronger direction, not by strength or date", () => {
+ const edges = [
+ // Strongest and most recent, but only ever half one-sided.
+ { ...withSupport("a.py", "b.py", 90, 0.5, 0.5), strength: 40, last_co_change: "2026-06-09" },
+ // Weaker and older, but one side has never changed alone.
+ { ...withSupport("c.py", "d.py", 4, 0.02, 1.0), strength: 2, last_co_change: "2026-06-01" },
+ ];
+ render(<CouplingTable edges={edges} />);
+ const rows = inTable().getAllByRole("row").slice(1);
+ expect(within(rows[0]!).getByText("4 commits")).toBeInTheDocument();
+ });
+
+ it("breaks a confidence tie with the shared-commit count", () => {
const edges = [
- { ...withSupport("a.py", "b.py", 2, 0.5, 0.5), last_co_change: "2026-06-09" },
- { ...withSupport("c.py", "d.py", 40, 0.9, 0.9), last_co_change: "2026-06-01" },
+ withSupport("a.py", "b.py", 2, 0.9, 0.9),
+ withSupport("c.py", "d.py", 40, 0.9, 0.9),
];
render(<CouplingTable edges={edges} />);
- fireEvent.click(inTable().getByText("Together"));
const rows = inTable().getAllByRole("row").slice(1);
- // Descending by support puts the 40 first; by date it would be the 2.
expect(within(rows[0]!).getByText("40 commits")).toBeInTheDocument();
});
+
+ it("states the asymmetry and the structural verdict as a sentence", () => {
+ const edges: CouplingEdge[] = [
+ {
+ ...withSupport("core/answer.py", "core/config.py", 27, 0.47, 1.0),
+ structural: "unexplained",
+ },
+ ];
+ render(<CouplingTable edges={edges} />);
+ expect(
+ inTable().getByText(
+ /config\.py has never changed without answer\.py \(27 shared commits\), while answer\.py changed without it 53% of the time\. No dependency in the graph connects them\./,
+ ),
+ ).toBeInTheDocument();
+ });
+
+ it("pins the whole pair on row click when the host understands pairs", () => {
+ const onPinPair = vi.fn();
+ const e = edge("a.py", "b.py", 4);
+ render(<CouplingTable edges={[e]} onPinPair={onPinPair} />);
+ fireEvent.click(inTable().getByText("a.py"));
+ expect(onPinPair).toHaveBeenCalledWith(e);
+ });
+
+ it("selects a row from either end of the pair, not only the smaller path", () => {
+ // `b.py` is the target: a pin on either end selects the row.
+ const { container } = render(
+ <CouplingTable edges={[edge("a.py", "b.py", 4)]} pinnedPath="b.py" />,
+ );
+ expect(container.querySelector("tr.bg-\\[var\\(--color-accent-muted\\)\\]\\/30")).not.toBeNull();
+ });
});
diff --git a/packages/ui/src/coupling/claim.ts b/packages/ui/src/coupling/claim.ts
new file mode 100644
index 000000000..6fc880987
--- /dev/null
+++ b/packages/ui/src/coupling/claim.ts
@@ -0,0 +1,131 @@
+/**
+ * The one place that turns a coupling edge into words and into a segment.
+ *
+ * `support` and the two directional confidences carry a claim a single
+ * strength score cannot: a file that never changes without its partner is a
+ * finding, while "they both change a lot" is not. Every surface that describes
+ * a pair — table, panel, AI prompt — phrases it from here.
+ */
+import type { CouplingEdge } from "@repowise-dev/types/coupling";
+
+/** An unordered pair of files, as the wire orders them (source < target). */
+export interface CouplingPair {
+ source: string;
+ target: string;
+}
+
+/** Whether *edge* is the pair described by *pair*. */
+export function isSamePair(edge: CouplingEdge, pair: CouplingPair | null | undefined): boolean {
+ return pair != null && edge.source === pair.source && edge.target === pair.target;
+}
+
+/** Whether *path* is one of the pair's two ends. */
+export function pairHas(pair: CouplingPair | null | undefined, path: string | null): boolean {
+ return pair != null && path != null && (pair.source === path || pair.target === path);
+}
+
+/**
+ * The reader-facing split of the list, derived from the wire's three-valued
+ * `structural`. `unexplained` is the finding; `explained` is a pair the
+ * dependency graph already accounts for; `outside` is a pair with at least one
+ * side the parser never ingested (a lockfile, a changelog), where there was no
+ * edge to look for and so no hidden coupling to claim.
+ */
+export type CouplingSegment = "unexplained" | "explained" | "outside";
+
+/** The segment an edge belongs to, or `null` on an index written before the label existed. */
+export function segmentOf(edge: CouplingEdge): CouplingSegment | null {
+ if (edge.structural === "unexplained") return "unexplained";
+ if (edge.structural === "corroborated") return "explained";
+ if (edge.structural === "not_applicable") return "outside";
+ return null;
+}
+
+/** The higher of the two directions: the strongest claim the pair supports. */
+export function peakConfidence(edge: CouplingEdge): number | null {
+ const values = [edge.confidence_ab, edge.confidence_ba].filter(
+ (v): v is number => typeof v === "number",
+ );
+ return values.length ? values.reduce((m, v) => Math.max(m, v), 0) : null;
+}
+
+function pct(value: number): number {
+ return Math.round(value * 100);
+}
+
+/**
+ * What the dependency graph says, as a clause. Empty for an older index that
+ * carries no label — silence is honest there, a guess is not.
+ */
+export function structuralClause(edge: CouplingEdge): string {
+ switch (segmentOf(edge)) {
+ case "unexplained":
+ return "No dependency in the graph connects them.";
+ case "explained":
+ return "The dependency graph already connects them.";
+ case "outside":
+ return "At least one side is outside the dependency graph.";
+ default:
+ return "";
+ }
+}
+
+/**
+ * The pair's claim as a sentence, using *label* to name each file the way the
+ * caller names it elsewhere.
+ *
+ * The asymmetry is the content: the side that rarely changes alone leads, and
+ * the other side's independence follows. Every figure is one the wire carries;
+ * no commit total is derived from a rounded share.
+ */
+export function couplingClaim(
+ edge: CouplingEdge,
+ label: (path: string) => string = (p) => p,
+): string {
+ const clause = structuralClause(edge);
+ const withClause = (lead: string) => (clause ? `${lead} ${clause}` : lead);
+
+ const ab = edge.confidence_ab;
+ const ba = edge.confidence_ba;
+ const support = edge.support;
+
+ if (!support) {
+ return withClause("The index recorded no shared-commit count for this pair.");
+ }
+
+ const shared = `${support} shared ${support === 1 ? "commit" : "commits"}`;
+
+ if (typeof ab === "number" && typeof ba === "number") {
+ // Lead with whichever side is the more dependent — that is the finding.
+ const abLeads = ab >= ba;
+ const hi = abLeads ? edge.source : edge.target;
+ const lo = abLeads ? edge.target : edge.source;
+ const hiConf = abLeads ? ab : ba;
+ const loConf = abLeads ? ba : ab;
+ const alone = 100 - pct(loConf);
+ const head =
+ pct(hiConf) >= 100
+ ? `${label(hi)} has never changed without ${label(lo)} (${shared})`
+ : `${label(hi)} changed with ${label(lo)} in ${pct(hiConf)}% of its own commits (${shared})`;
+ const tail =
+ alone <= 0
+ ? `and ${label(lo)} never changed without it either`
+ : `while ${label(lo)} changed without it ${alone}% of the time`;
+ return withClause(`${head}, ${tail}.`);
+ }
+
+ const only =
+ typeof ab === "number"
+ ? { self: edge.source, partner: edge.target, conf: ab }
+ : typeof ba === "number"
+ ? { self: edge.target, partner: edge.source, conf: ba }
+ : null;
+
+ if (only) {
+ return withClause(
+ `${label(only.self)} changed with ${label(only.partner)} in ${pct(only.conf)}% of its own commits (${shared}).`,
+ );
+ }
+
+ return withClause(`${shared} touched both files.`);
+}
diff --git a/packages/ui/src/coupling/coupling-explorer.tsx b/packages/ui/src/coupling/coupling-explorer.tsx
index e27733975..1a6372393 100644
--- a/packages/ui/src/coupling/coupling-explorer.tsx
+++ b/packages/ui/src/coupling/coupling-explorer.tsx
@@ -5,6 +5,8 @@ import { useEffect, useMemo, useState } from "react";
import { Search, X } from "lucide-react";
import { CouplingGraph } from "./coupling-graph";
import { CouplingTable } from "./coupling-table";
+import { CouplingPairDrawer } from "./coupling-pair-drawer";
+import { segmentOf, type CouplingPair, type CouplingSegment } from "./claim";
import { AiPromptModal, buildCouplingAiPrompt } from "../health";
import { fileEntityPath } from "../shared/entity/routes";
import { cn } from "../lib/cn";
@@ -16,6 +18,9 @@ import type { CouplingEdge, CouplingGraphResponse, CouplingNode } from "@repowis
const NO_NODES: CouplingNode[] = [];
const NO_EDGES: CouplingEdge[] = [];
+/** DOM id the diagram points at as its keyboard-accessible equivalent. */
+const TABLE_ID = "coupling-pairs-table";
+
/** Injected link component (e.g. Next's Link); defaults to a plain anchor. */
type LinkLike = React.ElementType<{
href: string;
@@ -30,16 +35,61 @@ export interface CouplingExplorerProps {
* links under `${prefix}/files/...`. Omit to render plain (non-link) names.
*/
repoLinkPrefix?: string;
+ /** Repo name, for the AI prompt's header line. */
+ repoName?: string;
/** Link component for file links (defaults to a plain anchor). */
LinkComponent?: LinkLike;
/**
- * Initial pinned file (e.g. from a `?focus=` deep link). When omitted the
+ * Initial pinned selection (e.g. from a `?focus=` deep link) — either a file
+ * path, or two paths joined by `|` for a pinned pair. When omitted the
* explorer opens with the most-coupled hub pinned so the diagram lands with a
* story already told rather than a flat ring.
*/
initialFocus?: string | null;
- /** Called when the user pins/clears a file — reflect it to the URL if wanted. */
- onFocusChange?: (path: string | null) => void;
+ /** Called when the user pins/clears — reflect it to the URL if wanted. */
+ onFocusChange?: (focus: string | null) => void;
+ /**
+ * Fetch beyond the current cap. Shown only while the payload is capped
+ * (`total_edges` exceeds the edges delivered), so "showing N of M" stops
+ * being a dead end.
+ */
+ onShowMore?: () => void;
+ /** Whether a `onShowMore` fetch is in flight. */
+ loadingMore?: boolean;
+}
+
+/**
+ * What is selected. A coupling is about two files and neither of them owns it,
+ * so a table row pins the pair; a dot in the ring still pins one file and its
+ * whole fan.
+ */
+type Selection =
+ | { kind: "file"; path: string }
+ | { kind: "pair"; source: string; target: string };
+
+/**
+ * The pair separator in a serialized selection. A path containing it
+ * round-trips as a plain file path, since the halves match no known node.
+ */
+const PAIR_SEP = "|";
+
+function serializeSelection(sel: Selection | null): string | null {
+ if (!sel) return null;
+ return sel.kind === "file" ? sel.path : `${sel.source}${PAIR_SEP}${sel.target}`;
+}
+
+function parseSelection(raw: string, known: ReadonlySet<string>): Selection | null {
+ if (!raw) return null;
+ const parts = raw.split(PAIR_SEP);
+ if (parts.length === 2 && known.has(parts[0]!) && known.has(parts[1]!)) {
+ return { kind: "pair", source: parts[0]!, target: parts[1]! };
+ }
+ return { kind: "file", path: raw };
+}
+
+/** Every file a selection depends on, for the stale-pin check. */
+function selectionPaths(sel: Selection): string[] {
+ return sel.kind === "file" ? [sel.path] : [sel.source, sel.target];
}
/** The file with the most couplings — the most useful default story to open on. */
@@ -60,92 +110,193 @@ function topHub(edges: CouplingEdge[]): string | null {
return best;
}
+/** The segments, in reading order, with the label each one carries. */
+const SEGMENTS: { key: CouplingSegment | "all"; label: string; help: string }[] = [
+ {
+ key: "unexplained",
+ label: "Unexplained",
+ help: "Both files are in the dependency graph and nothing joins them. This is the finding.",
+ },
+ {
+ key: "explained",
+ label: "Explained",
+ help: "An import, type use, framework wiring, or read already connects the two files.",
+ },
+ {
+ key: "outside",
+ label: "Outside the graph",
+ help: "At least one side was never parsed — lockfiles, changelogs, config, docs. Real coupling, but not a code question.",
+ },
+ { key: "all", label: "All", help: "Every coupling, including any the index never labelled." },
+];
+
/**
* The full change-coupling surface: the edge-bundling diagram (centerpiece)
- * over a precise, sortable, filterable table, sharing one focus model. A
- * transient `hover` peeks over a sticky `pinned` selection so the picture never
- * goes blank — hover a file (in either the ring or the table) to trace what it
- * changes with, click to pin, click empty canvas to clear.
+ * over a precise, sortable, filterable table, sharing one focus model *and* one
+ * filter. A transient `hover` peeks over a sticky `pinned` selection so the
+ * picture never goes blank — hover a file (in either the ring or the table) to
+ * trace what it changes with, click to pin, click empty space to clear.
+ *
+ * The structural segment is the page's front door. Unfiltered, the strongest
+ * couplings in any repo are release plumbing, which is true and useless, so the
+ * default segment is the pairs the dependency graph cannot explain. The segment
+ * and the search box both narrow the ring and the table together.
*
* This composition lives in the shared package (not the app) so both the OSS
* and hosted apps get the same interaction from a single source; the app only
- * supplies the link prefix and, optionally, URL sync for the pinned file.
+ * supplies the link prefix and, optionally, URL sync for the pinned selection.
*/
export function CouplingExplorer({
data,
repoLinkPrefix,
+ repoName,
LinkComponent,
initialFocus,
onFocusChange,
+ onShowMore,
+ loadingMore,
}: CouplingExplorerProps) {
// The wire type declares these required but a snapshot can omit them. The
// hosted client normalizes too; this covers every dereference below.
const nodes = data.nodes ?? NO_NODES;
const edges = data.edges ?? NO_EDGES;
- const defaultPin = useMemo(
- () =>
- initialFocus !== undefined && initialFocus !== ""
- ? initialFocus
- : topHub(edges),
- // Only seed once from the initial data/prop; user actions drive it after.
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [],
- );
- const [pinned, setPinned] = useState<string | null>(defaultPin);
- const [hover, setHover] = useState<string | null>(null);
+ const nodePaths = useMemo(() => new Set(nodes.map((n) => n.file_path)), [nodes]);
+
+ const [pinned, setPinned] = useState<Selection | null>(() => {
+ if (initialFocus !== undefined && initialFocus !== null && initialFocus !== "") {
+ return parseSelection(initialFocus, nodePaths);
+ }
+ const hub = topHub(edges);
+ return hub ? { kind: "file", path: hub } : null;
+ });
+ const [hover, setHover] = useState<Selection | null>(null);
const [query, setQuery] = useState("");
const [promptEdge, setPromptEdge] = useState<CouplingEdge | null>(null);
+ /** The pair whose detail panel is open. Set alongside the pin by a row click. */
+ const [detailEdge, setDetailEdge] = useState<CouplingEdge | null>(null);
- const changePin = (path: string | null) => {
- setPinned(path);
- onFocusChange?.(path);
+ // An index with no structural labels leaves the control nothing to offer,
+ // so it hides rather than filtering every segment to zero.
+ const counts = useMemo(() => {
+ const tally = { unexplained: 0, explained: 0, outside: 0, unlabelled: 0 };
+ for (const e of edges) {
+ const seg = segmentOf(e);
+ if (seg) tally[seg] += 1;
+ else tally.unlabelled += 1;
+ }
+ return tally;
+ }, [edges]);
+ const segmentsAvailable = counts.unexplained + counts.explained + counts.outside > 0;
+
+ const [segment, setSegment] = useState<CouplingSegment | "all">(() => {
+ // Default to the finding, but never open on an empty list: a repo whose
+ // couplings are all explained should still show them.
+ for (const e of edges) if (segmentOf(e) === "unexplained") return "unexplained";
+ return "all";
+ });
+
+ const changePin = (next: Selection | null) => {
+ setPinned(next);
+ onFocusChange?.(serializeSelection(next));
};
-
- // Drop a stale pin if a background revalidation returns an edge set that no
+
+ // Drop a stale pin if a background revalidation returns a payload that no
// longer contains it, so the guidance never claims to trace a vanished file.
- const nodePaths = useMemo(() => new Set(nodes.map((n) => n.file_path)), [nodes]);
useEffect(() => {
- if (pinned && !nodePaths.has(pinned)) changePin(null);
+ if (pinned && !selectionPaths(pinned).every((p) => nodePaths.has(p))) changePin(null);
// Intentionally keyed on pin + payload only; changePin always closes over
// the latest onFocusChange.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [pinned, nodePaths]);
-
+
// Transient hover peeks over the sticky pin: what the ring and table light up.
- const focus = hover ?? pinned;
+ const active = hover ?? pinned;
+
+ const focusedPath = active?.kind === "file" ? active.path : null;
+ const focusedPair: CouplingPair | null =
+ active?.kind === "pair" ? { source: active.source, target: active.target } : null;
+ const pinnedPath = pinned?.kind === "file" ? pinned.path : null;
+ const pinnedPair: CouplingPair | null =
+ pinned?.kind === "pair" ? { source: pinned.source, target: pinned.target } : null;
+ // One filter, both views. `filtered` feeds the ring and the table alike, and
+ // the ring's nodes are re-derived from it so a filtered-out file does not
+ // linger on the ring as a dot with no arcs.
const filtered = useMemo(() => {
const q = query.trim().toLowerCase();
- if (!q) return edges;
- return edges.filter(
- (e) => e.source.toLowerCase().includes(q) || e.target.toLowerCase().includes(q),
- );
- }, [edges, query]);
+ return edges.filter((e) => {
+ if (segment !== "all" && segmentOf(e) !== segment) return false;
+ if (!q) return true;
+ return e.source.toLowerCase().includes(q) || e.target.toLowerCase().includes(q);
+ });
+ }, [edges, query, segment]);
+
+ const filteredNodes = useMemo(() => {
+ if (filtered.length === edges.length) return nodes;
+ const referenced = new Set<string>();
+ for (const e of filtered) {
+ referenced.add(e.source);
+ referenced.add(e.target);
+ }
+ return nodes.filter((n) => referenced.has(n.file_path));
+ }, [nodes, edges, filtered]);
+
+ const nodeByPath = useMemo(() => {
+ const m = new Map<string, CouplingNode>();
+ for (const n of nodes) m.set(n.file_path, n);
+ return m;
+ }, [nodes]);
+
+ // Degree over the *unfiltered* edge set: "couples with 12 files" is a fact
+ // about the repo, not about the segment the reader happens to be in.
+ const degreeByPath = useMemo(() => {
+ const d = new Map<string, number>();
+ for (const e of edges) {
+ d.set(e.source, (d.get(e.source) ?? 0) + 1);
+ d.set(e.target, (d.get(e.target) ?? 0) + 1);
+ }
+ return d;
+ }, [edges]);
+
+ const moduleFor = useMemo(() => {
+ const anyModule = nodes.some((n) => n.module);
+ return anyModule ? (path: string) => nodeByPath.get(path)?.module ?? null : undefined;
+ }, [nodes, nodeByPath]);
const linkForPath = repoLinkPrefix
? (path: string) => fileEntityPath(repoLinkPrefix, path)
: undefined;
+ const segmentCount = (key: CouplingSegment | "all") =>
+ key === "all" ? edges.length : counts[key];
+
+ const capped = data.total_edges > edges.length;
+
return (
<div className="space-y-5">
{/* No GraphCanvasShell: it hosts fixed-height canvases behind an
`overflow-hidden` body, which clips this intrinsically-sized SVG. */}
<div className="mx-auto w-full max-w-[820px]">
{/* Guidance line so the diagram is not a mystery until you touch it.
- Echoes the pinned file so the sticky selection is always named. */}
+ Echoes the pinned selection so it is always named. */}
<p className="mb-2 text-xs text-[var(--color-text-tertiary)]">
{pinned ? (
<>
Tracing{" "}
{/* Trailing folders kept: a bare basename is ambiguous wherever
`mod.rs`/`index.ts`/`__init__.py` conventions apply. */}
- <span
- className="font-mono break-all text-[var(--color-text-secondary)]"
- title={pinned}
- >
- {truncatePath(pinned, 44)}
- </span>
+ {selectionPaths(pinned).map((path, i) => (
+ <React.Fragment key={path}>
+ {i > 0 ? " ↔ " : null}
+ <span
+ className="font-mono break-all text-[var(--color-text-secondary)]"
+ title={path}
+ >
+ {truncatePath(path, pinned.kind === "pair" ? 28 : 44)}
+ </span>
+ </React.Fragment>
+ ))}
. Hover any file to peek, tap or click to pin, or tap empty space
to clear.
</>
@@ -153,18 +304,83 @@ export function CouplingExplorer({
<>Tap or hover a file to trace what changes with it; click to pin.</>
)}
</p>
+ {/* No `totalEdges`: one number cannot honestly carry both the cap and
+ the active filter. The header line below owns that; the legend
+ counts the arcs it drew. */}
<CouplingGraph
- nodes={nodes}
- edges={edges}
- totalEdges={data.total_edges}
- focusedPath={focus}
- pinnedPath={pinned}
- onHover={setHover}
- onPinToggle={changePin}
+ nodes={filteredNodes}
+ edges={filtered}
+ focusedPath={focusedPath}
+ pinnedPath={pinnedPath}
+ focusedPair={focusedPair}
+ pinnedPair={pinnedPair}
+ tableId={TABLE_ID}
+ onHover={(path) => setHover(path ? { kind: "file", path } : null)}
+ onPinToggle={(path) => changePin(path ? { kind: "file", path } : null)}
/>
</div>
<div className="space-y-3 border-t border-[var(--color-border-default)] pt-4">
+ {/* Names the scope the segment counts are counted over, so "All 200"
+ and "14,115 couplings" stop looking like a contradiction. */}
+ <p className="text-xs text-[var(--color-text-secondary)]">
+ {capped ? (
+ <>
+ Showing the <strong className="font-medium">{edges.length}</strong> strongest
+ of{" "}
+ <strong className="font-medium">{data.total_edges.toLocaleString()}</strong>{" "}
+ couplings in this repository. The counts below describe those{" "}
+ {edges.length}.
+ </>
+ ) : (
+ <>
+ All <strong className="font-medium">{edges.length.toLocaleString()}</strong>{" "}
+ couplings in this repository.
+ </>
+ )}
+ </p>
+
+ {segmentsAvailable && (
+ <div className="flex flex-wrap items-center gap-2">
+ {/* Scrolls rather than wraps on a phone: a segmented control that
+ reflows to two rows stops reading as one control. */}
+ <div
+ role="group"
+ aria-label="Filter couplings by what the dependency graph says"
+ className="inline-flex max-w-full overflow-x-auto rounded-md border border-[var(--color-border-default)]"
+ >
+ {SEGMENTS.map((s) => {
+ const n = segmentCount(s.key);
+ const selected = segment === s.key;
+ return (
+ <button
+ key={s.key}
+ type="button"
+ title={s.help}
+ aria-pressed={selected}
+ onClick={() => setSegment(s.key)}
+ className={cn(
+ "h-8 shrink-0 whitespace-nowrap border-r border-[var(--color-border-default)] px-2.5 text-xs last:border-r-0",
+ selected
+ ? "bg-[var(--color-accent-muted)]/40 font-medium text-[var(--color-text-primary)]"
+ : "text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)]",
+ )}
+ >
+ {s.label}{" "}
+ <span className="tabular-nums text-[var(--color-text-tertiary)]">{n}</span>
+ </button>
+ );
+ })}
+ </div>
+ {counts.unlabelled > 0 && segment !== "all" && (
+ <span className="text-xs text-[var(--color-text-tertiary)]">
+ {counts.unlabelled} coupling{counts.unlabelled === 1 ? "" : "s"} predate the
+ structural check and appear only under All.
+ </span>
+ )}
+ </div>
+ )}
+
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="relative min-w-0 flex-1 sm:max-w-xs">
<Search className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-[var(--color-text-tertiary)]" />
@@ -172,44 +388,92 @@ export function CouplingExplorer({
type="text"
value={query}
onChange={(e) => setQuery(e.target.value)}
- placeholder="Filter table by file path…"
- aria-label="Filter the coupled-files table by path"
+ placeholder="Filter by file path…"
+ aria-label="Filter the couplings by file path"
className="h-8 w-full rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] pl-8 pr-3 text-xs text-[var(--color-text-primary)] placeholder:text-[var(--color-text-tertiary)] focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--color-accent-primary)]"
/>
</div>
- {pinned && (
- <button
- type="button"
- onClick={() => changePin(null)}
- className={cn(
- "inline-flex h-8 shrink-0 items-center gap-1 rounded-md border border-[var(--color-border-default)] px-2.5 text-xs text-[var(--color-text-secondary)]",
- "hover:bg-[var(--color-bg-elevated)]",
- )}
- >
- <X className="h-3.5 w-3.5" />
- Clear selection
- </button>
- )}
+ <div className="flex items-center gap-2">
+ {capped && onShowMore && (
+ <button
+ type="button"
+ onClick={onShowMore}
+ disabled={loadingMore}
+ className={cn(
+ "inline-flex h-8 shrink-0 items-center rounded-md border border-[var(--color-border-default)] px-2.5 text-xs text-[var(--color-text-secondary)]",
+ "hover:bg-[var(--color-bg-elevated)] disabled:opacity-60",
+ )}
+ >
+ {loadingMore ? "Loading…" : "Load more"}
+ </button>
+ )}
+ {pinned && (
+ <button
+ type="button"
+ onClick={() => changePin(null)}
+ className={cn(
+ "inline-flex h-8 shrink-0 items-center gap-1 rounded-md border border-[var(--color-border-default)] px-2.5 text-xs text-[var(--color-text-secondary)]",
+ "hover:bg-[var(--color-bg-elevated)]",
+ )}
+ >
+ <X className="h-3.5 w-3.5" />
+ Clear selection
+ </button>
+ )}
+ </div>
</div>
<CouplingTable
+ id={TABLE_ID}
edges={filtered}
- focusedPath={focus}
- pinnedPath={pinned}
- onHover={setHover}
- onPinToggle={changePin}
- onGeneratePrompt={setPromptEdge}
+ focusedPath={focusedPath}
+ pinnedPath={pinnedPath}
+ pinnedPair={pinnedPair}
+ onHover={(path) => setHover(path ? { kind: "file", path } : null)}
+ onPinToggle={(path) => changePin(path ? { kind: "file", path } : null)}
+ onPinPair={(edge) => {
+ // One gesture, both outcomes: the pair lights in the ring and its
+ // detail panel opens. Clicking the pinned row again clears both.
+ changePin(edge ? { kind: "pair", source: edge.source, target: edge.target } : null);
+ setDetailEdge(edge);
+ }}
+ onHoverPair={(edge) =>
+ setHover(edge ? { kind: "pair", source: edge.source, target: edge.target } : null)
+ }
+ moduleFor={moduleFor}
+ hasDetails
linkForPath={linkForPath}
LinkComponent={LinkComponent}
/>
</div>
+ <CouplingPairDrawer
+ edge={detailEdge}
+ onClose={() => setDetailEdge(null)}
+ nodeByPath={nodeByPath}
+ degreeByPath={degreeByPath}
+ linkForPath={linkForPath}
+ LinkComponent={LinkComponent}
+ onGeneratePrompt={setPromptEdge}
+ />
+
<AiPromptModal
open={promptEdge !== null}
onOpenChange={(o) => !o && setPromptEdge(null)}
getPrompt={
promptEdge
- ? (flavor) => buildCouplingAiPrompt({ edge: promptEdge, flavor })
+ ? (flavor) =>
+ buildCouplingAiPrompt({
+ edge: promptEdge,
+ flavor,
+ ...(repoName ? { repoName } : {}),
+ // The facts the page already holds, so the model is not
+ // asked to re-derive what it is being asked to judge.
+ nodes: {
+ [promptEdge.source]: nodeByPath.get(promptEdge.source) ?? {},
+ [promptEdge.target]: nodeByPath.get(promptEdge.target) ?? {},
+ },
+ })
: null
}
filePath={promptEdge ? `${promptEdge.source} ↔ ${promptEdge.target}` : null}
diff --git a/packages/ui/src/coupling/coupling-graph.tsx b/packages/ui/src/coupling/coupling-graph.tsx
index fbc5098df..4833602e8 100644
--- a/packages/ui/src/coupling/coupling-graph.tsx
+++ b/packages/ui/src/coupling/coupling-graph.tsx
@@ -10,6 +10,7 @@ import { bandForScore } from "@repowise-dev/types";
import type { CouplingEdge, CouplingNode } from "@repowise-dev/types/coupling";
import type { HealthBand } from "@repowise-dev/types/health";
import { disambiguateBasenames } from "../lib/format";
+import { isSamePair, pairHas, type CouplingPair } from "./claim";
export interface CouplingGraphProps {
nodes: CouplingNode[];
@@ -24,10 +25,25 @@ export interface CouplingGraphProps {
focusedPath?: string | null;
/** The sticky selection (persistent ring). Falls back to internal pin. */
pinnedPath?: string | null;
+ /**
+ * A focused *pair* rather than a single file — what a table row selects,
+ * since a coupling is about two files and neither of them owns it. When set
+ * it wins over `focusedPath`: the one arc between the two is lit and every
+ * other arc dims, instead of the whole fan of one end.
+ */
+ focusedPair?: CouplingPair | null;
+ /** The sticky pair selection (persistent rings on both ends). */
+ pinnedPair?: CouplingPair | null;
/** Transient hover peek — mouse enters a dot, or leaves the canvas (null). */
onHover?: (path: string | null) => void;
/** Sticky selection changed — click a dot toggles it, click empty space clears it. */
onPinToggle?: (path: string | null) => void;
+ /**
+ * DOM id of the table that lists the same couplings. The ring is not
+ * keyboard-operable, so it points at its accessible equivalent instead of
+ * pretending to be one.
+ */
+ tableId?: string;
/** Square render size in px (viewBox edge). */
size?: number;
}
@@ -126,8 +142,11 @@ export function CouplingGraph({
totalEdges,
focusedPath,
pinnedPath,
+ focusedPair,
+ pinnedPair,
onHover,
onPinToggle,
+ tableId,
size = 760,
}: CouplingGraphProps) {
// Internal fallback for uncontrolled use (tests, standalone). When the host
@@ -266,20 +285,25 @@ export function CouplingGraph({
// never overlap on a dense one.
const hitRadius = Math.min(14, ((2 * Math.PI * radius) / Math.max(leaves.length, 1)) / 2);
- // Neighbors of the focused file (for dimming + dot emphasis). O(1) lookup
- // into the precomputed adjacency map instead of an O(E) rescan per focus.
- const neighbors = (focus ? adjacency.get(focus) : undefined) ?? EMPTY_SET;
+ // Neighbors of the focused file, for dimming + dot emphasis. A focused pair
+ // has no fan to light, so it takes none.
+ const neighbors =
+ (focusedPair == null && focus ? adjacency.get(focus) : undefined) ?? EMPTY_SET;
+ // Something is selected — either one file's whole fan, or one arc.
+ const anyFocus = focusedPair != null || focus != null;
const dotR = (n: CouplingNode) =>
2 + Math.sqrt(n.nloc / maxNloc) * 2.4 + Math.min((degree.get(n.file_path) ?? 0) / 6, 2.6);
return (
<div>
+ {/* Decorative, not operable: the ring is mouse-only, and the table
+ below holds the same data in a form a keyboard can drive. */}
<svg
viewBox={`0 0 ${size} ${size}`}
width="100%"
- role="img"
- aria-label="Change-coupling diagram: files arranged in a ring, arcs link files that change together"
+ aria-hidden="true"
+ focusable="false"
onMouseLeave={() => hover(null)}
>
{/* Background target: entering empty canvas drops the hover peek so the
@@ -336,12 +360,24 @@ export function CouplingGraph({
couplings resolve to the partner's health color and the rest fade. */}
<g fill="none">
{drawn.map(({ edge, d }) => {
- const incident = focus === edge.source || focus === edge.target;
- const dim = focus != null && !incident;
+ const incident = focusedPair
+ ? isSamePair(edge, focusedPair)
+ : focus === edge.source || focus === edge.target;
+ const dim = anyFocus && !incident;
+ // One file focused: the partner's health. A pair focused: the
+ // worse of the two, since neither end is "the other" one.
const partnerPath = focus === edge.source ? edge.target : edge.source;
- const partnerNode = incident ? nodeByPath.get(partnerPath) : undefined;
+ const scores = focusedPair
+ ? [nodeByPath.get(edge.source)?.score, nodeByPath.get(edge.target)?.score].filter(
+ (s): s is number => typeof s === "number",
+ )
+ : [nodeByPath.get(partnerPath)?.score].filter(
+ (s): s is number => typeof s === "number",
+ );
const strengthFrac = edge.strength / maxStrength;
- const stroke = incident ? inkFor(partnerNode?.score ?? null) : NEUTRAL_INK;
+ const stroke = incident
+ ? inkFor(scores.length ? Math.min(...scores) : null)
+ : NEUTRAL_INK;
return (
<path
key={`${edge.source}|${edge.target}`}
@@ -360,14 +396,18 @@ export function CouplingGraph({
const n = leaf.data.node;
if (!n) return null;
const [x, y] = project(leaf.x!, leaf.y!);
- const isFocus = focus === n.file_path;
- const isPinned = pinned === n.file_path;
+ const isFocus = focusedPair
+ ? pairHas(focusedPair, n.file_path)
+ : focus === n.file_path;
+ const isPinned = pinnedPair
+ ? pairHas(pinnedPair, n.file_path)
+ : pinned === n.file_path;
const isNeighbor = neighbors.has(n.file_path);
- const dim = focus != null && !isFocus && !isNeighbor;
+ const dim = anyFocus && !isFocus && !isNeighbor;
const isHub = hubPaths.has(n.file_path);
- // Always label the top hubs; reveal the rest on hover (focus +
- // neighbors). No more all-or-nothing 36-node gate.
- const showLabel = isFocus || isNeighbor || (focus == null && isHub);
+ // Focus grows the labelled set rather than swapping it out, so
+ // the ring keeps the identity the reader oriented on.
+ const showLabel = isFocus || isNeighbor || isHub;
// Labels radiate along each file's own spoke so angularly-adjacent
// hubs fan out instead of stacking on a shared baseline. Flip the
// left half so the text never renders upside-down.
@@ -456,6 +496,22 @@ export function CouplingGraph({
dot size = lines + couplings · line opacity = strength
</span>
</div>
+
+ {/* The accessible equivalent, named and linked. */}
+ <p className="mt-1 text-xs text-[var(--color-text-tertiary)]">
+ The diagram is a visual summary.{" "}
+ {tableId ? (
+ <a
+ href={`#${tableId}`}
+ className="underline decoration-dotted underline-offset-2 hover:text-[var(--color-text-secondary)]"
+ >
+ The table below
+ </a>
+ ) : (
+ "The table below"
+ )}{" "}
+ lists the same couplings and is the keyboard-accessible version of it.
+ </p>
</div>
);
}
diff --git a/packages/ui/src/coupling/coupling-pair-drawer.tsx b/packages/ui/src/coupling/coupling-pair-drawer.tsx
new file mode 100644
index 000000000..0e484bc77
--- /dev/null
+++ b/packages/ui/src/coupling/coupling-pair-drawer.tsx
@@ -0,0 +1,321 @@
+"use client";
+
+import * as React from "react";
+import { ExternalLink } from "lucide-react";
+import { AdaptivePanel } from "../shared/adaptive-panel";
+import { HealthBadge } from "../health/health-badge";
+import { AiPromptButton } from "../health/ai-prompt-button";
+import { formatDate, formatDateTime } from "../lib/format";
+import { couplingClaim, segmentOf, type CouplingSegment } from "./claim";
+import type { CouplingEdge, CouplingNode } from "@repowise-dev/types/coupling";
+
+/** Injected link component (e.g. Next's Link); defaults to a plain anchor. */
+type LinkLike = React.ElementType<{
+ href: string;
+ className?: string;
+ children: React.ReactNode;
+}>;
+
+export interface CouplingPairDrawerProps {
+ /** The pair to describe; `null` closes the panel. */
+ edge: CouplingEdge | null;
+ onClose: () => void;
+ /** Node facts by path, for module / health / size. */
+ nodeByPath: ReadonlyMap<string, CouplingNode>;
+ /** How many files each end couples with, over the unfiltered edge set. */
+ degreeByPath: ReadonlyMap<string, number>;
+ /** Resolve a file's detail-page href; when absent, paths render unlinked. */
+ linkForPath?: ((path: string) => string) | undefined;
+ LinkComponent?: LinkLike | undefined;
+ /** Open the AI decouple prompt for this pair. */
+ onGeneratePrompt?: (edge: CouplingEdge) => void;
+}
+
+/**
+ * The graph's verdict as a dot plus a word, and the reasoning behind it.
+ *
+ * Only `unexplained` takes a semantic color: it is the exception worth
+ * marking. Explained and outside-the-graph are ordinary states, and coloring
+ * every verdict would make the mark mean nothing.
+ */
+const VERDICT: Record<CouplingSegment, { word: string; dot: string; body: string }> = {
+ unexplained: {
+ word: "Unexplained",
+ dot: "bg-[var(--color-caution)]",
+ body: "Both files are in the dependency graph, and no import, type use, framework wiring, or read connects them. They move together for a reason the code does not state — a shared concept with no owner, a leaky abstraction, or copy-paste.",
+ },
+ explained: {
+ word: "Explained",
+ dot: "bg-[var(--color-text-tertiary)]",
+ body: "A dependency already connects these files, so the co-change is accounted for. Worth a look only if the dependency itself is the wrong shape.",
+ },
+ outside: {
+ word: "Outside the graph",
+ dot: "bg-[var(--color-text-tertiary)]",
+ body: "At least one side was never parsed — a lockfile, changelog, config, or doc — so there was no edge to look for and its absence is not evidence of anything. The coupling is real, but it is release plumbing rather than a code-structure question.",
+ },
+};
+
+const MICRO = "font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]";
+
+function pct(v: number | null | undefined): string | null {
+ return typeof v === "number" ? `${Math.round(v * 100)}%` : null;
+}
+
+function basename(path: string): string {
+ return path.split("/").pop() ?? path;
+}
+
+/**
+ * Everything the page knows about one co-changing pair, in the surface a table
+ * row could never hold: the claim spelled out, the graph's verdict and why it
+ * does or does not matter, both directional shares side by side, each file's
+ * module / health / size / degree, and a route onward to either file page.
+ *
+ * Shaped like the file-health drawer: a lede sentence, a hairline definition
+ * list, then sections under mono micro-headings. A border is reserved for an
+ * object you can open or act on, so facts are separated by hairlines and space
+ * rather than each taking a card.
+ *
+ * `AdaptivePanel` makes it a non-modal right panel on desktop, leaving the lit
+ * arc visible behind it, and a bottom sheet on mobile.
+ */
+export function CouplingPairDrawer({
+ edge,
+ onClose,
+ nodeByPath,
+ degreeByPath,
+ linkForPath,
+ LinkComponent,
+ onGeneratePrompt,
+}: CouplingPairDrawerProps) {
+ const Anchor: LinkLike = LinkComponent ?? "a";
+ const segment = edge ? segmentOf(edge) : null;
+ const verdict = segment ? VERDICT[segment] : null;
+
+ const moduleA = edge ? (nodeByPath.get(edge.source)?.module ?? null) : null;
+ const moduleB = edge ? (nodeByPath.get(edge.target)?.module ?? null) : null;
+
+ const facts: { label: string; value: React.ReactNode }[] = edge
+ ? [
+ {
+ label: "Shared commits",
+ value: (
+ <span className="text-lg font-semibold tabular-nums text-[var(--color-text-primary)]">
+ {edge.support || (
+ <span className="text-xs font-normal text-[var(--color-text-tertiary)]">
+ not recorded
+ </span>
+ )}
+ </span>
+ ),
+ },
+ {
+ label: "Strength",
+ value: (
+ <span className="text-xs tabular-nums text-[var(--color-text-primary)]">
+ {edge.strength}{" "}
+ <span className="text-[var(--color-text-tertiary)]">recency-weighted</span>
+ </span>
+ ),
+ },
+ {
+ label: "Last together",
+ value: (
+ <span
+ className="text-xs tabular-nums text-[var(--color-text-primary)]"
+ title={edge.last_co_change ? formatDateTime(edge.last_co_change) : undefined}
+ >
+ {edge.last_co_change ? formatDate(edge.last_co_change) : "unknown"}
+ </span>
+ ),
+ },
+ {
+ label: "Modules",
+ value: (
+ <span className="block truncate text-xs text-[var(--color-text-primary)]">
+ {moduleA && moduleA === moduleB ? (
+ <>
+ within <span className="font-mono">{moduleA}</span>
+ </>
+ ) : moduleA || moduleB ? (
+ <span className="font-mono">
+ {moduleA ?? "—"} ↔ {moduleB ?? "—"}
+ </span>
+ ) : (
+ <span className="text-[var(--color-text-tertiary)]">none</span>
+ )}
+ </span>
+ ),
+ },
+ ]
+ : [];
+
+ return (
+ <AdaptivePanel
+ open={edge !== null}
+ onOpenChange={(o) => !o && onClose()}
+ modal={false}
+ widthClassName="md:max-w-[640px]"
+ eyebrow="Change coupling"
+ title={
+ edge ? (
+ <span className="break-all font-mono">
+ {basename(edge.source)} ↔ {basename(edge.target)}
+ </span>
+ ) : (
+ ""
+ )
+ }
+ >
+ {edge && (
+ <div className="flex flex-col gap-6 px-4 py-4">
+ {/* Lede: the verdict names the kind of finding, the claim is the
+ sentence that makes it mean something. */}
+ <div className="flex flex-col gap-2">
+ {verdict && (
+ <p className="flex items-center gap-1.5">
+ <span className={`h-1.5 w-1.5 shrink-0 rounded-full ${verdict.dot}`} aria-hidden />
+ <span className={MICRO}>{verdict.word}</span>
+ </p>
+ )}
+ <p className="text-[15px] leading-relaxed text-[var(--color-text-primary)] [text-wrap:pretty]">
+ {couplingClaim(edge, basename)}
+ </p>
+ {verdict && (
+ <p className="text-xs leading-relaxed text-[var(--color-text-secondary)] [text-wrap:pretty]">
+ {verdict.body}
+ </p>
+ )}
+ </div>
+
+ {/* A hairline ribbon, not tiles: four different kinds of fact, and
+ equal-weight boxes would claim they are one. */}
+ <dl className="grid grid-cols-2 border-y border-[var(--color-border-default)]">
+ {facts.map((f, i) => (
+ <div
+ key={f.label}
+ className={[
+ "min-w-0 px-3 py-2.5 border-[var(--color-border-default)]",
+ i % 2 === 1 ? "border-l" : "",
+ i >= 2 ? "border-t" : "",
+ ]
+ .filter(Boolean)
+ .join(" ")}
+ >
+ <dt className={MICRO}>{f.label}</dt>
+ <dd className="mt-1">{f.value}</dd>
+ </div>
+ ))}
+ </dl>
+
+ {/* The asymmetry is the finding, so each direction gets its own bar
+ rather than collapsing into a single "up to N%". */}
+ <section className="flex flex-col gap-2">
+ <h3 className={MICRO}>Share of each file&apos;s own commits</h3>
+ <div className="flex flex-col gap-3">
+ {(
+ [
+ { path: edge.source, conf: edge.confidence_ab, other: edge.target },
+ { path: edge.target, conf: edge.confidence_ba, other: edge.source },
+ ] as const
+ ).map(({ path, conf, other }) => {
+ const share = pct(conf);
+ return (
+ <div key={path} className="min-w-0">
+ <div className="flex items-baseline justify-between gap-2">
+ <span
+ className="truncate font-mono text-xs text-[var(--color-text-secondary)]"
+ title={path}
+ >
+ {basename(path)}
+ </span>
+ <span className="shrink-0 text-xs font-semibold tabular-nums text-[var(--color-text-primary)]">
+ {share ?? "unknown"}
+ </span>
+ </div>
+ <div
+ className="mt-1.5 h-1 overflow-hidden rounded-full bg-[var(--color-bg-inset)]"
+ role="presentation"
+ >
+ <div
+ className="h-full rounded-full bg-[var(--color-accent-primary)]"
+ style={{ width: share ?? "0%" }}
+ />
+ </div>
+ <p className="mt-1 text-xs text-[var(--color-text-tertiary)]">
+ {share
+ ? `${share} of its commits also touched ${basename(other)}`
+ : "This file's commit total is not on this index"}
+ </p>
+ </div>
+ );
+ })}
+ </div>
+ </section>
+
+ {/* The two files, as a hairline list. Each row is an object you can
+ open, so the row itself carries the one action. */}
+ <section className="flex flex-col gap-2">
+ <h3 className={MICRO}>The two files</h3>
+ <ul className="border-y border-[var(--color-border-default)]">
+ {[edge.source, edge.target].map((path) => {
+ const node = nodeByPath.get(path);
+ const degree = degreeByPath.get(path) ?? 0;
+ return (
+ <li
+ key={path}
+ className="min-w-0 border-t border-[var(--color-border-default)] px-3 py-2.5 first:border-t-0"
+ >
+ <div className="flex items-start justify-between gap-2">
+ {/* Wrapped, not truncated: the one place the exact file
+ is legible. */}
+ <p className="min-w-0 break-all font-mono text-xs text-[var(--color-text-secondary)]">
+ {path.slice(0, path.length - basename(path).length)}
+ <span className="text-[var(--color-text-primary)]">{basename(path)}</span>
+ </p>
+ <HealthBadge score={node?.score ?? null} />
+ </div>
+ <p className="mt-1 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-[var(--color-text-tertiary)]">
+ {node?.module && <span className="font-mono">{node.module}</span>}
+ {node?.nloc ? <span className="tabular-nums">{node.nloc} lines</span> : null}
+ <span className="tabular-nums">
+ couples with {degree} {degree === 1 ? "file" : "files"}
+ </span>
+ {linkForPath && (
+ <Anchor
+ href={linkForPath(path)}
+ className="inline-flex items-center gap-1 font-medium text-[var(--color-accent-primary)] hover:underline"
+ >
+ <ExternalLink className="h-3 w-3" />
+ Open file page
+ </Anchor>
+ )}
+ </p>
+ </li>
+ );
+ })}
+ </ul>
+ </section>
+
+ {/* The one action, named and explained. */}
+ {onGeneratePrompt && (
+ <section className="flex flex-col gap-2">
+ <h3 className={MICRO}>Hand this to an agent</h3>
+ <p className="text-xs leading-relaxed text-[var(--color-text-secondary)]">
+ Builds a prompt carrying the evidence above, so your agent can judge
+ whether the coupling is accidental or legitimate and propose the
+ smallest decoupling that holds.
+ </p>
+ <AiPromptButton
+ label="AI decouple prompt"
+ onClick={() => onGeneratePrompt(edge)}
+ className="w-fit"
+ />
+ </section>
+ )}
+ </div>
+ )}
+ </AdaptivePanel>
+ );
+}
diff --git a/packages/ui/src/coupling/coupling-table.tsx b/packages/ui/src/coupling/coupling-table.tsx
index 89b1d6fc3..f64ce61f4 100644
--- a/packages/ui/src/coupling/coupling-table.tsx
+++ b/packages/ui/src/coupling/coupling-table.tsx
@@ -2,11 +2,12 @@
import * as React from "react";
import { useMemo, useState } from "react";
+import { ChevronRight } from "lucide-react";
import { EmptyState } from "../shared/empty-state";
import { ResponsiveTable, type ResponsiveColumn } from "../shared/responsive-table";
-import { AiPromptButton } from "../health/ai-prompt-button";
import { cn } from "../lib/cn";
import { disambiguateBasenames, formatDate, formatDateTime } from "../lib/format";
+import { couplingClaim, isSamePair, peakConfidence, type CouplingPair } from "./claim";
import type { CouplingEdge } from "@repowise-dev/types/coupling";
/**
@@ -26,16 +27,33 @@ interface CouplingTableProps {
focusedPath?: string | null;
/** Sticky selection (drives the selected-row style; synced with the diagram). */
pinnedPath?: string | null;
+ /** Sticky pair selection — the row-level equivalent of `pinnedPath`. */
+ pinnedPair?: CouplingPair | null;
/** Transient hover peek — row/filename enter, or table leave (null). */
onHover?: (path: string | null) => void;
- /** Sticky selection toggle — clicking a row pins/unpins its source file. */
+ /** Sticky selection toggle — used for the single-file (diagram) selection. */
onPinToggle?: (path: string | null) => void;
- /** When set, each row shows an "AI decouple prompt" action. */
- onGeneratePrompt?: (edge: CouplingEdge) => void;
+ /**
+ * Sticky pair toggle. When provided, clicking a row pins *both* of its files
+ * rather than whichever of them sorts first; the host lights the one arc
+ * between them. Falls back to `onPinToggle(source)` when absent.
+ */
+ onPinPair?: (edge: CouplingEdge | null) => void;
+ /** Transient pair peek, the hover counterpart of `onPinPair`. */
+ onHoverPair?: (edge: CouplingEdge | null) => void;
+ /**
+ * A file's module, for the "does this cross a boundary" column. Omit to
+ * drop the column entirely rather than render a row of dashes.
+ */
+ moduleFor?: ((path: string) => string | null) | undefined;
+ /** Whether rows advertise that clicking opens the pair's detail panel. */
+ hasDetails?: boolean;
/** Resolve a file's detail-page href; when set, file names become links. */
linkForPath?: ((path: string) => string) | undefined;
/** Link component used for file links (defaults to a plain anchor). */
LinkComponent?: LinkLike | undefined;
+ /** DOM id for the table wrapper, so the diagram can name it as its equivalent. */
+ id?: string;
}
type SortKey = "strength" | "last" | "together";
@@ -51,20 +69,21 @@ const STRENGTH_HELP =
const TOGETHER_HELP =
"Shared commits, and how much of each file's own history they account for. A pair can be one-sided: a file that never changes alone is a stronger finding than two files that both change often.";
-// The higher of the two directions: the strongest claim the pair supports.
-function peakConfidence(e: CouplingEdge): number | null {
- const values = [e.confidence_ab, e.confidence_ba].filter(
- (v): v is number => typeof v === "number",
- );
- return values.length ? values.reduce((m, v) => Math.max(m, v), 0) : null;
-}
-
/**
* The precise, sortable companion to the coupling diagram: one row per
- * coupling. Clicking a row pins its source file in the ring; the two file
- * names are links to their detail pages, and hovering a row (or a name) peeks
- * that file's couplings in the diagram. Rows touching the focused file are
- * emphasized.
+ * coupling, led by the claim the numbers actually support rather than by a bare
+ * strength score. Clicking a row pins both of its files in the ring and opens
+ * the pair's detail panel; the two file names are links to their detail pages,
+ * and hovering a row peeks that pair in the diagram. Rows touching the focused
+ * file are emphasized.
+ *
+ * Row actions live in that panel, not in the row: an icon-only affordance in
+ * a dense row cannot say what it does.
+ *
+ * The default order is the higher of the two directional confidences, not
+ * strength: strength ranks "both change a lot" above "never changes without
+ * it", and the second is the finding. Strength stays available behind its own
+ * sortable header.
*
* The body is virtualized (windowed `<tbody>`) so long coupling lists stay
* cheap to render; below the wrapper's threshold every row renders, so the
@@ -74,13 +93,18 @@ export function CouplingTable({
edges,
focusedPath,
pinnedPath,
+ pinnedPair,
onHover,
onPinToggle,
- onGeneratePrompt,
+ onPinPair,
+ onHoverPair,
+ moduleFor,
+ hasDetails,
linkForPath,
LinkComponent,
+ id,
}: CouplingTableProps) {
- const [sortKey, setSortKey] = useState<SortKey>("strength");
+ const [sortKey, setSortKey] = useState<SortKey>("together");
const [sortDir, setSortDir] = useState<SortDir>("desc");
// Bars normalize to the strongest coupling. `reduce`, not `Math.max(...)`:
@@ -92,7 +116,9 @@ export function CouplingTable({
const dir = sortDir === "asc" ? 1 : -1;
const val = (e: CouplingEdge) => {
if (sortKey === "strength") return e.strength;
- if (sortKey === "together") return e.support;
+ // Confidence first, shared commits only to break a tie: two pairs that
+ // are both fully one-sided are ordered by how much history says so.
+ if (sortKey === "together") return (peakConfidence(e) ?? 0) * 1e6 + Math.min(e.support, 1e5);
return e.last_co_change ? Date.parse(e.last_co_change) : 0;
};
// Copy before sorting: never mutate the caller's edge array in place.
@@ -119,6 +145,8 @@ export function CouplingTable({
const Anchor: LinkLike = LinkComponent ?? "a";
+ const labelFor = (path: string) => labels.get(path) ?? path;
+
const fileCell = (path: string, e: CouplingEdge, prefix = "") => {
const hot = incident(e) && path === focusedPath;
const cls = cn(
@@ -143,7 +171,7 @@ export function CouplingTable({
className={cn(cls, "hover:text-[var(--color-accent-primary)] hover:underline")}
>
{prefix}
- {labels.get(path) ?? path}
+ {labelFor(path)}
</Anchor>
</span>
);
@@ -151,7 +179,7 @@ export function CouplingTable({
return (
<span className={cls} title={path}>
{prefix}
- {labels.get(path) ?? path}
+ {labelFor(path)}
</span>
);
};
@@ -170,46 +198,48 @@ export function CouplingTable({
key: "pair",
header: "Coupled files",
priority: 1,
- cellClassName: "min-w-[200px]",
- headerClassName: "min-w-[200px]",
+ cellClassName: "min-w-[260px]",
+ headerClassName: "min-w-[260px]",
render: (e) => (
<div className="flex flex-col gap-0.5">
{fileCell(e.source, e)}
{fileCell(e.target, e, "↔ ")}
+ {/* Lead with the claim, not the score: what the two shares actually
+ say about this pair, and whether the graph explains it. */}
+ <p className="mt-0.5 text-[11px] leading-snug text-[var(--color-text-tertiary)]">
+ {couplingClaim(e, labelFor)}
+ </p>
</div>
),
},
- {
- key: "strength",
- // Priority 1: strength is why the row is in the table at all.
- priority: 1,
- sortable: true,
- mobileLabel: "Strength",
- headerClassName: "w-36",
- header: (
- <span
- title={STRENGTH_HELP}
- className="cursor-help underline decoration-dotted underline-offset-2"
- >
- Strength
- </span>
- ),
- render: (e) => (
- <div className="flex items-center gap-2 min-w-[100px]">
- <div className="h-1.5 flex-1 overflow-hidden rounded-full bg-[var(--color-bg-inset)]">
- <div
- className="h-full rounded-full bg-[var(--color-accent-primary)]"
- style={{ width: `${Math.max(6, Math.round((e.strength / maxStrength) * 100))}%` }}
- />
- </div>
- <span className="w-8 text-right text-xs tabular-nums text-[var(--color-text-tertiary)]">
- {e.strength}
- </span>
- </div>
- ),
- // The bar is meaningless at card width; the number carries it.
- mobileRender: (e) => e.strength,
- },
+ ...(moduleFor
+ ? [
+ {
+ key: "modules",
+ header: "Modules",
+ mobileLabel: "Modules",
+ // A cross-module pair is the interesting kind, so this earns a
+ // column — but it is the first to go when width runs out.
+ priority: 3 as const,
+ headerClassName: "w-40",
+ cellClassName: "text-xs",
+ render: (e: CouplingEdge) => {
+ const a = moduleFor(e.source);
+ const b = moduleFor(e.target);
+ if (!a && !b) return <span className="text-[var(--color-text-tertiary)]">—</span>;
+ if (a && a === b) {
+ return <span className="text-[var(--color-text-tertiary)]">within {a}</span>;
+ }
+ return (
+ <span className="break-words text-[var(--color-text-secondary)]">
+ {a ?? "—"} <span className="text-[var(--color-text-tertiary)]">↔</span>{" "}
+ {b ?? "—"}
+ </span>
+ );
+ },
+ },
+ ]
+ : []),
{
key: "together",
header: (
@@ -221,7 +251,7 @@ export function CouplingTable({
</span>
),
mobileLabel: "Together",
- priority: 2,
+ priority: 1,
sortable: true,
headerClassName: "w-32",
cellClassName: "text-xs tabular-nums",
@@ -240,6 +270,38 @@ export function CouplingTable({
);
},
},
+ {
+ key: "strength",
+ // Behind the sentence and the shares: strength is a sort, not the
+ // headline the row leads with.
+ priority: 2,
+ sortable: true,
+ mobileLabel: "Strength",
+ headerClassName: "w-36",
+ header: (
+ <span
+ title={STRENGTH_HELP}
+ className="cursor-help underline decoration-dotted underline-offset-2"
+ >
+ Strength
+ </span>
+ ),
+ render: (e) => (
+ <div className="flex items-center gap-2 min-w-[100px]">
+ <div className="h-1.5 flex-1 overflow-hidden rounded-full bg-[var(--color-bg-inset)]">
+ <div
+ className="h-full rounded-full bg-[var(--color-accent-primary)]"
+ style={{ width: `${Math.max(6, Math.round((e.strength / maxStrength) * 100))}%` }}
+ />
+ </div>
+ <span className="w-8 text-right text-xs tabular-nums text-[var(--color-text-tertiary)]">
+ {e.strength}
+ </span>
+ </div>
+ ),
+ // The bar is meaningless at card width; the number carries it.
+ mobileRender: (e) => e.strength,
+ },
{
key: "last",
header: "Last",
@@ -253,43 +315,53 @@ export function CouplingTable({
</span>
),
},
- ...(onGeneratePrompt
+ ...(hasDetails
? [
{
- key: "prompt",
+ key: "details",
header: "",
- priority: 2 as const,
- headerClassName: "w-10",
- cellClassName: "w-10",
- render: (e: CouplingEdge) => (
- <AiPromptButton
- variant="icon"
- label="AI decouple prompt"
- onClick={() => onGeneratePrompt(e)}
- />
- ),
+ // Survives to the narrowest table; dropped from stacked cards,
+ // where the whole card is the target.
+ priority: 1 as const,
+ headerClassName: "w-8",
+ cellClassName: "w-8 text-[var(--color-text-tertiary)]",
+ hideInCard: true,
+ render: () => <ChevronRight className="h-4 w-4" aria-hidden />,
},
]
: []),
];
+ const clearHover = onHoverPair ?? onHover;
+ // A row selects the whole pair when the host understands pairs, and falls
+ // back to the single-file selection so an uncontrolled table still works.
+ const rowClick = onPinPair
+ ? (e: CouplingEdge) => onPinPair(isSamePair(e, pinnedPair) ? null : e)
+ : onPinToggle
+ ? (e: CouplingEdge) => onPinToggle(pinnedPath === e.source ? null : e.source)
+ : undefined;
+ const rowHover = onHoverPair
+ ? (e: CouplingEdge) => onHoverPair(e)
+ : onHover
+ ? (e: CouplingEdge) => onHover(e.source)
+ : undefined;
+
return (
- <div onMouseLeave={onHover ? () => onHover(null) : undefined}>
- {/* `rowClassName`, not `selectedKey`: a pin selects a file and several
- rows can share that source. */}
+ <div id={id} onMouseLeave={clearHover ? () => clearHover(null) : undefined}>
+ {/* `rowClassName`, not `selectedKey`: a single-file pin selects several
+ rows at once, and matches on either end since a pair is unordered. */}
<ResponsiveTable<CouplingEdge>
columns={columns}
rows={sorted}
rowKey={(e) => `${e.source}|${e.target}`}
rowClassName={(e) =>
- pinnedPath != null && pinnedPath === e.source
+ isSamePair(e, pinnedPair) ||
+ (pinnedPath != null && (pinnedPath === e.source || pinnedPath === e.target))
? "bg-[var(--color-accent-muted)]/30"
: undefined
}
- {...(onPinToggle
- ? { onRowClick: (e) => onPinToggle(pinnedPath === e.source ? null : e.source) }
- : {})}
- {...(onHover ? { onRowHover: (e) => onHover(e.source) } : {})}
+ {...(rowClick ? { onRowClick: rowClick } : {})}
+ {...(rowHover ? { onRowHover: rowHover } : {})}
sortField={sortKey}
sortOrder={sortDir}
onSort={toggleSort}
diff --git a/packages/ui/src/coupling/index.ts b/packages/ui/src/coupling/index.ts
index a8bcf9116..1639ff0e7 100644
--- a/packages/ui/src/coupling/index.ts
+++ b/packages/ui/src/coupling/index.ts
@@ -1,6 +1,20 @@
export { CouplingGraph, type CouplingGraphProps } from "./coupling-graph";
export { CouplingTable } from "./coupling-table";
export { CouplingExplorer, type CouplingExplorerProps } from "./coupling-explorer";
+export {
+ CouplingPairDrawer,
+ type CouplingPairDrawerProps,
+} from "./coupling-pair-drawer";
+export {
+ couplingClaim,
+ isSamePair,
+ pairHas,
+ peakConfidence,
+ segmentOf,
+ structuralClause,
+ type CouplingPair,
+ type CouplingSegment,
+} from "./claim";
/**
* The single canonical disclaimer for every change-coupling surface. Co-change
diff --git a/packages/ui/src/health/ai-prompt-builder.ts b/packages/ui/src/health/ai-prompt-builder.ts
index 8295f9dff..6b032922b 100644
--- a/packages/ui/src/health/ai-prompt-builder.ts
+++ b/packages/ui/src/health/ai-prompt-builder.ts
@@ -698,23 +698,70 @@ export interface CouplingPromptEdge {
target: string;
strength?: number | null;
last_co_change?: string | null;
+ /** Commits that touched both files, undecayed. */
+ support?: number | null;
+ /** Share of `source`'s own commits that also touched `target`. */
+ confidence_ab?: number | null;
+ /** The same share from `target`'s side. */
+ confidence_ba?: number | null;
+ /** `corroborated` / `unexplained` / `not_applicable`, or absent on an older index. */
+ structural?: string | null;
+}
+
+/** What the page already knows about one end of the pair. */
+export interface CouplingPromptNode {
+ module?: string | null;
+ score?: number | null;
+ nloc?: number | null;
}
export interface BuildCouplingPromptOptions {
edge: CouplingPromptEdge;
flavor?: AiPromptFlavor;
repoName?: string;
+ /** Per-file facts keyed by path; either end may be missing. */
+ nodes?: Record<string, CouplingPromptNode>;
+}
+
+/** The dependency-graph verdict, spelled out. `null` when the index has none. */
+function structuralLine(structural: string | null | undefined): string | null {
+ switch (structural) {
+ case "unexplained":
+ return "Dependency graph: **nothing connects them** — no import, type use, framework wiring, or read. This is the finding: they move together with no structural reason to.";
+ case "corroborated":
+ return "Dependency graph: a dependency already connects them, so the co-change is at least partly explained. Judge whether the dependency is the *right* one before treating this as accidental.";
+ case "not_applicable":
+ return "Dependency graph: at least one side was never parsed (a lockfile, changelog, config, or doc), so there was no edge to look for. The coupling is real but is probably release plumbing, not a code-structure problem.";
+ default:
+ return null;
+ }
+}
+
+/** One end's module / health / size, as a bullet, when anything is known. */
+function fileFacts(path: string, label: string, node: CouplingPromptNode | undefined): string {
+ const facts: string[] = [];
+ if (node?.module) facts.push(`module \`${node.module}\``);
+ if (typeof node?.score === "number") facts.push(`health ${node.score.toFixed(1)}/10`);
+ if (typeof node?.nloc === "number" && node.nloc > 0) facts.push(`${node.nloc} lines`);
+ return facts.length
+ ? `File ${label}: \`${path}\` (${facts.join(", ")})`
+ : `File ${label}: \`${path}\``;
}
export function buildCouplingAiPrompt({
edge,
flavor = "generic",
repoName,
+ nodes,
}: BuildCouplingPromptOptions): string {
const repoLine = repoName ? ` (\`${repoName}\`)` : "";
const last = edge.last_co_change
? new Date(edge.last_co_change).toISOString().slice(0, 10)
: null;
+ const pctOf = (v: number | null | undefined) =>
+ typeof v === "number" ? `${Math.round(v * 100)}%` : null;
+ const abPct = pctOf(edge.confidence_ab);
+ const baPct = pctOf(edge.confidence_ba);
const constraintList = [
"**Diagnose before decoupling.** Read both files and the commits that touched them together. The coupling may be legitimate (two halves of one feature) or accidental (a leaky abstraction, a shared constant, copy-paste). Name which it is before acting.",
@@ -742,10 +789,21 @@ export function buildCouplingAiPrompt({
`## Hidden coupling to untangle${repoLine}`,
"",
bulletList([
- `File A: \`${edge.source}\``,
- `File B: \`${edge.target}\``,
+ fileFacts(edge.source, "A", nodes?.[edge.source]),
+ fileFacts(edge.target, "B", nodes?.[edge.target]),
+ edge.support
+ ? `Shared commits: **${edge.support}** (undecayed count of commits that touched both)`
+ : null,
+ // The asymmetry is the content: a file that never changes alone is a
+ // different finding from two that both change often.
+ abPct && baPct
+ ? `Directional confidence: ${abPct} of A's own commits also touched B; ${baPct} of B's also touched A. The larger share is the stronger claim; the smaller one says how independent that side still is.`
+ : (abPct ?? baPct)
+ ? `Directional confidence: ${abPct ? `${abPct} of A's own commits also touched B` : `${baPct} of B's own commits also touched A`} (the other side's commit total is unknown).`
+ : null,
+ structuralLine(edge.structural),
edge.strength != null
- ? `Coupling strength: **${edge.strength}** (recency-weighted count of commits that changed both — not a verified dependency)`
+ ? `Coupling strength: ${edge.strength} (recency-weighted, not a percentage and not a verified dependency)`
: null,
last ? `Last changed together: ${last}` : null,
"Source: repowise co-change analysis (git history — treat as a lead).",
diff --git a/packages/web/src/app/repos/[id]/architecture/page.tsx b/packages/web/src/app/repos/[id]/architecture/page.tsx
index 93cafae67..335ee1330 100644
--- a/packages/web/src/app/repos/[id]/architecture/page.tsx
+++ b/packages/web/src/app/repos/[id]/architecture/page.tsx
@@ -197,7 +197,9 @@ export default function ArchitecturePage({
</div>
)}
{activeTab === "coupling" && (
- <div className="mx-auto max-w-[1100px] p-4 sm:p-6">
+ <div className="mx-auto max-w-[1500px] p-4 sm:p-6">
+ {/* Wider than the other tabs: the pairs table carries a sentence
+ per row plus both modules. The ring keeps its own 820px cap. */}
<div className="mb-2">
<h1 className="mb-1 flex items-center gap-2 text-xl font-semibold text-[var(--color-text-primary)]">
<Code2 className="h-5 w-5 text-[var(--color-accent-primary)]" />
diff --git a/packages/web/src/components/coupling/coupling-tab.tsx b/packages/web/src/components/coupling/coupling-tab.tsx
index 6932a8427..9791fddd1 100644
--- a/packages/web/src/components/coupling/coupling-tab.tsx
+++ b/packages/web/src/components/coupling/coupling-tab.tsx
@@ -1,5 +1,6 @@
"use client";
+import { useState } from "react";
import useSWR from "swr";
import Link from "next/link";
import { useQueryState } from "nuqs";
@@ -7,22 +8,33 @@ import { ApiError } from "@repowise-dev/ui/shared/api-error";
import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
import { CouplingExplorer } from "@repowise-dev/ui/coupling";
import { getCoupling } from "@/lib/api/coupling";
+import { useRepo } from "@/lib/hooks/use-repo";
import { toFriendlyMessage } from "@repowise-dev/ui/lib/errors";
+/** The route's own ceiling. Asking beyond it is rejected, not clamped. */
+const MAX_LIMIT = 1000;
+const INITIAL_LIMIT = 200;
+
/**
* Self-fetching host for the change-coupling Architecture tab. The Architecture
* page is a client component, so coupling data is fetched here via SWR (mirrors
* how the impact analyzer self-fetches) rather than on the server. The whole
* diagram + table interaction lives in `@repowise-dev/ui/coupling` so package
* bumps propagate it to hosted; this host only supplies the repo link prefix,
- * Next's Link, and `?focus=` URL sync for the pinned file.
+ * Next's Link, `?focus=` URL sync for the pinned selection, and the cap.
+ *
+ * The cap starts at 200 and the explorer offers to raise it to the route's
+ * ceiling, so the "showing N of M" line is never a dead end.
*/
export function CouplingTab({ repoId }: { repoId: string }) {
- const { data, error, isLoading, mutate } = useSWR(
- `coupling:${repoId}`,
- () => getCoupling(repoId, { limit: 200 }),
- { revalidateOnFocus: false },
+ const [limit, setLimit] = useState(INITIAL_LIMIT);
+ const { data, error, isLoading, isValidating, mutate } = useSWR(
+ `coupling:${repoId}:${limit}`,
+ () => getCoupling(repoId, { limit }),
+ { revalidateOnFocus: false, keepPreviousData: true },
);
+ // Already fetched by the page shell; SWR dedupes, so this is a cache read.
+ const { repo } = useRepo(repoId);
const [focus, setFocus] = useQueryState("focus");
return (
@@ -46,10 +58,13 @@ export function CouplingTab({ repoId }: { repoId: string }) {
<CouplingExplorer
data={data}
repoLinkPrefix={`/repos/${repoId}`}
+ {...(repo?.name ? { repoName: repo.name } : {})}
LinkComponent={Link}
// Absent / bare `?focus=` → let the explorer open on the most-coupled hub.
initialFocus={focus || undefined}
- onFocusChange={(path) => void setFocus(path)}
+ onFocusChange={(value) => void setFocus(value)}
+ {...(limit < MAX_LIMIT ? { onShowMore: () => setLimit(MAX_LIMIT) } : {})}
+ loadingMore={isValidating}
/>
)}
</div>