Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(coupling): open on area pairs and flag only coupling no import explains (#4152)
Raghav Chamadiya228ae1a74061
diff --git a/packages/api-client/src/coupling.ts b/packages/api-client/src/coupling.tsindex 2c6bf1861..55ede0776 100644--- a/packages/api-client/src/coupling.ts+++ b/packages/api-client/src/coupling.ts@@ -1,20 +1,64 @@/*** 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.+ * keeps only the fetch functions.*/-import type { CouplingGraphResponse } from "@repowise-dev/types/coupling";+import type {+ CouplingAreasResponse,+ CouplingFilters,+ CouplingGraphResponse,+} from "@repowise-dev/types/coupling";import { apiGet } from "./client";export type {+ CouplingAreaPair,+ CouplingAreaSummary,+ CouplingAreasResponse,CouplingEdge,+ CouplingFilters,CouplingGraphResponse,CouplingNode,} from "@repowise-dev/types/coupling";+/** The shared filters as query params; a false flag is left off the URL. */+function filterParams(f: CouplingFilters = {}) {+ return {+ depth: f.depth,+ root: f.root || undefined,+ min_support: f.minSupport || undefined,+ unexplained: f.unexplained || undefined,+ cross_area: f.crossArea || undefined,+ exclude_tests: f.excludeTests || undefined,+ recent_days: f.recentDays,+ };+}+export async function getCoupling(repoId: string,- opts?: { limit?: number },+ opts: CouplingFilters & {+ limit?: number;+ /** Only pairs with a file in this area... */+ area?: string;+ /** ...and, with `area`, their other file in this one. */+ partner?: string;+ } = {},): Promise<CouplingGraphResponse> {- return apiGet<CouplingGraphResponse>(`/api/repos/${repoId}/coupling`, opts);+ return apiGet<CouplingGraphResponse>(`/api/repos/${repoId}/coupling`, {+ ...filterParams(opts),+ limit: opts.limit,+ area: opts.area,+ partner: opts.partner,+ });+}++/** Which areas change together, ranked by file pairs no dependency explains. */+export async function getCouplingAreas(+ repoId: string,+ opts: CouplingFilters & { limit?: number; topPairs?: number } = {},+): Promise<CouplingAreasResponse> {+ return apiGet<CouplingAreasResponse>(`/api/repos/${repoId}/coupling/areas`, {+ ...filterParams(opts),+ limit: opts.limit,+ top_pairs: opts.topPairs,+ });}diff --git a/packages/core/src/repowise/core/analysis/areas/__init__.py b/packages/core/src/repowise/core/analysis/areas/__init__.pyindex 48e2f4904..98cdaee4e 100644--- a/packages/core/src/repowise/core/analysis/areas/__init__.py+++ b/packages/core/src/repowise/core/analysis/areas/__init__.py@@ -6,9 +6,10 @@ share. Reads health, git and finding rows; never re-scores anything.from __future__ import annotations+from .depth import choose_depth, group_countsfrom .detail import DETAIL_LIMIT, area_detailfrom .owners import FileOwner, file_owners-from .paths import ROOT_AREA, ancestors, area_depth, in_area, normalize_area+from .paths import ROOT_AREA, ancestors, area_at, area_depth, in_area, normalize_areafrom .rollup import AreaIndex, build_area_indexfrom .trend import area_score, area_scores, attach_deltas, baseline_index, nloc_weights@@ -18,6 +19,7 @@ __all__ = ["AreaIndex","FileOwner","ancestors",+ "area_at","area_depth","area_detail","area_score",@@ -25,7 +27,9 @@ __all__ = ["attach_deltas","baseline_index","build_area_index",+ "choose_depth","file_owners",+ "group_counts","in_area","nloc_weights","normalize_area",diff --git a/packages/core/src/repowise/core/analysis/areas/depth.py b/packages/core/src/repowise/core/analysis/areas/depth.pynew file mode 100644index 000000000..292360718--- /dev/null+++ b/packages/core/src/repowise/core/analysis/areas/depth.py@@ -0,0 +1,84 @@+"""How deep to group a set of files so the grouping says something.++A view grouped one level too shallow is one area holding everything; one+level too deep is an area per file. The chosen depth is the shallowest that+splits the files into enough areas with none holding most of them. The+performance queue and the coupling grid both choose their depth here, with+their own thresholds.+"""++from __future__ import annotations++from collections.abc import Iterable, Mapping++from .paths import ROOT_AREA, area_at, area_depth, in_area++__all__ = ["MAX_SHARE", "MIN_AREAS", "SMALL", "choose_depth", "group_counts"]++MIN_AREAS = 3+"""Fewer areas than this is barely a split."""++MAX_SHARE = 0.5+"""An area holding more than this share of the weight is most of the answer."""++SMALL = 10+"""Below this much weight two areas already say where it sits."""++MAX_EXTRA_DEPTH = 8+"""How many levels below the base the search looks."""+++def _weights(paths: Mapping[str, int] | Iterable[str]) -> dict[str, int]:+ if isinstance(paths, Mapping):+ return {path: int(weight) for path, weight in paths.items()}+ weights: dict[str, int] = {}+ for path in paths:+ weights[path] = weights.get(path, 0) + 1+ return weights+++def group_counts(weights: Mapping[str, int], depth: int) -> dict[str, int]:+ """*weights* (file path to a count) summed per area at *depth*."""+ grouped: dict[str, int] = {}+ for path, weight in weights.items():+ area = area_at(path, depth)+ grouped[area] = grouped.get(area, 0) + weight+ return grouped+++def choose_depth(+ paths: Mapping[str, int] | Iterable[str],+ *,+ base: str = ROOT_AREA,+ min_areas: int = MIN_AREAS,+ max_share: float = MAX_SHARE,+ small: int = SMALL,+ max_depth: int = MAX_EXTRA_DEPTH,+) -> int:+ """The absolute depth to group *paths* at below *base*.++ *paths* are file paths (each weighing one) or a mapping of path to+ weight; only those inside *base* count. The answer is the shallowest+ depth, at most *max_depth* levels below *base*, that splits them into at+ least *min_areas* areas (two when the total weight is under *small*)+ with none above *max_share* of the weight. Failing that, it is the depth+ whose largest area is smallest, the shallower on a tie, since going+ deeper without splitting adds nothing.+ """+ weights = {p: w for p, w in _weights(paths).items() if in_area(p, base)}+ start = area_depth(base) + 1+ total = sum(weights.values())+ if total == 0:+ return start+ needed = min_areas if total >= small else min(min_areas, 2)+ # Past the deepest directory, every depth groups the same way.+ deepest = max(path.count("/") for path in weights)+ best, best_share = start, 2.0+ for depth in range(start, max(start, min(deepest, start + max_depth - 1)) + 1):+ grouped = group_counts(weights, depth)+ share = max(grouped.values()) / total+ if len(grouped) >= needed and share <= max_share:+ return depth+ if share < best_share:+ best, best_share = depth, share+ return bestdiff --git a/packages/core/src/repowise/core/analysis/areas/detail.py b/packages/core/src/repowise/core/analysis/areas/detail.pyindex 36afe04f2..a57bea07a 100644--- a/packages/core/src/repowise/core/analysis/areas/detail.py+++ b/packages/core/src/repowise/core/analysis/areas/detail.py@@ -67,12 +67,15 @@ def area_detail(area: str,*,trend: Sequence[dict[str, Any]] = (),+ coupled: Sequence[dict[str, Any]] = (),limit: int = DETAIL_LIMIT,) -> dict[str, Any] | None:"""The area's rollup and lists, or ``None`` when no scored file is under it.*trend* is the area's score per snapshot (``[{taken_at, health}]``), read- from the history by the caller.+ from the history by the caller. *coupled* is the areas it changes with+ (:func:`repowise.core.analysis.coupling.coupled_areas`), folded by the+ caller from the co-change rows this index does not read."""node = index.nodes.get(area)if node is None:@@ -90,4 +93,5 @@ def area_detail("trend": list(trend),"top_findings": _top_findings(index, area, limit),"test_reach": _test_reach(group),+ "coupled_areas": list(coupled),}diff --git a/packages/core/src/repowise/core/analysis/areas/paths.py b/packages/core/src/repowise/core/analysis/areas/paths.pyindex b568a2259..c38481c44 100644--- a/packages/core/src/repowise/core/analysis/areas/paths.py+++ b/packages/core/src/repowise/core/analysis/areas/paths.py@@ -11,6 +11,7 @@ from __future__ import annotations__all__ = ["ROOT_AREA","ancestors",+ "area_at","area_depth","area_name","area_parent",@@ -33,6 +34,13 @@ def ancestors(file_path: str) -> list[str]:return [ROOT_AREA, *("/".join(parts[: i + 1]) for i in range(len(parts)))]+def area_at(file_path: str, depth: int) -> str:+ """The one area holding *file_path* at *depth*, or its own directory when+ that is shallower. Partitions files by level, as a grid of areas needs."""+ chain = ancestors(file_path)+ return chain[min(max(depth, 0), len(chain) - 1)]++def in_area(file_path: str, area: str) -> bool:return area == ROOT_AREA or file_path.startswith(area + "/")diff --git a/packages/core/src/repowise/core/analysis/coupling/__init__.py b/packages/core/src/repowise/core/analysis/coupling/__init__.pyindex 9255e72f2..2883b5679 100644--- a/packages/core/src/repowise/core/analysis/coupling/__init__.py+++ b/packages/core/src/repowise/core/analysis/coupling/__init__.py@@ -2,20 +2,51 @@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.+list, enriched with each file's module / health score / size, then scopes it+to areas (:mod:`.scope`) and folds it into area pairs (:mod:`.areas`). Pure+surfacing: no recompute, no new measurement, no LLM."""+from repowise.core.analysis.coupling.areas import (+ AREA_PAIR_LIMIT,+ COUPLED_AREA_LIMIT,+ TOP_PAIRS,+ area_coupling,+ coupled_areas,+ linked_area_pairs,+)from repowise.core.analysis.coupling.graph import (CouplingEdge,CouplingGraph,CouplingNode,+ coupling_edges,coupling_graph,+ graph_from_edges,+)+from repowise.core.analysis.coupling.scope import (+ MAX_DEPTH,+ CouplingScope,+ PlacedEdge,+ area_placer,+ place_edges,)__all__ = [+ "AREA_PAIR_LIMIT",+ "COUPLED_AREA_LIMIT",+ "MAX_DEPTH",+ "TOP_PAIRS","CouplingEdge","CouplingGraph","CouplingNode",+ "CouplingScope",+ "PlacedEdge",+ "area_coupling",+ "area_placer",+ "coupled_areas",+ "coupling_edges","coupling_graph",+ "graph_from_edges",+ "linked_area_pairs",+ "place_edges",]diff --git a/packages/core/src/repowise/core/analysis/coupling/areas.py b/packages/core/src/repowise/core/analysis/coupling/areas.pynew file mode 100644index 000000000..b55db74ea--- /dev/null+++ b/packages/core/src/repowise/core/analysis/coupling/areas.py@@ -0,0 +1,205 @@+"""Coupling between areas: which directories change together, and how much of+it the dependency graph cannot explain.++Folds placed file pairs (:func:`~.scope.place_edges`) into area pairs. An+area pair is *hidden* only when no dependency edge joins the two areas in+either direction: across a layer boundary (an app and the package it imports)+most file pairs never import each other directly, so the file-level+``unexplained`` label alone would flag every layered pair. An+area pair's figures are sums over its file pairs, so ``co_changes`` counts a+commit once per file pair it touched, not once per commit: the distinct-commit+count is not stored. Pure: no DB access.+"""++from __future__ import annotations++from collections.abc import Callable, Collection, Iterable, Sequence+from dataclasses import asdict, dataclass, field+from typing import Any++from repowise.core.analysis.areas import area_at, area_depth, in_area++from ...co_change import STRUCTURAL_UNEXPLAINED+from .graph import CouplingEdge+from .scope import PlacedEdge++__all__ = [+ "AREA_PAIR_LIMIT",+ "COUPLED_AREA_LIMIT",+ "TOP_PAIRS",+ "area_coupling",+ "coupled_areas",+ "linked_area_pairs",+]++#: Area pairs one answer carries, ranked; the total is always reported.+AREA_PAIR_LIMIT = 50+#: File pairs carried under each area pair.+TOP_PAIRS = 5+#: Areas an area card lists as changing with it.+COUPLED_AREA_LIMIT = 5+++@dataclass+class _Tally:+ """Running sums for one area or one area pair."""++ pairs: int = 0+ unexplained: int = 0+ strength: float = 0.0+ co_changes: int = 0+ last: str | None = None+ edges: list[CouplingEdge] = field(default_factory=list)++ def add(self, edge: CouplingEdge, *, keep: bool = False) -> None:+ self.pairs += 1+ self.unexplained += edge.structural == STRUCTURAL_UNEXPLAINED+ self.strength += edge.strength+ self.co_changes += edge.support+ if edge.last_co_change and (self.last is None or edge.last_co_change > self.last):+ self.last = edge.last_co_change+ if keep:+ self.edges.append(edge)++ def figures(self) -> dict[str, Any]:+ return {+ "pairs": self.pairs,+ "unexplained_pairs": self.unexplained,+ "unexplained_share": round(self.unexplained / self.pairs, 3) if self.pairs else 0.0,+ "strength": round(self.strength, 3),+ "co_changes": self.co_changes,+ "last_co_change": self.last,+ }+++AreaKey = tuple[str, str]+++def _key(a: str, b: str) -> AreaKey:+ return (a, b) if a <= b else (b, a)+++def linked_area_pairs(+ dependencies: Iterable[tuple[str, str]], place: Callable[[str], str]+) -> set[AreaKey]:+ """Area pairs a dependency joins, in either direction, from file-level+ ``(importer, imported)`` edges placed by *place* (the view's placer)."""+ return {_key(place(src), place(dst)) for src, dst in dependencies}+++def _verdict(key: AreaKey, tally: _Tally, linked: Collection[AreaKey]) -> dict[str, bool]:+ """``hidden`` only when no dependency joins the two areas at all and some+ file pair could have carried one: file pairs across a layer boundary rarely+ import each other directly, so a file-level gap alone is no finding."""+ is_linked = key in linked or key[0] == key[1]+ return {"linked": is_linked, "hidden": not is_linked and tally.unexplained > 0}+++def _rank(item: tuple[AreaKey, _Tally], linked: Collection[AreaKey]) -> tuple[bool, int, float]:+ """Hidden area pairs first, the finding; then unexplained pairs, then strength."""+ key, tally = item+ return (_verdict(key, tally, linked)["hidden"], tally.unexplained, tally.strength)+++def _top_edges(edges: list[CouplingEdge], limit: int) -> list[CouplingEdge]:+ """The strongest unexplained pairs first, then the strongest of the rest."""+ unexplained = [e for e in edges if e.structural == STRUCTURAL_UNEXPLAINED]+ rest = [e for e in edges if e.structural != STRUCTURAL_UNEXPLAINED]+ return (unexplained + rest)[:limit]+++def area_coupling(+ placed: Sequence[PlacedEdge],+ *,+ linked: Collection[AreaKey] = frozenset(),+ limit: int = AREA_PAIR_LIMIT,+ top_pairs: int = TOP_PAIRS,+) -> dict[str, Any]:+ """Area pairs and per-area totals over *placed* edges.++ *placed* is strongest first (as :func:`~.scope.place_edges` keeps it), so+ each pair's file list is too. *linked* is :func:`linked_area_pairs` under+ the same placement. A pair inside one area is an area pair with itself,+ present only when the scope kept same-area edges, and never hidden.+ """+ pairs: dict[AreaKey, _Tally] = {}+ areas: dict[str, _Tally] = {}+ cross = unexplained = unlabelled = 0+ for p in placed:+ key = _key(p.source_area, p.target_area)+ pairs.setdefault(key, _Tally()).add(p.edge, keep=True)+ for area in set(key):+ areas.setdefault(area, _Tally()).add(p.edge)+ cross += key[0] != key[1]+ unexplained += p.edge.structural == STRUCTURAL_UNEXPLAINED+ unlabelled += p.edge.structural is None++ ranked = sorted(pairs.items(), key=lambda kv: _rank(kv, linked), reverse=True)+ return {+ "totals": {+ "pairs": len(placed),+ "cross_area_pairs": cross,+ "unexplained_pairs": unexplained,+ "area_pairs": len(pairs),+ "unexplained_area_pairs": sum(1 for t in pairs.values() if t.unexplained),+ "hidden_area_pairs": sum(1 for kv in pairs.items() if _verdict(*kv, linked)["hidden"]),+ # Pairs from an index written before the dependency check: no+ # verdict either way, so a view must not call them clean.+ "unlabelled_pairs": unlabelled,+ },+ "areas": [+ {"path": area, **tally.figures()}+ for area, tally in sorted(+ areas.items(), key=lambda kv: (kv[1].unexplained, kv[1].strength), reverse=True+ )+ ],+ "area_pairs": [+ {+ "source": key[0],+ "target": key[1],+ **tally.figures(),+ **_verdict(key, tally, linked),+ "top_pairs": [asdict(e) for e in _top_edges(tally.edges, top_pairs)],+ }+ for key, tally in ranked[:limit]+ ],+ }+++def coupled_areas(+ edges: Sequence[CouplingEdge],+ area: str,+ *,+ dependencies: Iterable[tuple[str, str]] = (),+ keep: Callable[[CouplingEdge], bool] = lambda e: True,+ limit: int = COUPLED_AREA_LIMIT,+) -> list[dict[str, Any]]:+ """The areas outside *area* its files change with, most strongly first.++ A partner file is named by its area at *area*'s own depth, so+ ``packages/ui`` lists ``packages/web`` and ``tests/unit``, not single+ folders; each carries ``linked``/``hidden`` from *dependencies* as an area+ pair does. The root has nothing outside it and lists nothing.+ """+ depth = area_depth(area)+ if depth == 0:+ return []++ def outside(src: str, dst: str) -> str | None:+ """The other file's area when exactly one of the two is in *area*."""+ inside_a, inside_b = in_area(src, area), in_area(dst, area)+ if inside_a == inside_b:+ return None+ return area_at(dst if inside_a else src, depth)++ tallies: dict[str, _Tally] = {}+ for e in edges:+ other = outside(e.source, e.target)+ if other is not None and keep(e):+ tallies.setdefault(other, _Tally()).add(e)+ linked = {_key(area, o) for o in (outside(s, d) for s, d in dependencies) if o is not None}+ ranked = sorted(tallies.items(), key=lambda kv: kv[1].strength, reverse=True)+ return [+ {"path": path, **tally.figures(), **_verdict(_key(area, path), tally, linked)}+ for path, tally in ranked[:limit]+ ]diff --git a/packages/core/src/repowise/core/analysis/coupling/graph.py b/packages/core/src/repowise/core/analysis/coupling/graph.pyindex 49b13ad24..8e2ce6e35 100644--- a/packages/core/src/repowise/core/analysis/coupling/graph.py+++ b/packages/core/src/repowise/core/analysis/coupling/graph.py@@ -34,6 +34,7 @@ Honesty rules:from __future__ import annotations+from collections.abc import Mapping, Sequencefrom dataclasses import dataclassfrom typing import Any, Protocol@@ -104,6 +105,9 @@ class CouplingEdge:confidence_ba: float | None = Nonestructural: str | None = Nonedependency_kind: str | None = None+ #: Whether the two files sit in different areas at the asked depth; set+ #: by :func:`~.scope.place_edges`, ``None`` until an edge is placed.+ cross_area: bool | None = None@dataclass(frozen=True)@@ -152,31 +156,14 @@ def _node_score(metric: Any) -> float | None:return round(score, 2) if score is not None else None-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``.+def coupling_edges(git_meta_by_path: Mapping[str, GitMetaLike]) -> list[CouplingEdge]:+ """Every coupling the stored partner records describe, strongest first.Partners are stored symmetrically (a->b and b->a), so edges arededuplicated 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, ``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.+ observed strength and the most recent date and carrying both files' commit+ totals off it. No DB access and no recompute: a plain fold of the column."""- # Deduplicate symmetric partner records into undirected edges. Each side- # records the pair from its own vantage point, so keep whichever is- # strongest and carry both files' commit totals off it.best: dict[tuple[str, str], _Pair] = {}for src, meta in git_meta_by_path.items():for partner in parse_partners(meta.co_change_partners_json):@@ -213,35 +200,62 @@ def coupling_graph(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.- 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=_node_score(metric_by_path.get(path)),- nloc=(metric_by_path[path].nloc or 0 if path in metric_by_path else 0),- )- for path in sorted(referenced)- ]+ return edges+++def graph_from_edges(+ edges: Sequence[CouplingEdge],+ metric_by_path: Mapping[str, MetricLike],+ *,+ total_files: int,+ limit: int = 200,+) -> CouplingGraph:+ """Cap *edges* (strongest first) at *limit* and enrich the files they name.+ ``total_edges`` and ``coupled_files`` count *edges* before the cap, so a+ filtered list reports its own scope; ``total_files`` is the denominator the+ caller considered. Only files referenced by a kept edge become nodes.+ """+ coupled_files = len({path for e in edges for path in (e.source, e.target)})+ kept = list(edges[:limit])+ referenced = sorted({path for e in kept for path in (e.source, e.target)})+ nodes = []+ for path in referenced:+ metric = metric_by_path.get(path)+ nodes.append(+ CouplingNode(+ file_path=path,+ module=metric.module if metric is not None else None,+ score=_node_score(metric),+ nloc=(metric.nloc or 0) if metric is not None else 0,+ )+ )return CouplingGraph(nodes=nodes,- edges=edges,- total_edges=total,+ edges=kept,+ total_edges=len(edges),coupled_files=coupled_files,- # Every file the git walk recorded, coupled or not -- the denominator- # the coupled count is a share of.+ total_files=total_files,+ )+++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, whose ``co_change_partners_json`` carries the+ partners. ``total_files`` is every file the git walk recorded, coupled or+ not: the denominator the coupled count is a share of.+ """+ return graph_from_edges(+ coupling_edges(git_meta_by_path),+ {m.file_path: m for m in metrics},total_files=len(git_meta_by_path),+ limit=limit,)diff --git a/packages/core/src/repowise/core/analysis/coupling/scope.py b/packages/core/src/repowise/core/analysis/coupling/scope.pynew file mode 100644index 000000000..78e861689--- /dev/null+++ b/packages/core/src/repowise/core/analysis/coupling/scope.py@@ -0,0 +1,149 @@+"""Which couplings a view covers, and which areas each one joins.++A coupling view is read at one *depth* under one *root* area: every file is+placed in the area :func:`~repowise.core.analysis.areas.area_at` names for it,+so ``packages/ui/src/a.tsx`` at depth 2 is in ``packages/ui``. A file outside+the root is placed one level down from the repository at the root's own depth,+so drilling into ``packages/ui`` still shows it changing with ``packages/web``.++The filters narrow edges before anything is counted, so the totals a view+prints describe the edges it holds. Pure: callers pass loaded edges and a test+classifier and get placed edges back.+"""++from __future__ import annotations++from collections.abc import Callable, Sequence+from dataclasses import dataclass, replace+from datetime import date, timedelta++from repowise.core.analysis.areas import ROOT_AREA, area_at, area_depth, in_area++from ...co_change import STRUCTURAL_UNEXPLAINED+from .graph import CouplingEdge++__all__ = [+ "MAX_DEPTH",+ "CouplingScope",+ "PlacedEdge",+ "area_placer",+ "place_edges",+]++#: Deepest level a view groups by. Below it areas are single files' folders.+#: The default depth is chosen by ``areas.choose_depth`` within this bound.+MAX_DEPTH = 6+++@dataclass(frozen=True)+class CouplingScope:+ """The view: where it is rooted, how deep it groups, and what it keeps."""++ depth: int+ root: str = ROOT_AREA+ #: Shared commits a pair needs to count.+ min_support: int = 0+ #: Only pairs the dependency graph could explain and does not.+ unexplained: bool = False+ #: Only pairs whose two files sit in different areas.+ cross_area: bool = False+ #: Leave out pairs touching test material. A test is expected to change+ #: with its code, the rule the hidden-coupling finding applies.+ exclude_tests: bool = False+ #: Only pairs that last changed together within this many days of the+ #: newest co-change in the index (not of today, so an old index still reads).+ recent_days: int | None = None+ #: Only pairs with a file placed in this area at ``depth``, and with+ #: ``partner`` its other file placed there: one area-pair row's file pairs.+ area: str | None = None+ partner: str | None = None+++@dataclass(frozen=True, slots=True)+class PlacedEdge:+ """An edge with the two areas its files sit in, in the edge's own order."""++ edge: CouplingEdge+ source_area: str+ target_area: str+++def area_placer(scope: CouplingScope) -> Callable[[str], str]:+ """The area *scope* places a file in, memoised per path. One placer for+ co-change pairs and dependency edges, so the two always name the same area."""+ floor = area_depth(scope.root)+ areas: dict[str, str] = {}++ def area_of(path: str) -> str:+ found = areas.get(path)+ if found is None:+ depth = floor + scope.depth if in_area(path, scope.root) else floor+ found = areas[path] = area_at(path, depth)+ return found++ return area_of+++def _cutoff(edges: Sequence[CouplingEdge], days: int | None) -> str | None:+ """The oldest ``last_co_change`` a recency filter keeps, as an ISO date."""+ if days is None:+ return None+ newest = max((e.last_co_change[:10] for e in edges if e.last_co_change), default=None)+ if newest is None:+ return None+ try:+ return (date.fromisoformat(newest) - timedelta(days=days)).isoformat()+ except ValueError:+ return None+++def _between(placed: PlacedEdge, area: str, partner: str | None) -> bool:+ """Whether the pair has a file placed in *area* and, given *partner*, its+ other file placed there. Placed areas, not path prefixes, so the root-files+ area ``""`` names only the files at the root, as its area-pair row does."""+ ends = (placed.source_area, placed.target_area)+ for here, there in (ends, ends[::-1]):+ if here == area and (partner is None or there == partner):+ return True+ return False+++def _kept(+ e: CouplingEdge, scope: CouplingScope, cutoff: str | None, is_test: Callable[[str], bool]+) -> bool:+ """Whether *e* passes every filter that needs no area placement."""+ if not (in_area(e.source, scope.root) or in_area(e.target, scope.root)):+ return False+ if e.support < scope.min_support:+ return False+ if scope.unexplained and e.structural != STRUCTURAL_UNEXPLAINED:+ return False+ if cutoff is not None and (e.last_co_change or "")[:10] < cutoff:+ return False+ return not (scope.exclude_tests and (is_test(e.source) or is_test(e.target)))+++def place_edges(+ edges: Sequence[CouplingEdge],+ scope: CouplingScope,+ *,+ is_test: Callable[[str], bool],+) -> list[PlacedEdge]:+ """The edges *scope* keeps, each stamped ``cross_area`` and placed in its areas.++ Order is preserved, so strongest-first input stays strongest first. An+ edge needs a file under the root to be in the view.+ """+ cutoff = _cutoff(edges, scope.recent_days)+ area_of = area_placer(scope)+ out: list[PlacedEdge] = []+ for e in edges:+ if not _kept(e, scope, cutoff, is_test):+ continue+ a, b = area_of(e.source), area_of(e.target)+ if scope.cross_area and a == b:+ continue+ placed = PlacedEdge(replace(e, cross_area=a != b), a, b)+ if scope.area is None or _between(placed, scope.area, scope.partner):+ out.append(placed)+ return outdiff --git a/packages/server/src/repowise/server/job_executor.py b/packages/server/src/repowise/server/job_executor.pyindex 10bcc5bc7..7cabd8e0f 100644--- a/packages/server/src/repowise/server/job_executor.py+++ b/packages/server/src/repowise/server/job_executor.py@@ -60,6 +60,7 @@ from repowise.server.job_state import (_stamp_last_sync_commit,)from repowise.server.services.areas import warm_area_model+from repowise.server.services.coupling import warm_coupling_modellogger = structlog.get_logger(__name__)@@ -572,9 +573,10 @@ async def _run_index_job(run: _JobRun, app_state: Any) -> None:pages_generated = await _record_index_completion(run, result, all_pages, elapsed)await _write_index_state(run, docs, total_pages=len(all_pages))await _reload_cross_repo_enricher(app_state, spec.job_id)- # The area rollup is read on the first dashboard load after an index; fold- # it here, in the job's own task, instead of on that first request.+ # The area rollup and the coupling fold are read on the first dashboard+ # load after an index; fold them here, in the job's own task, instead.await warm_area_model(run.session_factory, spec.repo_id)+ await warm_coupling_model(run.session_factory, spec.repo_id)logger.info("job_completed",diff --git a/packages/server/src/repowise/server/routers/coupling.py b/packages/server/src/repowise/server/routers/coupling.pyindex bfccb5bd9..48a1602fa 100644--- a/packages/server/src/repowise/server/routers/coupling.py+++ b/packages/server/src/repowise/server/routers/coupling.py@@ -1,18 +1,27 @@-"""/api/repos/{repo_id}/coupling — repo-wide change-coupling graph.+"""/api/repos/{repo_id}/coupling — repo-wide change coupling, by file pair or by area.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.+(``GitMetadata.co_change_partners_json``) as a deduplicated, undirected edge+list, and folds it into area pairs. Pure surfacing: no recompute, no LLM.+Thin: the fold is :mod:`repowise.core.analysis.coupling`, the read model and+its cache are :mod:`repowise.server.services.coupling`."""from __future__ import annotations+from dataclasses import replace+from typing import Any+from fastapi import APIRouter, Depends, HTTPException, Queryfrom sqlalchemy.ext.asyncio import AsyncSession-from repowise.core.analysis.coupling import coupling_graph+from repowise.core.analysis.areas import ROOT_AREA, normalize_area+from repowise.core.analysis.coupling import (+ AREA_PAIR_LIMIT,+ MAX_DEPTH,+ TOP_PAIRS,+ CouplingScope,+)from repowise.core.persistence import crudfrom repowise.server.deps import get_db_session, verify_api_keyfrom repowise.server.schemas import (@@ -20,6 +29,12 @@ from repowise.server.schemas import (CouplingGraphResponse,CouplingNodeResponse,)+from repowise.server.schemas.coupling import CouplingAreasResponse+from repowise.server.services.coupling import (+ area_coupling_payload,+ coupling_answer,+ graph_payload,+)router = APIRouter(tags=["coupling"],@@ -27,29 +42,92 @@ router = APIRouter()+def _optional_area(raw: str | None) -> str | None:+ return None if raw is None else normalize_area(raw)+++def coupling_scope(+ depth: int | None = Query(+ None, ge=1, le=MAX_DEPTH, description="Area depth below the root; chosen when omitted."+ ),+ root: str = Query(ROOT_AREA, max_length=1024, description="Area the view is rooted at."),+ min_support: int = Query(0, ge=0, le=10_000, description="Shared commits a pair needs."),+ unexplained: bool = Query(False, description="Only pairs no dependency explains."),+ cross_area: bool = Query(False, description="Only pairs spanning two areas."),+ exclude_tests: bool = Query(False, description="Leave out pairs touching test material."),+ recent_days: int | None = Query(+ None, ge=1, le=36_500, description="Only pairs co-changed this recently, by index time."+ ),+) -> CouplingScope:+ """The filters both coupling routes share; ``depth=0`` stands for "choose"."""+ return CouplingScope(+ depth=depth or 0,+ root=normalize_area(root),+ min_support=min_support,+ unexplained=unexplained,+ cross_area=cross_area,+ exclude_tests=exclude_tests,+ recent_days=recent_days,+ )+++async def _require_repo(session: AsyncSession, repo_id: str) -> None:+ if await crud.get_repository(session, repo_id) is None:+ raise HTTPException(status_code=404, detail="Repository not found")++@router.get("/api/repos/{repo_id}/coupling", response_model=CouplingGraphResponse)async def coupling(repo_id: str,limit: int = Query(200, ge=1, le=1000),+ area: str | None = Query(+ None, max_length=1024, description="Only pairs with a file placed in this area."+ ),+ partner: str | None = Query(+ None, max_length=1024, description="With ``area``: only pairs whose other file is placed here."+ ),+ scope: CouplingScope = Depends(coupling_scope),session: AsyncSession = Depends(get_db_session),) -> CouplingGraphResponse:- """Return the repo's change-coupling graph (strongest *limit* edges).+ """The repo's change-coupling graph under the filters (strongest *limit* edges).Co-change is a temporal hint (files committed together), not a verifieddependency; ``strength`` is the decay-weighted count, not a percentage,- while ``support`` is the plain number of shared commits.+ while ``support`` is the plain number of shared commits. ``total_edges``+ and ``coupled_files`` count what the filters kept, before the cap."""- 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)+ await _require_repo(session, repo_id)+ if partner is not None and area is None:+ raise HTTPException(status_code=422, detail="partner needs area")+ # An empty ``area`` is the root-files area, as its area-pair row names it.+ scope = replace(scope, area=_optional_area(area), partner=_optional_area(partner))+ graph, depth = await coupling_answer(+ session, repo_id, ("graph", scope, limit), lambda m: graph_payload(m, scope, limit)+ )return CouplingGraphResponse(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,+ depth=depth,+ )++[email protected]("/api/repos/{repo_id}/coupling/areas", response_model=CouplingAreasResponse)+async def coupling_areas(+ repo_id: str,+ limit: int = Query(AREA_PAIR_LIMIT, ge=1, le=200, description="Area pairs to return."),+ top_pairs: int = Query(TOP_PAIRS, ge=1, le=20, description="File pairs per area pair."),+ scope: CouplingScope = Depends(coupling_scope),+ session: AsyncSession = Depends(get_db_session),+) -> dict[str, Any]:+ """Which areas change together, and how many of their file pairs no+ dependency explains. Ranked by unexplained pairs, then strength."""+ await _require_repo(session, repo_id)+ return await coupling_answer(+ session,+ repo_id,+ ("areas", scope, limit, top_pairs),+ lambda m: area_coupling_payload(m, scope, limit, top_pairs),)diff --git a/packages/server/src/repowise/server/schemas/areas.py b/packages/server/src/repowise/server/schemas/areas.pyindex 1dea824aa..d42203979 100644--- a/packages/server/src/repowise/server/schemas/areas.py+++ b/packages/server/src/repowise/server/schemas/areas.py@@ -9,7 +9,9 @@ from __future__ import annotationsfrom typing import Literal-from pydantic import BaseModel+from pydantic import BaseModel, Field++from .coupling import CouplingAreaSummaryBand = Literal["at_risk", "needs_work", "fair", "good", "excellent"]@@ -168,3 +170,6 @@ class AreaDetailResponse(BaseModel):top_findings: list[AreaFinding]test_reach: AreaTestReachdelta_window: AreaDeltaWindow+ #: Areas outside this one its files change with, strongest first; test+ #: material left out. Each named at this area's own depth.+ coupled_areas: list[CouplingAreaSummary] = Field(default_factory=list)diff --git a/packages/server/src/repowise/server/schemas/coupling.py b/packages/server/src/repowise/server/schemas/coupling.pyindex 3b71cacfe..f26a25304 100644--- a/packages/server/src/repowise/server/schemas/coupling.py+++ b/packages/server/src/repowise/server/schemas/coupling.py@@ -34,6 +34,8 @@ class CouplingEdgeResponse(BaseModel):#: The graph edge behind a ``corroborated`` verdict (``imports``,#: ``type_use``, ``framework``, ...). ``None`` for every other verdict.dependency_kind: str | None = None+ #: Whether the two files sit in different areas at the response's depth.+ cross_area: bool | None = Noneclass CouplingGraphResponse(BaseModel):@@ -45,3 +47,65 @@ class CouplingGraphResponse(BaseModel):#: commit history, so the count has a scale.coupled_files: int = 0total_files: int = 0+ #: Area depth ``cross_area`` was placed at: the asked one, else the default.+ depth: int | None = None+++class CouplingFigures(BaseModel):+ """Sums over the file pairs an area or an area pair holds."""++ pairs: int+ #: Pairs the dependency graph could explain and does not.+ unexplained_pairs: int+ #: ``unexplained_pairs`` over ``pairs``, 0-1.+ unexplained_share: float+ #: Summed decay-weighted strength, not a percentage.+ strength: float+ #: Shared commits summed per file pair: a commit counts once per pair it touched.+ co_changes: int+ last_co_change: str | None = None+ #: Area pairs only: a dependency joins the two areas in either direction.+ linked: bool | None = None+ #: Area pairs only: unexplained file pairs and no dependency between the+ #: areas at all. The finding; layered areas that import each other are not.+ hidden: bool | None = None+++class CouplingAreaSummary(CouplingFigures):+ """One area's coupling: every kept pair with a file in it."""++ path: str+++class CouplingAreaPair(CouplingFigures):+ """Two areas whose files change together; ``source == target`` for same-area pairs."""++ source: str+ target: str+ #: Strongest unexplained file pairs first, then the strongest of the rest.+ top_pairs: list[CouplingEdgeResponse] = Field(default_factory=list)+++class CouplingAreaTotals(BaseModel):+ #: File pairs the filters kept.+ pairs: int+ cross_area_pairs: int+ unexplained_pairs: int+ #: Area pairs before the cap.+ area_pairs: int+ #: Area pairs holding at least one unexplained file pair.+ unexplained_area_pairs: int+ #: Area pairs with unexplained file pairs and no dependency between the areas.+ hidden_area_pairs: int+ #: Pairs indexed before the dependency check ran: neither explained nor not.+ unlabelled_pairs: int+++class CouplingAreasResponse(BaseModel):+ root: str+ depth: int+ totals: CouplingAreaTotals+ #: Every area a kept pair touches, unexplained-heaviest first.+ areas: list[CouplingAreaSummary] = Field(default_factory=list)+ #: Hidden first, then by unexplained pairs and strength; capped at the asked limit.+ area_pairs: list[CouplingAreaPair] = Field(default_factory=list)diff --git a/packages/server/src/repowise/server/services/areas.py b/packages/server/src/repowise/server/services/areas.pyindex 214446506..13bf223d5 100644--- a/packages/server/src/repowise/server/services/areas.py+++ b/packages/server/src/repowise/server/services/areas.py@@ -43,6 +43,7 @@ from repowise.core.persistence.models import (HealthFinding,HealthSnapshot,)+from repowise.server.services.coupling import coupled_areas_for, coupling_answer__all__ = ["MAX_TREE_DEPTH",@@ -240,5 +241,8 @@ async def area_detail_payload(score = area_score(_score_map(snap.per_file_scores_json), area, model.weights)if score is not None:trend.append({"taken_at": _iso(snap.taken_at), "health": score})- detail = area_detail(model.index, area, trend=trend)+ coupled = await coupling_answer(+ session, repo_id, ("coupled", area), lambda m: coupled_areas_for(m, area)+ )+ detail = area_detail(model.index, area, trend=trend, coupled=coupled)return _details.remember(key, {**detail, "delta_window": _delta_window(model)})diff --git a/packages/server/src/repowise/server/services/coupling.py b/packages/server/src/repowise/server/services/coupling.pynew file mode 100644index 000000000..eeceeb91a--- /dev/null+++ b/packages/server/src/repowise/server/services/coupling.py@@ -0,0 +1,208 @@+"""Coupling read model: every co-change pair, folded once per index state.++The fold and the area grouping live in :mod:`repowise.core.analysis.coupling`;+this module reads the two columns they need, keeps the folded edges per+(database, repository, index stamp) in the shared :class:`IndexStampCache`,+and keeps each answer beside it, keyed on the query. Co-change rows are+rewritten by the index run that moves the stamp, so nothing else invalidates.+"""++from __future__ import annotations++import asyncio+from collections.abc import Callable, Hashable+from dataclasses import dataclass, field, replace+from typing import Any, TypeVar++import structlog+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from repowise.core.analysis.areas import area_depth, choose_depth+from repowise.core.analysis.coupling import (+ MAX_DEPTH,+ CouplingEdge,+ CouplingGraph,+ CouplingScope,+ area_coupling,+ area_placer,+ coupled_areas,+ coupling_edges,+ graph_from_edges,+ linked_area_pairs,+ place_edges,+)+from repowise.core.ingestion.models import FILE_DEPENDENCY_EDGE_TYPES+from repowise.core.persistence.database import get_session+from repowise.core.persistence.index_cache import IndexStampCache+from repowise.core.persistence.models import GitMetadata, GraphEdge, HealthFileMetric+from repowise.core.test_paths import is_test_related_path++__all__ = [+ "CouplingModel",+ "area_coupling_payload",+ "clear_coupling_cache",+ "coupled_areas_for",+ "coupling_answer",+ "graph_payload",+ "warm_coupling_model",+]++logger = structlog.get_logger(__name__)++T = TypeVar("T")++#: Folded edge lists, one per repository (older states are dropped).+_models = IndexStampCache(4)+#: Answers over them, one per distinct query a reader asks.+_answers = IndexStampCache(128)+#: One build per repository at a time, as the area model does.+_locks: dict[str, asyncio.Lock] = {}+++def clear_coupling_cache() -> None:+ _models.clear()+ _answers.clear()+ # A lock is bound to the loop that first waited on it.+ _locks.clear()+++@dataclass+class CouplingModel:+ edges: list[CouplingEdge]+ #: ``{path: (file_path, module, score, nloc)}`` rows, for node enrichment.+ metrics: dict[str, Any]+ #: Files the git walk recorded: the denominator of the coupled-file count.+ total_files: int+ #: File-level ``(importer, imported)`` dependency edges, for area linkage.+ dependencies: list[tuple[str, str]] = field(default_factory=list)+ _tests: dict[str, bool] = field(default_factory=dict, repr=False)+ _depths: dict[str, int] = field(default_factory=dict, repr=False)++ def is_test(self, path: str) -> bool:+ """Test material by path, memoised: partner files carry no stored flag."""+ found = self._tests.get(path)+ if found is None:+ found = self._tests[path] = is_test_related_path(path)+ return found++ def depth_for(self, root: str) -> int:+ """The default depth under *root*, over every coupled file so filters never move it."""+ found = self._depths.get(root)+ if found is None:+ paths = {p for e in self.edges for p in (e.source, e.target)}+ # Any area that holds no more than half the coupled files will do,+ # so no minimum count of areas; the depth is relative to the root.+ found = self._depths[root] = (+ choose_depth(paths, base=root, min_areas=1, small=0, max_depth=MAX_DEPTH)+ - area_depth(root)+ )+ return found+++async def _build(session: AsyncSession, repo_id: str) -> CouplingModel:+ git = select(GitMetadata.file_path, GitMetadata.co_change_partners_json).where(+ GitMetadata.repository_id == repo_id+ )+ git_rows = {row.file_path: row for row in (await session.execute(git)).all()}+ m = HealthFileMetric+ metric_q = select(m.file_path, m.module, m.score, m.nloc).where(m.repository_id == repo_id)+ metrics = {row.file_path: row for row in (await session.execute(metric_q)).all()}+ return CouplingModel(+ coupling_edges(git_rows), metrics, len(git_rows), await _dependencies(session, repo_id)+ )+++async def _dependencies(session: AsyncSession, repo_id: str) -> list[tuple[str, str]]:+ """File-to-file dependency edges, the kinds that corroborate a co-change+ pair. Symbol and external nodes are left out; workspace-package imports+ (``@repowise-dev/ui``, ``repowise.core``) already resolve to files."""+ e = GraphEdge+ q = select(e.source_node_id, e.target_node_id).where(+ e.repository_id == repo_id, e.edge_type.in_(FILE_DEPENDENCY_EDGE_TYPES)+ )+ return list(+ {+ (src, dst)+ for src, dst in (await session.execute(q)).all()+ if src != dst and "::" not in src + dst and not dst.startswith("external:")+ }+ )+++async def coupling_answer(+ session: AsyncSession,+ repo_id: str,+ query: tuple[Hashable, ...],+ build: Callable[[CouplingModel], T],+) -> T:+ """*build* over the repository's model, kept per index state and *query*."""+ base = await _models.key(session, repo_id)+ key = (*base, *query)+ if key in _answers:+ return _answers.get(key)+ return _answers.remember(key, build(await _model(session, repo_id, base)))+++async def _model(session: AsyncSession, repo_id: str, key: tuple[Any, ...]) -> CouplingModel:+ """The folded model for *key*, built once even under concurrent first reads."""+ if key in _models:+ return _models.get(key)+ async with _locks.setdefault(repo_id, asyncio.Lock()):+ if key in _models:+ return _models.get(key)+ model = await _build(session, repo_id)+ _models.drop_repo(repo_id)+ return _models.remember(key, model)+++def _resolved(model: CouplingModel, scope: CouplingScope) -> CouplingScope:+ """*scope* with a depth, the default for its root when it asked for none."""+ return scope if scope.depth > 0 else replace(scope, depth=model.depth_for(scope.root))+++def graph_payload(model: CouplingModel, scope: CouplingScope, limit: int) -> tuple[CouplingGraph, int]:+ """The file-pair graph the scope keeps, capped, and the depth it was placed at."""+ scope = _resolved(model, scope)+ placed = place_edges(model.edges, scope, is_test=model.is_test)+ graph = graph_from_edges(+ [p.edge for p in placed], model.metrics, total_files=model.total_files, limit=limit+ )+ return graph, scope.depth+++def area_coupling_payload(+ model: CouplingModel, scope: CouplingScope, limit: int, top_pairs: int+) -> dict[str, Any]:+ """Area pairs and per-area totals under the scope."""+ scope = _resolved(model, scope)+ placed = place_edges(model.edges, scope, is_test=model.is_test)+ linked = linked_area_pairs(model.dependencies, area_placer(scope))+ return {+ "root": scope.root,+ "depth": scope.depth,+ **area_coupling(placed, linked=linked, limit=limit, top_pairs=top_pairs),+ }+++def coupled_areas_for(model: CouplingModel, area: str) -> list[dict[str, Any]]:+ """The areas *area* changes with, test material left out as the coupling view's default."""+ return coupled_areas(+ model.edges,+ area,+ dependencies=model.dependencies,+ keep=lambda e: not (model.is_test(e.source) or model.is_test(e.target)),+ )+++async def warm_coupling_model(+ session_factory: async_sessionmaker[AsyncSession], repo_id: str+) -> None:+ """Fold *repo_id*'s co-change edges now, so the first reader after an index+ run does not pay for it. Best effort, as the area model's warm is; an+ index written outside this process is still folded on first read."""+ try:+ async with get_session(session_factory) as session:+ await _model(session, repo_id, await _models.key(session, repo_id))+ except Exception:+ logger.warning("coupling_warm_failed", repo_id=repo_id, exc_info=True)diff --git a/packages/types/src/coupling.ts b/packages/types/src/coupling.tsindex 805aaa8c6..ad06ed356 100644--- a/packages/types/src/coupling.ts+++ b/packages/types/src/coupling.ts@@ -53,6 +53,11 @@ export interface CouplingEdge {* written before the kind was recorded.*/dependency_kind: string | null;+ /**+ * Whether the two files sit in different areas at the response's `depth`.+ * Absent from a server older than area coupling.+ */+ cross_area?: boolean | null;}/** What the dependency graph says about a co-changing pair. */@@ -68,4 +73,32 @@ export interface CouplingGraphResponse {coupled_files: number;/** Files with any commit history: the denominator `coupled_files` is a share of. */total_files: number;+ /** Area depth `cross_area` was placed at. */+ depth?: number | null;+}++/**+ * Area-level coupling (`GET /api/repos/{repo_id}/coupling/areas`) and the+ * area card's `coupled_areas`. Generated from the server's response models.+ */+export type {+ CouplingAreaPair,+ CouplingAreaSummary,+ CouplingAreaTotals,+ CouplingAreasResponse,+} from "./generated/http.js";++/**+ * The filters `/coupling` and `/coupling/areas` share. `depth` is chosen by+ * the server when omitted; `recentDays` counts back from the newest co-change+ * in the index, not from today.+ */+export interface CouplingFilters {+ depth?: number;+ root?: string;+ minSupport?: number;+ unexplained?: boolean;+ crossArea?: boolean;+ excludeTests?: boolean;+ recentDays?: number;}diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.tsindex fd12e9650..ec4325087 100644--- a/packages/types/src/generated/http.ts+++ b/packages/types/src/generated/http.ts@@ -293,6 +293,7 @@ export interface AreaDetailResponse {top_findings: AreaFinding[];test_reach: AreaTestReach;delta_window: AreaDeltaWindow;+ coupled_areas?: CouplingAreaSummary[];}export interface AreaDistribution {@@ -1231,6 +1232,52 @@ export interface CostSummaryResponse {since: string | null;}+/** Two areas whose files change together; ``source == target`` for same-area pairs. */+export interface CouplingAreaPair {+ pairs: number;+ unexplained_pairs: number;+ unexplained_share: number;+ strength: number;+ co_changes: number;+ last_co_change?: string | null;+ linked?: boolean | null;+ hidden?: boolean | null;+ source: string;+ target: string;+ top_pairs?: CouplingEdgeResponse[];+}++/** One area's coupling: every kept pair with a file in it. */+export interface CouplingAreaSummary {+ pairs: number;+ unexplained_pairs: number;+ unexplained_share: number;+ strength: number;+ co_changes: number;+ last_co_change?: string | null;+ linked?: boolean | null;+ hidden?: boolean | null;+ path: string;+}++export interface CouplingAreaTotals {+ pairs: number;+ cross_area_pairs: number;+ unexplained_pairs: number;+ area_pairs: number;+ unexplained_area_pairs: number;+ hidden_area_pairs: number;+ unlabelled_pairs: number;+}++export interface CouplingAreasResponse {+ root: string;+ depth: number;+ totals: CouplingAreaTotals;+ areas?: CouplingAreaSummary[];+ area_pairs?: CouplingAreaPair[];+}+export interface CouplingEdgeResponse {source: string;target: string;@@ -1241,6 +1288,7 @@ export interface CouplingEdgeResponse {confidence_ba?: number | null;structural?: "corroborated" | "unexplained" | "not_applicable" | null;dependency_kind?: string | null;+ cross_area?: boolean | null;}export interface CouplingGraphResponse {@@ -1249,6 +1297,7 @@ export interface CouplingGraphResponse {total_edges?: number;coupled_files?: number;total_files?: number;+ depth?: number | null;}export interface CouplingNodeResponse {diff --git a/packages/ui/__tests__/coupling/area-coupling.test.tsx b/packages/ui/__tests__/coupling/area-coupling.test.tsxnew file mode 100644index 000000000..6b1328a5c--- /dev/null+++ b/packages/ui/__tests__/coupling/area-coupling.test.tsx@@ -0,0 +1,179 @@+import { describe, it, expect, vi } from "vitest";+import { render, screen, fireEvent } from "@testing-library/react";+import type {+ CouplingAreaPair,+ CouplingAreasResponse,+ CouplingEdge,+} from "@repowise-dev/types/coupling";+import { CouplingAreaPairList } from "../../src/coupling/area-pair-list.js";+import { DEFAULT_AREA_COUPLING_COPY } from "../../src/coupling/area-copy.js";+import {+ DEFAULT_AREA_FILTERS,+ parseAreaPair,+ serializeAreaPair,+ toCouplingFilters,+} from "../../src/coupling/area-view-state.js";+import { couplingIntensityByArea, couplingIntensityByFile } from "../../src/coupling/lens.js";+import { buildAreaCouplingAiPrompt } from "../../src/health/ai-prompt-builder.js";++function areaPair(+ source: string,+ target: string,+ unexplained: number,+ pairs = 10,+ linked = false,+): CouplingAreaPair {+ return {+ linked,+ hidden: !linked && unexplained > 0,+ source,+ target,+ pairs,+ unexplained_pairs: unexplained,+ unexplained_share: unexplained / pairs,+ strength: 2,+ co_changes: 30,+ last_co_change: "2026-10-15",+ top_pairs: [],+ };+}++function response(pairs: CouplingAreaPair[]): CouplingAreasResponse {+ return {+ root: "",+ depth: 2,+ totals: {+ pairs: 20,+ cross_area_pairs: 20,+ unexplained_pairs: pairs.reduce((n, p) => n + p.unexplained_pairs, 0),+ area_pairs: pairs.length + 3,+ unexplained_area_pairs: pairs.filter((p) => p.unexplained_pairs > 0).length,+ hidden_area_pairs: pairs.filter((p) => p.hidden).length,+ unlabelled_pairs: 0,+ },+ areas: [],+ area_pairs: pairs,+ };+}++function renderList(data: CouplingAreasResponse) {+ const onOpen = vi.fn();+ const onPrompt = vi.fn();+ render(+ <CouplingAreaPairList+ data={data}+ copy={DEFAULT_AREA_COUPLING_COPY}+ testsIncluded={false}+ onOpen={onOpen}+ onPrompt={onPrompt}+ />,+ );+ return { onOpen, onPrompt };+}++describe("CouplingAreaPairList", () => {+ it("marks only area pairs with no dependency between them", () => {+ const pairs = [+ areaPair("packages/server", "packages/ui", 7),+ areaPair("packages/ui", "packages/web", 9, 10, true),+ areaPair("docs", "packages/core", 0),+ ];+ const { onOpen, onPrompt } = renderList(response(pairs));+ expect(screen.getByText(/This area pair changes together although no file in one imports/)).toBeTruthy();+ expect(screen.getByText(/Test files are left out/)).toBeTruthy();+ // One mark, on the hidden pair; the layered pair reads as plain figures.+ expect(screen.getAllByText("No import link between the areas")).toHaveLength(1);+ expect(screen.getByText("9 file pairs with no direct import (90%)")).toBeTruthy();+ expect(screen.getByText("All explained")).toBeTruthy();+ expect(screen.getAllByRole("button", { name: /^Copy prompt for your agent/ })).toHaveLength(1);+ expect(screen.getByText(/Showing the top 3 of 6 area pairs/)).toBeTruthy();++ fireEvent.click(screen.getByText("packages/server/ ↔ packages/ui/"));+ expect(onOpen).toHaveBeenCalledWith({ source: "packages/server", target: "packages/ui" });+ fireEvent.click(screen.getByRole("button", { name: "Copy prompt for these 1" }));+ expect(onPrompt).toHaveBeenCalledWith([pairs[0]]);+ });++ it("names a clean result with its scope", () => {+ renderList(response([areaPair("packages/ui", "packages/web", 4, 10, true)]));+ expect(+ screen.getByText("Every area pair that changes together also has an import link, 2 levels down"),+ ).toBeTruthy();+ expect(screen.getByText(/Checked 20 file pairs/)).toBeTruthy();+ });++ it("gives no verdict on an index that predates the dependency check", () => {+ const data = response([areaPair("a", "b", 0)]);+ data.totals.unlabelled_pairs = data.totals.pairs;+ renderList(data);+ expect(screen.getByText(/predates the dependency check/)).toBeTruthy();+ expect(screen.queryByText(/Every area pair/)).toBeNull();+ });+});++describe("area view state", () => {+ it("round-trips an area pair, the root included", () => {+ const pair = { source: "", target: "packages" };+ expect(parseAreaPair(serializeAreaPair(pair))).toEqual(pair);+ expect(parseAreaPair("all")).toBeNull();+ expect(parseAreaPair("a|b|c")).toBeNull();+ });++ it("leaves tests out and omits unset filters by default", () => {+ expect(toCouplingFilters(DEFAULT_AREA_FILTERS)).toEqual({+ root: "",+ unexplained: false,+ crossArea: true,+ excludeTests: true,+ });+ });+});++describe("coupling lens", () => {+ it("normalises unexplained pairs against the most coupled area", () => {+ const lens = couplingIntensityByArea([+ { path: "a", pairs: 10, unexplained_pairs: 4, unexplained_share: 0.4, strength: 1, co_changes: 1 },+ { path: "b", pairs: 2, unexplained_pairs: 2, unexplained_share: 1, strength: 1, co_changes: 1 },+ ]);+ expect(lens.get("a")?.intensity).toBe(1);+ expect(lens.get("b")?.intensity).toBe(0.5);+ expect(couplingIntensityByArea([], { measure: "all" }).size).toBe(0);+ });++ it("counts each pair for both files", () => {+ const e = (s: string, t: string, structural: CouplingEdge["structural"]): CouplingEdge => ({+ source: s,+ target: t,+ strength: 1,+ last_co_change: null,+ support: 2,+ confidence_ab: null,+ confidence_ba: null,+ structural,+ dependency_kind: null,+ });+ const lens = couplingIntensityByFile([e("x", "y", "unexplained"), e("x", "z", "corroborated")]);+ expect(lens.get("x")).toEqual({ intensity: 1, pairs: 2, unexplained: 1 });+ expect(lens.get("z")?.intensity).toBe(0);+ });+});++describe("buildAreaCouplingAiPrompt", () => {+ it("hands the agent each area pair and its strongest file pairs", () => {+ const prompt = buildAreaCouplingAiPrompt({+ repoName: "repowise",+ areaPairs: [+ {+ ...areaPair("packages/server", "packages/types", 5),+ top_pairs: [+ { source: "packages/server/a.py", target: "packages/types/a.ts", structural: "unexplained", support: 9 },+ ],+ },+ ],+ });+ expect(prompt).toContain("## Hidden coupling between areas (`repowise`)");+ expect(prompt).toContain("### `packages/server/` ↔ `packages/types/`");+ expect(prompt).toContain("no dependency joins the two areas in either direction; **5**");+ expect(prompt).toContain("`packages/server/a.py` ↔ `packages/types/a.ts` (no dependency joins them, 9 shared commits)");+ });+});diff --git a/packages/ui/src/coupling/area-copy.ts b/packages/ui/src/coupling/area-copy.tsnew file mode 100644index 000000000..2dba1b29b--- /dev/null+++ b/packages/ui/src/coupling/area-copy.ts@@ -0,0 +1,74 @@+/**+ * Every string the area coupling view prints, with English defaults. The+ * package has no i18n: a host passes translated copy for any key it overrides.+ */++const fmt = (n: number) => n.toLocaleString();+const plural = (n: number, one: string, many: string) => `${fmt(n)} ${n === 1 ? one : many}`;++export const DEFAULT_AREA_COUPLING_COPY = {+ rootLabel: "Repository root",+ ledeLabel: "Hidden coupling",+ ledeUnit: (n: number): string => (n === 1 ? "area pair" : "area pairs"),+ verdict: (n: number) =>+ `${n === 1 ? "This area pair changes" : "These area pairs change"} together although no file in one imports a file in the other, so a change on one side quietly needs one on the other.`,+ scope: (pairs: number, depth: number, testsIncluded: boolean) =>+ `Across ${plural(pairs, "file pair", "file pairs")}, grouped ${depth} ${depth === 1 ? "level" : "levels"} down.` ++ (testsIncluded ? "" : " Test files are left out: a test is expected to change with its code."),+ cleanTitle: (depth: number) =>+ `Every area pair that changes together also has an import link, ${depth} ${depth === 1 ? "level" : "levels"} down`,+ cleanBody: (pairs: number) =>+ pairs > 0+ ? `Checked ${plural(pairs, "file pair", "file pairs")} that change together across areas.`+ : "No file pairs change together across areas under these filters.",+ unchecked:+ "Part of this index predates the dependency check, so it cannot say which areas change together without an import link. Run repowise update to add it.",+ hiddenMark: "No import link between the areas",+ showing: (shown: number, total: number) => `Showing the top ${fmt(shown)} of ${fmt(total)} area pairs.`,+ filePairs: (n: number) => plural(n, "file pair", "file pairs"),+ coChanges: (n: number) => plural(n, "co-change", "co-changes"),+ lastTogether: (date: string) => `last ${date}`,+ unexplained: (n: number, pct: number) =>+ `${plural(n, "file pair", "file pairs")} with no direct import (${pct}%)`,+ allExplained: "All explained",+ promptLabel: "Copy prompt for your agent",+ bulkPromptLabel: (n: number) => `Copy prompt for these ${fmt(n)}`,+ promptTitle: "Decouple prompt",+ promptDescription:+ "A ready-to-paste prompt asking your agent to find why these areas change together with no dependency between them, and to decouple what is accidental.",+ backToAreas: "All area pairs",+ pairHeadline: (unexplained: number, pairs: number) =>+ `${fmt(unexplained)} of ${plural(pairs, "file pair has", "file pairs have")} no direct import.`,+ allFilePairs: "Every file pair",+ browseFilePairs: "Browse every file pair",+ workspaceLink: "Coupling across repositories",+ filters: {+ label: "Filter couplings",+ unexplained: "Unexplained only",+ crossArea: "Across areas only",+ includeTests: "Include tests",+ minSupport: "Shared commits",+ anySupport: "Any",+ atLeast: (n: number) => `${n}+`,+ recency: "Changed together",+ anyTime: "Any time",+ lastDays: (days: number) => (days >= 365 ? "Last year of history" : `Last ${days} days of history`),+ depth: "Group at depth",+ autoDepth: (n: number) => `Auto (${n})`,+ },+};++export type AreaCouplingCopy = typeof DEFAULT_AREA_COUPLING_COPY;++/** Host overrides on top of the defaults; filter copy merges key by key. */+export type AreaCouplingCopyOverrides = Partial<Omit<AreaCouplingCopy, "filters">> & {+ filters?: Partial<AreaCouplingCopy["filters"]>;+};++export function resolveAreaCouplingCopy(over?: AreaCouplingCopyOverrides): AreaCouplingCopy {+ return {+ ...DEFAULT_AREA_COUPLING_COPY,+ ...over,+ filters: { ...DEFAULT_AREA_COUPLING_COPY.filters, ...over?.filters },+ };+}diff --git a/packages/ui/src/coupling/area-coupling-view.tsx b/packages/ui/src/coupling/area-coupling-view.tsxnew file mode 100644index 000000000..254f58ec9--- /dev/null+++ b/packages/ui/src/coupling/area-coupling-view.tsx@@ -0,0 +1,133 @@+"use client";++import { useCallback, useMemo, type ReactNode } from "react";+import type { CouplingAreaPair, CouplingAreasResponse } from "@repowise-dev/types/coupling";+import { useAiPromptAction } from "../health/ai-prompt-action";+import { buildAreaCouplingAiPrompt } from "../health/ai-prompt-builder";+import { resolveAreaCouplingCopy, type AreaCouplingCopyOverrides } from "./area-copy";+import { CouplingAreaFiltersBar } from "./area-filters";+import { AreaPairHeader } from "./area-pair-header";+import { CouplingAreaPairList } from "./area-pair-list";+import {+ ALL_FILE_PAIRS,+ areaLabel,+ type AreaPairRef,+ type CouplingAreaFilters,+} from "./area-view-state";++type LinkLike = React.ElementType<{ href: string; className?: string; children: ReactNode }>;++export interface CouplingAreaViewProps {+ data: CouplingAreasResponse;+ filters: CouplingAreaFilters;+ onFiltersChange: (next: CouplingAreaFilters) => void;+ /** The open area pair, `"all"` for every file pair, or `null` for the area list. */+ selection: AreaPairRef | typeof ALL_FILE_PAIRS | null;+ onSelectionChange: (next: AreaPairRef | typeof ALL_FILE_PAIRS | null) => void;+ /** The file-pair explorer for the open selection, fetched and rendered by the host. */+ children?: ReactNode;+ repoName?: string;+ /** Cross-repo co-changes, when the repository is part of a workspace. */+ workspaceHref?: string;+ LinkComponent?: LinkLike;+ copy?: AreaCouplingCopyOverrides;+}++/** The list row for the open pair, when the list holds it. */+function openedRow(+ data: CouplingAreasResponse,+ selection: AreaPairRef | typeof ALL_FILE_PAIRS | null,+): CouplingAreaPair | undefined {+ if (!selection || selection === ALL_FILE_PAIRS) return undefined;+ return (data.area_pairs ?? []).find(+ (p) => p.source === selection.source && p.target === selection.target,+ );+}++const LINK = "text-xs text-[var(--color-accent-primary)] hover:underline";++/**+ * Change coupling, opened at area level: which directories change together+ * with no dependency between their files. A selected area pair drills into+ * its file pairs, drawn by the existing explorer the host passes as children.+ */+export function CouplingAreaView({+ data,+ filters,+ onFiltersChange,+ selection,+ onSelectionChange,+ children,+ repoName,+ workspaceHref,+ LinkComponent = "a",+ copy: overrides,+}: CouplingAreaViewProps) {+ const copy = useMemo(() => resolveAreaCouplingCopy(overrides), [overrides]);+ const { openPrompt, promptModal } = useAiPromptAction();++ const prompt = useCallback(+ (pairs: CouplingAreaPair[]) =>+ openPrompt({+ title: copy.promptTitle,+ description: copy.promptDescription,+ filePath: pairs+ .map((p) => `${areaLabel(p.source, copy.rootLabel)} ↔ ${areaLabel(p.target, copy.rootLabel)}`)+ .join(", "),+ getPrompt: (flavor) =>+ buildAreaCouplingAiPrompt({ areaPairs: pairs, flavor, ...(repoName ? { repoName } : {}) }),+ }),+ [openPrompt, copy, repoName],+ );++ const open = useCallback((pair: AreaPairRef) => onSelectionChange(pair), [onSelectionChange]);++ const opened = openedRow(data, selection);++ const footer = (+ <span className="flex flex-wrap items-center gap-4">+ <button type="button" className={LINK} onClick={() => onSelectionChange(ALL_FILE_PAIRS)}>+ {copy.browseFilePairs}+ </button>+ {workspaceHref && (+ <LinkComponent href={workspaceHref} className={LINK}>+ {copy.workspaceLink}+ </LinkComponent>+ )}+ </span>+ );++ return (+ <div className="space-y-5">+ <CouplingAreaFiltersBar+ value={filters}+ onChange={onFiltersChange}+ resolvedDepth={data.depth}+ copy={copy.filters}+ />++ {selection === null ? (+ <CouplingAreaPairList+ data={data}+ copy={copy}+ testsIncluded={filters.includeTests}+ onOpen={open}+ onPrompt={prompt}+ footer={footer}+ />+ ) : (+ <div className="space-y-4">+ <AreaPairHeader+ selection={selection}+ opened={opened}+ copy={copy}+ onBack={() => onSelectionChange(null)}+ onPrompt={prompt}+ />+ {children}+ </div>+ )}+ {promptModal}+ </div>+ );+}diff --git a/packages/ui/src/coupling/area-filters.tsx b/packages/ui/src/coupling/area-filters.tsxnew file mode 100644index 000000000..f0db9a1cf--- /dev/null+++ b/packages/ui/src/coupling/area-filters.tsx@@ -0,0 +1,137 @@+"use client";++import { cn } from "../lib/cn";+import type { AreaCouplingCopy } from "./area-copy";+import type { CouplingAreaFilters } from "./area-view-state";++const SUPPORT_STEPS = [0, 3, 5, 10];+const RECENCY_STEPS = [90, 365];+const DEPTHS = [1, 2, 3, 4];++const CONTROL =+ "h-8 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-2 text-xs text-[var(--color-text-primary)] focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--color-accent-primary)]";++function Toggle({+ label,+ pressed,+ onChange,+}: {+ label: string;+ pressed: boolean;+ onChange: (next: boolean) => void;+}) {+ return (+ <button+ type="button"+ aria-pressed={pressed}+ onClick={() => onChange(!pressed)}+ className={cn(+ CONTROL,+ "px-2.5",+ pressed+ ? "bg-[var(--color-bg-selected)] font-medium shadow-[inset_0_-2px_0_var(--color-accent-primary)]"+ : "text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)]",+ )}+ >+ {label}+ </button>+ );+}++/** *options*, plus *value* when a shared link carries one the list does not offer. */+function withCurrent(+ options: { value: string; label: string }[],+ value: string,+ label: (value: string) => string,+): { value: string; label: string }[] {+ return options.some((o) => o.value === value) ? options : [...options, { value, label: label(value) }];+}++function Select({+ label,+ value,+ options,+ onChange,+}: {+ label: string;+ value: string;+ options: { value: string; label: string }[];+ onChange: (value: string) => void;+}) {+ return (+ <label className="inline-flex items-center gap-1.5 text-xs text-[var(--color-text-secondary)]">+ {label}+ <select value={value} onChange={(e) => onChange(e.target.value)} className={CONTROL}>+ {options.map((o) => (+ <option key={o.value} value={o.value}>+ {o.label}+ </option>+ ))}+ </select>+ </label>+ );+}++export interface CouplingAreaFiltersBarProps {+ value: CouplingAreaFilters;+ onChange: (next: CouplingAreaFilters) => void;+ /** The depth the server chose, named on the "Auto" option. */+ resolvedDepth: number;+ copy: AreaCouplingCopy["filters"];+}++/** The four filters and the grouping depth, one row that wraps on a phone. */+export function CouplingAreaFiltersBar({+ value,+ onChange,+ resolvedDepth,+ copy,+}: CouplingAreaFiltersBarProps) {+ const set = (patch: Partial<CouplingAreaFilters>) => onChange({ ...value, ...patch });+ return (+ <div role="group" aria-label={copy.label} className="flex flex-wrap items-center gap-2">+ <Toggle label={copy.unexplained} pressed={value.unexplained} onChange={(v) => set({ unexplained: v })} />+ <Toggle label={copy.crossArea} pressed={value.crossArea} onChange={(v) => set({ crossArea: v })} />+ <Toggle label={copy.includeTests} pressed={value.includeTests} onChange={(v) => set({ includeTests: v })} />+ <Select+ label={copy.minSupport}+ value={String(value.minSupport)}+ options={withCurrent(+ SUPPORT_STEPS.map((n) => ({+ value: String(n),+ label: n === 0 ? copy.anySupport : copy.atLeast(n),+ })),+ String(value.minSupport),+ (v) => copy.atLeast(Number(v)),+ )}+ onChange={(v) => set({ minSupport: Number(v) })}+ />+ <Select+ label={copy.recency}+ value={String(value.recentDays ?? "")}+ options={withCurrent(+ [+ { value: "", label: copy.anyTime },+ ...RECENCY_STEPS.map((d) => ({ value: String(d), label: copy.lastDays(d) })),+ ],+ String(value.recentDays ?? ""),+ (v) => copy.lastDays(Number(v)),+ )}+ onChange={(v) => set({ recentDays: v ? Number(v) : null })}+ />+ <Select+ label={copy.depth}+ value={String(value.depth ?? "")}+ options={withCurrent(+ [+ { value: "", label: copy.autoDepth(resolvedDepth) },+ ...DEPTHS.map((d) => ({ value: String(d), label: String(d) })),+ ],+ String(value.depth ?? ""),+ (v) => v,+ )}+ onChange={(v) => set({ depth: v ? Number(v) : null })}+ />+ </div>+ );+}diff --git a/packages/ui/src/coupling/area-pair-header.tsx b/packages/ui/src/coupling/area-pair-header.tsxnew file mode 100644index 000000000..749bbdc9d--- /dev/null+++ b/packages/ui/src/coupling/area-pair-header.tsx@@ -0,0 +1,51 @@+"use client";++import { ChevronLeft } from "lucide-react";+import type { CouplingAreaPair } from "@repowise-dev/types/coupling";+import { AiPromptButton } from "../health/ai-prompt-button";+import type { AreaCouplingCopy } from "./area-copy";+import { ALL_FILE_PAIRS, areaLabel, type AreaPairRef } from "./area-view-state";++export interface AreaPairHeaderProps {+ selection: AreaPairRef | typeof ALL_FILE_PAIRS;+ /** The open pair's row, when the list holds it; absent past the list's cap. */+ opened?: CouplingAreaPair | undefined;+ copy: AreaCouplingCopy;+ onBack: () => void;+ onPrompt: (pairs: CouplingAreaPair[]) => void;+}++/** The drill-down's header: back to the list, the pair named, its headline and prompt. */+export function AreaPairHeader({ selection, opened, copy, onBack, onPrompt }: AreaPairHeaderProps) {+ const title =+ selection === ALL_FILE_PAIRS+ ? copy.allFilePairs+ : `${areaLabel(selection.source, copy.rootLabel)} ↔ ${areaLabel(selection.target, copy.rootLabel)}`;+ return (+ <>+ <nav aria-label={copy.backToAreas} className="flex flex-wrap items-center gap-2 text-xs">+ <button+ type="button"+ onClick={onBack}+ className="inline-flex items-center gap-1 text-[var(--color-accent-primary)] hover:underline"+ >+ <ChevronLeft className="h-3.5 w-3.5" aria-hidden />+ {copy.backToAreas}+ </button>+ </nav>+ <div className="flex flex-wrap items-start justify-between gap-3">+ <div className="min-w-0 space-y-1">+ <h2 className="break-all font-mono text-[18px] text-[var(--color-text-primary)]">{title}</h2>+ {opened && (+ <p className="text-xs text-[var(--color-text-secondary)]">+ {copy.pairHeadline(opened.unexplained_pairs, opened.pairs)}+ </p>+ )}+ </div>+ {opened?.hidden && (+ <AiPromptButton label={copy.promptLabel} onClick={() => onPrompt([opened])} />+ )}+ </div>+ </>+ );+}diff --git a/packages/ui/src/coupling/area-pair-list.tsx b/packages/ui/src/coupling/area-pair-list.tsxnew file mode 100644index 000000000..b0fe8101d--- /dev/null+++ b/packages/ui/src/coupling/area-pair-list.tsx@@ -0,0 +1,186 @@+"use client";++import { memo } from "react";+import type { CouplingAreaPair, CouplingAreasResponse } from "@repowise-dev/types/coupling";+import { PromptForRowsButton, RowPromptAction } from "../health/row-prompt-action";+import { CleanState } from "../shared/clean-state";+import { PageLede } from "../shared/page-lede";+import type { AreaCouplingCopy } from "./area-copy";+import { areaLabel, type AreaPairRef } from "./area-view-state";++/**+ * The row's reading. Only a hidden pair (no dependency between the two areas)+ * is marked, with a dot and a word; a layered pair that imports across is+ * expected coupling and reads as plain figures. The share bar is neutral ink,+ * never a warning or accent colour on every row.+ */+function PairReading({ pair, copy }: { pair: CouplingAreaPair; copy: AreaCouplingCopy }) {+ const pct = Math.round(pair.unexplained_share * 100);+ return (+ <span className="flex min-w-0 flex-col items-start gap-1 sm:items-end">+ {pair.hidden && (+ <span className="inline-flex items-center gap-1.5 whitespace-nowrap text-xs font-medium text-[var(--color-text-primary)]">+ <span aria-hidden className="h-1.5 w-1.5 rounded-full bg-[var(--color-warning)]" />+ {copy.hiddenMark}+ </span>+ )}+ <span className="whitespace-nowrap text-xs tabular-nums text-[var(--color-text-secondary)]">+ {pair.unexplained_pairs > 0 ? copy.unexplained(pair.unexplained_pairs, pct) : copy.allExplained}+ </span>+ <span aria-hidden className="block h-1 w-24 overflow-hidden rounded-full bg-[var(--color-bg-elevated)]">+ <span className="block h-full" style={{ width: `${pct}%`, background: "var(--color-text-tertiary)" }} />+ </span>+ </span>+ );+}++interface RowProps {+ pair: CouplingAreaPair;+ copy: AreaCouplingCopy;+ onOpen: (pair: AreaPairRef) => void;+ onPrompt: (pairs: CouplingAreaPair[]) => void;+}++const AreaPairRow = memo(function AreaPairRow({ pair, copy, onOpen, onPrompt }: RowProps) {+ const name = `${areaLabel(pair.source, copy.rootLabel)} ↔ ${areaLabel(pair.target, copy.rootLabel)}`;+ const meta = [+ copy.filePairs(pair.pairs),+ copy.coChanges(pair.co_changes),+ pair.last_co_change ? copy.lastTogether(pair.last_co_change.slice(0, 10)) : null,+ ].filter(Boolean);+ return (+ <li className="group/row flex flex-col gap-2 border-b border-[var(--color-border-default)] py-3 last:border-b-0 sm:flex-row sm:items-center sm:gap-4">+ <button+ type="button"+ onClick={() => onOpen({ source: pair.source, target: pair.target })}+ className="flex min-w-0 flex-1 flex-col gap-3 rounded-md px-1 py-1 text-left hover:bg-[var(--color-bg-elevated)] focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--color-accent-primary)] sm:flex-row sm:items-center"+ >+ <span className="flex min-w-0 flex-1 flex-col gap-1">+ <span className="break-all font-mono text-[15px] text-[var(--color-text-primary)] group-hover/row:text-[var(--color-accent-primary)]">+ {name}+ </span>+ <span className="text-xs tabular-nums text-[var(--color-text-secondary)]">+ {meta.join(" · ")}+ </span>+ </span>+ <PairReading pair={pair} copy={copy} />+ </button>+ {pair.hidden && (+ <RowPromptAction+ label={copy.promptLabel}+ subject={name}+ onClick={() => onPrompt([pair])}+ className="self-start sm:self-center"+ />+ )}+ </li>+ );+});++export interface CouplingAreaPairListProps {+ data: CouplingAreasResponse;+ copy: AreaCouplingCopy;+ testsIncluded: boolean;+ onOpen: (pair: AreaPairRef) => void;+ onPrompt: (pairs: CouplingAreaPair[]) => void;+ /** Rendered beside the "showing" line: the escape to every file pair, a workspace link. */+ footer?: React.ReactNode;+}++/** The lede: hidden pairs when there are any, else a clean or an unchecked state. */+function Lede({+ data,+ copy,+ testsIncluded,+ hiddenRows,+ onPrompt,+}: Omit<CouplingAreaPairListProps, "onOpen" | "footer"> & { hiddenRows: CouplingAreaPair[] }) {+ const { totals, depth } = data;+ const hidden = totals.hidden_area_pairs;+ if (hidden > 0) {+ return (+ <PageLede+ label={copy.ledeLabel}+ value={hidden.toLocaleString()}+ unit={copy.ledeUnit(hidden)}+ action={+ <PromptForRowsButton+ count={hiddenRows.length}+ label={copy.bulkPromptLabel}+ onClick={() => onPrompt(hiddenRows)}+ />+ }+ >+ <p className="text-[15px] text-[var(--color-text-primary)]">{copy.verdict(hidden)}</p>+ <p className="mt-1 text-xs text-[var(--color-text-secondary)]">+ {copy.scope(totals.pairs, depth, testsIncluded)}+ </p>+ </PageLede>+ );+ }+ // Some kept pairs predate the dependency check: "all clear" would claim more+ // than was checked.+ if (totals.unlabelled_pairs > 0) {+ return <p className="text-xs text-[var(--color-text-secondary)]">{copy.unchecked}</p>;+ }+ return (+ <CleanState+ align="start"+ title={copy.cleanTitle(depth)}+ description={copy.cleanBody(totals.pairs)}+ />+ );+}++/**+ * The area view's body: a verdict lede, then area pairs, hidden ones first. An+ * area pair is hidden only when no dependency joins the two areas at all;+ * layered areas that import each other are expected coupling, listed but not+ * marked. A ranked list rather than a matrix: on real indexes a few dozen of+ * a few hundred area pairs carry the finding, so a grid would be mostly empty.+ */+export function CouplingAreaPairList({+ data,+ copy,+ testsIncluded,+ onOpen,+ onPrompt,+ footer,+}: CouplingAreaPairListProps) {+ const pairs = data.area_pairs ?? [];+ const hiddenRows = pairs.filter((p) => p.hidden);+ return (+ <div className="space-y-6">+ <Lede+ data={data}+ copy={copy}+ testsIncluded={testsIncluded}+ hiddenRows={hiddenRows}+ onPrompt={onPrompt}+ />++ {pairs.length > 0 && (+ <ul className="border-t border-[var(--color-border-default)]">+ {pairs.map((pair) => (+ <AreaPairRow+ key={`${pair.source}|${pair.target}`}+ pair={pair}+ copy={copy}+ onOpen={onOpen}+ onPrompt={onPrompt}+ />+ ))}+ </ul>+ )}++ <div className="flex flex-wrap items-center justify-between gap-3 text-xs text-[var(--color-text-secondary)]">+ <span>+ {data.totals.area_pairs > pairs.length+ ? copy.showing(pairs.length, data.totals.area_pairs)+ : null}+ </span>+ {footer}+ </div>+ </div>+ );+}diff --git a/packages/ui/src/coupling/area-view-state.ts b/packages/ui/src/coupling/area-view-state.tsnew file mode 100644index 000000000..aed7537f5--- /dev/null+++ b/packages/ui/src/coupling/area-view-state.ts@@ -0,0 +1,72 @@+/**+ * The area coupling view's state, as plain data a host can keep in its URL.+ *+ * Defaults describe the view a reader opens on: area pairs across areas, test+ * files left out (a test is expected to change with its code). Pure, so the+ * host's URL parsers and the filter bar agree on one shape.+ */+import type { CouplingFilters } from "@repowise-dev/types/coupling";++export interface CouplingAreaFilters {+ /** Only file pairs no dependency explains. */+ unexplained: boolean;+ /** Only file pairs spanning two areas. */+ crossArea: boolean;+ /** Keep pairs touching test material. */+ includeTests: boolean;+ /** Shared commits a pair needs; 0 keeps every stored pair. */+ minSupport: number;+ /** Days back from the newest co-change in the index; `null` for all history. */+ recentDays: number | null;+ /** Area depth; `null` lets the server choose. */+ depth: number | null;+}++export const DEFAULT_AREA_FILTERS: CouplingAreaFilters = {+ unexplained: false,+ crossArea: true,+ includeTests: false,+ minSupport: 0,+ recentDays: null,+ depth: null,+};++/** The wire filters both coupling routes take, rooted at *root*. */+export function toCouplingFilters(f: CouplingAreaFilters, root = ""): CouplingFilters {+ return {+ root,+ unexplained: f.unexplained,+ crossArea: f.crossArea,+ excludeTests: !f.includeTests,+ ...(f.minSupport > 0 ? { minSupport: f.minSupport } : {}),+ ...(f.recentDays ? { recentDays: f.recentDays } : {}),+ ...(f.depth ? { depth: f.depth } : {}),+ };+}++/** One area pair, the drill-down's subject. */+export interface AreaPairRef {+ source: string;+ target: string;+}++/** The URL value that opens every file pair instead of one area pair. */+export const ALL_FILE_PAIRS = "all";++const PAIR_SEP = "|";++export function serializeAreaPair(pair: AreaPairRef): string {+ return `${pair.source}${PAIR_SEP}${pair.target}`;+}++/** An area pair from its URL value; `null` for anything that is not one. */+export function parseAreaPair(raw: string | null | undefined): AreaPairRef | null {+ if (!raw || !raw.includes(PAIR_SEP)) return null;+ const [source, target, ...rest] = raw.split(PAIR_SEP);+ return rest.length === 0 ? { source: source ?? "", target: target ?? "" } : null;+}++/** An area's display name: its path with a trailing slash, or the root's label. */+export function areaLabel(path: string, rootLabel: string): string {+ return path ? `${path}/` : rootLabel;+}diff --git a/packages/ui/src/coupling/index.ts b/packages/ui/src/coupling/index.tsindex b19ee1933..df78fd002 100644--- a/packages/ui/src/coupling/index.ts+++ b/packages/ui/src/coupling/index.ts@@ -1,6 +1,28 @@export { CouplingGraph, type CouplingGraphProps } from "./coupling-graph";export { CouplingTable } from "./coupling-table";export { CouplingExplorer, type CouplingExplorerProps } from "./coupling-explorer";+export { CouplingAreaView, type CouplingAreaViewProps } from "./area-coupling-view";+export {+ DEFAULT_AREA_COUPLING_COPY,+ type AreaCouplingCopy,+ type AreaCouplingCopyOverrides,+} from "./area-copy";+export {+ ALL_FILE_PAIRS,+ DEFAULT_AREA_FILTERS,+ areaLabel,+ parseAreaPair,+ serializeAreaPair,+ toCouplingFilters,+ type AreaPairRef,+ type CouplingAreaFilters,+} from "./area-view-state";+export {+ couplingIntensityByArea,+ couplingIntensityByFile,+ type CouplingIntensity,+ type CouplingLensOptions,+} from "./lens";export {CouplingPairDrawer,type CouplingPairDrawerProps,diff --git a/packages/ui/src/coupling/lens.ts b/packages/ui/src/coupling/lens.tsnew file mode 100644index 000000000..ad50585d8--- /dev/null+++ b/packages/ui/src/coupling/lens.ts@@ -0,0 +1,69 @@+/**+ * The coupling lens for the area map: how strongly each area or file changes+ * together with code it does not depend on.+ *+ * Pure. Area figures come from `GET /coupling/areas` at the depth and root the+ * map is drawn at, so no path arithmetic happens here; file figures come from a+ * `GET /coupling` edge list. Intensity is normalised to 0-1 against the+ * strongest item, with the raw counts beside it so a legend can name them.+ * Ceiling: file intensity is only as complete as the edge list passed in+ * (capped at the route's 1,000); the map lane's lens adapter should say so.+ */+import type { CouplingAreaSummary, CouplingEdge } from "@repowise-dev/types/coupling";++export interface CouplingIntensity {+ /** 0-1 against the most coupled item in the same set. */+ intensity: number;+ /** File pairs counted. */+ pairs: number;+ /** Of those, pairs no dependency explains. */+ unexplained: number;+}++export interface CouplingLensOptions {+ /** Measure by unexplained pairs (default), the actionable reading, or by every pair. */+ measure?: "unexplained" | "all";+}++function normalise(+ tallies: Map<string, { pairs: number; unexplained: number }>,+ measure: "unexplained" | "all",+): Map<string, CouplingIntensity> {+ const value = (t: { pairs: number; unexplained: number }) =>+ measure === "all" ? t.pairs : t.unexplained;+ let max = 0;+ for (const t of tallies.values()) max = Math.max(max, value(t));+ const out = new Map<string, CouplingIntensity>();+ for (const [key, t] of tallies) {+ out.set(key, { intensity: max > 0 ? value(t) / max : 0, ...t });+ }+ return out;+}++/** Per-area intensity, keyed by area path. */+export function couplingIntensityByArea(+ areas: readonly CouplingAreaSummary[],+ { measure = "unexplained" }: CouplingLensOptions = {},+): Map<string, CouplingIntensity> {+ const tallies = new Map<string, { pairs: number; unexplained: number }>();+ for (const a of areas) tallies.set(a.path, { pairs: a.pairs, unexplained: a.unexplained_pairs });+ return normalise(tallies, measure);+}++/** Per-file intensity, keyed by file path; each pair counts for both files. */+export function couplingIntensityByFile(+ edges: readonly CouplingEdge[],+ { measure = "unexplained" }: CouplingLensOptions = {},+): Map<string, CouplingIntensity> {+ const tallies = new Map<string, { pairs: number; unexplained: number }>();+ for (const e of edges) {+ const hidden = e.structural === "unexplained" ? 1 : 0;+ for (const path of [e.source, e.target]) {+ const t = tallies.get(path) ?? { pairs: 0, unexplained: 0 };+ t.pairs += 1;+ t.unexplained += hidden;+ tallies.set(path, t);+ }+ }+ return normalise(tallies, measure);+}diff --git a/packages/ui/src/health/ai-prompt-builder.ts b/packages/ui/src/health/ai-prompt-builder.tsindex 337a10e28..ab5daac50 100644--- a/packages/ui/src/health/ai-prompt-builder.ts+++ b/packages/ui/src/health/ai-prompt-builder.ts@@ -31,7 +31,10 @@ export {type DocDriftPromptFinding,} from "./ai-prompts/doc-drift-prompt";export {+ buildAreaCouplingAiPrompt,buildCouplingAiPrompt,+ type AreaCouplingPromptPair,+ type BuildAreaCouplingPromptOptions,type BuildCouplingPromptOptions,type CouplingPromptEdge,type CouplingPromptNode,diff --git a/packages/ui/src/health/ai-prompts/coupling-prompt.ts b/packages/ui/src/health/ai-prompts/coupling-prompt.tsindex 8f0f1cdc8..bcca21cd5 100644--- a/packages/ui/src/health/ai-prompts/coupling-prompt.ts+++ b/packages/ui/src/health/ai-prompts/coupling-prompt.ts@@ -143,3 +143,80 @@ export function buildCouplingAiPrompt({: "Start by reading both files and `git log` for the commits that changed them together. The co-change count is a symptom; find the shared concern driving it before you restructure anything.",]);}++// ─────────────────────────────────────────────────────────────────────+// Area coupling prompt (one or more area pairs)+// ─────────────────────────────────────────────────────────────────────++/** One area pair as the coupling view holds it. */+export interface AreaCouplingPromptPair {+ source: string;+ target: string;+ pairs: number;+ unexplained_pairs: number;+ co_changes: number;+ last_co_change?: string | null;+ /** The strongest file pairs, unexplained first. */+ top_pairs?: CouplingPromptEdge[];+}++export interface BuildAreaCouplingPromptOptions {+ areaPairs: AreaCouplingPromptPair[];+ flavor?: AiPromptFlavor;+ repoName?: string;+}++function areaName(path: string): string {+ return path ? `\`${path}/\`` : "the repository root";+}++function filePairLine(edge: CouplingPromptEdge): string {+ const verdict =+ edge.structural === "unexplained" ? "no dependency joins them" : (edge.structural ?? "unlabelled");+ const support = edge.support ? `, ${edge.support} shared commits` : "";+ return `\`${edge.source}\` ↔ \`${edge.target}\` (${verdict}${support})`;+}++function areaPairSection(pair: AreaCouplingPromptPair): string {+ const last = pair.last_co_change ? `, last on ${pair.last_co_change.slice(0, 10)}` : "";+ return [+ `### ${areaName(pair.source)} ↔ ${areaName(pair.target)}`,+ "",+ bulletList([+ `${pair.pairs} file pairs change together across these areas, and no dependency joins the two areas in either direction; **${pair.unexplained_pairs}** of the pairs are files that could have carried one.`,+ `${pair.co_changes} shared commits summed over those pairs${last}.`,+ ...(pair.top_pairs ?? []).map(filePairLine),+ ]),+ ].join("\n");+}++const AREA_EXPECTED = [+ "1. Per area pair: the shared concern behind the hidden coupling (a wire contract, a duplicated constant, a feature split across layers), named with evidence from the commits.",+ "2. Which of it is legitimate (two halves of one feature, a generated mirror) and which is accidental.",+ "3. For the accidental part: a decoupling plan, smallest-risk first, and the first behavior-preserving change with its tests.",+];++/**+ * A prompt asking an agent to investigate why whole areas change together+ * with no dependency between their files, and to decouple what is accidental.+ */+export function buildAreaCouplingAiPrompt({+ areaPairs,+ flavor = "generic",+ repoName,+}: BuildAreaCouplingPromptOptions): string {+ const first = areaPairs[0];+ return joinSections([+ FLAVOR_PREAMBLE[flavor],+ "",+ `## Hidden coupling between areas${repoSuffix(repoName)}`,+ "",+ "Files in these directories keep changing in the same commits although no file in one area imports, uses or wires a file in the other. Across languages that usually means an unwritten contract (a wire format, a schema mirrored by hand, a command a script runs). Source: repowise co-change analysis of git history; treat it as a lead, not proof. Test files are left out, since a test is expected to change with its code.",+ "",+ ...areaPairs.flatMap((pair) => [areaPairSection(pair), ""]),+ ...closingSections(CONSTRAINTS, AREA_EXPECTED),+ flavor === "claude-code-mcp" && first+ ? `Call \`get_context(['${first.source}', '${first.target}'])\` and \`get_risk\` on the file pairs above before planning: repowise already holds the dependency graph and co-change history.`+ : "Start with `git log` for the commits that touched both sides of a pair. The co-change count is a symptom; find the shared concern before restructuring anything.",+ ]);+}diff --git a/packages/web/messages/en.json b/packages/web/messages/en.jsonindex 9e276ecca..2af0a97e7 100644--- a/packages/web/messages/en.json+++ b/packages/web/messages/en.json@@ -1040,7 +1040,50 @@}},"coupling": {- "loadFailed": "Couldn't load change coupling"+ "loadFailed": "Couldn't load change coupling",+ "area": {+ "rootLabel": "Repository root",+ "ledeLabel": "Hidden coupling",+ "ledeUnit": "{count, plural, one {area pair} other {area pairs}}",+ "verdict": "{count, plural, one {This area pair changes} other {These area pairs change}} together although no file in one imports a file in the other, so a change on one side quietly needs one on the other.",+ "scope": "Across {pairs, plural, one {# file pair} other {# file pairs}}, grouped {depth, plural, one {# level} other {# levels}} down. Test files are left out: a test is expected to change with its code.",+ "scopeWithTests": "Across {pairs, plural, one {# file pair} other {# file pairs}}, grouped {depth, plural, one {# level} other {# levels}} down, tests included.",+ "cleanTitle": "Every area pair that changes together also has an import link, {depth, plural, one {# level} other {# levels}} down",+ "cleanBody": "Checked {pairs, plural, one {# file pair} other {# file pairs}} that change together across areas.",+ "cleanEmpty": "No file pairs change together across areas under these filters.",+ "showing": "Showing the top {shown, number} of {total, number} area pairs.",+ "filePairs": "{count, plural, one {# file pair} other {# file pairs}}",+ "coChanges": "{count, plural, one {# co-change} other {# co-changes}}",+ "lastTogether": "last {date}",+ "unexplained": "{count, plural, one {# file pair} other {# file pairs}} with no direct import ({pct}%)",+ "allExplained": "All explained",+ "promptLabel": "Copy prompt for your agent",+ "bulkPromptLabel": "Copy prompt for these {count, number}",+ "promptTitle": "Decouple prompt",+ "promptDescription": "A ready-to-paste prompt asking your agent to find why these areas change together with no dependency between them, and to decouple what is accidental.",+ "backToAreas": "All area pairs",+ "pairHeadline": "{unexplained, number} of {pairs, plural, one {# file pair has} other {# file pairs have}} no direct import.",+ "allFilePairs": "Every file pair",+ "browseFilePairs": "Browse every file pair",+ "workspaceLink": "Coupling across repositories",+ "filters": {+ "label": "Filter couplings",+ "unexplained": "Unexplained only",+ "crossArea": "Across areas only",+ "includeTests": "Include tests",+ "minSupport": "Shared commits",+ "anySupport": "Any",+ "atLeast": "{count}+",+ "recency": "Changed together",+ "anyTime": "Any time",+ "lastDays": "Last {days} days of history",+ "lastYear": "Last year of history",+ "depth": "Group at depth",+ "autoDepth": "Auto ({depth})"+ },+ "unchecked": "Part of this index predates the dependency check, so it cannot say which areas change together without an import link. Run repowise update to add it.",+ "hiddenMark": "No import link between the areas"+ }},"coverage": {"jobRunning": "A generation job is already running. Wait for it to finish.",diff --git a/packages/web/messages/zh-CN.json b/packages/web/messages/zh-CN.jsonindex 225ba2e80..3812a3586 100644--- a/packages/web/messages/zh-CN.json+++ b/packages/web/messages/zh-CN.json@@ -1040,7 +1040,50 @@}},"coupling": {- "loadFailed": "无法加载变更耦合"+ "loadFailed": "无法加载变更耦合",+ "area": {+ "rootLabel": "仓库根目录",+ "ledeLabel": "隐性耦合",+ "ledeUnit": "{count, plural, other {组区域}}",+ "verdict": "{count, plural, other {这些区域对}}一起变更,但其中一方没有任何文件导入另一方的文件,因此一侧的修改会悄悄要求另一侧也随之修改。",+ "scope": "覆盖 {pairs, plural, other {# 个文件对}},按向下 {depth, plural, other {# 层}}分组。已排除测试文件:测试本应随其代码一起变更。",+ "scopeWithTests": "覆盖 {pairs, plural, other {# 个文件对}},按向下 {depth, plural, other {# 层}}分组,包含测试。",+ "cleanTitle": "向下 {depth, plural, other {# 层}},每个一起变更的区域对之间都有导入关联",+ "cleanBody": "已检查 {pairs, plural, other {# 个}}跨区域一起变更的文件对。",+ "cleanEmpty": "在当前筛选条件下,没有跨区域一起变更的文件对。",+ "showing": "显示 {total, number} 组区域中排名前 {shown, number} 的。",+ "filePairs": "{count, plural, other {# 个文件对}}",+ "coChanges": "{count, plural, other {# 次共同变更}}",+ "lastTogether": "最近一次 {date}",+ "unexplained": "{count, number} 个文件对没有直接导入({pct}%)",+ "allExplained": "全部可解释",+ "promptLabel": "为你的智能体复制提示词",+ "bulkPromptLabel": "为这 {count, number} 组复制提示词",+ "promptTitle": "解耦提示词",+ "promptDescription": "一段可直接粘贴的提示词,让你的智能体找出这些区域在彼此没有依赖的情况下为何一起变更,并对偶然产生的耦合进行解耦。",+ "backToAreas": "全部区域对",+ "pairHeadline": "{pairs, plural, other {# 个文件对}}中有 {unexplained, number} 个没有直接导入。",+ "allFilePairs": "全部文件对",+ "browseFilePairs": "浏览全部文件对",+ "workspaceLink": "跨仓库耦合",+ "filters": {+ "label": "筛选耦合",+ "unexplained": "仅无法解释的",+ "crossArea": "仅跨区域的",+ "includeTests": "包含测试",+ "minSupport": "共同提交数",+ "anySupport": "不限",+ "atLeast": "{count}+",+ "recency": "共同变更时间",+ "anyTime": "全部时间",+ "lastDays": "历史中最近 {days} 天",+ "lastYear": "历史中最近一年",+ "depth": "分组深度",+ "autoDepth": "自动({depth})"+ },+ "unchecked": "此索引的部分内容早于依赖检查,因此无法判断哪些区域在没有导入关联的情况下一起变更。运行 repowise update 以补充该检查。",+ "hiddenMark": "区域之间没有导入关联"+ }},"coverage": {"jobRunning": "已有生成任务正在运行,请等它完成。",diff --git a/packages/web/src/app/repos/[id]/architecture/page.tsx b/packages/web/src/app/repos/[id]/architecture/page.tsxindex 50c8cbb36..3a8e269c4 100644--- a/packages/web/src/app/repos/[id]/architecture/page.tsx+++ b/packages/web/src/app/repos/[id]/architecture/page.tsx@@ -45,7 +45,7 @@import { use, useCallback, useEffect } from "react";import { useRouter } from "next/navigation";import { useTranslations } from "next-intl";-import { useQueryState, parseAsStringLiteral } from "nuqs";+import { useQueryState, useQueryStates, parseAsStringLiteral } from "nuqs";import { PageFrame } from "@repowise-dev/ui/shared/page-shell";import { ViewTabs } from "@repowise-dev/ui/shared/view-tabs";import { ErrorBoundary } from "@repowise-dev/ui/shared";@@ -55,6 +55,7 @@ import { SymbolTableWrapper as SymbolTable } from "@/components/symbols/symbol-timport { SymbolIndexHeader } from "@repowise-dev/ui/symbols";import { COUPLING_DISCLAIMER } from "@repowise-dev/ui/coupling";import { CouplingTab } from "@/components/coupling/coupling-tab";+import { couplingUrlParsers } from "@/components/coupling/coupling-url";// The curated layered view now lives under the dedicated Knowledge Graph route.const KNOWLEDGE_GRAPH_VIEWS = new Set(["layers"]);@@ -137,6 +138,7 @@ export default function ArchitecturePage({const [, setShow] = useQueryState("show");const [, setFocus] = useQueryState("focus");const [, setNode] = useQueryState("node");+ const [, setCouplingUrl] = useQueryStates(couplingUrlParsers);// The curated layers view now lives at /knowledge-graph. `?view=layers`// redirects there so shared links keep working.@@ -185,8 +187,9 @@ export default function ArchitecturePage({void setShow(null);void setNode(null);}+ if (id !== "coupling") void setCouplingUrl(null);},- [setView, setFocus, setSignal, setModule, setCommunity, setShow, setNode],+ [setView, setFocus, setSignal, setModule, setCommunity, setShow, setNode, setCouplingUrl],);const handleScopeChange = useCallback(diff --git a/packages/web/src/components/coupling/coupling-pair-panel.tsx b/packages/web/src/components/coupling/coupling-pair-panel.tsxnew file mode 100644index 000000000..6122d35c2--- /dev/null+++ b/packages/web/src/components/coupling/coupling-pair-panel.tsx@@ -0,0 +1,71 @@+"use client";++import { useState } from "react";+import useSWR from "swr";+import Link from "next/link";+import { useQueryState } from "nuqs";+import { useTranslations } from "next-intl";+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 { toFriendlyMessage } from "@repowise-dev/ui/lib/errors";+import type { CouplingFilters } from "@repowise-dev/types/coupling";+import { getCoupling } from "@/lib/api/coupling";++/** The route's own ceiling. Asking beyond it is rejected, not clamped. */+const MAX_LIMIT = 1000;+const INITIAL_LIMIT = 200;++export function LoadingRows() {+ return (+ <div className="space-y-2">+ {Array.from({ length: 6 }).map((_, i) => (+ <Skeleton key={i} className="h-12" />+ ))}+ </div>+ );+}++export interface CouplingPairPanelProps {+ repoId: string;+ repoName?: string | undefined;+ /** The list's filters at the depth it was grouped at, plus the pair's two areas. */+ query: CouplingFilters & { area?: string; partner?: string };+}++/**+ * One area pair's file pairs (or every file pair) in the existing explorer.+ * The host keys it by the open pair, so the page size and the pinned file+ * reset when the reader opens another pair; "Load more" keeps the explorer+ * mounted while the larger page loads.+ */+export function CouplingPairPanel({ repoId, repoName, query }: CouplingPairPanelProps) {+ const t = useTranslations("coupling");+ const [limit, setLimit] = useState(INITIAL_LIMIT);+ const [focus, setFocus] = useQueryState("focus");+ const { data, error, isValidating, mutate } = useSWR(+ ["coupling", repoId, query, limit],+ () => getCoupling(repoId, { ...query, limit }),+ { revalidateOnFocus: false, keepPreviousData: true },+ );++ if (error) {+ return (+ <ApiError title={t("loadFailed")} message={toFriendlyMessage(error)} onRetry={() => void mutate()} />+ );+ }+ if (!data) return <LoadingRows />;+ return (+ <CouplingExplorer+ data={data}+ repoLinkPrefix={`/repos/${repoId}`}+ {...(repoName ? { repoName } : {})}+ LinkComponent={Link}+ // Absent / bare `?focus=` → let the explorer open on the most-coupled hub.+ initialFocus={focus || undefined}+ onFocusChange={(value) => void setFocus(value)}+ {...(limit < MAX_LIMIT ? { onShowMore: () => setLimit(MAX_LIMIT) } : {})}+ loadingMore={isValidating}+ />+ );+}diff --git a/packages/web/src/components/coupling/coupling-tab.tsx b/packages/web/src/components/coupling/coupling-tab.tsxindex c019bbd40..4e19a0578 100644--- a/packages/web/src/components/coupling/coupling-tab.tsx+++ b/packages/web/src/components/coupling/coupling-tab.tsx@@ -1,74 +1,112 @@"use client";-import { useState } from "react";+import { useCallback } from "react";import useSWR from "swr";import Link from "next/link";-import { useQueryState } from "nuqs";+import { useQueryState, useQueryStates } from "nuqs";+import { useTranslations } from "next-intl";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 {+ ALL_FILE_PAIRS,+ CouplingAreaView,+ toCouplingFilters,+ type AreaPairRef,+ type CouplingAreaFilters,+} from "@repowise-dev/ui/coupling";import { toFriendlyMessage } from "@repowise-dev/ui/lib/errors";-import { useTranslations } from "next-intl";+import type { CouplingFilters } from "@repowise-dev/types/coupling";+import { getCouplingAreas } from "@/lib/api/coupling";+import { getWorkspace } from "@/lib/api/workspace";+import { useRepo } from "@/lib/hooks/use-repo";+import { useAreaCouplingCopy } from "./use-area-coupling-copy";+import { CouplingPairPanel, LoadingRows } from "./coupling-pair-panel";+import {+ couplingUrlParsers,+ filtersFromUrl,+ filtersToUrl,+ selectionFromUrl,+ selectionToUrl,+} from "./coupling-url";-/** The route's own ceiling. Asking beyond it is rejected, not clamped. */-const MAX_LIMIT = 1000;-const INITIAL_LIMIT = 200;+type Selection = AreaPairRef | typeof ALL_FILE_PAIRS | null;++/**+ * The file-pair query for the open selection, placed at the depth the list+ * was grouped at so the pair holds exactly the files its row counted; `null`+ * with nothing open or while that depth is not settled.+ */+function pairQueryFor(selection: Selection, wire: CouplingFilters, depth: number | undefined) {+ if (!selection || !depth) return null;+ if (selection === ALL_FILE_PAIRS) return { ...wire, depth };+ return { ...wire, depth, area: selection.source, partner: selection.target };+}/**- * 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, `?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.+ * Self-fetching host for the change-coupling Architecture tab. It opens on+ * area pairs (`/coupling/areas`); choosing one fetches its file pairs into the+ * existing explorer. Filters and the open pair live in the URL; the shared+ * package owns every pixel, so hosted gets the same view from a package bump.*/export function CouplingTab({ repoId }: { repoId: string }) {const t = useTranslations("coupling");- 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 copy = useAreaCouplingCopy();+ const [url, setUrl] = useQueryStates(couplingUrlParsers);+ const [, setFocus] = useQueryState("focus");+ const filters = filtersFromUrl(url);+ const selection = selectionFromUrl(url.pair);+ const wire = toCouplingFilters(filters);++ const areas = useSWR(["coupling-areas", repoId, wire], () => getCouplingAreas(repoId, wire), {+ revalidateOnFocus: false,+ keepPreviousData: true,+ });+ // Not while the list revalidates: the kept response may hold the old depth.+ const pairQuery = pairQueryFor(selection, wire, areas.isValidating ? undefined : areas.data?.depth);const { repo } = useRepo(repoId);- const [focus, setFocus] = useQueryState("focus");+ const { data: workspace } = useSWR("workspace:info", () => getWorkspace(), {+ revalidateOnFocus: false,+ });++ const onFiltersChange = useCallback(+ (next: CouplingAreaFilters) => void setUrl(filtersToUrl(next)),+ [setUrl],+ );+ const onSelectionChange = useCallback(+ (next: Selection) => {+ void setFocus(null);+ void setUrl({ pair: selectionToUrl(next) });+ },+ [setUrl, setFocus],+ );++ if (areas.error) {+ return (+ <ApiError+ title={t("loadFailed")}+ message={toFriendlyMessage(areas.error)}+ onRetry={() => void areas.mutate()}+ />+ );+ }+ if (!areas.data) return <LoadingRows />;return (- <div className="space-y-6">- {error ? (- <ApiError- title={t("loadFailed")}- message={toFriendlyMessage(error)}- onRetry={() => void mutate()}- />- ) : isLoading || !data ? (- <div className="space-y-4">- <Skeleton className="mx-auto h-[420px] w-full max-w-[820px] rounded-xl" />- <div className="space-y-2">- {Array.from({ length: 6 }).map((_, i) => (- <Skeleton key={i} className="h-10" />- ))}- </div>- </div>+ <CouplingAreaView+ data={areas.data}+ filters={filters}+ onFiltersChange={onFiltersChange}+ selection={selection}+ onSelectionChange={onSelectionChange}+ {...(repo?.name ? { repoName: repo.name } : {})}+ {...(workspace?.is_workspace ? { workspaceHref: "/workspace/co-changes" } : {})}+ LinkComponent={Link}+ copy={copy}+ >+ {pairQuery ? (+ <CouplingPairPanel key={url.pair ?? ""} repoId={repoId} repoName={repo?.name} query={pairQuery} />) : (- <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={(value) => void setFocus(value)}- {...(limit < MAX_LIMIT ? { onShowMore: () => setLimit(MAX_LIMIT) } : {})}- loadingMore={isValidating}- />+ <LoadingRows />)}- </div>+ </CouplingAreaView>);}diff --git a/packages/web/src/components/coupling/coupling-url.ts b/packages/web/src/components/coupling/coupling-url.tsnew file mode 100644index 000000000..26e568b22--- /dev/null+++ b/packages/web/src/components/coupling/coupling-url.ts@@ -0,0 +1,67 @@+import { parseAsBoolean, parseAsInteger, parseAsString } from "nuqs";+import {+ ALL_FILE_PAIRS,+ DEFAULT_AREA_FILTERS,+ parseAreaPair,+ serializeAreaPair,+ type AreaPairRef,+ type CouplingAreaFilters,+} from "@repowise-dev/ui/coupling";++/**+ * The Coupling tab's URL state. A value at its default leaves the URL, so a+ * shared link carries only what the reader changed. The Architecture page+ * clears every key here when the reader leaves the tab.+ */+export const couplingUrlParsers = {+ unexplained: parseAsBoolean.withDefault(DEFAULT_AREA_FILTERS.unexplained),+ cross: parseAsBoolean.withDefault(DEFAULT_AREA_FILTERS.crossArea),+ tests: parseAsBoolean.withDefault(DEFAULT_AREA_FILTERS.includeTests),+ min: parseAsInteger.withDefault(DEFAULT_AREA_FILTERS.minSupport),+ recent: parseAsInteger,+ depth: parseAsInteger,+ /** `a|b` for one area pair, `all` for every file pair. */+ pair: parseAsString,+};++type UrlState = {+ unexplained: boolean;+ cross: boolean;+ tests: boolean;+ min: number;+ recent: number | null;+ depth: number | null;+ pair: string | null;+};++export function filtersFromUrl(s: UrlState): CouplingAreaFilters {+ return {+ unexplained: s.unexplained,+ crossArea: s.cross,+ includeTests: s.tests,+ minSupport: Math.max(s.min, 0),+ recentDays: s.recent && s.recent > 0 ? s.recent : null,+ // The route accepts 1-6; a hand-edited link past that falls back to the default.+ depth: s.depth && s.depth > 0 && s.depth <= 6 ? s.depth : null,+ };+}++export function filtersToUrl(f: CouplingAreaFilters): Omit<UrlState, "pair"> {+ return {+ unexplained: f.unexplained,+ cross: f.crossArea,+ tests: f.includeTests,+ min: f.minSupport,+ recent: f.recentDays,+ depth: f.depth,+ };+}++export function selectionFromUrl(raw: string | null): AreaPairRef | typeof ALL_FILE_PAIRS | null {+ return raw === ALL_FILE_PAIRS ? ALL_FILE_PAIRS : parseAreaPair(raw);+}++export function selectionToUrl(sel: AreaPairRef | typeof ALL_FILE_PAIRS | null): string | null {+ if (sel === null) return null;+ return sel === ALL_FILE_PAIRS ? ALL_FILE_PAIRS : serializeAreaPair(sel);+}diff --git a/packages/web/src/components/coupling/use-area-coupling-copy.ts b/packages/web/src/components/coupling/use-area-coupling-copy.tsnew file mode 100644index 000000000..6c7ecaec5--- /dev/null+++ b/packages/web/src/components/coupling/use-area-coupling-copy.ts@@ -0,0 +1,53 @@+import { useMemo } from "react";+import { useTranslations } from "next-intl";+import type { AreaCouplingCopyOverrides } from "@repowise-dev/ui/coupling";++/** The area coupling view's copy from `coupling.area.*`, stable per locale. */+export function useAreaCouplingCopy(): AreaCouplingCopyOverrides {+ const t = useTranslations("coupling.area");+ return useMemo(+ () => ({+ rootLabel: t("rootLabel"),+ ledeLabel: t("ledeLabel"),+ ledeUnit: (count: number) => t("ledeUnit", { count }),+ verdict: (count: number) => t("verdict", { count }),+ scope: (pairs: number, depth: number, testsIncluded: boolean) =>+ t(testsIncluded ? "scopeWithTests" : "scope", { pairs, depth }),+ cleanTitle: (depth: number) => t("cleanTitle", { depth }),+ cleanBody: (pairs: number) => (pairs > 0 ? t("cleanBody", { pairs }) : t("cleanEmpty")),+ unchecked: t("unchecked"),+ hiddenMark: t("hiddenMark"),+ showing: (shown: number, total: number) => t("showing", { shown, total }),+ filePairs: (count: number) => t("filePairs", { count }),+ coChanges: (count: number) => t("coChanges", { count }),+ lastTogether: (date: string) => t("lastTogether", { date }),+ unexplained: (count: number, pct: number) => t("unexplained", { count, pct }),+ allExplained: t("allExplained"),+ promptLabel: t("promptLabel"),+ bulkPromptLabel: (count: number) => t("bulkPromptLabel", { count }),+ promptTitle: t("promptTitle"),+ promptDescription: t("promptDescription"),+ backToAreas: t("backToAreas"),+ pairHeadline: (unexplained: number, pairs: number) =>+ t("pairHeadline", { unexplained, pairs }),+ allFilePairs: t("allFilePairs"),+ browseFilePairs: t("browseFilePairs"),+ workspaceLink: t("workspaceLink"),+ filters: {+ label: t("filters.label"),+ unexplained: t("filters.unexplained"),+ crossArea: t("filters.crossArea"),+ includeTests: t("filters.includeTests"),+ minSupport: t("filters.minSupport"),+ anySupport: t("filters.anySupport"),+ atLeast: (count: number) => t("filters.atLeast", { count }),+ recency: t("filters.recency"),+ anyTime: t("filters.anyTime"),+ lastDays: (days: number) => t(days >= 365 ? "filters.lastYear" : "filters.lastDays", { days }),+ depth: t("filters.depth"),+ autoDepth: (depth: number) => t("filters.autoDepth", { depth }),+ },+ }),+ [t],+ );+}diff --git a/tests/unit/conftest.py b/tests/unit/conftest.pyindex 016d5a4b1..d0ee332a7 100644--- a/tests/unit/conftest.py+++ b/tests/unit/conftest.py@@ -26,9 +26,12 @@ def fresh_test_map_cache():index stamp, so the process-wide index-state caches start empty per test."""from repowise.core.analysis.test_reachability import clear_test_map_cachefrom repowise.server.services.areas import clear_area_cache+ from repowise.server.services.coupling import clear_coupling_cacheclear_test_map_cache()clear_area_cache()+ clear_coupling_cache()yieldclear_test_map_cache()clear_area_cache()+ clear_coupling_cache()diff --git a/tests/unit/coupling/test_area_coupling.py b/tests/unit/coupling/test_area_coupling.pynew file mode 100644index 000000000..9def09dc5--- /dev/null+++ b/tests/unit/coupling/test_area_coupling.py@@ -0,0 +1,140 @@+"""Area-level coupling: placing file pairs in areas, filtering, and folding them."""++from __future__ import annotations++from repowise.core.analysis.areas import area_at, area_depth, choose_depth+from repowise.core.analysis.coupling import (+ MAX_DEPTH,+ CouplingEdge,+ CouplingScope,+ area_coupling,+ area_placer,+ coupled_areas,+ linked_area_pairs,+ place_edges,+)+++def _edge(+ a: str,+ b: str,+ strength: float = 1.0,+ *,+ support: int = 3,+ structural: str | None = "unexplained",+ last: str | None = "2026-06-01",+) -> CouplingEdge:+ return CouplingEdge(a, b, strength, last, support=support, structural=structural)+++def _no_tests(path: str) -> bool:+ return path.startswith("tests/")+++EDGES = [+ _edge("src/ui/a.ts", "src/web/b.ts", 5.0),+ _edge("src/ui/a.ts", "src/ui/c.ts", 4.0, structural="corroborated"),+ _edge("src/core/x.py", "src/web/b.ts", 3.0, structural="corroborated", support=2),+ _edge("src/core/x.py", "tests/test_x.py", 2.0),+ _edge("src/ui/d.ts", "src/web/e.ts", 1.0, last="2025-01-01"),+ _edge("README.md", "src/core/x.py", 0.5, structural="not_applicable"),+]+++def test_area_at_partitions_by_level():+ assert area_at("src/ui/a.ts", 1) == "src"+ assert area_at("src/ui/a.ts", 2) == "src/ui"+ # Shallower than the depth: the file's own directory.+ assert area_at("src/ui/a.ts", 5) == "src/ui"+ assert area_at("README.md", 2) == ""+++def test_placement_stamps_cross_area_and_keeps_order():+ placed = place_edges(EDGES, CouplingScope(depth=2), is_test=_no_tests)+ assert [p.edge.strength for p in placed] == [5.0, 4.0, 3.0, 2.0, 1.0, 0.5]+ assert placed[0].edge.cross_area is True+ assert (placed[1].source_area, placed[1].edge.cross_area) == ("src/ui", False)+++def test_filters_narrow_before_counting():+ def keep(**kw) -> list[tuple[str, str]]:+ placed = place_edges(EDGES, CouplingScope(depth=2, **kw), is_test=_no_tests)+ return [(p.edge.source, p.edge.target) for p in placed]++ assert len(keep(unexplained=True)) == 3+ assert ("src/ui/a.ts", "src/ui/c.ts") not in keep(cross_area=True)+ assert ("src/core/x.py", "tests/test_x.py") not in keep(exclude_tests=True)+ assert ("src/core/x.py", "src/web/b.ts") not in keep(min_support=3)+ # Recency counts back from the newest co-change in the index, not today.+ assert ("src/ui/d.ts", "src/web/e.ts") not in keep(recent_days=90)+ assert keep(area="src/ui", partner="src/web") == [+ ("src/ui/a.ts", "src/web/b.ts"),+ ("src/ui/d.ts", "src/web/e.ts"),+ ]+++def test_a_rooted_view_names_outside_files_at_the_roots_level():+ placed = place_edges(EDGES, CouplingScope(depth=1, root="src/ui"), is_test=_no_tests)+ assert {(p.source_area, p.target_area) for p in placed} == {+ ("src/ui", "src/web"),+ ("src/ui", "src/ui"),+ }+++def test_area_pairs_rank_unexplained_first_and_carry_their_file_pairs():+ placed = place_edges(EDGES, CouplingScope(depth=2, cross_area=True), is_test=_no_tests)+ out = area_coupling(placed, top_pairs=1)+ first = out["area_pairs"][0]+ assert (first["source"], first["target"]) == ("src/ui", "src/web")+ assert first["pairs"] == 2 and first["unexplained_share"] == 1.0+ assert first["co_changes"] == 6 and first["last_co_change"] == "2026-06-01"+ assert [p["source"] for p in first["top_pairs"]] == ["src/ui/a.ts"]+ totals = out["totals"]+ assert totals["pairs"] == len(placed) == totals["cross_area_pairs"]+ assert totals["unexplained_area_pairs"] == 2 and totals["unlabelled_pairs"] == 0+ web = next(a for a in out["areas"] if a["path"] == "src/web")+ assert web["pairs"] == 3+++def test_top_pairs_lead_with_unexplained_ones():+ edges = [_edge("a/1", "b/1", 9.0, structural="corroborated"), _edge("a/2", "b/2", 1.0)]+ placed = place_edges(edges, CouplingScope(depth=1), is_test=_no_tests)+ tops = area_coupling(placed)["area_pairs"][0]["top_pairs"]+ assert [t["source"] for t in tops] == ["a/2", "a/1"]+++def test_coupled_areas_names_partners_at_the_areas_depth():+ out = coupled_areas(EDGES, "src/ui", keep=lambda e: not _no_tests(e.target))+ assert [(c["path"], c["pairs"], c["unexplained_pairs"]) for c in out] == [("src/web", 2, 2)]+ assert coupled_areas(EDGES, "") == []+++def default_depth(paths, root=""):+ """Coupling's default depth below *root*, as the service chooses it."""+ return choose_depth(paths, base=root, min_areas=1, small=0, max_depth=MAX_DEPTH) - area_depth(root)+++def test_default_depth_splits_a_dominant_area():+ paths = ["src/ui/a.ts", "src/web/b.ts", "src/core/x.py", "docs/r.md"]+ assert default_depth(paths) == 2+ assert default_depth(["a/x.py", "b/y.py"]) == 1+ # Nothing deeper to split into.+ assert default_depth(["src/a.py", "src/b.py"]) == 1+ assert default_depth(paths, root="src") == 1+++def test_a_dependency_anywhere_between_two_areas_makes_their_pair_expected():+ scope = CouplingScope(depth=2, cross_area=True)+ placed = place_edges(EDGES, scope, is_test=_no_tests)+ # One import from web into ui, between files that never co-change.+ linked = linked_area_pairs([("src/web/z.ts", "src/ui/y.ts")], area_placer(scope))+ assert linked == {("src/ui", "src/web")}+ out = area_coupling(placed, linked=linked)+ verdict = {(p["source"], p["target"]): (p["linked"], p["hidden"]) for p in out["area_pairs"]}+ assert verdict[("src/ui", "src/web")] == (True, False)+ # core and tests: unexplained pairs and no dependency at all.+ assert verdict[("src/core", "tests")] == (False, True)+ # core and web: corroborated pairs only, so nothing to hide.+ assert verdict[("src/core", "src/web")] == (False, False)+ assert out["totals"]["hidden_area_pairs"] == 1+ assert out["area_pairs"][0]["hidden"] is Truediff --git a/tests/unit/server/conftest.py b/tests/unit/server/conftest.pyindex 54bad97dc..6b351adc2 100644--- a/tests/unit/server/conftest.py+++ b/tests/unit/server/conftest.py@@ -37,6 +37,7 @@ def _create_test_app():changes,code_health,costs,+ coupling,dead_code,decisions,doc_drift,@@ -107,6 +108,7 @@ def _create_test_app():app.include_router(owners.router)app.include_router(modules.router)app.include_router(areas.router)+ app.include_router(coupling.router)app.include_router(decisions.router)app.include_router(episodes.router)app.include_router(external_systems.router)diff --git a/tests/unit/server/test_coupling.py b/tests/unit/server/test_coupling.pyindex 1c5448b0d..d9690aba3 100644--- a/tests/unit/server/test_coupling.py+++ b/tests/unit/server/test_coupling.py@@ -53,6 +53,7 @@ def test_edge_wire_shape() -> None:"confidence_ba": 0.1,"structural": "unexplained","dependency_kind": None,+ "cross_area": None,}@@ -69,6 +70,7 @@ def test_an_edge_from_an_older_index_still_serializes() -> None:"confidence_ba": None,"structural": None,"dependency_kind": None,+ "cross_area": None,}diff --git a/tests/unit/server/test_coupling_routes.py b/tests/unit/server/test_coupling_routes.pynew file mode 100644index 000000000..54f84abb0--- /dev/null+++ b/tests/unit/server/test_coupling_routes.py@@ -0,0 +1,141 @@+"""/coupling filters, /coupling/areas and the area card's coupled areas over a seeded store."""++from __future__ import annotations++import json++from httpx import AsyncClient++from repowise.core.persistence import crud+from repowise.core.persistence.models import GraphEdge+from tests.unit.server.conftest import create_test_repo+++def _partner(path: str, count: float, structural: str, support: int = 4) -> dict:+ return {+ "file_path": path,+ "co_change_count": count,+ "frequency": support,+ "self_commits": 10,+ "partner_commits": 10,+ "last_co_change": "2026-06-01",+ "structural": structural,+ }+++PARTNERS = {+ "src/ui/a.ts": [+ _partner("src/web/b.ts", 3.0, "unexplained"),+ _partner("src/ui/c.ts", 2.0, "corroborated"),+ _partner("src/api/q.py", 2.5, "unexplained"),+ ],+ "src/core/x.py": [+ _partner("src/web/b.ts", 1.0, "corroborated", support=2),+ _partner("tests/test_x.py", 0.5, "unexplained"),+ ],+}+++async def _seed(app, client: AsyncClient) -> str:+ repo_id = (await create_test_repo(client))["id"]+ async with app.state.session_factory() as session:+ await crud.save_health_metrics(+ session,+ repo_id,+ [+ {+ "file_path": path,+ "score": 8.0,+ "max_ccn": 1,+ "max_nesting": 1,+ "nloc": 10,+ "duplication_pct": 0.0,+ "has_test_file": False,+ "line_coverage_pct": None,+ "branch_coverage_pct": None,+ "module": path.split("/")[1],+ }+ for path in ("src/ui/a.ts", "src/ui/c.ts", "src/web/b.ts", "src/core/x.py")+ ],+ )+ for path, partners in PARTNERS.items():+ await crud.upsert_git_metadata(+ session,+ repository_id=repo_id,+ file_path=path,+ co_change_partners_json=json.dumps(partners),+ )+ # web imports a different ui file: ui and web are linked as areas even+ # though the co-changing pair has no edge of its own.+ session.add(+ GraphEdge(+ repository_id=repo_id,+ source_node_id="src/web/b.ts",+ target_node_id="src/ui/c.ts",+ edge_type="imports",+ )+ )+ await session.commit()+ return repo_id+++async def test_graph_filters_and_stamps_cross_area(app, client):+ repo_id = await _seed(app, client)+ url = f"/api/repos/{repo_id}/coupling"+ whole = (await client.get(url)).json()+ assert whole["total_edges"] == 5 and whole["depth"] == 2+ cross = {(e["source"], e["target"]): e["cross_area"] for e in whole["edges"]}+ assert cross[("src/ui/a.ts", "src/ui/c.ts")] is False+ assert cross[("src/ui/a.ts", "src/web/b.ts")] is True++ hidden = (+ await client.get(url, params={"unexplained": True, "exclude_tests": True})+ ).json()+ assert {(e["source"], e["target"]) for e in hidden["edges"]} == {+ ("src/ui/a.ts", "src/web/b.ts"),+ ("src/api/q.py", "src/ui/a.ts"),+ }+ assert hidden["total_edges"] == 2 and hidden["coupled_files"] == 3++ between = (+ await client.get(url, params={"area": "src/core", "partner": "src/web"})+ ).json()+ assert [(e["source"], e["target"]) for e in between["edges"]] == [+ ("src/core/x.py", "src/web/b.ts")+ ]+ assert (await client.get(url, params={"min_support": 3})).json()["total_edges"] == 4+ assert (await client.get(url, params={"partner": "src/web"})).status_code == 422+++async def test_only_areas_with_no_dependency_between_them_are_hidden(app, client):+ repo_id = await _seed(app, client)+ out = (+ await client.get(+ f"/api/repos/{repo_id}/coupling/areas",+ params={"cross_area": True, "exclude_tests": True, "depth": 2},+ )+ ).json()+ assert out["depth"] == 2 and out["root"] == ""+ totals = out["totals"]+ assert (totals["area_pairs"], totals["unexplained_area_pairs"]) == (3, 2)+ assert (totals["hidden_area_pairs"], totals["unlabelled_pairs"]) == (1, 0)+ verdicts = {(p["source"], p["target"]): (p["linked"], p["hidden"]) for p in out["area_pairs"]}+ # ui and web import each other elsewhere: expected coupling, not a finding.+ assert verdicts[("src/ui", "src/web")] == (True, False)+ assert verdicts[("src/api", "src/ui")] == (False, True)+ # Hidden pairs rank first.+ assert (out["area_pairs"][0]["source"], out["area_pairs"][0]["target"]) == ("src/api", "src/ui")+ assert out["area_pairs"][0]["top_pairs"][0]["structural"] == "unexplained"+ missing = await client.get("/api/repos/nope/coupling/areas")+ assert missing.status_code == 404+++async def test_area_card_lists_the_areas_it_changes_with(app, client):+ repo_id = await _seed(app, client)+ card = (await client.get(f"/api/repos/{repo_id}/areas/src/ui")).json()+ assert [+ (c["path"], c["unexplained_pairs"], c["linked"], c["hidden"]) for c in card["coupled_areas"]+ ] == [("src/web", 1, True, False), ("src/api", 1, False, True)]+ # The test partner is left out, so the core card lists web alone.+ core = (await client.get(f"/api/repos/{repo_id}/areas/src/core")).json()+ assert [c["path"] for c in core["coupled_areas"]] == ["src/web"]