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): add repo-wide change-coupling graph (#497)

Raghav Chamadiyacf0b382316a5
diff --git a/packages/core/src/repowise/core/analysis/coupling/__init__.py b/packages/core/src/repowise/core/analysis/coupling/__init__.py
new file mode 100644
index 000000000..9255e72f2
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/coupling/__init__.py
@@ -0,0 +1,21 @@
+"""Change-coupling graph surfacing.
+
+Aggregates the per-file co-change partners we already compute and persist
+(``GitMetadata.co_change_partners_json``) into a deduplicated repo-wide edge
+list, enriched with each file's module / health score / size. Pure surfacing:
+no recompute, no new measurement, no LLM.
+"""
+
+from repowise.core.analysis.coupling.graph import (
+ CouplingEdge,
+ CouplingGraph,
+ CouplingNode,
+ coupling_graph,
+)
+
+__all__ = [
+ "CouplingEdge",
+ "CouplingGraph",
+ "CouplingNode",
+ "coupling_graph",
+]
diff --git a/packages/core/src/repowise/core/analysis/coupling/graph.py b/packages/core/src/repowise/core/analysis/coupling/graph.py
new file mode 100644
index 000000000..cea506d83
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/coupling/graph.py
@@ -0,0 +1,188 @@
+"""Repo-wide change-coupling graph (the "files that change together" view).
+
+Promotes the per-file co-change partners the git indexer already computes
+(``GitMetadata.co_change_partners_json``) into a single deduplicated,
+undirected edge list for the whole repo, with each node enriched by its module
+/ health score / size so the UI can group, color, and size it. Pure surfacing:
+every input is already computed and persisted; no recompute, no new
+measurement, no LLM.
+
+State-free like :mod:`analysis.health.churn_complexity`, :mod:`signals`, and
+:mod:`trends` so the join logic stays unit-testable without a DB -- callers
+pass already-loaded rows and get plain dataclasses back. The same
+:func:`coupling_graph` assembler backs the REST endpoint today and any future
+export.
+
+Honesty rules:
+
+* Co-change is a *temporal* hint (files committed together), not a verified
+ code dependency -- the strength is the decay-weighted count the indexer
+ already thresholds (``>= 0.5``); we surface it verbatim and never invent one.
+* We do **not** fabricate a "strengthening / weakening" trend: co-change history
+ is not snapshotted, so a trend is not derivable. ``strength`` (magnitude) and
+ ``last_co_change`` (recency) are the only honest encodings.
+* Only files that actually participate in a coupling appear as nodes. An
+ isolated file has nothing to say on this surface, so it is omitted rather than
+ drawn as a lonely dot.
+"""
+
+from __future__ import annotations
+
+import json
+from dataclasses import dataclass
+from typing import Protocol
+
+
+class MetricLike(Protocol):
+ """The health-metric fields the graph reads (duck-typed).
+
+ Matches ``persistence.models.HealthFileMetric``; a Protocol so the assembler
+ stays free of any ORM import and tests can pass a stub.
+ """
+
+ file_path: str
+ score: float
+ nloc: int
+ module: str | None
+
+
+class GitMetaLike(Protocol):
+ """The git fields the graph reads (duck-typed).
+
+ ``co_change_partners_json`` is the raw Text column: a JSON list of
+ ``{"file_path", "co_change_count", "last_co_change"}`` partner records
+ (see ``ingestion.git_indexer.co_change``).
+ """
+
+ co_change_partners_json: str
+
+
+@dataclass
+class CouplingNode:
+ """One file that participates in at least one coupling.
+
+ ``module`` groups the node in the legend / table (the ring hierarchy itself
+ is derived from the path on the UI side). ``score`` drives the dot's health
+ band color and is ``None`` only when the file has no health metric (a rare
+ non-source file with git history); the UI renders that as a neutral dot.
+ ``nloc`` encodes dot size.
+ """
+
+ file_path: str
+ module: str | None
+ score: float | None
+ nloc: int
+
+
+@dataclass
+class CouplingEdge:
+ """One undirected coupling between two files.
+
+ ``source``/``target`` are sorted lexicographically so the pair is stable and
+ deduplicated. ``strength`` is the decay-weighted co-change count (verbatim
+ from the indexer; not a percentage). ``last_co_change`` is the ISO date of
+ the most recent shared commit, or ``None`` if unknown.
+ """
+
+ source: str
+ target: str
+ strength: float
+ last_co_change: str | None
+
+
+@dataclass
+class CouplingGraph:
+ """The assembled graph: nodes referenced by the (possibly capped) edges."""
+
+ nodes: list[CouplingNode]
+ edges: list[CouplingEdge]
+ total_edges: int
+
+
+def _parse_partners(raw: str | None) -> list[dict]:
+ """Parse a ``co_change_partners_json`` cell, tolerating absent/bad JSON.
+
+ Mirrors the defensive parsing in :mod:`analysis.health.trends`: a malformed
+ cell yields no partners rather than raising.
+ """
+ if not raw:
+ return []
+ try:
+ parsed = json.loads(raw)
+ except (ValueError, TypeError):
+ return []
+ return parsed if isinstance(parsed, list) else []
+
+
+def coupling_graph(
+ metrics: list[MetricLike],
+ git_meta_by_path: dict[str, GitMetaLike],
+ *,
+ limit: int = 200,
+) -> CouplingGraph:
+ """Assemble the repo-wide coupling graph from already-loaded rows.
+
+ *metrics* are the repo's ``HealthFileMetric`` rows (for module / score /
+ nloc enrichment); *git_meta_by_path* maps ``file_path`` to its
+ ``GitMetadata`` row (from ``get_all_git_metadata``), whose
+ ``co_change_partners_json`` carries the partners. No DB access and no
+ recompute -- a plain join keyed on ``file_path``.
+
+ Partners are stored symmetrically (a->b and b->a), so edges are
+ deduplicated on the sorted ``(source, target)`` pair, keeping the strongest
+ observed strength and the most recent date. Edges are sorted by strength
+ descending and capped at *limit* so a caller keeps the most consequential
+ couplings; ``total_edges`` reports the pre-cap count for an honest "showing
+ N of M" line. Only files referenced by a kept edge become nodes.
+ """
+ # Deduplicate symmetric partner records into undirected edges.
+ best: dict[tuple[str, str], tuple[float, str | None]] = {}
+ for src, meta in git_meta_by_path.items():
+ for partner in _parse_partners(meta.co_change_partners_json):
+ dst = partner.get("file_path")
+ if not dst or dst == src:
+ continue
+ try:
+ strength = float(partner.get("co_change_count") or 0.0)
+ except (ValueError, TypeError):
+ continue
+ if strength <= 0:
+ continue
+ last = partner.get("last_co_change")
+ key = (src, dst) if src < dst else (dst, src)
+ prev = best.get(key)
+ if prev is None:
+ best[key] = (strength, last)
+ else:
+ prev_strength, prev_last = prev
+ best[key] = (
+ max(prev_strength, strength),
+ max((d for d in (prev_last, last) if d), default=None),
+ )
+
+ edges = [
+ CouplingEdge(source=a, target=b, strength=round(strength, 2), last_co_change=last)
+ for (a, b), (strength, last) in best.items()
+ ]
+ edges.sort(key=lambda e: e.strength, reverse=True)
+ total = len(edges)
+ edges = edges[:limit]
+
+ # Build nodes only for files referenced by a kept edge.
+ metric_by_path = {m.file_path: m for m in metrics}
+ referenced: set[str] = set()
+ for e in edges:
+ referenced.add(e.source)
+ referenced.add(e.target)
+
+ nodes = [
+ CouplingNode(
+ file_path=path,
+ module=(metric_by_path[path].module if path in metric_by_path else None),
+ score=(round(metric_by_path[path].score, 2) if path in metric_by_path else None),
+ nloc=(metric_by_path[path].nloc or 0 if path in metric_by_path else 0),
+ )
+ for path in sorted(referenced)
+ ]
+
+ return CouplingGraph(nodes=nodes, edges=edges, total_edges=total)
diff --git a/packages/server/src/repowise/server/app.py b/packages/server/src/repowise/server/app.py
index 43dc519fb..594209bd9 100644
--- a/packages/server/src/repowise/server/app.py
+++ b/packages/server/src/repowise/server/app.py
@@ -37,6 +37,7 @@ from repowise.server.routers import (
claude_md,
code_health,
costs,
+ coupling,
dead_code,
decisions,
external_systems,
@@ -389,6 +390,7 @@ def create_app() -> FastAPI:
app.include_router(git.router)
app.include_router(dead_code.router)
app.include_router(code_health.router)
+ app.include_router(coupling.router)
app.include_router(claude_md.router)
app.include_router(decisions.router)
app.include_router(chat.router)
diff --git a/packages/server/src/repowise/server/routers/coupling.py b/packages/server/src/repowise/server/routers/coupling.py
new file mode 100644
index 000000000..6f579c75e
--- /dev/null
+++ b/packages/server/src/repowise/server/routers/coupling.py
@@ -0,0 +1,71 @@
+"""/api/repos/{repo_id}/coupling — repo-wide change-coupling graph.
+
+Surfaces the per-file co-change partners the git indexer already persists
+(``GitMetadata.co_change_partners_json``) as a single deduplicated, undirected
+edge list, enriched with each node's module / health score / size so the UI can
+group, color, and size the graph. Pure surfacing: no recompute, no LLM. The
+join mirrors ``code_health.py``'s churn-complexity endpoint.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from fastapi import APIRouter, Depends, HTTPException, Query
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from repowise.core.analysis.coupling import (
+ CouplingEdge,
+ CouplingNode,
+ coupling_graph,
+)
+from repowise.core.persistence import crud
+from repowise.server.deps import get_db_session, verify_api_key
+
+router = APIRouter(
+ tags=["coupling"],
+ dependencies=[Depends(verify_api_key)],
+)
+
+
+def _node_to_dict(n: CouplingNode) -> dict[str, Any]:
+ return {
+ "file_path": n.file_path,
+ "module": n.module,
+ "score": n.score,
+ "nloc": n.nloc,
+ }
+
+
+def _edge_to_dict(e: CouplingEdge) -> dict[str, Any]:
+ return {
+ "source": e.source,
+ "target": e.target,
+ "strength": e.strength,
+ "last_co_change": e.last_co_change,
+ }
+
+
[email protected]("/api/repos/{repo_id}/coupling")
+async def coupling(
+ repo_id: str,
+ limit: int = Query(200, ge=1, le=1000),
+ session: AsyncSession = Depends(get_db_session), # noqa: B008
+) -> dict:
+ """Return the repo's change-coupling graph (strongest *limit* edges).
+
+ Co-change is a temporal hint (files committed together), not a verified
+ dependency; ``strength`` is the decay-weighted count, not a percentage.
+ """
+ repo = await crud.get_repository(session, repo_id)
+ if repo is None:
+ raise HTTPException(status_code=404, detail="Repository not found")
+
+ metrics = await crud.get_health_metrics(session, repo_id)
+ git_meta = await crud.get_all_git_metadata(session, repo_id)
+ graph = coupling_graph(metrics, git_meta, limit=limit)
+ return {
+ "nodes": [_node_to_dict(n) for n in graph.nodes],
+ "edges": [_edge_to_dict(e) for e in graph.edges],
+ "total_edges": graph.total_edges,
+ }
diff --git a/packages/types/package.json b/packages/types/package.json
index a1871bcf5..0e6d8a7ef 100644
--- a/packages/types/package.json
+++ b/packages/types/package.json
@@ -26,7 +26,8 @@
"./overview": "./src/overview.ts",
"./files": "./src/files.ts",
"./external-systems": "./src/external-systems.ts",
- "./health": "./src/health.ts"
+ "./health": "./src/health.ts",
+ "./coupling": "./src/coupling.ts"
},
"publishConfig": {
"registry": "https://npm.pkg.github.com",
diff --git a/packages/types/src/coupling.ts b/packages/types/src/coupling.ts
new file mode 100644
index 000000000..29d63fd16
--- /dev/null
+++ b/packages/types/src/coupling.ts
@@ -0,0 +1,43 @@
+/**
+ * Change-coupling (co-change) wire contract — shared by the web dashboard
+ * (`packages/web`), the shared UI (`packages/ui`), and any future hosted
+ * consumer. Mirrors the server's `routers/coupling.py` response shape.
+ *
+ * The graph is a pure surfacing of `GitMetadata.co_change_partners_json`: files
+ * that have been committed together, deduplicated into an undirected edge list.
+ * Co-change is a TEMPORAL hint (shared commits), not a verified code
+ * dependency, and `strength` is a decay-weighted count — not a percentage. No
+ * "strengthening/weakening" trend is carried because co-change history is not
+ * snapshotted; only magnitude and recency are honest signals.
+ */
+
+/** One file that participates in at least one coupling. */
+export interface CouplingNode {
+ file_path: string;
+ /** Module grouping for the legend/table; `null` when the file has no health metric. */
+ module: string | null;
+ /** Health score (drives the band dot color); `null` for a file with no health metric. */
+ score: number | null;
+ /** Logical lines of code; encodes dot size. */
+ nloc: number;
+}
+
+/** One undirected coupling between two files. */
+export interface CouplingEdge {
+ /** Lexicographically-smaller file path (stable, deduplicated pair). */
+ source: string;
+ /** Lexicographically-larger file path. */
+ target: string;
+ /** Decay-weighted co-change count (verbatim from the indexer; not a percentage). */
+ strength: number;
+ /** ISO date of the most recent shared commit, or `null` if unknown. */
+ last_co_change: string | null;
+}
+
+/** Response of `GET /api/repos/{repo_id}/coupling`. */
+export interface CouplingGraphResponse {
+ nodes: CouplingNode[];
+ edges: CouplingEdge[];
+ /** Pre-cap edge count, for an honest "showing N of M couplings" line. */
+ total_edges: number;
+}
diff --git a/packages/types/src/index.ts b/packages/types/src/index.ts
index 3dbdf470a..e12ed4cee 100644
--- a/packages/types/src/index.ts
+++ b/packages/types/src/index.ts
@@ -26,3 +26,4 @@ export * from "./overview.js";
export * from "./files.js";
export * from "./external-systems.js";
export * from "./health.js";
+export * from "./coupling.js";
diff --git a/packages/ui/COMPONENT_CONTRACTS.md b/packages/ui/COMPONENT_CONTRACTS.md
index 60b3e1620..d290f76a5 100644
--- a/packages/ui/COMPONENT_CONTRACTS.md
+++ b/packages/ui/COMPONENT_CONTRACTS.md
@@ -354,6 +354,47 @@ files list.
---
+## `coupling/*` — Change-coupling visualisation
+
+Renders the repo-wide change-coupling graph (files that change together).
+Pure presentation over `@repowise-dev/types/coupling`; fetching belongs to
+the caller. Co-change is a temporal hint, not a verified dependency, and
+`strength` is a decay-weighted count (never a percentage or a trend).
+
+### `coupling/coupling-graph` — `CouplingGraph`
+
+Hierarchical edge-bundling diagram (`d3-hierarchy` radial cluster +
+`d3-shape` `curveBundle`). Files sit on a ring grouped by their directory
+hierarchy; bundled arcs link files that change together. Dots are colored by
+health band and sized by lines + coupling degree. Hovering a file lifts its
+couplings (colored by the partner's health band) and dims the rest. Focus is
+controllable (`focusedPath`/`onFocusChange`) for cross-highlight with a table,
+or falls back to internal hover state.
+
+| Prop | Type | Required |
+|------|------|----------|
+| `nodes` | `CouplingNode[]` (`@repowise-dev/types/coupling`) | yes |
+| `edges` | `CouplingEdge[]` (`@repowise-dev/types/coupling`) | yes |
+| `totalEdges` | `number` (pre-cap count, for the "showing N of M" line) | no |
+| `focusedPath` | `string \| null` (controlled focus) | no |
+| `onFocusChange` | `(path: string \| null) => void` | no |
+| `size` | `number` (square viewBox edge, default 760) | no |
+
+### `coupling/coupling-table` — `CouplingTable`
+
+The precise, ranked companion to the diagram: one row per coupling
+(strongest first) with a strength bar and last-shared-commit date. Clicking a
+row toggles focus on that file; rows incident to the focused file are
+emphasised. Uses `shared/responsive-table`.
+
+| Prop | Type | Required |
+|------|------|----------|
+| `edges` | `CouplingEdge[]` (`@repowise-dev/types/coupling`) | yes |
+| `focusedPath` | `string \| null` | no |
+| `onFocusChange` | `(path: string \| null) => void` | no |
+
+---
+
## `jobs/job-log` — `JobLog`
Auto-scrolling fixed-height log viewer for streaming job progress
diff --git a/packages/ui/__tests__/coupling/coupling-graph.test.tsx b/packages/ui/__tests__/coupling/coupling-graph.test.tsx
new file mode 100644
index 000000000..1ac8e2be7
--- /dev/null
+++ b/packages/ui/__tests__/coupling/coupling-graph.test.tsx
@@ -0,0 +1,69 @@
+import { describe, it, expect } from "vitest";
+import { render, screen, fireEvent } from "@testing-library/react";
+import type { CouplingEdge, CouplingNode } from "@repowise-dev/types/coupling";
+import { CouplingGraph } from "../../src/coupling/coupling-graph.js";
+import { CouplingTable } from "../../src/coupling/coupling-table.js";
+
+function node(path: string, score: number | null = 7, nloc = 100): CouplingNode {
+ return { file_path: path, module: path.split("/")[0] ?? null, score, nloc };
+}
+function edge(s: string, t: string, strength = 3, last: string | null = "2026-06-01"): CouplingEdge {
+ return { source: s, target: t, strength, last_co_change: last };
+}
+
+describe("CouplingGraph", () => {
+ it("shows the empty state when there is nothing to bundle", () => {
+ render(<CouplingGraph nodes={[]} edges={[]} />);
+ expect(screen.getByText(/not enough shared git history/i)).toBeInTheDocument();
+ });
+
+ it("renders an arc per drawn coupling and the honest count line", () => {
+ const nodes = [node("api/a.py", 3), node("core/b.py", 9), node("ui/c.py", 6)];
+ const edges = [edge("api/a.py", "core/b.py", 5), edge("core/b.py", "ui/c.py", 2)];
+ const { container } = render(<CouplingGraph nodes={nodes} edges={edges} totalEdges={9} />);
+ // Two bundled edge paths drawn (module arc bands are separate <path>s but
+ // edges live in the dedicated fill="none" group).
+ expect(container.querySelectorAll("svg path").length).toBeGreaterThanOrEqual(2);
+ expect(screen.getByText(/showing 2 of 9 couplings/i)).toBeInTheDocument();
+ });
+
+ it("emphasizes a file's couplings on hover (focus changes)", () => {
+ const nodes = [node("api/a.py"), node("core/b.py")];
+ const edges = [edge("api/a.py", "core/b.py")];
+ let focus: string | null = null;
+ const { container } = render(
+ <CouplingGraph
+ nodes={nodes}
+ edges={edges}
+ focusedPath={focus}
+ onFocusChange={(p) => (focus = p)}
+ />,
+ );
+ const circle = container.querySelector("circle");
+ expect(circle).not.toBeNull();
+ fireEvent.mouseEnter(circle!.parentElement!);
+ expect(focus).not.toBeNull();
+ });
+});
+
+describe("CouplingTable", () => {
+ it("renders a row per coupling, strongest first", () => {
+ const edges = [edge("a.py", "b.py", 4), edge("c.py", "d.py", 1)];
+ render(<CouplingTable edges={edges} />);
+ expect(screen.getByText("a.py")).toBeInTheDocument();
+ expect(screen.getByText("↔ b.py")).toBeInTheDocument();
+ });
+
+ it("toggles focus on row click", () => {
+ const edges = [edge("a.py", "b.py", 4)];
+ let focus: string | null = null;
+ render(<CouplingTable edges={edges} focusedPath={focus} onFocusChange={(p) => (focus = p)} />);
+ fireEvent.click(screen.getByText("a.py"));
+ expect(focus).toBe("a.py");
+ });
+
+ it("shows the empty state with no couplings", () => {
+ render(<CouplingTable edges={[]} />);
+ expect(screen.getByText(/no couplings detected/i)).toBeInTheDocument();
+ });
+});
diff --git a/packages/ui/package.json b/packages/ui/package.json
index bac243695..ef5b8c761 100644
--- a/packages/ui/package.json
+++ b/packages/ui/package.json
@@ -33,6 +33,8 @@
"./dead-code/*": "./src/dead-code/*.tsx",
"./health": "./src/health/index.ts",
"./health/*": "./src/health/*.tsx",
+ "./coupling": "./src/coupling/index.ts",
+ "./coupling/*": "./src/coupling/*.tsx",
"./decisions": "./src/decisions/index.ts",
"./decisions/*": "./src/decisions/*.tsx",
"./files": "./src/files/index.ts",
@@ -121,6 +123,7 @@
"clsx": "^2.1.1",
"d3-force": "^3.0.0",
"d3-hierarchy": "^3.1.2",
+ "d3-shape": "^3.2.0",
"elkjs": "^0.11.1",
"framer-motion": "^11.11.0",
"fuse.js": "^7.0.0",
@@ -147,6 +150,7 @@
"devDependencies": {
"@testing-library/jest-dom": "^6.5.0",
"@testing-library/react": "^16.0.0",
+ "@types/d3-shape": "^3.1.8",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"@vitejs/plugin-react": "^4.3.0",
diff --git a/packages/ui/src/coupling/coupling-graph.tsx b/packages/ui/src/coupling/coupling-graph.tsx
new file mode 100644
index 000000000..b523173b9
--- /dev/null
+++ b/packages/ui/src/coupling/coupling-graph.tsx
@@ -0,0 +1,358 @@
+"use client";
+
+import { useMemo, useState } from "react";
+import { cluster, hierarchy, type HierarchyNode } from "d3-hierarchy";
+import { curveBundle, lineRadial } from "d3-shape";
+// Value imports must come from the package root, not the `/coupling` subpath:
+// the vite/rollup base alias clobbers subpath value resolution. Type-only
+// subpath imports are fine (erased before resolution).
+import { bandForScore } from "@repowise-dev/types";
+import type { CouplingEdge, CouplingNode } from "@repowise-dev/types/coupling";
+import type { HealthBand } from "@repowise-dev/types/health";
+
+export interface CouplingGraphProps {
+ nodes: CouplingNode[];
+ edges: CouplingEdge[];
+ /** Pre-cap edge count, for the honest "showing N of M" line. */
+ totalEdges?: number;
+ /** Controlled focus (sync with the table); falls back to internal hover. */
+ focusedPath?: string | null;
+ onFocusChange?: (path: string | null) => void;
+ /** Square render size in px (viewBox edge). */
+ size?: number;
+}
+
+/* CSS-var ink per canonical health band (the 3-bucket currency). A file with
+ * no health metric resolves to neutral. SVG stroke/fill accept `var()`. */
+const NEUTRAL_INK = "var(--color-text-tertiary)";
+const BAND_INK: Record<HealthBand, string> = {
+ alert: "var(--color-error)",
+ warning: "var(--color-caution)",
+ healthy: "var(--color-success)",
+};
+
+function inkFor(score: number | null): string {
+ return score == null ? NEUTRAL_INK : BAND_INK[bandForScore(score)];
+}
+
+/** A leaf in the radial cluster: a file, plus its layout angle/radius. */
+interface TreeDatum {
+ name: string; // path segment (display)
+ path?: string; // full original file_path (leaves only)
+ node?: CouplingNode;
+ children?: TreeDatum[];
+}
+
+/**
+ * Strip the longest path-segment prefix shared by every file so the radial
+ * dendrogram branches on the segments that actually differ (otherwise a deep
+ * monorepo prefix like `packages/core/src/...` wastes the whole inner radius on
+ * a single unbranching chain). The arc-group labels then read as real modules.
+ */
+function stripCommonPrefix(paths: string[]): { stripped: string[]; prefix: string[] } {
+ if (paths.length === 0) return { stripped: [], prefix: [] };
+ const split = paths.map((p) => p.split("/"));
+ const first = split[0]!;
+ let common = 0;
+ for (let i = 0; i < first.length - 1; i++) {
+ const seg = first[i];
+ if (split.every((s) => s.length > i + 1 && s[i] === seg)) common++;
+ else break;
+ }
+ return {
+ stripped: split.map((s) => s.slice(common).join("/")),
+ prefix: first.slice(0, common),
+ };
+}
+
+/** Build a nested folder tree from file paths (leaves carry the node datum). */
+function buildTree(nodes: CouplingNode[]): TreeDatum {
+ const { stripped } = stripCommonPrefix(nodes.map((n) => n.file_path));
+ const root: TreeDatum = { name: "", children: [] };
+ nodes.forEach((node, i) => {
+ const segs = stripped[i]!.split("/");
+ let cursor = root;
+ segs.forEach((seg, depth) => {
+ const isLeaf = depth === segs.length - 1;
+ if (isLeaf) {
+ (cursor.children ??= []).push({ name: seg, path: node.file_path, node });
+ return;
+ }
+ let child = cursor.children?.find((c) => c.name === seg && c.path === undefined);
+ if (!child) {
+ child = { name: seg, children: [] };
+ (cursor.children ??= []).push(child);
+ }
+ cursor = child;
+ });
+ });
+ return root;
+}
+
+/** Polar -> cartesian, with 0 rad at 12 o'clock (matches d3 cluster + lineRadial). */
+function project(angle: number, radius: number): [number, number] {
+ const a = angle - Math.PI / 2;
+ return [Math.cos(a) * radius, Math.sin(a) * radius];
+}
+
+/**
+ * Hierarchical edge-bundling view of change coupling. Files sit on a ring,
+ * grouped by their directory hierarchy; an arc between two files means they are
+ * frequently committed together. Edges are bundled through the folder tree so
+ * the picture reads as module-to-module flow rather than a hairball. Dots are
+ * colored by health band; hovering a file lifts its couplings (colored by the
+ * partner's health) and dims the rest.
+ *
+ * Co-change is a temporal hint, not a verified dependency; edge thickness/
+ * opacity encode the decay-weighted strength, never a fabricated trend.
+ */
+export function CouplingGraph({
+ nodes,
+ edges,
+ totalEdges,
+ focusedPath,
+ onFocusChange,
+ size = 760,
+}: CouplingGraphProps) {
+ const [internalFocus, setInternalFocus] = useState<string | null>(null);
+ const focus = focusedPath !== undefined ? focusedPath : internalFocus;
+ const setFocus = (p: string | null) => {
+ if (onFocusChange) onFocusChange(p);
+ else setInternalFocus(p);
+ };
+
+ const layout = useMemo(() => {
+ if (nodes.length < 2 || edges.length === 0) return null;
+ const radius = size / 2 - 96; // leave room for arc labels
+ const root = hierarchy<TreeDatum>(buildTree(nodes), (d) => d.children);
+ root.sort((a, b) => (a.data.name < b.data.name ? -1 : a.data.name > b.data.name ? 1 : 0));
+ cluster<TreeDatum>().size([2 * Math.PI, radius])(root);
+
+ const leaves = root.leaves();
+ const leafByPath = new Map<string, HierarchyNode<TreeDatum>>();
+ for (const leaf of leaves) if (leaf.data.path) leafByPath.set(leaf.data.path, leaf);
+
+ const line = lineRadial<HierarchyNode<TreeDatum>>()
+ .curve(curveBundle.beta(0.82))
+ .radius((d) => d.y!)
+ .angle((d) => d.x!);
+
+ const maxStrength = Math.max(...edges.map((e) => e.strength), 1);
+ const drawn = edges
+ .map((e) => {
+ const s = leafByPath.get(e.source);
+ const t = leafByPath.get(e.target);
+ if (!s || !t) return null;
+ return { edge: e, d: line(s.path(t)) ?? "" };
+ })
+ .filter((x): x is { edge: CouplingEdge; d: string } => x !== null);
+
+ // Degree per file -> dot radius emphasis for highly-coupled hubs.
+ const degree = new Map<string, number>();
+ for (const e of edges) {
+ degree.set(e.source, (degree.get(e.source) ?? 0) + 1);
+ degree.set(e.target, (degree.get(e.target) ?? 0) + 1);
+ }
+ const maxNloc = Math.max(...nodes.map((n) => n.nloc), 1);
+
+ // Arc groups: the first stripped segment of each leaf (the module band).
+ const groups = new Map<string, { a0: number; a1: number }>();
+ for (const leaf of leaves) {
+ const top = leaf.ancestors().reverse()[1]; // child of root
+ const name = top?.data.name ?? "";
+ if (!name) continue;
+ const g = groups.get(name);
+ if (!g) groups.set(name, { a0: leaf.x!, a1: leaf.x! });
+ else {
+ g.a0 = Math.min(g.a0, leaf.x!);
+ g.a1 = Math.max(g.a1, leaf.x!);
+ }
+ }
+
+ return { radius, leaves, leafByPath, drawn, degree, maxNloc, maxStrength, groups };
+ }, [nodes, edges, size]);
+
+ if (!layout) {
+ return (
+ <div
+ className="flex items-center justify-center rounded-xl border border-dashed border-[var(--color-border-default)] bg-[var(--color-bg-surface)] text-center text-sm text-[var(--color-text-tertiary)]"
+ style={{ minHeight: size * 0.6 }}
+ >
+ Not enough shared git history to map coupling yet. Files need to have
+ been committed together.
+ </div>
+ );
+ }
+
+ const { radius, leaves, drawn, degree, maxNloc, maxStrength, groups } = layout;
+ const c = size / 2;
+
+ // Neighbors of the focused file (for dimming + dot emphasis).
+ const neighbors = new Set<string>();
+ if (focus) {
+ for (const e of edges) {
+ if (e.source === focus) neighbors.add(e.target);
+ if (e.target === focus) neighbors.add(e.source);
+ }
+ }
+
+ const dotR = (n: CouplingNode) =>
+ 2 + Math.sqrt(n.nloc / maxNloc) * 2.4 + Math.min((degree.get(n.file_path) ?? 0) / 6, 2.6);
+
+ const labelFor = (full: string) => full.split("/").pop() ?? full;
+
+ return (
+ <div className="rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-4">
+ <div className="mb-1 flex items-baseline justify-between gap-3">
+ <h3 className="text-sm font-semibold tracking-tight text-[var(--color-text-primary)]">
+ Change coupling
+ </h3>
+ <span className="text-xs text-[var(--color-text-tertiary)]">
+ {totalEdges && totalEdges > drawn.length
+ ? `showing ${drawn.length} of ${totalEdges} couplings`
+ : `${drawn.length} couplings`}
+ </span>
+ </div>
+ <p className="mb-2 text-xs text-[var(--color-text-tertiary)]">
+ Files that tend to change in the same commit. A temporal hint, not a
+ verified dependency.
+ </p>
+
+ <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"
+ onMouseLeave={() => setFocus(null)}
+ >
+ <g transform={`translate(${c},${c})`}>
+ {/* Module arc bands + labels around the perimeter. */}
+ {[...groups.entries()].map(([name, g]) => {
+ const mid = (g.a0 + g.a1) / 2;
+ const [lx, ly] = project(mid, radius + 30);
+ const deg = (mid * 180) / Math.PI - 90;
+ const flip = mid > Math.PI;
+ const [x0, y0] = project(g.a0 - 0.012, radius + 12);
+ const [x1, y1] = project(g.a1 + 0.012, radius + 12);
+ const large = g.a1 - g.a0 > Math.PI ? 1 : 0;
+ return (
+ <g key={name}>
+ <path
+ d={`M ${x0} ${y0} A ${radius + 12} ${radius + 12} 0 ${large} 1 ${x1} ${y1}`}
+ fill="none"
+ stroke="currentColor"
+ className="text-[var(--color-border-strong)]"
+ strokeOpacity={0.5}
+ strokeWidth={1.5}
+ strokeLinecap="round"
+ />
+ <text
+ x={lx}
+ y={ly}
+ fontSize={10}
+ textAnchor="middle"
+ dominantBaseline="middle"
+ transform={`rotate(${flip ? deg + 180 : deg} ${lx} ${ly})`}
+ className="fill-[var(--color-text-tertiary)] font-medium uppercase tracking-wider"
+ >
+ {name}
+ </text>
+ </g>
+ );
+ })}
+
+ {/* Edges. Quiet hairlines by default; on focus, the focused file's
+ 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 partnerPath = focus === edge.source ? edge.target : edge.source;
+ const partnerNode = incident
+ ? nodes.find((n) => n.file_path === partnerPath)
+ : undefined;
+ const strengthFrac = edge.strength / maxStrength;
+ const stroke = incident ? inkFor(partnerNode?.score ?? null) : NEUTRAL_INK;
+ return (
+ <path
+ key={`${edge.source}|${edge.target}`}
+ d={d}
+ stroke={stroke}
+ strokeWidth={incident ? 1.1 + strengthFrac * 2.4 : 0.7 + strengthFrac * 0.8}
+ strokeOpacity={incident ? 0.9 : dim ? 0.04 : 0.1 + strengthFrac * 0.14}
+ style={{ transition: "stroke-opacity 160ms ease, stroke-width 160ms ease" }}
+ />
+ );
+ })}
+ </g>
+
+ {/* File dots + (focused) labels. */}
+ {leaves.map((leaf) => {
+ const n = leaf.data.node;
+ if (!n) return null;
+ const [x, y] = project(leaf.x!, leaf.y!);
+ const isFocus = focus === n.file_path;
+ const isNeighbor = neighbors.has(n.file_path);
+ const dim = focus != null && !isFocus && !isNeighbor;
+ const showLabel = isFocus || isNeighbor || (focus == null && leaves.length <= 36);
+ const deg = (leaf.x! * 180) / Math.PI - 90;
+ const flip = leaf.x! > Math.PI;
+ const [lx, ly] = project(leaf.x!, leaf.y! + 8);
+ return (
+ <g
+ key={n.file_path}
+ style={{ transition: "opacity 160ms ease", opacity: dim ? 0.18 : 1 }}
+ onMouseEnter={() => setFocus(n.file_path)}
+ className="cursor-pointer"
+ >
+ <circle
+ cx={x}
+ cy={y}
+ r={dotR(n) * (isFocus ? 1.5 : 1)}
+ fill={inkFor(n.score)}
+ fillOpacity={0.92}
+ stroke="var(--color-bg-surface)"
+ strokeWidth={isFocus ? 1.6 : 1}
+ >
+ <title>{`${n.file_path}${n.score != null ? ` · score ${n.score.toFixed(1)}` : ""} · ${degree.get(n.file_path) ?? 0} couplings`}</title>
+ </circle>
+ {showLabel ? (
+ <text
+ x={lx}
+ y={ly}
+ fontSize={9}
+ textAnchor={flip ? "end" : "start"}
+ dominantBaseline="middle"
+ transform={`rotate(${flip ? deg + 180 : deg} ${lx} ${ly})`}
+ className={
+ isFocus
+ ? "fill-[var(--color-text-primary)] font-medium"
+ : "fill-[var(--color-text-secondary)]"
+ }
+ style={{ pointerEvents: "none" }}
+ >
+ {labelFor(n.file_path)}
+ </text>
+ ) : null}
+ </g>
+ );
+ })}
+ </g>
+ </svg>
+
+ {/* Legend */}
+ <div className="mt-1 flex flex-wrap items-center gap-x-4 gap-y-1 text-[11px] text-[var(--color-text-tertiary)]">
+ <span className="inline-flex items-center gap-1.5">
+ <span className="h-2 w-2 rounded-full bg-[var(--color-success)]" /> healthy
+ </span>
+ <span className="inline-flex items-center gap-1.5">
+ <span className="h-2 w-2 rounded-full bg-[var(--color-caution)]" /> warning
+ </span>
+ <span className="inline-flex items-center gap-1.5">
+ <span className="h-2 w-2 rounded-full bg-[var(--color-error)]" /> alert
+ </span>
+ <span className="ml-auto">dot size = lines + couplings · line opacity = strength</span>
+ </div>
+ </div>
+ );
+}
diff --git a/packages/ui/src/coupling/coupling-table.tsx b/packages/ui/src/coupling/coupling-table.tsx
new file mode 100644
index 000000000..b62b00d88
--- /dev/null
+++ b/packages/ui/src/coupling/coupling-table.tsx
@@ -0,0 +1,117 @@
+"use client";
+
+import { EmptyState } from "../shared/empty-state";
+import {
+ ResponsiveTable,
+ type ResponsiveColumn,
+} from "../shared/responsive-table";
+import type { CouplingEdge } from "@repowise-dev/types/coupling";
+
+interface CouplingTableProps {
+ edges: CouplingEdge[];
+ /** Focused file (emphasizes rows incident to it; synced with the diagram). */
+ focusedPath?: string | null;
+ onFocusChange?: (path: string | null) => void;
+}
+
+function basename(path: string): string {
+ return path.split("/").pop() ?? path;
+}
+
+/**
+ * The precise, sortable companion to the coupling diagram: one row per
+ * coupling, strongest first. Clicking a row focuses that file in the ring;
+ * rows touching the focused file are emphasized.
+ */
+export function CouplingTable({ edges, focusedPath, onFocusChange }: CouplingTableProps) {
+ const maxStrength = Math.max(...edges.map((e) => e.strength), 1);
+ const incident = (e: CouplingEdge) =>
+ focusedPath != null && (e.source === focusedPath || e.target === focusedPath);
+
+ const fileCell = (path: string, e: CouplingEdge, prefix = "") => {
+ const hot = incident(e) && path === focusedPath;
+ return (
+ <span
+ className={`block truncate font-mono text-xs ${
+ hot ? "text-[var(--color-text-primary)] font-medium" : "text-[var(--color-text-secondary)]"
+ }`}
+ title={path}
+ >
+ {prefix}
+ {basename(path)}
+ </span>
+ );
+ };
+
+ const columns: ResponsiveColumn<CouplingEdge>[] = [
+ {
+ key: "pair",
+ header: "Coupled files",
+ priority: 1,
+ cellClassName: "min-w-[200px]",
+ render: (e) => (
+ <div className="flex flex-col gap-0.5">
+ {fileCell(e.source, e)}
+ {fileCell(e.target, e, "↔ ")}
+ </div>
+ ),
+ },
+ {
+ key: "strength",
+ header: (
+ <span
+ title="Recency-weighted count of commits that touched both files. Higher means more or more-recent shared changes. It is not a percentage or a verified dependency."
+ className="cursor-help underline decoration-dotted underline-offset-2"
+ >
+ Strength
+ </span>
+ ),
+ mobileLabel: "Strength",
+ priority: 2,
+ headerClassName: "w-36",
+ 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>
+ ),
+ mobileRender: (e) => e.strength,
+ },
+ {
+ key: "last",
+ header: "Last",
+ priority: 3,
+ cellClassName: "text-xs text-[var(--color-text-tertiary)]",
+ render: (e) => (
+ <span title={e.last_co_change ? new Date(e.last_co_change).toLocaleString() : undefined}>
+ {e.last_co_change ? new Date(e.last_co_change).toLocaleDateString() : "—"}
+ </span>
+ ),
+ },
+ ];
+
+ return (
+ <ResponsiveTable
+ columns={columns}
+ rows={edges}
+ rowKey={(e) => `${e.source}|${e.target}`}
+ bare
+ onRowClick={
+ onFocusChange ? (e) => onFocusChange(focusedPath === e.source ? null : e.source) : undefined
+ }
+ empty={
+ <EmptyState
+ title="No couplings detected"
+ description="No files in this repository have a history of changing together yet."
+ />
+ }
+ />
+ );
+}
diff --git a/packages/ui/src/coupling/index.ts b/packages/ui/src/coupling/index.ts
new file mode 100644
index 000000000..a0962c0de
--- /dev/null
+++ b/packages/ui/src/coupling/index.ts
@@ -0,0 +1,2 @@
+export { CouplingGraph, type CouplingGraphProps } from "./coupling-graph";
+export { CouplingTable } from "./coupling-table";
diff --git a/packages/web/src/app/repos/[id]/coupling/page.tsx b/packages/web/src/app/repos/[id]/coupling/page.tsx
new file mode 100644
index 000000000..824c7ad13
--- /dev/null
+++ b/packages/web/src/app/repos/[id]/coupling/page.tsx
@@ -0,0 +1,39 @@
+import { notFound } from "next/navigation";
+import { getCoupling } from "@/lib/api/coupling";
+import { ApiClientError } from "@/lib/api/client";
+import { CouplingView } from "@/components/coupling/coupling-view";
+
+export const revalidate = 30;
+
+interface Props {
+ params: Promise<{ id: string }>;
+}
+
+export default async function CouplingPage({ params }: Props) {
+ const { id: repoId } = await params;
+
+ let data;
+ try {
+ data = await getCoupling(repoId, { limit: 200 });
+ } catch (err) {
+ if (err instanceof ApiClientError && err.status === 404) {
+ notFound();
+ }
+ throw err;
+ }
+
+ return (
+ <div className="space-y-6 p-6">
+ <div>
+ <h1 className="text-2xl font-semibold text-[var(--color-text-primary)]">
+ Change coupling
+ </h1>
+ <p className="mt-1 text-sm text-[var(--color-text-tertiary)]">
+ Files that tend to change together in the same commit. A temporal hint
+ for hidden relationships, not a verified code dependency.
+ </p>
+ </div>
+ <CouplingView data={data} />
+ </div>
+ );
+}
diff --git a/packages/web/src/components/coupling/coupling-view.tsx b/packages/web/src/components/coupling/coupling-view.tsx
new file mode 100644
index 000000000..bd8f2b52a
--- /dev/null
+++ b/packages/web/src/components/coupling/coupling-view.tsx
@@ -0,0 +1,39 @@
+"use client";
+
+import { useState } from "react";
+import { CouplingGraph, CouplingTable } from "@repowise-dev/ui/coupling";
+import type { CouplingGraphResponse } from "@repowise-dev/types/coupling";
+
+interface CouplingViewProps {
+ data: CouplingGraphResponse;
+}
+
+/**
+ * Hosts the coupling diagram (centerpiece) and the precise ranked table below
+ * it, sharing a single `focusedPath` so hovering the ring emphasizes the table
+ * rows and clicking a row lifts the ring — one focus model across both.
+ */
+export function CouplingView({ data }: CouplingViewProps) {
+ const [focusedPath, setFocusedPath] = useState<string | null>(null);
+
+ return (
+ <div className="space-y-5">
+ <div className="mx-auto w-full max-w-[820px]">
+ <CouplingGraph
+ nodes={data.nodes}
+ edges={data.edges}
+ totalEdges={data.total_edges}
+ focusedPath={focusedPath}
+ onFocusChange={setFocusedPath}
+ />
+ </div>
+ <div className="rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-1.5">
+ <CouplingTable
+ edges={data.edges}
+ focusedPath={focusedPath}
+ onFocusChange={setFocusedPath}
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/packages/web/src/components/layout/nav-items.ts b/packages/web/src/components/layout/nav-items.ts
index fa6229e33..175de7d09 100644
--- a/packages/web/src/components/layout/nav-items.ts
+++ b/packages/web/src/components/layout/nav-items.ts
@@ -21,6 +21,7 @@ import {
MessageSquare,
Settings,
Users,
+ Waypoints,
} from "lucide-react";
export interface NavItem {
@@ -56,6 +57,7 @@ export function repoNavGroups(repoId: string): NavGroup[] {
{ label: "Docs", href: `${base}/docs`, icon: BookOpen },
{ label: "Architecture", href: `${base}/architecture`, icon: Boxes },
{ label: "Code Health", href: `${base}/code-health`, icon: HeartPulse },
+ { label: "Coupling", href: `${base}/coupling`, icon: Waypoints },
],
},
{
diff --git a/packages/web/src/lib/api/coupling.ts b/packages/web/src/lib/api/coupling.ts
new file mode 100644
index 000000000..2c6bf1861
--- /dev/null
+++ b/packages/web/src/lib/api/coupling.ts
@@ -0,0 +1,20 @@
+/**
+ * Change-coupling API client. The response types live in the shared
+ * `@repowise-dev/types/coupling` contract; this module re-exports them and
+ * keeps only the fetch function.
+ */
+import type { CouplingGraphResponse } from "@repowise-dev/types/coupling";
+import { apiGet } from "./client";
+
+export type {
+ CouplingEdge,
+ CouplingGraphResponse,
+ CouplingNode,
+} from "@repowise-dev/types/coupling";
+
+export async function getCoupling(
+ repoId: string,
+ opts?: { limit?: number },
+): Promise<CouplingGraphResponse> {
+ return apiGet<CouplingGraphResponse>(`/api/repos/${repoId}/coupling`, opts);
+}
diff --git a/tests/unit/coupling/__init__.py b/tests/unit/coupling/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/tests/unit/coupling/test_graph.py b/tests/unit/coupling/test_graph.py
new file mode 100644
index 000000000..345ffbb02
--- /dev/null
+++ b/tests/unit/coupling/test_graph.py
@@ -0,0 +1,133 @@
+"""Tests for ``analysis/coupling/graph.py`` -- the repo-wide co-change join.
+
+The assembler is a pure surfacing layer: it deduplicates the symmetric partner
+records into undirected edges, enriches nodes from the health metrics, sorts by
+strength, caps at a limit while reporting the pre-cap total, and only emits
+nodes that participate in a kept edge.
+"""
+
+from __future__ import annotations
+
+import json
+from dataclasses import dataclass
+
+from repowise.core.analysis.coupling.graph import (
+ CouplingEdge,
+ CouplingNode,
+ coupling_graph,
+)
+
+
+@dataclass
+class _Metric:
+ """Stub mirroring the HealthFileMetric fields the graph reads."""
+
+ file_path: str
+ score: float = 8.0
+ nloc: int = 100
+ module: str | None = "core"
+
+
+@dataclass
+class _Git:
+ """Stub mirroring the GitMetadata field the graph reads."""
+
+ co_change_partners_json: str = "[]"
+
+
+def _git(*partners: tuple[str, float, str | None]) -> _Git:
+ return _Git(
+ co_change_partners_json=json.dumps(
+ [
+ {"file_path": p, "co_change_count": c, "last_co_change": d}
+ for p, c, d in partners
+ ]
+ )
+ )
+
+
+def test_dedupes_symmetric_partners_into_one_edge() -> None:
+ metrics = [_Metric("a.py"), _Metric("b.py")]
+ git = {
+ "a.py": _git(("b.py", 3.0, "2026-06-01")),
+ "b.py": _git(("a.py", 3.0, "2026-06-01")),
+ }
+ g = coupling_graph(metrics, git)
+ assert len(g.edges) == 1
+ assert g.edges[0] == CouplingEdge("a.py", "b.py", 3.0, "2026-06-01")
+ assert g.total_edges == 1
+
+
+def test_edges_sorted_by_strength_and_capped_with_total() -> None:
+ metrics = [_Metric(p) for p in ("a.py", "b.py", "c.py")]
+ git = {
+ "a.py": _git(("b.py", 1.0, None), ("c.py", 5.0, None)),
+ "b.py": _git(("a.py", 1.0, None), ("c.py", 2.0, None)),
+ "c.py": _git(("a.py", 5.0, None), ("b.py", 2.0, None)),
+ }
+ g = coupling_graph(metrics, git, limit=2)
+ assert [e.strength for e in g.edges] == [5.0, 2.0]
+ assert g.total_edges == 3 # pre-cap count preserved for the "showing N of M" line
+
+
+def test_nodes_only_for_files_in_kept_edges_and_enriched() -> None:
+ metrics = [
+ _Metric("a.py", score=3.0, nloc=200, module="api"),
+ _Metric("b.py", score=9.0, nloc=50, module="ui"),
+ _Metric("lonely.py", score=7.0), # has a metric but no coupling
+ ]
+ git = {
+ "a.py": _git(("b.py", 4.0, "2026-05-01")),
+ "b.py": _git(("a.py", 4.0, "2026-05-01")),
+ }
+ g = coupling_graph(metrics, git)
+ paths = {n.file_path for n in g.nodes}
+ assert paths == {"a.py", "b.py"} # lonely.py omitted
+ by_path = {n.file_path: n for n in g.nodes}
+ assert by_path["a.py"] == CouplingNode("a.py", "api", 3.0, 200)
+ assert by_path["b.py"] == CouplingNode("b.py", "ui", 9.0, 50)
+
+
+def test_missing_metric_yields_null_score_module() -> None:
+ # A file with git co-change but no health metric (e.g. a config file).
+ metrics = [_Metric("a.py")]
+ git = {
+ "a.py": _git(("config.yaml", 2.0, None)),
+ "config.yaml": _git(("a.py", 2.0, None)),
+ }
+ g = coupling_graph(metrics, git)
+ cfg = next(n for n in g.nodes if n.file_path == "config.yaml")
+ assert cfg.score is None
+ assert cfg.module is None
+ assert cfg.nloc == 0
+
+
+def test_keeps_strongest_and_most_recent_on_asymmetric_records() -> None:
+ # Defensive: if the two stored directions disagree, keep max strength and
+ # the most recent date.
+ metrics = [_Metric("a.py"), _Metric("b.py")]
+ git = {
+ "a.py": _git(("b.py", 3.0, "2026-01-01")),
+ "b.py": _git(("a.py", 5.0, "2026-06-01")),
+ }
+ g = coupling_graph(metrics, git)
+ assert g.edges[0] == CouplingEdge("a.py", "b.py", 5.0, "2026-06-01")
+
+
+def test_ignores_self_loops_zero_and_bad_json() -> None:
+ metrics = [_Metric("a.py"), _Metric("b.py")]
+ git = {
+ "a.py": _git(("a.py", 9.0, None), ("b.py", 0.0, None)), # self + zero dropped
+ "b.py": _Git(co_change_partners_json="not json"), # tolerated
+ }
+ g = coupling_graph(metrics, git)
+ assert g.edges == []
+ assert g.nodes == []
+ assert g.total_edges == 0
+
+
+def test_empty_inputs() -> None:
+ g = coupling_graph([], {})
+ assert g.nodes == []
+ assert g.edges == []
+ assert g.total_edges == 0
diff --git a/tests/unit/server/test_coupling.py b/tests/unit/server/test_coupling.py
new file mode 100644
index 000000000..d62165972
--- /dev/null
+++ b/tests/unit/server/test_coupling.py
@@ -0,0 +1,41 @@
+"""Wire-shape tests for the coupling router serializers.
+
+The graph assembly itself is covered by ``tests/unit/coupling/test_graph.py``;
+here we lock the JSON keys the endpoint emits so the wire contract (mirrored in
+``packages/types/src/coupling.ts``) cannot drift silently.
+"""
+
+from __future__ import annotations
+
+from repowise.core.analysis.coupling import CouplingEdge, CouplingNode
+from repowise.server.routers.coupling import _edge_to_dict, _node_to_dict
+
+
+def test_node_to_dict_wire_shape() -> None:
+ n = CouplingNode(file_path="a.py", module="api", score=3.4, nloc=420)
+ assert _node_to_dict(n) == {
+ "file_path": "a.py",
+ "module": "api",
+ "score": 3.4,
+ "nloc": 420,
+ }
+
+
+def test_node_to_dict_null_score_module() -> None:
+ n = CouplingNode(file_path="config.yaml", module=None, score=None, nloc=0)
+ assert _node_to_dict(n) == {
+ "file_path": "config.yaml",
+ "module": None,
+ "score": None,
+ "nloc": 0,
+ }
+
+
+def test_edge_to_dict_wire_shape() -> None:
+ e = CouplingEdge(source="a.py", target="b.py", strength=4.25, last_co_change="2026-06-01")
+ assert _edge_to_dict(e) == {
+ "source": "a.py",
+ "target": "b.py",
+ "strength": 4.25,
+ "last_co_change": "2026-06-01",
+ }