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): ask whether an edge was possible, not whether it was a node (#1975)

Raghav Chamadiyaf8c263a15e93
diff --git a/packages/api-client/src/hosted.test.ts b/packages/api-client/src/hosted.test.ts
index c5683f6f9..69b195049 100644
--- a/packages/api-client/src/hosted.test.ts
+++ b/packages/api-client/src/hosted.test.ts
@@ -557,9 +557,12 @@ describe("getCoupling", () => {
confidence_ab: 0.9,
confidence_ba: 0.1,
structural: "unexplained",
+ dependency_kind: null,
},
],
total_edges: 9,
+ coupled_files: 6,
+ total_files: 20,
};
const { p } = provider([REPOS_ROUTE, ["/coupling", body]]);
expect(await p.getCoupling("repo-1")).toEqual(body);
@@ -570,12 +573,16 @@ describe("getCoupling", () => {
// existed has neither, and the table reads them straight into a cell.
const wire = [{ source: "a.rs", target: "b.rs", strength: 3, last_co_change: null }];
const { p } = provider([REPOS_ROUTE, ["/coupling", { edges: wire, total_edges: 1 }]]);
- const { edges } = await p.getCoupling("repo-1");
+ const { edges, coupled_files, total_files } = await p.getCoupling("repo-1");
expect(edges[0]).toMatchObject({
support: 0,
confidence_ab: null,
confidence_ba: null,
structural: null,
+ dependency_kind: null,
});
+ // Zero reads as "not measured", which the scope line renders by omitting
+ // the denominator rather than claiming nothing is coupled.
+ expect({ coupled_files, total_files }).toEqual({ coupled_files: 0, total_files: 0 });
});
});
diff --git a/packages/api-client/src/hosted.ts b/packages/api-client/src/hosted.ts
index 845b64182..a8b10328c 100644
--- a/packages/api-client/src/hosted.ts
+++ b/packages/api-client/src/hosted.ts
@@ -228,6 +228,8 @@ interface WireCoupling {
nodes?: CouplingGraphResponse["nodes"];
edges?: Partial<CouplingEdge>[];
total_edges?: number;
+ coupled_files?: number;
+ total_files?: number;
}
// ---------------------------------------------------------------------------
@@ -854,10 +856,19 @@ export function createHostedProvider(config: HostedProviderConfig): HostedProvid
confidence_ab: e.confidence_ab ?? null,
confidence_ba: e.confidence_ba ?? null,
structural: e.structural ?? null,
+ dependency_kind: e.dependency_kind ?? null,
}));
// Falling back to the post-cap length understates the pre-cap count, but
// an honest "showing N of N" beats `NaN` downstream.
- return { nodes, edges, total_edges: res.total_edges ?? edges.length };
+ return {
+ nodes,
+ edges,
+ total_edges: res.total_edges ?? edges.length,
+ // An older snapshot carries no file count; deriving one from the
+ // capped edges would understate it, and 0 already reads as unknown.
+ coupled_files: res.coupled_files ?? 0,
+ total_files: res.total_files ?? 0,
+ };
},
async getFilesIndex(repoId): Promise<FilesIndexResponse> {
diff --git a/packages/core/src/repowise/core/analysis/coupling/graph.py b/packages/core/src/repowise/core/analysis/coupling/graph.py
index 801ee718e..7d29c885d 100644
--- a/packages/core/src/repowise/core/analysis/coupling/graph.py
+++ b/packages/core/src/repowise/core/analysis/coupling/graph.py
@@ -91,7 +91,8 @@ class CouplingEdge:
both. ``confidence_ab`` is the share of ``source``'s commits that also
touched ``target``, and ``confidence_ba`` the reverse; either is ``None``
when the commit total is unknown. ``last_co_change`` is the ISO date of the
- most recent shared commit, or ``None`` if unknown.
+ most recent shared commit, or ``None`` if unknown. ``dependency_kind`` is
+ the graph edge behind a ``corroborated`` verdict, and ``None`` otherwise.
"""
source: str
@@ -102,6 +103,7 @@ class CouplingEdge:
confidence_ab: float | None = None
confidence_ba: float | None = None
structural: str | None = None
+ dependency_kind: str | None = None
@dataclass(frozen=True)
@@ -114,6 +116,7 @@ class _Pair:
commits_a: int
commits_b: int
structural: str | None
+ dependency_kind: str | None
def merge(self, other: _Pair) -> _Pair:
"""Combine the two directions of the same pair, keeping the best of each."""
@@ -124,6 +127,7 @@ class _Pair:
commits_a=max(self.commits_a, other.commits_a),
commits_b=max(self.commits_b, other.commits_b),
structural=self.structural or other.structural,
+ dependency_kind=self.dependency_kind or other.dependency_kind,
)
@@ -141,6 +145,12 @@ class CouplingGraph:
nodes: list[CouplingNode]
edges: list[CouplingEdge]
total_edges: int
+ #: Distinct files appearing in at least one pre-cap pair, over the files
+ #: with any commit history. Gives ``total_edges`` a scale: 14,115
+ #: couplings across 300 files and across 3,000 files describe different
+ #: repositories.
+ coupled_files: int = 0
+ total_files: int = 0
def coupling_graph(
@@ -162,7 +172,8 @@ def coupling_graph(
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.
+ N of M" line, ``coupled_files`` the distinct files those pairs span, and ``total_files``
+ how many files were considered at all. Only files referenced by a kept edge become nodes.
"""
# Deduplicate symmetric partner records into undirected edges. Each side
# records the pair from its own vantage point, so keep whichever is
@@ -183,6 +194,7 @@ def coupling_graph(
commits_a=partner.self_commits if forward else partner.partner_commits,
commits_b=partner.partner_commits if forward else partner.self_commits,
structural=partner.structural,
+ dependency_kind=partner.dependency_kind,
)
prev = best.get(key)
best[key] = seen if prev is None else prev.merge(seen)
@@ -197,11 +209,15 @@ def coupling_graph(
confidence_ab=_ratio(pair.support, pair.commits_a),
confidence_ba=_ratio(pair.support, pair.commits_b),
structural=pair.structural,
+ dependency_kind=pair.dependency_kind,
)
for (a, b), pair in best.items()
]
edges.sort(key=lambda e: e.strength, reverse=True)
total = len(edges)
+ # Counted over the keys of the pre-cap dict, so it scales `total_edges`
+ # rather than the capped slice below it.
+ coupled_files = len({path for key in best for path in key})
edges = edges[:limit]
# Build nodes only for files referenced by a kept edge.
@@ -221,4 +237,12 @@ def coupling_graph(
for path in sorted(referenced)
]
- return CouplingGraph(nodes=nodes, edges=edges, total_edges=total)
+ return CouplingGraph(
+ nodes=nodes,
+ edges=edges,
+ total_edges=total,
+ coupled_files=coupled_files,
+ # Every file the git walk recorded, coupled or not -- the denominator
+ # the coupled count is a share of.
+ total_files=len(git_meta_by_path),
+ )
diff --git a/packages/core/src/repowise/core/analysis/graph_view.py b/packages/core/src/repowise/core/analysis/graph_view.py
index 7c5439004..2e3c64d48 100644
--- a/packages/core/src/repowise/core/analysis/graph_view.py
+++ b/packages/core/src/repowise/core/analysis/graph_view.py
@@ -11,21 +11,31 @@ than one of them needs it, and a view of the graph belongs to none of them.
from __future__ import annotations
+from pathlib import PurePosixPath
from typing import Any, Protocol
+from ..ingestion.languages import REGISTRY
from ..ingestion.models import FILE_DEPENDENCY_EDGE_TYPES
__all__ = ["HasEdge", "ImportEdgeView"]
+def _language_of(path: str) -> str:
+ """The registry's language tag for *path*, or ``"unknown"``."""
+ name = PurePosixPath(path.replace("\\", "/")).name
+ return REGISTRY.from_filename(name) or REGISTRY.from_extension(
+ PurePosixPath(name).suffix.lower()
+ )
+
+
class HasEdge(Protocol):
"""Minimal graph view: does an edge of some type join these two files?"""
def has_edge(self, src: str, dst: str, key: str = "imports") -> bool: ...
- def has_dependency(self, a: str, b: str) -> bool: ...
+ def dependency_kind(self, a: str, b: str) -> str | None: ...
- def knows(self, path: str) -> bool: ...
+ def can_carry_dependency(self, path: str) -> bool: ...
class ImportEdgeView:
@@ -54,38 +64,55 @@ class ImportEdgeView:
return False
return data.get("edge_type") == key
- def has_dependency(self, a: str, b: str) -> bool:
- """Whether any file-level dependency joins the two, either direction.
+ def dependency_kind(self, a: str, b: str) -> str | None:
+ """The ``edge_type`` of any file-level dependency joining the two.
``imports`` is only one of these; matching it alone reports a pair as
unexplained when a type reference or a framework binding already
- accounts for it.
+ accounts for it. The kind, not just a yes/no, because an import and a
+ framework binding are different claims about why two files move
+ together. Direction is not reported: the pair is undirected, and
+ ``a -> b`` is tried first only to make the answer deterministic.
"""
return self._typed(a, b) or self._typed(b, a)
- def _typed(self, src: str, dst: str) -> bool:
+ def _typed(self, src: str, dst: str) -> str | None:
g = self._graph
if g is None:
- return False
+ return None
try:
if not g.has_edge(src, dst):
- return False
+ return None
data = g.get_edge_data(src, dst) or {}
except Exception:
- return False
- return data.get("edge_type") in FILE_DEPENDENCY_EDGE_TYPES
-
- def knows(self, path: str) -> bool:
- """Whether the parser ingested this file, so an edge is possible at all.
-
- A lockfile or a changelog is tracked by git and co-changes constantly,
- but never becomes a node, so it has no edge to find and its absence
- says nothing.
+ return None
+ kind = data.get("edge_type")
+ return kind if kind in FILE_DEPENDENCY_EDGE_TYPES else None
+
+ def can_carry_dependency(self, path: str) -> bool:
+ """Whether an absent edge at *path* would mean anything.
+
+ Being a node is not enough. ``pyproject.toml`` and ``README.md`` are
+ both ingested and both become nodes, yet no resolver can ever emit an
+ edge for them, so "no edge found" is a fact about the language rather
+ than about the repository. The registry already grades this per
+ language as ``import_support``; ``"none"`` is the generic stem-lookup
+ fallback, which is not a mechanism a finding can rest on.
+
+ A file the parser never saw fails here too: a lockfile in a blocked
+ directory has no edge to look for either.
"""
g = self._graph
if g is None:
return False
try:
- return path in g
+ attrs = g.nodes[path]
except Exception:
return False
+ language = attrs.get("language")
+ if not isinstance(language, str):
+ # Not every node carries the attribute: a node synthesised for a
+ # dynamic edge target has none, and persistence drops null
+ # columns on rehydrate. The path answers the same question.
+ language = _language_of(path)
+ return REGISTRY.import_support_for(language) != "none"
diff --git a/packages/core/src/repowise/core/co_change.py b/packages/core/src/repowise/core/co_change.py
index d00136943..d72135774 100644
--- a/packages/core/src/repowise/core/co_change.py
+++ b/packages/core/src/repowise/core/co_change.py
@@ -55,10 +55,10 @@ MIN_CO_CHANGE_SUPPORT: int = 2
MAX_PARTNERS_PER_FILE: int = 25
# Whether an import-graph edge explains a pair. ``NOT_APPLICABLE`` is not a
-# weaker ``UNEXPLAINED``: a file the parser never ingested cannot carry an edge
-# in either direction, so there is nothing to corroborate. Only
-# ``UNEXPLAINED`` is a finding. ``None`` means an index written before the
-# distinction existed.
+# weaker ``UNEXPLAINED``: no resolver can emit an edge for a manifest, a
+# changelog or a file the parser never saw, so there is nothing to
+# corroborate. Only ``UNEXPLAINED`` is a finding. ``None`` means an index
+# written before the distinction existed.
STRUCTURAL_CORROBORATED = "corroborated"
STRUCTURAL_UNEXPLAINED = "unexplained"
STRUCTURAL_NOT_APPLICABLE = "not_applicable"
@@ -74,6 +74,9 @@ class CoChangePartner:
``support / self_commits`` is an honest directional confidence. They are
zero on an index written before they were recorded.
+ ``dependency_kind`` is the ``edge_type`` behind a ``corroborated``
+ verdict, and is ``None`` for every other verdict.
+
``record`` is the verbatim source record, for callers that put it back on
the wire or read a field this module does not model; it is excluded from
equality so two partners compare on their meaning.
@@ -86,6 +89,7 @@ class CoChangePartner:
self_commits: int = 0
partner_commits: int = 0
structural: str | None = None
+ dependency_kind: str | None = None
record: dict = field(default_factory=dict, compare=False, repr=False)
@@ -132,6 +136,7 @@ def parse_partners(raw: object) -> list[CoChangePartner]:
continue
last = record.get("last_co_change")
structural = record.get("structural")
+ kind = record.get("dependency_kind")
out.append(
CoChangePartner(
file_path=str(path),
@@ -141,6 +146,7 @@ def parse_partners(raw: object) -> list[CoChangePartner]:
self_commits=_as_count(record.get("self_commits")),
partner_commits=_as_count(record.get("partner_commits")),
structural=structural if isinstance(structural, str) else None,
+ dependency_kind=kind if isinstance(kind, str) else None,
record=record,
)
)
diff --git a/packages/core/src/repowise/core/ingestion/graph/_edges.py b/packages/core/src/repowise/core/ingestion/graph/_edges.py
index 750612601..7cf607959 100644
--- a/packages/core/src/repowise/core/ingestion/graph/_edges.py
+++ b/packages/core/src/repowise/core/ingestion/graph/_edges.py
@@ -31,8 +31,15 @@ class EdgesMixin:
"""Record, on each partner, whether the graph explains the pair.
Co-change is mined from git with no view of the code, so this is the
- only point where both are in hand. Writes ``structural`` in place and
- returns how many pairs came back unexplained.
+ only point where both are in hand. Writes ``structural`` and, when a
+ dependency was found, ``dependency_kind`` in place; returns how many
+ pairs came back unexplained.
+
+ An edge that exists is checked first, so a pair is never dismissed as
+ not-applicable while the graph is holding the very edge that explains
+ it. Only when nothing was found does it matter whether anything
+ *could* have been -- see
+ :meth:`~...analysis.graph_view.ImportEdgeView.can_carry_dependency`.
Takes decoded partner lists; the wrapper in the git phase handles the
JSON column the records are persisted in.
@@ -48,17 +55,22 @@ class EdgesMixin:
view = ImportEdgeView(self._graph)
unexplained = 0
for file_path, partners in partners_by_file.items():
- known_self = view.knows(file_path)
+ eligible_self = view.can_carry_dependency(file_path)
for record in partners:
if not isinstance(record, dict):
continue
partner_path = record.get("file_path") or record.get("path")
if not partner_path:
continue
- if not known_self or not view.knows(str(partner_path)):
- record["structural"] = STRUCTURAL_NOT_APPLICABLE
- elif view.has_dependency(file_path, str(partner_path)):
+ partner_path = str(partner_path)
+ kind = view.dependency_kind(file_path, partner_path)
+ if kind is not None:
record["structural"] = STRUCTURAL_CORROBORATED
+ record["dependency_kind"] = kind
+ continue
+ record.pop("dependency_kind", None)
+ if not eligible_self or not view.can_carry_dependency(partner_path):
+ record["structural"] = STRUCTURAL_NOT_APPLICABLE
else:
record["structural"] = STRUCTURAL_UNEXPLAINED
unexplained += 1
diff --git a/packages/server/src/repowise/server/routers/coupling.py b/packages/server/src/repowise/server/routers/coupling.py
index 1a2b5e7a6..bfccb5bd9 100644
--- a/packages/server/src/repowise/server/routers/coupling.py
+++ b/packages/server/src/repowise/server/routers/coupling.py
@@ -50,4 +50,6 @@ async def coupling(
nodes=[CouplingNodeResponse(**vars(n)) for n in graph.nodes],
edges=[CouplingEdgeResponse(**vars(e)) for e in graph.edges],
total_edges=graph.total_edges,
+ coupled_files=graph.coupled_files,
+ total_files=graph.total_files,
)
diff --git a/packages/server/src/repowise/server/schemas/coupling.py b/packages/server/src/repowise/server/schemas/coupling.py
index 56d06c8c6..3b71cacfe 100644
--- a/packages/server/src/repowise/server/schemas/coupling.py
+++ b/packages/server/src/repowise/server/schemas/coupling.py
@@ -31,6 +31,9 @@ class CouplingEdgeResponse(BaseModel):
#: Whether the dependency graph explains the pair: ``corroborated``,
#: ``unexplained``, or ``not_applicable`` when a side is not in the graph.
structural: Literal["corroborated", "unexplained", "not_applicable"] | None = None
+ #: The graph edge behind a ``corroborated`` verdict (``imports``,
+ #: ``type_use``, ``framework``, ...). ``None`` for every other verdict.
+ dependency_kind: str | None = None
class CouplingGraphResponse(BaseModel):
@@ -38,3 +41,7 @@ class CouplingGraphResponse(BaseModel):
edges: list[CouplingEdgeResponse] = Field(default_factory=list)
#: Pre-cap edge count, for an honest "showing N of M" line.
total_edges: int = 0
+ #: Distinct files spanned by those pre-cap pairs, over every file with
+ #: commit history, so the count has a scale.
+ coupled_files: int = 0
+ total_files: int = 0
diff --git a/packages/types/src/coupling.ts b/packages/types/src/coupling.ts
index 921c66790..805aaa8c6 100644
--- a/packages/types/src/coupling.ts
+++ b/packages/types/src/coupling.ts
@@ -47,6 +47,12 @@ export interface CouplingEdge {
* absence is not evidence of hidden coupling. `null` on an older index.
*/
structural: CouplingStructure | null;
+ /**
+ * The graph edge behind a `corroborated` verdict -- `imports`, `type_use`,
+ * `framework`, and so on. `null` for every other verdict, and on an index
+ * written before the kind was recorded.
+ */
+ dependency_kind: string | null;
}
/** What the dependency graph says about a co-changing pair. */
@@ -58,4 +64,8 @@ export interface CouplingGraphResponse {
edges: CouplingEdge[];
/** Pre-cap edge count, for an honest "showing N of M couplings" line. */
total_edges: number;
+ /** Distinct files spanned by those pre-cap pairs, so the count has a scale. */
+ coupled_files: number;
+ /** Files with any commit history: the denominator `coupled_files` is a share of. */
+ total_files: number;
}
diff --git a/packages/ui/__tests__/coupling/coupling-explorer.test.tsx b/packages/ui/__tests__/coupling/coupling-explorer.test.tsx
index bc5d1c88f..695b5546d 100644
--- a/packages/ui/__tests__/coupling/coupling-explorer.test.tsx
+++ b/packages/ui/__tests__/coupling/coupling-explorer.test.tsx
@@ -26,6 +26,7 @@ function edge(s: string, t: string, strength = 3): CouplingEdge {
confidence_ab: null,
confidence_ba: null,
structural: null,
+ dependency_kind: null,
};
}
@@ -33,7 +34,13 @@ function graph(
nodes: CouplingNode[],
edges: CouplingEdge[],
): CouplingGraphResponse {
- return { nodes, edges, total_edges: edges.length };
+ return {
+ nodes,
+ edges,
+ total_edges: edges.length,
+ coupled_files: nodes.length,
+ total_files: nodes.length,
+ };
}
describe("CouplingExplorer", () => {
@@ -208,6 +215,66 @@ describe("CouplingExplorer pair selection", () => {
expect(panel.getByText("Unexplained")).toBeInTheDocument();
});
+ it("names the dependency behind an explained pair", () => {
+ const explained = graph(
+ [node("core/a.py"), node("core/b.py")],
+ [
+ {
+ ...edge("core/a.py", "core/b.py", 5),
+ support: 9,
+ structural: "corroborated",
+ dependency_kind: "type_use",
+ },
+ ],
+ );
+ render(<CouplingExplorer data={explained} />);
+ fireEvent.click(inTable().getAllByRole("row")[1]!);
+ const panel = within(screen.getByRole("dialog"));
+ // "Explained" alone does not say how the graph explains it.
+ expect(panel.getByText("Explained")).toBeInTheDocument();
+ // Both the verdict chip and the claim sentence name it, from one helper.
+ expect(panel.getByText("· a type reference")).toBeInTheDocument();
+ expect(
+ panel.getByText(/A type reference in the graph already connects them/),
+ ).toBeInTheDocument();
+ });
+
+ it("says nothing about the kind when the index recorded none", () => {
+ const explained = graph(
+ [node("core/a.py"), node("core/b.py")],
+ [{ ...edge("core/a.py", "core/b.py", 5), support: 9, structural: "corroborated" }],
+ );
+ render(<CouplingExplorer data={explained} />);
+ fireEvent.click(inTable().getAllByRole("row")[1]!);
+ const panel = within(screen.getByRole("dialog"));
+ expect(panel.getByText("Explained")).toBeInTheDocument();
+ expect(panel.getByText(/The dependency graph already connects them/i)).toBeInTheDocument();
+ });
+
+ it("gives the coupling total a denominator in files", () => {
+ const scaled: CouplingGraphResponse = {
+ ...graph([node("core/a.py"), node("core/b.py")], [edge("core/a.py", "core/b.py")]),
+ total_edges: 14147,
+ coupled_files: 2038,
+ total_files: 3787,
+ };
+ render(<CouplingExplorer data={scaled} />);
+ expect(screen.getByText(/files with commit history/)).toHaveTextContent(
+ "across 2,038 of 3,787 files with commit history",
+ );
+ });
+
+ it("omits the denominator when the index does not carry one", () => {
+ const older: CouplingGraphResponse = {
+ ...graph([node("core/a.py"), node("core/b.py")], [edge("core/a.py", "core/b.py")]),
+ coupled_files: 0,
+ total_files: 0,
+ };
+ render(<CouplingExplorer data={older} />);
+ expect(screen.queryByText(/files with commit history/)).not.toBeInTheDocument();
+ expect(screen.getByText(/in this repository/)).toBeInTheDocument();
+ });
+
it("treats an unrecognized pipe path as one file, not a pair", () => {
const odd = graph(
[node("weird|name.py"), node("core/b.py")],
diff --git a/packages/ui/__tests__/coupling/coupling-graph.test.tsx b/packages/ui/__tests__/coupling/coupling-graph.test.tsx
index 8b6cec691..111c2e806 100644
--- a/packages/ui/__tests__/coupling/coupling-graph.test.tsx
+++ b/packages/ui/__tests__/coupling/coupling-graph.test.tsx
@@ -17,6 +17,7 @@ function edge(s: string, t: string, strength = 3, last: string | null = "2026-06
confidence_ab: null,
confidence_ba: null,
structural: null,
+ dependency_kind: null,
};
}
diff --git a/packages/ui/__tests__/coupling/coupling-table.test.tsx b/packages/ui/__tests__/coupling/coupling-table.test.tsx
index 5f719bcc5..22dacce4d 100644
--- a/packages/ui/__tests__/coupling/coupling-table.test.tsx
+++ b/packages/ui/__tests__/coupling/coupling-table.test.tsx
@@ -18,6 +18,7 @@ function edge(
confidence_ab: null,
confidence_ba: null,
structural: null,
+ dependency_kind: null,
};
}
diff --git a/packages/ui/src/coupling/claim.ts b/packages/ui/src/coupling/claim.ts
index 6fc880987..c72807919 100644
--- a/packages/ui/src/coupling/claim.ts
+++ b/packages/ui/src/coupling/claim.ts
@@ -28,8 +28,9 @@ export function pairHas(pair: CouplingPair | null | undefined, path: string | nu
* 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.
+ * side no resolver could ever emit an edge for (a manifest, a changelog, a
+ * file the parser never saw), where there was no edge to look for and so no
+ * hidden coupling to claim.
*/
export type CouplingSegment = "unexplained" | "explained" | "outside";
@@ -41,6 +42,32 @@ export function segmentOf(edge: CouplingEdge): CouplingSegment | null {
return null;
}
+/**
+ * How the graph joins two files, as a noun phrase. Keyed on the wire's
+ * `edge_type`, so an unrecognized kind reads as `null` and the caller falls
+ * back to naming no kind at all rather than printing a raw identifier.
+ */
+const DEPENDENCY_KIND_WORDS: Record<string, string> = {
+ imports: "An import",
+ type_use: "A type reference",
+ framework: "Framework wiring",
+ dynamic_uses: "A dynamic reference",
+ dynamic_imports: "A dynamic import",
+ dynamic_url_route: "A URL route",
+ reads: "A member read",
+};
+
+/**
+ * The named dependency behind an explained pair, or `null` when there is none
+ * to name: a different segment, an index written before the kind was
+ * recorded, or a kind this table does not know.
+ */
+export function dependencyKindPhrase(edge: CouplingEdge): string | null {
+ if (segmentOf(edge) !== "explained") return null;
+ const kind = edge.dependency_kind;
+ return kind ? (DEPENDENCY_KIND_WORDS[kind] ?? null) : 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(
@@ -61,10 +88,16 @@ 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 "explained": {
+ // Naming the kind is the point: an import and a framework binding are
+ // different explanations, and "explained" alone says neither.
+ const phrase = dependencyKindPhrase(edge);
+ return phrase
+ ? `${phrase} in the graph already connects them.`
+ : "The dependency graph already connects them.";
+ }
case "outside":
- return "At least one side is outside the dependency graph.";
+ return "At least one side cannot carry a dependency edge.";
default:
return "";
}
diff --git a/packages/ui/src/coupling/coupling-explorer.tsx b/packages/ui/src/coupling/coupling-explorer.tsx
index 1a6372393..4521d2cda 100644
--- a/packages/ui/src/coupling/coupling-explorer.tsx
+++ b/packages/ui/src/coupling/coupling-explorer.tsx
@@ -125,7 +125,7 @@ const SEGMENTS: { key: CouplingSegment | "all"; label: string; help: string }[]
{
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.",
+ help: "At least one side can carry no dependency edge: manifests, changelogs, config, docs. Real coupling, but not a code question.",
},
{ key: "all", label: "All", help: "Every coupling, including any the index never labelled." },
];
@@ -273,6 +273,22 @@ export function CouplingExplorer({
const capped = data.total_edges > edges.length;
+ // The span the couplings are drawn across. Both counts are pre-cap, so the
+ // clause holds whether or not the edge list was capped; an older index
+ // reports neither, and "in this repository" stays true without them.
+ const spanClause =
+ data.coupled_files > 0 && data.total_files > 0 ? (
+ <>
+ {" "}
+ across{" "}
+ <strong className="font-medium">{data.coupled_files.toLocaleString()}</strong> of{" "}
+ <strong className="font-medium">{data.total_files.toLocaleString()}</strong> files
+ with commit history
+ </>
+ ) : (
+ " in this repository"
+ );
+
return (
<div className="space-y-5">
{/* No GraphCanvasShell: it hosts fixed-height canvases behind an
@@ -322,20 +338,21 @@ export function CouplingExplorer({
<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. */}
+ and "14,115 couplings" stop looking like a contradiction, and gives
+ that total a denominator: the same number over 300 files and over
+ 3,000 files describes two different repositories. */}
<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}.
+ couplings{spanClause}. The counts below describe those {edges.length}.
</>
) : (
<>
All <strong className="font-medium">{edges.length.toLocaleString()}</strong>{" "}
- couplings in this repository.
+ couplings{spanClause}.
</>
)}
</p>
diff --git a/packages/ui/src/coupling/coupling-pair-drawer.tsx b/packages/ui/src/coupling/coupling-pair-drawer.tsx
index 0e484bc77..f64dcd257 100644
--- a/packages/ui/src/coupling/coupling-pair-drawer.tsx
+++ b/packages/ui/src/coupling/coupling-pair-drawer.tsx
@@ -6,7 +6,12 @@ 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 {
+ couplingClaim,
+ dependencyKindPhrase,
+ 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. */
@@ -52,7 +57,7 @@ const VERDICT: Record<CouplingSegment, { word: string; dot: string; body: string
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.",
+ body: "At least one side is a manifest, changelog, config, or doc, and no resolver can emit a dependency edge for it, 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.",
},
};
@@ -92,6 +97,7 @@ export function CouplingPairDrawer({
const Anchor: LinkLike = LinkComponent ?? "a";
const segment = edge ? segmentOf(edge) : null;
const verdict = segment ? VERDICT[segment] : null;
+ const kindPhrase = edge ? dependencyKindPhrase(edge) : null;
const moduleA = edge ? (nodeByPath.get(edge.source)?.module ?? null) : null;
const moduleB = edge ? (nodeByPath.get(edge.target)?.module ?? null) : null;
@@ -177,6 +183,11 @@ export function CouplingPairDrawer({
<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>
+ {/* The kind rides in the verdict line, where the reader is
+ already asking what connects them. */}
+ {kindPhrase && (
+ <span className={MICRO}>· {kindPhrase.toLowerCase()}</span>
+ )}
</p>
)}
<p className="text-[15px] leading-relaxed text-[var(--color-text-primary)] [text-wrap:pretty]">
diff --git a/packages/ui/src/coupling/index.ts b/packages/ui/src/coupling/index.ts
index 1639ff0e7..b19ee1933 100644
--- a/packages/ui/src/coupling/index.ts
+++ b/packages/ui/src/coupling/index.ts
@@ -7,6 +7,7 @@ export {
} from "./coupling-pair-drawer";
export {
couplingClaim,
+ dependencyKindPhrase,
isSamePair,
pairHas,
peakConfidence,
diff --git a/tests/unit/coupling/test_graph.py b/tests/unit/coupling/test_graph.py
index 6fa6f6a2d..3d204b9b3 100644
--- a/tests/unit/coupling/test_graph.py
+++ b/tests/unit/coupling/test_graph.py
@@ -70,6 +70,26 @@ def test_edges_sorted_by_strength_and_capped_with_total() -> None:
assert g.total_edges == 3 # pre-cap count preserved for the "showing N of M" line
+def test_coupled_files_counts_the_pre_cap_span_not_the_kept_nodes() -> None:
+ """The denominator scales ``total_edges``, so it must be counted before the
+ cap: keeping one of two disjoint pairs leaves two nodes, but four files
+ are coupled."""
+ metrics = [_Metric(p) for p in ("a.py", "b.py", "c.py", "d.py")]
+ git = {
+ "a.py": _git(("b.py", 5.0, None)),
+ "b.py": _git(("a.py", 5.0, None)),
+ "c.py": _git(("d.py", 1.0, None)),
+ "d.py": _git(("c.py", 1.0, None)),
+ }
+ g = coupling_graph(metrics, git, limit=1)
+ assert g.coupled_files == 4
+ assert len(g.nodes) == 2
+
+
+def test_coupled_files_is_zero_with_no_couplings() -> None:
+ assert coupling_graph([], {}).coupled_files == 0
+
+
def test_nodes_only_for_files_in_kept_edges_and_enriched() -> None:
metrics = [
_Metric("a.py", score=3.0, nloc=200, module="api"),
diff --git a/tests/unit/ingestion/test_co_change_edges.py b/tests/unit/ingestion/test_co_change_edges.py
index 1d9a40f32..a38dbfa98 100644
--- a/tests/unit/ingestion/test_co_change_edges.py
+++ b/tests/unit/ingestion/test_co_change_edges.py
@@ -105,6 +105,54 @@ class TestStructuralLabel:
partners = {"a.py": ["b.py", {"nope": 1}, {"file_path": "b.py", "frequency": 9}]}
assert builder.label_co_change_structure(partners) == 1
+ def test_a_manifest_in_the_graph_is_still_not_applicable(
+ self, builder: GraphBuilder
+ ) -> None:
+ """The bug this replaced: a manifest *is* a node, so membership said
+ "unexplained" and dropped release plumbing into the findings segment.
+ No resolver can emit an edge for TOML, so there is nothing to find."""
+ builder._graph.add_node("pyproject.toml", language="toml")
+ partners = {"a.py": [{"file_path": "pyproject.toml", "frequency": 40}]}
+ assert builder.label_co_change_structure(partners) == 0
+ assert partners["a.py"][0]["structural"] == "not_applicable"
+
+ def test_a_doc_in_the_graph_is_not_applicable(self, builder: GraphBuilder) -> None:
+ builder._graph.add_node("README.md", language="markdown")
+ partners = {"a.py": [{"file_path": "README.md", "frequency": 40}]}
+ assert builder.label_co_change_structure(partners) == 0
+ assert partners["a.py"][0]["structural"] == "not_applicable"
+
+ def test_a_language_with_a_resolver_stays_a_finding(self, builder: GraphBuilder) -> None:
+ """The gate is "can a resolver emit an edge", not "is it code": HTML is
+ markup, but it resolves asset references, so a missing one is real."""
+ builder._graph.add_node("page.html", language="html")
+ partners = {"a.py": [{"file_path": "page.html", "frequency": 9}]}
+ assert builder.label_co_change_structure(partners) == 1
+ assert partners["a.py"][0]["structural"] == "unexplained"
+
+ def test_an_edge_outranks_the_language_gate(self, builder: GraphBuilder) -> None:
+ """An edge that exists explains the pair whatever the language is."""
+ builder._graph.add_node("page.html", language="markdown")
+ builder._graph.add_edge("a.py", "page.html", edge_type="framework")
+ partners = {"a.py": [{"file_path": "page.html", "frequency": 9}]}
+ assert builder.label_co_change_structure(partners) == 0
+ assert partners["a.py"][0]["structural"] == "corroborated"
+
+ def test_the_corroborating_edge_names_itself(self, builder: GraphBuilder) -> None:
+ builder._graph.add_edge("a.py", "b.py", edge_type="type_use")
+ partners = {"a.py": [{"file_path": "b.py", "frequency": 9}]}
+ builder.label_co_change_structure(partners)
+ assert partners["a.py"][0]["dependency_kind"] == "type_use"
+
+ def test_a_stale_kind_is_cleared_when_the_edge_goes(self, builder: GraphBuilder) -> None:
+ """Records are relabelled in place across runs, so a kind left behind
+ would claim a dependency the graph no longer has."""
+ partners = {
+ "a.py": [{"file_path": "b.py", "frequency": 9, "dependency_kind": "imports"}]
+ }
+ assert builder.label_co_change_structure(partners) == 1
+ assert "dependency_kind" not in partners["a.py"][0]
+
class TestLabelPersistence:
"""``label_co_change_structure`` writes through the JSON column.
diff --git a/tests/unit/server/test_coupling.py b/tests/unit/server/test_coupling.py
index b62de664f..1c5448b0d 100644
--- a/tests/unit/server/test_coupling.py
+++ b/tests/unit/server/test_coupling.py
@@ -41,6 +41,7 @@ def test_edge_wire_shape() -> None:
confidence_ab=0.9,
confidence_ba=0.1,
structural="unexplained",
+ dependency_kind=None,
)
assert CouplingEdgeResponse(**vars(e)).model_dump() == {
"source": "a.py",
@@ -51,6 +52,7 @@ def test_edge_wire_shape() -> None:
"confidence_ab": 0.9,
"confidence_ba": 0.1,
"structural": "unexplained",
+ "dependency_kind": None,
}
@@ -66,4 +68,21 @@ def test_an_edge_from_an_older_index_still_serializes() -> None:
"confidence_ab": None,
"confidence_ba": None,
"structural": None,
+ "dependency_kind": None,
}
+
+
+def test_a_corroborated_edge_names_the_dependency() -> None:
+ """The kind rides beside the verdict: "explained" alone does not say how."""
+ e = CouplingEdge(
+ source="a.py",
+ target="b.py",
+ strength=4.25,
+ last_co_change="2026-06-01",
+ support=9,
+ structural="corroborated",
+ dependency_kind="type_use",
+ )
+ dumped = CouplingEdgeResponse(**vars(e)).model_dump()
+ assert dumped["structural"] == "corroborated"
+ assert dumped["dependency_kind"] == "type_use"