Skip to content

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

feat(coupling): say whether co-changing files should change together (#1972)

Raghav Chamadiya63bf8069fd1e
diff --git a/packages/api-client/src/hosted.test.ts b/packages/api-client/src/hosted.test.ts
index a60516835..c5683f6f9 100644
--- a/packages/api-client/src/hosted.test.ts
+++ b/packages/api-client/src/hosted.test.ts
@@ -547,10 +547,35 @@ describe("getCoupling", () => {
it("passes a well-formed payload through unchanged", async () => {
const body = {
nodes: [{ file_path: "a.rs", module: "src", score: 7, nloc: 100 }],
- edges: [{ source: "a.rs", target: "b.rs", strength: 3, last_co_change: "2026-06-01" }],
+ edges: [
+ {
+ source: "a.rs",
+ target: "b.rs",
+ strength: 3,
+ last_co_change: "2026-06-01",
+ support: 11,
+ confidence_ab: 0.9,
+ confidence_ba: 0.1,
+ structural: "unexplained",
+ },
+ ],
total_edges: 9,
};
const { p } = provider([REPOS_ROUTE, ["/coupling", body]]);
expect(await p.getCoupling("repo-1")).toEqual(body);
});
+
+ it("defaults the support fields a pre-support snapshot omits", async () => {
+ // The wire type declares them required; a snapshot written before they
+ // existed has neither, and the table reads them straight into a cell.
+ const wire = [{ source: "a.rs", target: "b.rs", strength: 3, last_co_change: null }];
+ const { p } = provider([REPOS_ROUTE, ["/coupling", { edges: wire, total_edges: 1 }]]);
+ const { edges } = await p.getCoupling("repo-1");
+ expect(edges[0]).toMatchObject({
+ support: 0,
+ confidence_ab: null,
+ confidence_ba: null,
+ structural: null,
+ });
+ });
});
diff --git a/packages/api-client/src/hosted.ts b/packages/api-client/src/hosted.ts
index bf2cbfaa4..845b64182 100644
--- a/packages/api-client/src/hosted.ts
+++ b/packages/api-client/src/hosted.ts
@@ -16,7 +16,7 @@
*/
import type { ArchitectureView, C4L1, C4L2, C4L3 } from "@repowise-dev/ui/c4";
-import type { CouplingGraphResponse } from "@repowise-dev/types/coupling";
+import type { CouplingEdge, CouplingGraphResponse } from "@repowise-dev/types/coupling";
import type { FileDetailResponse, FilesIndexResponse } from "@repowise-dev/types/files";
import type {
ChurnComplexityResponse,
@@ -221,11 +221,12 @@ interface WireFilesIndex {
/**
* Coupling as it arrives, not as `CouplingGraphResponse` promises: a snapshot
- * written before the coupling analyzer ran omits `nodes`/`edges` entirely.
+ * written before the coupling analyzer ran omits `nodes`/`edges` entirely, and
+ * one written before support/confidence existed omits those per edge.
*/
interface WireCoupling {
nodes?: CouplingGraphResponse["nodes"];
- edges?: CouplingGraphResponse["edges"];
+ edges?: Partial<CouplingEdge>[];
total_edges?: number;
}
@@ -842,7 +843,18 @@ export function createHostedProvider(config: HostedProviderConfig): HostedProvid
async getCoupling(repoId, opts): Promise<CouplingGraphResponse> {
const res = await snapGet<WireCoupling>(repoId, "/coupling", opts);
const nodes = res.nodes ?? [];
- const edges = res.edges ?? [];
+ // An older snapshot has no support/confidence/structural. Zero and null
+ // read as "not measured", which the table already renders as a dash.
+ const edges: CouplingEdge[] = (res.edges ?? []).map((e) => ({
+ source: e.source ?? "",
+ target: e.target ?? "",
+ strength: e.strength ?? 0,
+ last_co_change: e.last_co_change ?? null,
+ support: e.support ?? 0,
+ confidence_ab: e.confidence_ab ?? null,
+ confidence_ba: e.confidence_ba ?? null,
+ structural: e.structural ?? null,
+ }));
// Falling back to the post-cap length understates the pre-cap count, but
// an honest "showing N of N" beats `NaN` downstream.
return { nodes, edges, total_edges: res.total_edges ?? edges.length };
diff --git a/packages/core/src/repowise/core/analysis/coupling/graph.py b/packages/core/src/repowise/core/analysis/coupling/graph.py
index e924f25be..801ee718e 100644
--- a/packages/core/src/repowise/core/analysis/coupling/graph.py
+++ b/packages/core/src/repowise/core/analysis/coupling/graph.py
@@ -16,9 +16,14 @@ export.
Honesty rules:
* Co-change is a *temporal* hint (files committed together), not a verified
- code dependency -- the strength is the decay-weighted count the indexer
- already thresholds (``MIN_CO_CHANGE_WEIGHT``); we surface it verbatim and
- never invent one.
+ code dependency. ``strength`` is the indexer's decay-weighted score, surfaced
+ verbatim; ``support`` is the plain number of shared commits behind it.
+* ``confidence_ab`` and ``confidence_ba`` are read off the two files' own commit
+ totals, so they can disagree: a file that never changes without its partner
+ is a different finding from two files that merely change often. Both come
+ from the same walk as ``support``, so the ratio is not mixing populations.
+* ``structural`` says whether the dependency graph explains the pair. Absent
+ for a file the parser never ingested, where there is no edge to look for.
* We do **not** fabricate a "strengthening / weakening" trend: co-change history
is not snapshotted, so a trend is not derivable. ``strength`` (magnitude) and
``last_co_change`` (recency) are the only honest encodings.
@@ -82,14 +87,51 @@ class CouplingEdge:
``source``/``target`` are sorted lexicographically so the pair is stable and
deduplicated. ``strength`` is the decay-weighted co-change count (verbatim
- from the indexer; not a percentage). ``last_co_change`` is the ISO date of
- the most recent shared commit, or ``None`` if unknown.
+ from the indexer; not a percentage). ``support`` is how many commits touched
+ both. ``confidence_ab`` is the share of ``source``'s commits that also
+ touched ``target``, and ``confidence_ba`` the reverse; either is ``None``
+ when the commit total is unknown. ``last_co_change`` is the ISO date of the
+ most recent shared commit, or ``None`` if unknown.
"""
source: str
target: str
strength: float
last_co_change: str | None
+ support: int = 0
+ confidence_ab: float | None = None
+ confidence_ba: float | None = None
+ structural: str | None = None
+
+
+@dataclass(frozen=True)
+class _Pair:
+ """One pair mid-merge, before it becomes an edge."""
+
+ strength: float
+ last: str | None
+ support: int
+ commits_a: int
+ commits_b: int
+ structural: str | None
+
+ def merge(self, other: _Pair) -> _Pair:
+ """Combine the two directions of the same pair, keeping the best of each."""
+ return _Pair(
+ strength=max(self.strength, other.strength),
+ last=max((d for d in (self.last, other.last) if d), default=None),
+ support=max(self.support, other.support),
+ commits_a=max(self.commits_a, other.commits_a),
+ commits_b=max(self.commits_b, other.commits_b),
+ structural=self.structural or other.structural,
+ )
+
+
+def _ratio(support: int, commits: int) -> float | None:
+ """Share of *commits* that also touched the partner, or ``None`` if unknown."""
+ if support <= 0 or commits <= 0:
+ return None
+ return round(min(support / commits, 1.0), 3)
@dataclass
@@ -122,28 +164,41 @@ def coupling_graph(
couplings; ``total_edges`` reports the pre-cap count for an honest "showing
N of M" line. Only files referenced by a kept edge become nodes.
"""
- # Deduplicate symmetric partner records into undirected edges.
- best: dict[tuple[str, str], tuple[float, str | None]] = {}
+ # 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):
dst = partner.file_path
if dst == src or partner.weight <= 0:
continue
- strength, last = partner.weight, partner.last_co_change
key = canonical_pair(src, dst)
+ # Orient the record's two commit totals onto the canonical pair.
+ forward = src == key[0]
+ seen = _Pair(
+ strength=partner.weight,
+ last=partner.last_co_change,
+ support=partner.support,
+ commits_a=partner.self_commits if forward else partner.partner_commits,
+ commits_b=partner.partner_commits if forward else partner.self_commits,
+ structural=partner.structural,
+ )
prev = best.get(key)
- if prev is None:
- best[key] = (strength, last)
- else:
- prev_strength, prev_last = prev
- best[key] = (
- max(prev_strength, strength),
- max((d for d in (prev_last, last) if d), default=None),
- )
+ best[key] = seen if prev is None else prev.merge(seen)
edges = [
- CouplingEdge(source=a, target=b, strength=round(strength, 2), last_co_change=last)
- for (a, b), (strength, last) in best.items()
+ CouplingEdge(
+ source=a,
+ target=b,
+ strength=round(pair.strength, 4),
+ last_co_change=pair.last,
+ support=pair.support,
+ confidence_ab=_ratio(pair.support, pair.commits_a),
+ confidence_ba=_ratio(pair.support, pair.commits_b),
+ structural=pair.structural,
+ )
+ for (a, b), pair in best.items()
]
edges.sort(key=lambda e: e.strength, reverse=True)
total = len(edges)
diff --git a/packages/core/src/repowise/core/analysis/graph_view.py b/packages/core/src/repowise/core/analysis/graph_view.py
index ecfa18bec..7c5439004 100644
--- a/packages/core/src/repowise/core/analysis/graph_view.py
+++ b/packages/core/src/repowise/core/analysis/graph_view.py
@@ -13,6 +13,8 @@ from __future__ import annotations
from typing import Any, Protocol
+from ..ingestion.models import FILE_DEPENDENCY_EDGE_TYPES
+
__all__ = ["HasEdge", "ImportEdgeView"]
@@ -21,6 +23,10 @@ class HasEdge(Protocol):
def has_edge(self, src: str, dst: str, key: str = "imports") -> bool: ...
+ def has_dependency(self, a: str, b: str) -> bool: ...
+
+ def knows(self, path: str) -> bool: ...
+
class ImportEdgeView:
"""``HasEdge`` over a NetworkX DiGraph, matched on the ``edge_type`` attribute.
@@ -47,3 +53,39 @@ class ImportEdgeView:
except Exception:
return False
return data.get("edge_type") == key
+
+ def has_dependency(self, a: str, b: str) -> bool:
+ """Whether any file-level dependency joins the two, either direction.
+
+ ``imports`` is only one of these; matching it alone reports a pair as
+ unexplained when a type reference or a framework binding already
+ accounts for it.
+ """
+ return self._typed(a, b) or self._typed(b, a)
+
+ def _typed(self, src: str, dst: str) -> bool:
+ g = self._graph
+ if g is None:
+ return False
+ try:
+ if not g.has_edge(src, dst):
+ return False
+ data = g.get_edge_data(src, dst) or {}
+ except Exception:
+ return False
+ return data.get("edge_type") in FILE_DEPENDENCY_EDGE_TYPES
+
+ def knows(self, path: str) -> bool:
+ """Whether the parser ingested this file, so an edge is possible at all.
+
+ A lockfile or a changelog is tracked by git and co-changes constantly,
+ but never becomes a node, so it has no edge to find and its absence
+ says nothing.
+ """
+ g = self._graph
+ if g is None:
+ return False
+ try:
+ return path in g
+ except Exception:
+ return False
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/base.py b/packages/core/src/repowise/core/analysis/health/biomarkers/base.py
index 69ead053c..5a85146dd 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/base.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/base.py
@@ -70,11 +70,6 @@ class FileContext:
# Thin graph view exposing only ``has_edge``. ``None`` on test fixtures
# that never construct a graph.
graph_view: HasEdge | None = None
- # Repo-wide per-file commit totals (``commit_count_total`` from
- # git_meta), keyed by repo-relative POSIX path. Used by
- # ``hidden_coupling`` to compute correlation denominators against
- # the partner file. Empty when git indexing was skipped.
- repo_commit_counts: dict[str, int] = field(default_factory=dict)
# Per-line blame index produced by the FULL git tier (see
# ``ingestion.git_indexer.function_blame``). ``None`` on ESSENTIAL
# tier until the FULL-tier backfill (``backfill_full_tier()``) runs;
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/co_change_scatter.py b/packages/core/src/repowise/core/analysis/health/biomarkers/co_change_scatter.py
index 2d1506838..78210b2f5 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/co_change_scatter.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/co_change_scatter.py
@@ -7,9 +7,9 @@ rippling across the codebase. This is the breadth complement to
flag a file coupled to *many* others regardless of whether the links are
declared.
-Reads ``git_meta["co_change_partners_json"]`` (the decay-weighted partner list
-the git indexer already stores). **scatter** = the number of distinct partners
-whose ``co_change_count`` clears the indexer's recording threshold (2.0).
+Reads ``git_meta["co_change_partners_json"]`` (the partner list the git indexer
+already stores). **scatter** = the number of distinct partners recorded for the
+file, which the indexer has already filtered to pairs sharing real commits.
Fires when the file is actively changing and broadly coupled:
@@ -28,15 +28,15 @@ from ....co_change import parse_partners
from ..models import Severity
from .base import BiomarkerResult, FileContext
-_MIN_PARTNER_WEIGHT = 2.0
_SCATTER_THRESHOLD = 8
_HIGH_SCATTER = 15
_MIN_COMMITS_90D = 3
def _count_scatter(meta: dict[str, Any]) -> int:
- partners = parse_partners(meta.get("co_change_partners_json"))
- return sum(1 for p in partners if p.weight >= _MIN_PARTNER_WEIGHT)
+ # No second cutoff here: the indexer already dropped pairs that share too
+ # few commits, so every recorded partner counts.
+ return len(parse_partners(meta.get("co_change_partners_json")))
def _as_int(value: object, default: int = 0) -> int:
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/hidden_coupling.py b/packages/core/src/repowise/core/analysis/health/biomarkers/hidden_coupling.py
index aae488f38..51fcc31f0 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/hidden_coupling.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/hidden_coupling.py
@@ -1,20 +1,31 @@
"""Hidden Coupling — files that change together but don't import each other.
-Joins two existing signals: ``co_change_partners_json`` (from the git
-indexer) and the file-level import edges in the dependency graph. A
-high correlation between commits of files A and B that have no static
-dependency between them captures behavioral coupling invisible to a
-pure type/import analyzer — shared protocols, parallel config, hidden
-test fixtures, copy-pasted constants.
+Reads the co-change records the git indexer persists, each already carrying
+what the dependency graph says about the pair. A high correlation between
+commits of files A and B that no dependency explains captures behavioral
+coupling invisible to a pure type/import analyzer — shared protocols,
+parallel config, hidden test fixtures, copy-pasted constants.
Fires when:
-- ``commit_count_total`` for both files is at or above the noise floor
-- ``co_change_count(A, B) / min(total_A, total_B) >= 0.5``
-- there is **no** ``imports`` edge in either direction
+- both files clear the commit noise floor
+- ``shared_commits(A, B) / min(commits_A, commits_B) >= 0.5``
+- the graph does not explain the pair, and could have: a file the parser
+ never ingested (a lockfile, a changelog) carries no edge either way, so
+ its absence is not evidence
- the pair is not a test ↔ production pairing (those are expected to
co-change)
+Counts come from the co-change walk itself. ``commit_count_total`` looks like
+the denominator but is not one: it is collected over a shorter window and
+only for files with a code extension, so dividing by it mixes two
+populations and understates every ratio it does not simply zero.
+
+An index written before the walk recorded those counts carries neither them
+nor the structural label, and yields no findings until it is rebuilt. Silence
+is the honest answer there: without the label the detector cannot tell a pair
+the graph explains from one it does not.
+
Tier-aware: when ``co_change_partners_json`` is empty (ESSENTIAL git
tier) the detector short-circuits to zero findings. The empty
short-circuit is explicit so backfill behavior is testable.
@@ -22,7 +33,7 @@ short-circuit is explicit so backfill behavior is testable.
from __future__ import annotations
-from ....co_change import parse_partners
+from ....co_change import STRUCTURAL_UNEXPLAINED, parse_partners
from ....test_paths import is_test_to_production_pair
from ..models import Severity
from .base import BiomarkerResult, FileContext
@@ -41,14 +52,7 @@ _MAX_FINDINGS_PER_FILE = 3
_MIN_CO_CHANGE_FOR_HIGH = 8
-def _as_int(value: object, default: int = 0) -> int:
- try:
- return int(value or 0) # type: ignore[arg-type]
- except (TypeError, ValueError):
- return default
-
-
-def _severity_for(correlation: float, co_count: float) -> Severity:
+def _severity_for(correlation: float, co_count: int) -> Severity:
# Confidence-weight by absolute sample size: below the co-change floor the
# ratio isn't trustworthy enough to assert HIGH/CRITICAL, so cap at MEDIUM.
if co_count < _MIN_CO_CHANGE_FOR_HIGH:
@@ -71,25 +75,22 @@ class HiddenCouplingDetector:
if not partners:
return []
- total_self = _as_int(meta.get("commit_count_total"))
- if total_self < _MIN_COMMITS:
- return []
-
- graph = ctx.graph_view
- counts = ctx.repo_commit_counts or {}
-
- candidates: list[tuple[float, str, float]] = []
+ candidates: list[tuple[float, str, int, int, int]] = []
for partner in partners:
- partner_path, co_count = partner.file_path, partner.weight
+ partner_path = partner.file_path
if partner_path == ctx.file_path:
continue
- partner_total = counts.get(partner_path, 0)
- if partner_total < _MIN_COMMITS:
+ # Only a pair the graph could have explained and did not.
+ if partner.structural != STRUCTURAL_UNEXPLAINED:
+ continue
+ total_self = partner.self_commits
+ partner_total = partner.partner_commits
+ if total_self < _MIN_COMMITS or partner_total < _MIN_COMMITS:
continue
denom = min(total_self, partner_total)
if denom <= 0:
continue
- correlation = co_count / denom
+ correlation = partner.support / denom
if correlation < _MIN_CORRELATION:
continue
# Test ↔ production pairs are expected to co-change, so they carry
@@ -98,14 +99,9 @@ class HiddenCouplingDetector:
ctx.file_path, partner_path, code_language=ctx.language
):
continue
- # Skip when an explicit import edge already documents the
- # coupling.
- if graph is not None and (
- graph.has_edge(ctx.file_path, partner_path, "imports")
- or graph.has_edge(partner_path, ctx.file_path, "imports")
- ):
- continue
- candidates.append((correlation, partner_path, co_count))
+ candidates.append(
+ (correlation, partner_path, partner.support, total_self, partner_total)
+ )
if not candidates:
return []
@@ -114,25 +110,25 @@ class HiddenCouplingDetector:
capped = candidates[:_MAX_FINDINGS_PER_FILE]
findings: list[BiomarkerResult] = []
- for correlation, partner_path, co_count in capped:
+ for correlation, partner_path, support, total_self, partner_total in capped:
findings.append(
BiomarkerResult(
biomarker_type=self.name,
- severity=_severity_for(correlation, co_count),
+ severity=_severity_for(correlation, support),
function_name=None,
line_start=None,
line_end=None,
details={
"partner": partner_path,
"correlation": round(correlation, 3),
- "co_change_count": round(co_count, 2),
+ "co_change_count": support,
"self_commits": total_self,
- "partner_commits": counts.get(partner_path, 0),
+ "partner_commits": partner_total,
},
reason=(
- f"{partner_path} co-changes with this file "
- f"{round(co_count, 2)} times ({correlation:.0%} of shared "
- "commits) but no static dependency exists"
+ f"{partner_path} changed with this file in {support} of its "
+ f"{total_self} commits ({correlation:.0%}) but no static "
+ "dependency exists"
),
)
)
diff --git a/packages/core/src/repowise/core/analysis/health/duplication/detector.py b/packages/core/src/repowise/core/analysis/health/duplication/detector.py
index fd1574dad..fd19d7131 100644
--- a/packages/core/src/repowise/core/analysis/health/duplication/detector.py
+++ b/packages/core/src/repowise/core/analysis/health/duplication/detector.py
@@ -56,7 +56,7 @@ class ClonePair:
b_start_line: int
b_end_line: int
token_count: int
- co_change_count: float = 0.0 # 0 when files don't share co-change history
+ co_change_count: int = 0 # shared commits; 0 when the files have no history together
@property
def is_intra_file(self) -> bool:
@@ -93,25 +93,29 @@ def _read_source(abs_path: str) -> bytes | None:
return None
-def _partner_weight(meta: dict[str, Any], partner_path: str) -> float:
- """The decayed co-change weight *meta*'s file carries for *partner_path*."""
+def _partner_support(meta: dict[str, Any], partner_path: str) -> int:
+ """Commits *meta*'s file shares with *partner_path*.
+
+ The plain count, not the decayed weight: consumers render it as "co-changed
+ N times" and compare it to a whole number.
+ """
for p in parse_partners(meta.get("co_change_partners_json")):
if p.file_path == partner_path:
- return p.weight
- return 0.0
+ return p.support
+ return 0
def _co_change_score(
file_a: str,
file_b: str,
git_meta_map: dict[str, dict[str, Any]],
-) -> float:
+) -> int:
"""Bidirectional max — co-change matrices are stored per file, but
- the same pair shows up from both sides, sometimes with slightly
- different counts depending on the window. Take the max."""
+ the same pair shows up from both sides, and a per-file cap can drop it from
+ one of them. Take the max."""
a_meta = git_meta_map.get(file_a, {}) or {}
b_meta = git_meta_map.get(file_b, {}) or {}
- return max(_partner_weight(a_meta, file_b), _partner_weight(b_meta, file_a))
+ return max(_partner_support(a_meta, file_b), _partner_support(b_meta, file_a))
def _tokens_equal(
diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.py
index b3d09f905..35c73fd4b 100644
--- a/packages/core/src/repowise/core/analysis/health/engine.py
+++ b/packages/core/src/repowise/core/analysis/health/engine.py
@@ -234,18 +234,6 @@ def _compute_repo_active_contributors(git_meta_map: dict[str, dict]) -> int | No
return None
-def _build_repo_commit_counts(git_meta_map: dict[str, dict]) -> dict[str, int]:
- out: dict[str, int] = {}
- for path, meta in git_meta_map.items():
- if not isinstance(meta, dict):
- continue
- try:
- out[path] = int(meta.get("commit_count_total") or 0)
- except (TypeError, ValueError):
- continue
- return out
-
-
def _path_basenames(all_paths: set[str]) -> set[str]:
"""Final path components of *all_paths*, split on ``/`` only.
@@ -435,7 +423,6 @@ class HealthAnalyzer:
analyzed_paths = {pf.file_info.path for pf in self.parsed_files}
path_basenames = _path_basenames(analyzed_paths)
package_roots = self._package_boundaries(analyzed_paths)
- repo_commit_counts = _build_repo_commit_counts(self.git_meta_map)
graph_view: HasEdge | None = ImportEdgeView(self.graph) if self.graph is not None else None
# Duplication runs once, up-front, so each file biomarker can see
@@ -529,7 +516,6 @@ class HealthAnalyzer:
disabled=file_disabled,
dup_report=dup_report,
graph_view=graph_view,
- repo_commit_counts=repo_commit_counts,
repo_function_mod_p80=repo_fn_mod_p80,
repo_dependents_p80=repo_dependents_p80,
repo_active_contributors_90d=repo_active_contributors,
@@ -619,7 +605,6 @@ class HealthAnalyzer:
analyzed_paths = {pf.file_info.path for pf in self.parsed_files}
path_basenames = _path_basenames(analyzed_paths)
package_roots = self._package_boundaries(analyzed_paths)
- repo_commit_counts = _build_repo_commit_counts(self.git_meta_map)
graph_view: HasEdge | None = ImportEdgeView(self.graph) if self.graph is not None else None
# Duplication is only consumed by the biomarker stage, so it can
@@ -727,7 +712,6 @@ class HealthAnalyzer:
disabled=file_disabled,
dup_report=dup_report,
graph_view=graph_view,
- repo_commit_counts=repo_commit_counts,
repo_function_mod_p80=repo_fn_mod_p80,
repo_dependents_p80=repo_dependents_p80,
repo_active_contributors_90d=repo_active_contributors,
@@ -939,7 +923,6 @@ class HealthAnalyzer:
disabled: list[str],
dup_report: DuplicationReport,
graph_view: HasEdge | None = None,
- repo_commit_counts: dict[str, int] | None = None,
repo_function_mod_p80: int | None = None,
repo_dependents_p80: int | None = None,
repo_active_contributors_90d: int | None = None,
@@ -1024,7 +1007,6 @@ class HealthAnalyzer:
clones=list(clones),
duplication_pct=dup_pct,
graph_view=graph_view,
- repo_commit_counts=repo_commit_counts or {},
blame_index=blame_index,
repo_function_mod_p80=repo_function_mod_p80,
repo_active_contributors_90d=repo_active_contributors_90d,
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/extract_helper.py b/packages/core/src/repowise/core/analysis/health/refactoring/extract_helper.py
index 8c85e0dbd..73ff38852 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/extract_helper.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/extract_helper.py
@@ -245,7 +245,7 @@ class _Block:
self.anchor_start = min(self.anchor_start, start)
self.anchor_end = max(self.anchor_end, end)
self.token_count = max(self.token_count, int(getattr(pair, "token_count", 0)))
- self.co_change = max(self.co_change, int(getattr(pair, "co_change_count", 0)))
+ self.co_change = max(self.co_change, int(getattr(pair, "co_change_count", 0) or 0))
# The anchor-side region of this pair is always an occurrence; add it
# plus the partner region(s). Intra-file pairs contribute both regions.
self.occurrences.add((anchor, start, end))
@@ -278,7 +278,7 @@ class ExtractHelperDetector(RefactoringDetector):
# Stable order: biggest recovery first, then — because dry_violation
# deductions are near-uniform, so impact rarely separates clones — the
- # plan's "co_change x span" priority (actively co-modified, larger
+ # co-change x span priority (actively co-modified, larger
# blocks first), then target for a fully deterministic tie-break.
out.sort(
key=lambda s: (
diff --git a/packages/core/src/repowise/core/analysis/pr_blast.py b/packages/core/src/repowise/core/analysis/pr_blast.py
index 6548681bd..cf48ddcdd 100644
--- a/packages/core/src/repowise/core/analysis/pr_blast.py
+++ b/packages/core/src/repowise/core/analysis/pr_blast.py
@@ -330,11 +330,7 @@ class PRBlastRadiusAnalyzer:
"direction": "undirected",
"evidence_kind": "historical",
"provenance": "git_history",
- **(
- {"support": partner.record["frequency"]}
- if partner.record.get("frequency") is not None
- else {}
- ),
+ **({"support": partner.support} if partner.support else {}),
}
)
diff --git a/packages/core/src/repowise/core/co_change.py b/packages/core/src/repowise/core/co_change.py
index d5b05a188..d00136943 100644
--- a/packages/core/src/repowise/core/co_change.py
+++ b/packages/core/src/repowise/core/co_change.py
@@ -29,7 +29,11 @@ from dataclasses import dataclass, field
__all__ = [
"CO_CHANGE_DECAY_TAU",
- "MIN_CO_CHANGE_WEIGHT",
+ "MAX_PARTNERS_PER_FILE",
+ "MIN_CO_CHANGE_SUPPORT",
+ "STRUCTURAL_CORROBORATED",
+ "STRUCTURAL_NOT_APPLICABLE",
+ "STRUCTURAL_UNEXPLAINED",
"CoChangePartner",
"canonical_pair",
"parse_partners",
@@ -42,9 +46,22 @@ __all__ = [
# between them would silently change what a weight means.
CO_CHANGE_DECAY_TAU: float = 180.0
-# Minimum decayed weight for a pair to be worth recording. Two co-changes in
-# the last few weeks clear it; older ones need proportionally more.
-MIN_CO_CHANGE_WEIGHT: int = 2
+# Minimum number of shared commits for a pair to be worth recording. Counted
+# raw, so it keeps its meaning if the weighting changes.
+MIN_CO_CHANGE_SUPPORT: int = 2
+
+# Strongest partners kept per file. Bounds the column on a repo where a few
+# files co-change with thousands of others.
+MAX_PARTNERS_PER_FILE: int = 25
+
+# Whether an import-graph edge explains a pair. ``NOT_APPLICABLE`` is not a
+# weaker ``UNEXPLAINED``: a file the parser never ingested cannot carry an edge
+# in either direction, so there is nothing to corroborate. Only
+# ``UNEXPLAINED`` is a finding. ``None`` means an index written before the
+# distinction existed.
+STRUCTURAL_CORROBORATED = "corroborated"
+STRUCTURAL_UNEXPLAINED = "unexplained"
+STRUCTURAL_NOT_APPLICABLE = "not_applicable"
@dataclass(frozen=True)
@@ -52,17 +69,34 @@ class CoChangePartner:
"""One file that changed together with the file the record belongs to.
``weight`` is the recency-decayed sum the indexer persists, not a number of
- commits. ``record`` is the verbatim source record, for callers that put it
- back on the wire or read a field this module does not model; it is excluded
- from equality so two partners compare on their meaning.
+ commits; ``support`` is that plain count. ``self_commits`` and
+ ``partner_commits`` are each file's commit total over the same walk, so
+ ``support / self_commits`` is an honest directional confidence. They are
+ zero on an index written before they were recorded.
+
+ ``record`` is the verbatim source record, for callers that put it back on
+ the wire or read a field this module does not model; it is excluded from
+ equality so two partners compare on their meaning.
"""
file_path: str
weight: float
last_co_change: str | None = None
+ support: int = 0
+ self_commits: int = 0
+ partner_commits: int = 0
+ structural: str | None = None
record: dict = field(default_factory=dict, compare=False, repr=False)
+def _as_count(value: object) -> int:
+ """A non-negative integer, or 0 for anything that is not one."""
+ try:
+ return max(int(value), 0) # type: ignore[arg-type]
+ except (TypeError, ValueError):
+ return 0
+
+
def parse_partners(raw: object) -> list[CoChangePartner]:
"""Partners from a ``co_change_partners_json`` cell, strongest first.
@@ -70,7 +104,8 @@ def parse_partners(raw: object) -> list[CoChangePartner]:
elements within it, yielding fewer partners rather than raising. Also
accepts an already-decoded list, which the graph builder holds. The ``path``
and ``count`` aliases are accepted alongside the canonical ``file_path`` and
- ``co_change_count``.
+ ``co_change_count``; ``frequency`` is the support count, named to match the
+ cross-repo miner's records.
"""
if not raw:
return []
@@ -96,11 +131,16 @@ def parse_partners(raw: object) -> list[CoChangePartner]:
except (TypeError, ValueError):
continue
last = record.get("last_co_change")
+ structural = record.get("structural")
out.append(
CoChangePartner(
file_path=str(path),
weight=weight,
last_co_change=last if isinstance(last, str) else None,
+ support=_as_count(record.get("frequency")),
+ self_commits=_as_count(record.get("self_commits")),
+ partner_commits=_as_count(record.get("partner_commits")),
+ structural=structural if isinstance(structural, str) else None,
record=record,
)
)
diff --git a/packages/core/src/repowise/core/generation/context/assembler.py b/packages/core/src/repowise/core/generation/context/assembler.py
index 1a9a5b923..2bc2392a3 100644
--- a/packages/core/src/repowise/core/generation/context/assembler.py
+++ b/packages/core/src/repowise/core/generation/context/assembler.py
@@ -23,7 +23,7 @@ from repowise.core.ingestion.package_roots import (
scan_package_roots,
)
-from ...co_change import parse_partners
+from ...co_change import STRUCTURAL_UNEXPLAINED, parse_partners
from ..categories import file_category
from ..entry_points import orientation_entry_points, rank_entry_point_paths
from ..models import GenerationConfig
@@ -680,11 +680,12 @@ class ContextAssembler:
single_owner_files = sum(1 for m in metas if 0 < (m.get("bus_factor") or 0) <= 1)
# Files this subsystem changes together with in history but that live in
- # another module. History coupling the import graph never shows.
+ # another module. Restricted to pairs the dependency graph does not
+ # explain, because the page claims exactly that.
coupled: Counter[str] = Counter()
for m in metas:
for p in parse_partners(m.get("co_change_partners_json")):
- if p.file_path in member_set:
+ if p.file_path in member_set or p.structural != STRUCTURAL_UNEXPLAINED:
continue
module = module_for(p.file_path, roots)
if module:
diff --git a/packages/core/src/repowise/core/generation/templates/module_page.j2 b/packages/core/src/repowise/core/generation/templates/module_page.j2
index 2d19fd59d..e0e58bfdd 100644
--- a/packages/core/src/repowise/core/generation/templates/module_page.j2
+++ b/packages/core/src/repowise/core/generation/templates/module_page.j2
@@ -89,9 +89,9 @@ Use these to explain *why* the subsystem is shaped the way it is. Do not invent
{% if ctx.coupled_modules %}
### Change-coupled with (co-changes in history, not import edges)
-These modules change together with this one in history without importing it — hidden coupling worth naming.
+These modules change together with this one in history and nothing in the dependency graph accounts for it — hidden coupling worth naming.
{% for cm in ctx.coupled_modules %}
-- `{{ cm.path }}` (co-changed {{ cm.count }}×)
+- `{{ cm.path }}` ({{ cm.count }} co-changing file{{ "s" if cm.count != 1 else "" }})
{% endfor %}
{% endif %}
diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/_constants.py b/packages/core/src/repowise/core/ingestion/git_indexer/_constants.py
index eaabf5bdf..55b087161 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/_constants.py
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/_constants.py
@@ -10,7 +10,11 @@ import contextlib
import re
from typing import Any
-from ...co_change import CO_CHANGE_DECAY_TAU, MIN_CO_CHANGE_WEIGHT
+from ...co_change import (
+ CO_CHANGE_DECAY_TAU,
+ MAX_PARTNERS_PER_FILE,
+ MIN_CO_CHANGE_SUPPORT,
+)
from ..languages.registry import REGISTRY as _LANG_REGISTRY
# Silence GitPython's _CatFileContentStream.__del__ ValueError spam.
@@ -132,19 +136,18 @@ _PR_BODY_MARKERS: tuple[str, ...] = (
)
# Co-change pair extraction widens the window because individual files
-# may only co-change a handful of times in 500 commits — well below the
-# ``min_count`` threshold. On low-churn repos the 500-commit window
-# produced 0 co-change pairs every run; 2000 commits captures enough
-# history for the decay-weighted score to clear the bar without
-# meaningfully blowing up wall-clock time (single `git log` call).
+# may only co-change a handful of times in 500 commits. On low-churn repos
+# the 500-commit window produced 0 co-change pairs every run; 2000 commits
+# captures enough history without meaningfully blowing up wall-clock time
+# (single `git log` call).
_DEFAULT_CO_CHANGE_COMMIT_LIMIT: int = 2000
-# Minimum decay-weighted co-occurrence weight for a pair to be recorded.
-# Was 3 historically; on repos with sparse change history (libraries,
-# stable services) that produced empty co-change tables. Two recent
-# co-changes is enough signal to surface in the UI, and the dashboard
-# already sorts partners by weight so the ranking is unaffected.
-_DEFAULT_CO_CHANGE_MIN_COUNT: int = MIN_CO_CHANGE_WEIGHT
+# What a pair must clear to be recorded, and how many survive per file. Both
+# are counts rather than weights: a cutoff on the weight has to be re-tuned
+# whenever the weighting changes, and the value that keeps a monorepo honest
+# empties a library's table entirely.
+_MIN_CO_CHANGE_SUPPORT: int = MIN_CO_CHANGE_SUPPORT
+_MAX_PARTNERS_PER_FILE: int = MAX_PARTNERS_PER_FILE
# Commits that touch a very large number of files (mass renames,
# copyright header sweeps, code-mod runs) produce O(N^2) pairs and
diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/co_change.py b/packages/core/src/repowise/core/ingestion/git_indexer/co_change.py
index 77b6504bb..6a9edb310 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/co_change.py
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/co_change.py
@@ -2,7 +2,8 @@
A single ``git log --name-only`` walk feeds two history signals at once:
-* **Co-change** — decay-weighted co-occurrence pairs across tracked files.
+* **Co-change** — decay-weighted co-occurrence pairs across tracked files,
+ each carrying its raw shared-commit count and both files' commit totals.
* **Change entropy** — Hassan's History Complexity Metric (2009), capturing
how scattered each file's changes are over time.
@@ -13,6 +14,7 @@ defers the whole walk; absent fields are treated as "no signal" downstream.
from __future__ import annotations
+import heapq
import math
import time
from collections import defaultdict
@@ -25,9 +27,10 @@ import structlog
from ._constants import (
_CO_CHANGE_DECAY_TAU,
_DEFAULT_CO_CHANGE_COMMIT_LIMIT,
- _DEFAULT_CO_CHANGE_MIN_COUNT,
_MAX_FILES_PER_COMMIT_FOR_COCHANGE,
_MAX_FILES_PER_COMMIT_FOR_ENTROPY,
+ _MAX_PARTNERS_PER_FILE,
+ _MIN_CO_CHANGE_SUPPORT,
)
logger = structlog.get_logger(__name__)
@@ -39,7 +42,7 @@ def compute_co_changes_and_entropy(
repo: Any,
all_files: set[str],
commit_limit: int = _DEFAULT_CO_CHANGE_COMMIT_LIMIT,
- min_count: int = _DEFAULT_CO_CHANGE_MIN_COUNT,
+ max_partners: int = _MAX_PARTNERS_PER_FILE,
on_commit_done: Callable[[], None] | None = None,
on_co_change_start: Callable[[int], None] | None = None,
as_of_ts: float | None = None,
@@ -50,9 +53,22 @@ def compute_co_changes_and_entropy(
``git diff`` subprocess per commit — O(1) processes vs O(commit_limit).
**Co-change** applies exponential temporal decay so recent co-changes weigh
- more than ancient ones. ``on_co_change_start(total)`` is called once with the
- actual number of commits found; ``on_commit_done()`` after each commit block.
- Both run from a thread-pool thread; callers must ensure thread safety.
+ more than ancient ones, and divides each commit's weight by ``n - 1`` so a
+ pair carries the same mass whether it was seen alone or alongside a hundred
+ other files. Without that, a commit contributes ``O(n^2)`` pairs at full
+ weight and wide commits drown the signal.
+
+ Each pair also keeps ``frequency`` (shared commits, undecayed) and both
+ files' commit totals from this same walk, so a caller can state a
+ directional confidence without borrowing a denominator computed over a
+ different window. Pairs below ``_MIN_CO_CHANGE_SUPPORT`` shared commits are
+ dropped, then each file keeps its ``max_partners`` strongest — both
+ scale-free, unlike a cutoff on the weight, which shifts whenever the
+ weighting does.
+
+ ``on_co_change_start(total)`` is called once with the actual number of
+ commits found; ``on_commit_done()`` after each commit block. Both run from a
+ thread-pool thread; callers must ensure thread safety.
**Change entropy** adapts Hassan's History Complexity Metric: each commit is
a one-period window whose entropy is ``log2(|F|)`` (``|F|`` = tracked files
@@ -64,7 +80,9 @@ def compute_co_changes_and_entropy(
value maps ``file_path → decayed HCM sum`` (only files with a positive sum).
"""
pair_scores: defaultdict[tuple[str, str], float] = defaultdict(float)
+ pair_support: defaultdict[tuple[str, str], int] = defaultdict(int)
pair_last_date: dict[tuple[str, str], int] = {} # pair → latest Unix ts
+ file_commits: defaultdict[str, int] = defaultdict(int)
entropy_scores: defaultdict[str, float] = defaultdict(float)
# Anchor the decay reference to the repo's most recent commit (passed by the
# orchestrator) rather than wall-clock time, so the decay is deterministic
@@ -93,6 +111,11 @@ def compute_co_changes_and_entropy(
def _flush_commit() -> None:
nonlocal current_ts
n = len(current)
+ # Counted before the pair guard: a commit where a file changed alone is
+ # still one of its commits, and it is the denominator that decides
+ # whether the file ever changes without its partner.
+ for path in current:
+ file_commits[path] += 1
if n < 2:
return
age_days = max((now_ts - current_ts) / 86400.0, 0.0)
@@ -116,11 +139,15 @@ def compute_co_changes_and_entropy(
threshold=_MAX_FILES_PER_COMMIT_FOR_COCHANGE,
)
return
+ # Split the commit's weight across the files it touched, so a pair from
+ # a two-file commit outweighs one from a fifty-file commit.
+ pair_weight = weight / (n - 1)
sorted_files = sorted(current)
for i in range(len(sorted_files)):
for j in range(i + 1, len(sorted_files)):
pair = (sorted_files[i], sorted_files[j])
- pair_scores[pair] += weight
+ pair_scores[pair] += pair_weight
+ pair_support[pair] += 1
if pair not in pair_last_date or current_ts > pair_last_date[pair]:
pair_last_date[pair] = current_ts
@@ -143,34 +170,46 @@ def compute_co_changes_and_entropy(
_flush_commit() # final commit
- # Build result: for each file, list partners above threshold.
- result: dict[str, list[dict]] = defaultdict(list)
- for (a, b), score in pair_scores.items():
- if score >= min_count:
- last_ts = pair_last_date.get((a, b), 0)
- last_date = (
- datetime.fromtimestamp(last_ts, tz=UTC).strftime("%Y-%m-%d")
- if last_ts > 0
- else None
- )
- result[a].append(
+ # Keep each file's strongest partners, via a bounded min-heap per file so
+ # the persisted column stays linear in the file count.
+ kept: defaultdict[str, list[tuple[float, str]]] = defaultdict(list)
+
+ def _offer(owner: str, other: str, score: float) -> None:
+ heap = kept[owner]
+ if len(heap) < max_partners:
+ heapq.heappush(heap, (score, other))
+ elif score > heap[0][0]:
+ heapq.heapreplace(heap, (score, other))
+
+ for pair, score in pair_scores.items():
+ if pair_support[pair] < _MIN_CO_CHANGE_SUPPORT:
+ continue
+ a, b = pair
+ _offer(a, b, score)
+ _offer(b, a, score)
+
+ result: dict[str, list[dict]] = {}
+ for owner, heap in kept.items():
+ records = []
+ for score, other in heap:
+ pair = (owner, other) if owner < other else (other, owner)
+ last_ts = pair_last_date.get(pair, 0)
+ records.append(
{
- "file_path": b,
- "co_change_count": round(score, 2),
- "last_co_change": last_date,
+ "file_path": other,
+ "co_change_count": round(score, 4),
+ "frequency": pair_support[pair],
+ "self_commits": file_commits[owner],
+ "partner_commits": file_commits[other],
+ "last_co_change": (
+ datetime.fromtimestamp(last_ts, tz=UTC).strftime("%Y-%m-%d")
+ if last_ts > 0
+ else None
+ ),
}
)
- result[b].append(
- {
- "file_path": a,
- "co_change_count": round(score, 2),
- "last_co_change": last_date,
- }
- )
-
- # Sort partners by score descending
- for fp in result:
- result[fp].sort(key=lambda x: x["co_change_count"], reverse=True)
+ records.sort(key=lambda x: x["co_change_count"], reverse=True)
+ result[owner] = records
entropy = {fp: round(score, 6) for fp, score in entropy_scores.items() if score > 0.0}
@@ -179,11 +218,12 @@ def compute_co_changes_and_entropy(
commits=actual_commits,
tracked_files=len(all_files),
pairs_considered=len(pair_scores),
- pairs_above_threshold=sum(1 for s in pair_scores.values() if s >= min_count),
+ pairs_above_support=sum(1 for c in pair_support.values() if c >= _MIN_CO_CHANGE_SUPPORT),
files_with_partners=len(result),
files_with_entropy=len(entropy),
- min_count=min_count,
+ min_support=_MIN_CO_CHANGE_SUPPORT,
+ max_partners=max_partners,
commit_limit=commit_limit,
)
- return dict(result), entropy
+ return result, entropy
diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py b/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py
index 8a7c8b736..a2f1e643a 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py
@@ -24,9 +24,9 @@ from ._constants import (
_DEEP_WALK_COMMIT_LIMIT,
_DEEP_WALK_MIN_FALLBACK,
_DEFAULT_CO_CHANGE_COMMIT_LIMIT,
- _DEFAULT_CO_CHANGE_MIN_COUNT,
_DEFAULT_COMMIT_LIMIT,
_FILE_INDEX_TIMEOUT_SECS,
+ _MAX_PARTNERS_PER_FILE,
)
from .co_change import compute_co_changes_and_entropy
from .enrich import compute_percentiles
@@ -255,7 +255,7 @@ class GitIndexer:
repo,
set(tracked_files),
max(self.commit_limit, _DEFAULT_CO_CHANGE_COMMIT_LIMIT),
- _DEFAULT_CO_CHANGE_MIN_COUNT,
+ _MAX_PARTNERS_PER_FILE,
on_commit_done,
on_co_change_start,
as_of_ts,
@@ -540,7 +540,7 @@ class GitIndexer:
repo,
set(all_files),
max(self.commit_limit, _DEFAULT_CO_CHANGE_COMMIT_LIMIT),
- _DEFAULT_CO_CHANGE_MIN_COUNT,
+ _MAX_PARTNERS_PER_FILE,
None,
None,
as_of_ts,
diff --git a/packages/core/src/repowise/core/ingestion/graph/_edges.py b/packages/core/src/repowise/core/ingestion/graph/_edges.py
index de1bd4332..750612601 100644
--- a/packages/core/src/repowise/core/ingestion/graph/_edges.py
+++ b/packages/core/src/repowise/core/ingestion/graph/_edges.py
@@ -9,7 +9,14 @@ from __future__ import annotations
import structlog
-from ...co_change import canonical_pair, parse_partners
+from ...co_change import (
+ MIN_CO_CHANGE_SUPPORT,
+ STRUCTURAL_CORROBORATED,
+ STRUCTURAL_NOT_APPLICABLE,
+ STRUCTURAL_UNEXPLAINED,
+ canonical_pair,
+ parse_partners,
+)
from ..resolvers import ResolverContext
from ..resolvers.go import read_go_module_path, read_go_modules
from ._stem import build_stem_map
@@ -20,15 +27,59 @@ log = structlog.get_logger(__name__)
class EdgesMixin:
"""Non-import edge construction for :class:`GraphBuilder`."""
- def add_co_change_edges(self, git_meta_map: dict, min_count: int = 3) -> int:
- """Add co_changes edges from git metadata. Returns count of edges added."""
+ def label_co_change_structure(self, partners_by_file: dict[str, list[dict]]) -> int:
+ """Record, on each partner, whether the graph explains the pair.
+
+ Co-change is mined from git with no view of the code, so this is the
+ only point where both are in hand. Writes ``structural`` in place and
+ returns how many pairs came back unexplained.
+
+ Takes decoded partner lists; the wrapper in the git phase handles the
+ JSON column the records are persisted in.
+ """
+ # Deferred: every other ingestion import of analysis is, to keep the
+ # package pair acyclic at module load.
+ from ...analysis.graph_view import ImportEdgeView
+
+ if not self._graph.number_of_nodes():
+ # Nothing to answer with, and writing "not applicable" for every
+ # pair would erase a label an earlier run got right.
+ return 0
+ view = ImportEdgeView(self._graph)
+ unexplained = 0
+ for file_path, partners in partners_by_file.items():
+ known_self = view.knows(file_path)
+ for record in partners:
+ if not isinstance(record, dict):
+ continue
+ partner_path = record.get("file_path") or record.get("path")
+ if not partner_path:
+ continue
+ if not known_self or not view.knows(str(partner_path)):
+ record["structural"] = STRUCTURAL_NOT_APPLICABLE
+ elif view.has_dependency(file_path, str(partner_path)):
+ record["structural"] = STRUCTURAL_CORROBORATED
+ else:
+ record["structural"] = STRUCTURAL_UNEXPLAINED
+ unexplained += 1
+ log.info("Co-change structure labelled", unexplained=unexplained)
+ return unexplained
+
+ def add_co_change_edges(
+ self, git_meta_map: dict, min_support: int = MIN_CO_CHANGE_SUPPORT
+ ) -> int:
+ """Add co_changes edges from git metadata. Returns count of edges added.
+
+ Gated on shared commits rather than the decayed weight, whose scale
+ depends on how wide the commits were.
+ """
count = 0
seen: set[tuple[str, str]] = set()
for file_path, meta in git_meta_map.items():
for partner in parse_partners(meta.get("co_change_partners_json")):
partner_path, co_count = partner.file_path, partner.weight
- if co_count < min_count:
+ if partner.support < min_support:
continue
if partner_path not in self._graph:
continue
@@ -55,14 +106,16 @@ class EdgesMixin:
self._invalidate_subgraph_caches()
return count
- def update_co_change_edges(self, updated_meta: dict, min_count: int = 3) -> None:
+ def update_co_change_edges(
+ self, updated_meta: dict, min_support: int = MIN_CO_CHANGE_SUPPORT
+ ) -> None:
"""Remove old co_changes edges for updated files, add new ones."""
edges_to_remove = []
for u, v, data in self._graph.edges(data=True):
if data.get("edge_type") == "co_changes" and (u in updated_meta or v in updated_meta):
edges_to_remove.append((u, v))
self._graph.remove_edges_from(edges_to_remove)
- self.add_co_change_edges(updated_meta, min_count)
+ self.add_co_change_edges(updated_meta, min_support)
self._invalidate_subgraph_caches()
def add_dynamic_edges(self, edges: list) -> None:
diff --git a/packages/core/src/repowise/core/pipeline/incremental.py b/packages/core/src/repowise/core/pipeline/incremental.py
index d7b6a6fe6..b0e646d88 100644
--- a/packages/core/src/repowise/core/pipeline/incremental.py
+++ b/packages/core/src/repowise/core/pipeline/incremental.py
@@ -273,6 +273,7 @@ async def rebuild_graph_and_git(
try:
from repowise.core.ingestion.git_indexer import GitIndexer
from repowise.core.ingestion.git_indexer.tiers import GitIndexTier
+ from repowise.core.pipeline.phases.git import label_co_change_structure
try:
tier = GitIndexTier(git_tier) if git_tier else GitIndexTier.FULL
@@ -303,6 +304,11 @@ async def rebuild_graph_and_git(
on_warning=log,
)
git_meta_map = {m["file_path"]: m for m in updated_meta}
+ label_co_change_structure(graph_builder, git_meta_map)
+ if idle_decay_sink:
+ # Idle rows carry the same column and are persisted on their own
+ # path, having been serialized before the graph existed.
+ label_co_change_structure(graph_builder, idle_decay_sink)
if co_change_full:
graph_builder.update_co_change_edges(
{
diff --git a/packages/core/src/repowise/core/pipeline/orchestrator.py b/packages/core/src/repowise/core/pipeline/orchestrator.py
index aca4cc77a..057c92d3d 100644
--- a/packages/core/src/repowise/core/pipeline/orchestrator.py
+++ b/packages/core/src/repowise/core/pipeline/orchestrator.py
@@ -40,7 +40,11 @@ from .phases.analysis import (
_run_health_analysis,
)
from .phases.generation import run_generation
-from .phases.git import _run_git_indexing, drop_transient_git_signals
+from .phases.git import (
+ _run_git_indexing,
+ drop_transient_git_signals,
+ label_co_change_structure,
+)
from .phases.ingestion import _run_ingestion, reparse_for_resume
from .resume import ResumePhase
from .resume.controller import ResumeController
@@ -345,6 +349,9 @@ async def run_pipeline(
derive_environment_facts=derive_environment_facts,
)
traversal_stats = None
+ # Rehydrated rows can predate the structural label, and nothing
+ # else on this path recomputes it.
+ label_co_change_structure(graph_builder, git_meta_map)
git_metadata_list = list(git_meta_map.values())
except Exception as exc:
logger.warning("resume_rehydrate_failed_recomputing", error=str(exc))
@@ -370,6 +377,7 @@ async def run_pipeline(
# Add co-change edges to the graph (rehydrated graphs already carry them)
if git_meta_map:
+ label_co_change_structure(graph_builder, git_meta_map)
graph_builder.add_co_change_edges(git_meta_map)
# ---- External systems (C4 L1) ------------------------------------------
diff --git a/packages/core/src/repowise/core/pipeline/phases/git.py b/packages/core/src/repowise/core/pipeline/phases/git.py
index 046895324..322115d4d 100644
--- a/packages/core/src/repowise/core/pipeline/phases/git.py
+++ b/packages/core/src/repowise/core/pipeline/phases/git.py
@@ -6,11 +6,13 @@ orchestrator.py) imports these phase functions. No CLI/click/rich imports.
from __future__ import annotations
+import json
from pathlib import Path
from typing import Any
import structlog
+from repowise.core.co_change import parse_partners
from repowise.core.ingestion.git_indexer import GitIndexTier
from repowise.core.pipeline.progress import ProgressCallback, emit_warning
@@ -36,6 +38,26 @@ def drop_transient_git_signals(git_metadata_list: list[dict]) -> None:
meta.pop("blame_index", None)
+def label_co_change_structure(graph_builder: Any, git_meta_map: dict[str, dict]) -> int:
+ """Stamp each persisted co-change record with what the graph says about it.
+
+ The column holds JSON, so the records are decoded, labelled, and written
+ back; labelling the decoded copies alone would be discarded on persist.
+ Returns the number of pairs left unexplained.
+ """
+ decoded = {}
+ for file_path, meta in git_meta_map.items():
+ partners = parse_partners(meta.get("co_change_partners_json"))
+ if partners:
+ decoded[file_path] = [p.record for p in partners]
+ if not decoded:
+ return 0
+ unexplained = graph_builder.label_co_change_structure(decoded)
+ for file_path, records in decoded.items():
+ git_meta_map[file_path]["co_change_partners_json"] = json.dumps(records)
+ return unexplained
+
+
async def _run_git_indexing(
repo_path: Path,
*,
diff --git a/packages/server/src/repowise/server/mcp_server/tool_risk/assessment.py b/packages/server/src/repowise/server/mcp_server/tool_risk/assessment.py
index c033939de..bb34c0bed 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_risk/assessment.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_risk/assessment.py
@@ -341,9 +341,8 @@ def _build_co_changes(
}
if types:
row["structural_relationship_types"] = types
- support = partner.record.get("frequency", partner.record.get("shared_commit_count"))
- if support is not None:
- row["support"] = support
+ if partner.support:
+ row["support"] = partner.support
rows.append(row)
population = filter_dicts_by_key(rows, "file_path", exclude_spec)
return population, len(population)
diff --git a/packages/server/src/repowise/server/routers/coupling.py b/packages/server/src/repowise/server/routers/coupling.py
index 6518d9f90..1a2b5e7a6 100644
--- a/packages/server/src/repowise/server/routers/coupling.py
+++ b/packages/server/src/repowise/server/routers/coupling.py
@@ -9,18 +9,17 @@ join mirrors ``code_health.py``'s churn-complexity endpoint.
from __future__ import annotations
-from typing import Any
-
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession
-from repowise.core.analysis.coupling import (
- CouplingEdge,
- CouplingNode,
- coupling_graph,
-)
+from repowise.core.analysis.coupling import coupling_graph
from repowise.core.persistence import crud
from repowise.server.deps import get_db_session, verify_api_key
+from repowise.server.schemas import (
+ CouplingEdgeResponse,
+ CouplingGraphResponse,
+ CouplingNodeResponse,
+)
router = APIRouter(
tags=["coupling"],
@@ -28,34 +27,17 @@ router = APIRouter(
)
-def _node_to_dict(n: CouplingNode) -> dict[str, Any]:
- return {
- "file_path": n.file_path,
- "module": n.module,
- "score": n.score,
- "nloc": n.nloc,
- }
-
-
-def _edge_to_dict(e: CouplingEdge) -> dict[str, Any]:
- return {
- "source": e.source,
- "target": e.target,
- "strength": e.strength,
- "last_co_change": e.last_co_change,
- }
-
-
[email protected]("/api/repos/{repo_id}/coupling")
[email protected]("/api/repos/{repo_id}/coupling", response_model=CouplingGraphResponse)
async def coupling(
repo_id: str,
limit: int = Query(200, ge=1, le=1000),
session: AsyncSession = Depends(get_db_session),
-) -> dict:
+) -> CouplingGraphResponse:
"""Return the repo's change-coupling graph (strongest *limit* edges).
Co-change is a temporal hint (files committed together), not a verified
- dependency; ``strength`` is the decay-weighted count, not a percentage.
+ dependency; ``strength`` is the decay-weighted count, not a percentage,
+ while ``support`` is the plain number of shared commits.
"""
repo = await crud.get_repository(session, repo_id)
if repo is None:
@@ -64,8 +46,8 @@ async def coupling(
metrics = await crud.get_health_metrics(session, repo_id)
git_meta = await crud.get_all_git_metadata(session, repo_id)
graph = coupling_graph(metrics, git_meta, limit=limit)
- return {
- "nodes": [_node_to_dict(n) for n in graph.nodes],
- "edges": [_edge_to_dict(e) for e in graph.edges],
- "total_edges": graph.total_edges,
- }
+ 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,
+ )
diff --git a/packages/server/src/repowise/server/routers/git.py b/packages/server/src/repowise/server/routers/git.py
index babd6069f..4e26d6f85 100644
--- a/packages/server/src/repowise/server/routers/git.py
+++ b/packages/server/src/repowise/server/routers/git.py
@@ -33,7 +33,7 @@ from repowise.core.analysis.change_risk import (
scores_excluding,
)
from repowise.core.analysis.risk_semantics import change_risk_authority
-from repowise.core.co_change import parse_partners
+from repowise.core.co_change import MIN_CO_CHANGE_SUPPORT, parse_partners
from repowise.core.ingestion.git_indexer._constants import (
EVOLUTION_CATEGORIES,
classify_commit_category,
@@ -601,18 +601,19 @@ async def get_ownership(
async def get_co_changes(
repo_id: str,
file_path: str = Query(..., description="Relative file path"),
- min_count: int = Query(3, ge=1),
+ min_count: int = Query(MIN_CO_CHANGE_SUPPORT, ge=1),
session: AsyncSession = Depends(get_db_session),
) -> dict:
- """Get files that frequently change together with the given file."""
+ """Get files that frequently change together with the given file.
+
+ ``min_count`` is a number of shared commits, not the decayed weight.
+ """
meta = await crud.get_git_metadata(session, repo_id, file_path)
if meta is None:
raise HTTPException(status_code=404, detail="Git metadata not found")
filtered = [
- p.record
- for p in parse_partners(meta.co_change_partners_json)
- if p.weight >= min_count
+ p.record for p in parse_partners(meta.co_change_partners_json) if p.support >= min_count
]
return {
diff --git a/packages/server/src/repowise/server/routers/stats.py b/packages/server/src/repowise/server/routers/stats.py
index abae58e5f..aebb743e6 100644
--- a/packages/server/src/repowise/server/routers/stats.py
+++ b/packages/server/src/repowise/server/routers/stats.py
@@ -725,12 +725,13 @@ async def _records(
"pagerank": round(float(central[1]), 4),
}
- # Strongest hidden coupling pair (max co-change count across files)
+ # The pair with the most shared commits. Counted, not weighted: the card
+ # renders it as "changed together N times".
best_pair: dict[str, Any] | None = None
for m in all_meta:
for p in parse_partners(m.co_change_partners_json):
- if best_pair is None or p.weight > best_pair["count"]:
- best_pair = {"a": m.file_path, "b": p.file_path, "count": p.weight}
+ if best_pair is None or p.support > best_pair["count"]:
+ best_pair = {"a": m.file_path, "b": p.file_path, "count": p.support}
if best_pair and best_pair["count"] > 0:
out["strongest_coupling"] = best_pair
diff --git a/packages/server/src/repowise/server/schemas/__init__.py b/packages/server/src/repowise/server/schemas/__init__.py
index 45a88b6cf..d188ab51f 100644
--- a/packages/server/src/repowise/server/schemas/__init__.py
+++ b/packages/server/src/repowise/server/schemas/__init__.py
@@ -49,6 +49,11 @@ from .code_quality import (
RepoStatsResponse,
SecurityFindingResponse,
)
+from .coupling import (
+ CouplingEdgeResponse,
+ CouplingGraphResponse,
+ CouplingNodeResponse,
+)
from .decisions import (
DecisionCodeEdge,
DecisionCountsResponse,
@@ -275,6 +280,9 @@ __all__ = [
"CoordinatorHealthResponse",
"CostGroupResponse",
"CostSummaryResponse",
+ "CouplingEdgeResponse",
+ "CouplingGraphResponse",
+ "CouplingNodeResponse",
"DeadCodeFindingResponse",
"DeadCodeGraphNodeResponse",
"DeadCodeGraphResponse",
diff --git a/packages/server/src/repowise/server/schemas/coupling.py b/packages/server/src/repowise/server/schemas/coupling.py
new file mode 100644
index 000000000..56d06c8c6
--- /dev/null
+++ b/packages/server/src/repowise/server/schemas/coupling.py
@@ -0,0 +1,40 @@
+"""Change-coupling response models."""
+
+from __future__ import annotations
+
+from typing import Literal
+
+from pydantic import BaseModel, Field
+
+
+class CouplingNodeResponse(BaseModel):
+ file_path: str
+ #: ``None`` when the file has no health metric row.
+ module: str | None = None
+ score: float | None = None
+ nloc: int = 0
+
+
+class CouplingEdgeResponse(BaseModel):
+ #: Lexicographically-smaller path, so a pair has one stable orientation.
+ source: str
+ target: str
+ #: Decay-weighted co-change score, not a percentage.
+ strength: float
+ last_co_change: str | None = None
+ #: Commits that touched both files, undecayed.
+ support: int = 0
+ #: Share of ``source``'s commits that also touched ``target``, and the
+ #: reverse. They differ whenever one file changes more often than the other.
+ confidence_ab: float | None = None
+ confidence_ba: float | None = None
+ #: Whether the dependency graph explains the pair: ``corroborated``,
+ #: ``unexplained``, or ``not_applicable`` when a side is not in the graph.
+ structural: Literal["corroborated", "unexplained", "not_applicable"] | None = None
+
+
+class CouplingGraphResponse(BaseModel):
+ nodes: list[CouplingNodeResponse] = Field(default_factory=list)
+ edges: list[CouplingEdgeResponse] = Field(default_factory=list)
+ #: Pre-cap edge count, for an honest "showing N of M" line.
+ total_edges: int = 0
diff --git a/packages/types/src/coupling.ts b/packages/types/src/coupling.ts
index 29d63fd16..921c66790 100644
--- a/packages/types/src/coupling.ts
+++ b/packages/types/src/coupling.ts
@@ -6,7 +6,10 @@
* The graph is a pure surfacing of `GitMetadata.co_change_partners_json`: files
* that have been committed together, deduplicated into an undirected edge list.
* Co-change is a TEMPORAL hint (shared commits), not a verified code
- * dependency, and `strength` is a decay-weighted count — not a percentage. No
+ * dependency, and `strength` is a decay-weighted count — not a percentage.
+ * `support` is the plain number of shared commits behind it, and the two
+ * confidences read that against each file's own commit total, so they differ
+ * whenever one file changes more often than the other. No
* "strengthening/weakening" trend is carried because co-change history is not
* snapshotted; only magnitude and recency are honest signals.
*/
@@ -32,8 +35,23 @@ export interface CouplingEdge {
strength: number;
/** ISO date of the most recent shared commit, or `null` if unknown. */
last_co_change: string | null;
+ /** Commits that touched both files, undecayed. `0` on an older index. */
+ support: number;
+ /** Share of `source`'s commits that also touched `target`; `null` if unknown. */
+ confidence_ab: number | null;
+ /** The same share from `target`'s side. */
+ confidence_ba: number | null;
+ /**
+ * Whether the dependency graph explains the pair. `not_applicable` means a
+ * side is not in the graph at all — a lockfile has no edge to find, so its
+ * absence is not evidence of hidden coupling. `null` on an older index.
+ */
+ structural: CouplingStructure | null;
}
+/** What the dependency graph says about a co-changing pair. */
+export type CouplingStructure = "corroborated" | "unexplained" | "not_applicable";
+
/** Response of `GET /api/repos/{repo_id}/coupling`. */
export interface CouplingGraphResponse {
nodes: CouplingNode[];
diff --git a/packages/ui/__tests__/coupling/coupling-explorer.test.tsx b/packages/ui/__tests__/coupling/coupling-explorer.test.tsx
index 6311d8e9a..94a5cc185 100644
--- a/packages/ui/__tests__/coupling/coupling-explorer.test.tsx
+++ b/packages/ui/__tests__/coupling/coupling-explorer.test.tsx
@@ -22,6 +22,10 @@ function edge(s: string, t: string, strength = 3): CouplingEdge {
target: t,
strength,
last_co_change: "2026-06-01",
+ support: 0,
+ confidence_ab: null,
+ confidence_ba: null,
+ structural: null,
};
}
diff --git a/packages/ui/__tests__/coupling/coupling-graph.test.tsx b/packages/ui/__tests__/coupling/coupling-graph.test.tsx
index 749381c10..66f1c4242 100644
--- a/packages/ui/__tests__/coupling/coupling-graph.test.tsx
+++ b/packages/ui/__tests__/coupling/coupling-graph.test.tsx
@@ -8,7 +8,16 @@ function node(path: string, score: number | null = 7, nloc = 100): CouplingNode
return { file_path: path, module: path.split("/")[0] ?? null, score, nloc };
}
function edge(s: string, t: string, strength = 3, last: string | null = "2026-06-01"): CouplingEdge {
- return { source: s, target: t, strength, last_co_change: last };
+ return {
+ source: s,
+ target: t,
+ strength,
+ last_co_change: last,
+ support: 0,
+ confidence_ab: null,
+ confidence_ba: null,
+ structural: null,
+ };
}
describe("CouplingGraph", () => {
diff --git a/packages/ui/__tests__/coupling/coupling-table.test.tsx b/packages/ui/__tests__/coupling/coupling-table.test.tsx
index 884c4c148..ed92956d8 100644
--- a/packages/ui/__tests__/coupling/coupling-table.test.tsx
+++ b/packages/ui/__tests__/coupling/coupling-table.test.tsx
@@ -9,7 +9,16 @@ function edge(
strength = 3,
last: string | null = "2026-06-01",
): CouplingEdge {
- return { source: s, target: t, strength, last_co_change: last };
+ return {
+ source: s,
+ target: t,
+ strength,
+ last_co_change: last,
+ support: 0,
+ confidence_ab: null,
+ confidence_ba: null,
+ structural: null,
+ };
}
// The table collapses to stacked cards below `md`, and ResponsiveTable keeps
@@ -76,3 +85,48 @@ describe("CouplingTable (virtualized)", () => {
expect(onGenerate).toHaveBeenCalledTimes(1);
});
});
+
+describe("CouplingTable together column", () => {
+ const withSupport = (
+ s: string,
+ t: string,
+ support: number,
+ ab: number | null,
+ ba: number | null,
+ ): CouplingEdge => ({
+ ...edge(s, t),
+ support,
+ confidence_ab: ab,
+ confidence_ba: ba,
+ });
+
+ it("shows the shared commit count and the stronger of the two directions", () => {
+ render(<CouplingTable edges={[withSupport("a/README.md", "b/BENCH.md", 11, 0.11, 0.92)]} />);
+ expect(inTable().getByText("11 commits")).toBeInTheDocument();
+ // 0.92 is the claim the pair actually supports; 0.11 would undersell it.
+ expect(inTable().getByText("up to 92% of one side")).toBeInTheDocument();
+ });
+
+ it("renders a dash when the index recorded no support", () => {
+ render(<CouplingTable edges={[edge("a.py", "b.py")]} />);
+ expect(inTable().queryByText(/commits$/)).not.toBeInTheDocument();
+ });
+
+ it("omits the confidence line when neither side has a commit total", () => {
+ render(<CouplingTable edges={[withSupport("a.py", "b.py", 4, null, null)]} />);
+ expect(inTable().getByText("4 commits")).toBeInTheDocument();
+ expect(inTable().queryByText(/of one side/)).not.toBeInTheDocument();
+ });
+
+ it("sorts by shared commits, not by date", () => {
+ const edges = [
+ { ...withSupport("a.py", "b.py", 2, 0.5, 0.5), last_co_change: "2026-06-09" },
+ { ...withSupport("c.py", "d.py", 40, 0.9, 0.9), last_co_change: "2026-06-01" },
+ ];
+ render(<CouplingTable edges={edges} />);
+ fireEvent.click(inTable().getByText("Together"));
+ const rows = inTable().getAllByRole("row").slice(1);
+ // Descending by support puts the 40 first; by date it would be the 2.
+ expect(within(rows[0]!).getByText("40 commits")).toBeInTheDocument();
+ });
+});
diff --git a/packages/ui/src/coupling/coupling-table.tsx b/packages/ui/src/coupling/coupling-table.tsx
index 948773d53..89b1d6fc3 100644
--- a/packages/ui/src/coupling/coupling-table.tsx
+++ b/packages/ui/src/coupling/coupling-table.tsx
@@ -38,7 +38,7 @@ interface CouplingTableProps {
LinkComponent?: LinkLike | undefined;
}
-type SortKey = "strength" | "last";
+type SortKey = "strength" | "last" | "together";
type SortDir = "asc" | "desc";
// Capped against the viewport, not a flat 600px, so the inner scroller is not
@@ -48,6 +48,17 @@ const VIRTUALIZE = { maxHeight: "min(600px, 70vh)" };
const STRENGTH_HELP =
"Recency-weighted count of commits that touched both files. Higher means more or more-recent shared changes. It is not a percentage or a verified dependency.";
+const TOGETHER_HELP =
+ "Shared commits, and how much of each file's own history they account for. A pair can be one-sided: a file that never changes alone is a stronger finding than two files that both change often.";
+
+// The higher of the two directions: the strongest claim the pair supports.
+function peakConfidence(e: CouplingEdge): number | null {
+ const values = [e.confidence_ab, e.confidence_ba].filter(
+ (v): v is number => typeof v === "number",
+ );
+ return values.length ? values.reduce((m, v) => Math.max(m, v), 0) : null;
+}
+
/**
* The precise, sortable companion to the coupling diagram: one row per
* coupling. Clicking a row pins its source file in the ring; the two file
@@ -79,8 +90,11 @@ export function CouplingTable({
const sorted = useMemo(() => {
const dir = sortDir === "asc" ? 1 : -1;
- const val = (e: CouplingEdge) =>
- sortKey === "strength" ? e.strength : e.last_co_change ? Date.parse(e.last_co_change) : 0;
+ const val = (e: CouplingEdge) => {
+ if (sortKey === "strength") return e.strength;
+ if (sortKey === "together") return e.support;
+ return e.last_co_change ? Date.parse(e.last_co_change) : 0;
+ };
// Copy before sorting: never mutate the caller's edge array in place.
return [...edges].sort((a, b) => (val(a) - val(b)) * dir);
}, [edges, sortKey, sortDir]);
@@ -196,6 +210,36 @@ export function CouplingTable({
// The bar is meaningless at card width; the number carries it.
mobileRender: (e) => e.strength,
},
+ {
+ key: "together",
+ header: (
+ <span
+ title={TOGETHER_HELP}
+ className="cursor-help underline decoration-dotted underline-offset-2"
+ >
+ Together
+ </span>
+ ),
+ mobileLabel: "Together",
+ priority: 2,
+ sortable: true,
+ headerClassName: "w-32",
+ cellClassName: "text-xs tabular-nums",
+ render: (e) => {
+ if (!e.support) return <span className="text-[var(--color-text-tertiary)]">—</span>;
+ const peak = peakConfidence(e);
+ return (
+ <div className="flex flex-col leading-tight">
+ <span>{e.support} commits</span>
+ {peak !== null && (
+ <span className="text-[var(--color-text-tertiary)]">
+ up to {Math.round(peak * 100)}% of one side
+ </span>
+ )}
+ </div>
+ );
+ },
+ },
{
key: "last",
header: "Last",
diff --git a/tests/unit/coupling/test_graph.py b/tests/unit/coupling/test_graph.py
index 8c03db8ed..6fa6f6a2d 100644
--- a/tests/unit/coupling/test_graph.py
+++ b/tests/unit/coupling/test_graph.py
@@ -145,3 +145,111 @@ def test_a_bare_string_partner_does_not_crash_the_join() -> None:
}
g = coupling_graph(metrics, git)
assert g.edges == [CouplingEdge("a.py", "b.py", 4.0, None)]
+
+
+def _rich(*records: dict) -> _Git:
+ return _Git(co_change_partners_json=json.dumps(list(records)))
+
+
+class TestDirectionalConfidence:
+ """The two ends of a pair need not agree, and that asymmetry is the point."""
+
+ def test_each_side_confidence_reads_its_own_commit_total(self) -> None:
+ # README changes constantly; the benchmark doc only ever moves with it.
+ git = {
+ "README.md": _rich(
+ {
+ "file_path": "docs/BENCHMARKS.md",
+ "co_change_count": 5.0,
+ "frequency": 11,
+ "self_commits": 104,
+ "partner_commits": 12,
+ }
+ )
+ }
+ (edge,) = coupling_graph([], git).edges
+ assert (edge.source, edge.target) == ("README.md", "docs/BENCHMARKS.md")
+ assert edge.support == 11
+ assert edge.confidence_ab == 0.106
+ assert edge.confidence_ba == 0.917
+
+ def test_confidence_follows_the_canonical_orientation_not_the_record(self) -> None:
+ """Only the larger-sorting side holds the record, so the two commit
+ totals have to be swapped onto the canonical pair or the ratios invert.
+ """
+ git = {
+ "z.py": _rich(
+ {
+ "file_path": "a.py",
+ "co_change_count": 5.0,
+ "frequency": 9,
+ "self_commits": 90,
+ "partner_commits": 10,
+ }
+ )
+ }
+ (edge,) = coupling_graph([], git).edges
+ assert (edge.source, edge.target) == ("a.py", "z.py")
+ # a.py is the source and has 10 commits, so its confidence is the high one.
+ assert edge.confidence_ab == 0.9
+ assert edge.confidence_ba == 0.1
+
+ def test_the_structural_label_reaches_the_edge(self) -> None:
+ git = {
+ "a.py": _rich(
+ {
+ "file_path": "b.py",
+ "co_change_count": 5.0,
+ "frequency": 9,
+ "structural": "not_applicable",
+ }
+ )
+ }
+ (edge,) = coupling_graph([], git).edges
+ assert edge.structural == "not_applicable"
+
+ def test_an_older_index_yields_an_edge_with_no_confidence(self) -> None:
+ git = {"a.py": _rich({"file_path": "b.py", "co_change_count": 5.0})}
+ (edge,) = coupling_graph([], git).edges
+ assert edge.support == 0
+ assert edge.confidence_ab is None
+ assert edge.confidence_ba is None
+ assert edge.structural is None
+
+ def test_the_two_directions_of_a_pair_merge_without_losing_either_side(self) -> None:
+ """A per-file cap can leave one side holding a weaker view of the pair.
+
+ Each side is authoritative about its own commit total, so the merge has
+ to keep both rather than take whichever record it saw last.
+ """
+ git = {
+ "a.py": _rich(
+ {
+ "file_path": "z.py",
+ "co_change_count": 2.0,
+ "frequency": 7,
+ "self_commits": 10,
+ "partner_commits": 0,
+ "last_co_change": "2026-05-01",
+ }
+ ),
+ "z.py": _rich(
+ {
+ "file_path": "a.py",
+ "co_change_count": 5.0,
+ "frequency": 9,
+ "self_commits": 40,
+ "partner_commits": 10,
+ "structural": "unexplained",
+ "last_co_change": "2026-06-01",
+ }
+ ),
+ }
+ (edge,) = coupling_graph([], git).edges
+ assert edge.strength == 5.0
+ assert edge.support == 9
+ assert edge.last_co_change == "2026-06-01"
+ assert edge.structural == "unexplained"
+ # a.py: 9/10 from its own record; z.py: 9/40 from the other side's.
+ assert edge.confidence_ab == 0.9
+ assert edge.confidence_ba == 0.225
diff --git a/tests/unit/generation/test_context_assembler.py b/tests/unit/generation/test_context_assembler.py
index 2c2e785f6..e28218b3d 100644
--- a/tests/unit/generation/test_context_assembler.py
+++ b/tests/unit/generation/test_context_assembler.py
@@ -547,7 +547,13 @@ def test_coupled_modules_name_the_package_not_the_parent_directory(sample_config
"packages/ui/package.json": {},
"packages/core/src/a.py": {
"co_change_partners_json": json.dumps(
- [{"file_path": "packages/ui/src/deep/nested/widget.ts", "co_change_count": 5}]
+ [
+ {
+ "file_path": "packages/ui/src/deep/nested/widget.ts",
+ "co_change_count": 5,
+ "structural": "unexplained",
+ }
+ ]
)
},
}
@@ -575,7 +581,13 @@ def test_coupled_modules_survive_a_changed_files_only_git_map(sample_config, tmp
changed_only = {
"packages/core/src/a.py": {
"co_change_partners_json": json.dumps(
- [{"file_path": "packages/ui/src/deep/widget.ts", "co_change_count": 5}]
+ [
+ {
+ "file_path": "packages/ui/src/deep/widget.ts",
+ "co_change_count": 5,
+ "structural": "unexplained",
+ }
+ ]
)
}
}
@@ -585,3 +597,35 @@ def test_coupled_modules_survive_a_changed_files_only_git_map(sample_config, tmp
)
assert coupled_modules == [{"path": "packages/ui", "count": 1}]
+
+
+def test_coupled_modules_exclude_pairs_the_graph_explains(sample_config):
+ """The page says these modules co-change *without* a dependency between
+ them, so a pair the graph accounts for must not be listed."""
+ assembler = ContextAssembler(sample_config)
+ git_meta_map = {
+ "packages/core/pyproject.toml": {},
+ "packages/ui/package.json": {},
+ "packages/core/src/a.py": {
+ "co_change_partners_json": json.dumps(
+ [
+ {
+ "file_path": "packages/ui/src/imported.ts",
+ "co_change_count": 9,
+ "structural": "corroborated",
+ },
+ {
+ "file_path": "packages/ui/src/lockfile-ish.json",
+ "co_change_count": 9,
+ "structural": "not_applicable",
+ },
+ ]
+ )
+ },
+ }
+
+ _, _, _, coupled_modules, _, _ = assembler._module_git_enrichment(
+ ["packages/core/src/a.py"], {"packages/core/src/a.py"}, git_meta_map
+ )
+
+ assert coupled_modules == []
diff --git a/tests/unit/health/test_duplication.py b/tests/unit/health/test_duplication.py
index df77f0a66..588dbe054 100644
--- a/tests/unit/health/test_duplication.py
+++ b/tests/unit/health/test_duplication.py
@@ -144,10 +144,10 @@ def test_detect_clones_attaches_co_change_count(tmp_path: Path):
parsed = [_pf("a.py", str(a)), _pf("b.py", str(b))]
git_meta_map = {
"a.py": {
- "co_change_partners_json": json.dumps([{"file_path": "b.py", "co_change_count": 7}])
+ "co_change_partners_json": json.dumps([{"file_path": "b.py", "co_change_count": 7, "frequency": 7}])
},
"b.py": {
- "co_change_partners_json": json.dumps([{"file_path": "a.py", "co_change_count": 5}])
+ "co_change_partners_json": json.dumps([{"file_path": "a.py", "co_change_count": 5, "frequency": 5}])
},
}
report = detect_clones(parsed, git_meta_map, window_tokens=20, min_lines=4)
diff --git a/tests/unit/health/test_duplication_incremental.py b/tests/unit/health/test_duplication_incremental.py
index 1cb8cfc90..a884940ff 100644
--- a/tests/unit/health/test_duplication_incremental.py
+++ b/tests/unit/health/test_duplication_incremental.py
@@ -371,7 +371,7 @@ def test_co_change_weight_applied_live_on_splice(tmp_path: Path):
parsed = _parsed(tmp_path)
meta = {
"a.py": {
- "co_change_partners_json": json.dumps([{"file_path": "b.py", "co_change_count": 7}])
+ "co_change_partners_json": json.dumps([{"file_path": "b.py", "co_change_count": 7, "frequency": 7}])
}
}
report = detect_clones(
diff --git a/tests/unit/health/test_ff_track_iljk_structural.py b/tests/unit/health/test_ff_track_iljk_structural.py
index 4b913100b..9508deb83 100644
--- a/tests/unit/health/test_ff_track_iljk_structural.py
+++ b/tests/unit/health/test_ff_track_iljk_structural.py
@@ -213,10 +213,18 @@ def test_detector_caps_small_sample_pair_at_medium():
git_meta={
"commit_count_total": 5,
"co_change_partners_json": json.dumps(
- [{"file_path": "src/billing.py", "co_change_count": 4}]
+ [
+ {
+ "file_path": "src/billing.py",
+ "co_change_count": 4,
+ "frequency": 4,
+ "self_commits": 5,
+ "partner_commits": 5,
+ "structural": "unexplained",
+ }
+ ]
),
},
- repo_commit_counts={"src/payments.py": 5, "src/billing.py": 5},
)
out = HiddenCouplingDetector().detect(ctx)
assert len(out) == 1
diff --git a/tests/unit/health/test_hidden_coupling.py b/tests/unit/health/test_hidden_coupling.py
index f3ce839cf..a36edd5cf 100644
--- a/tests/unit/health/test_hidden_coupling.py
+++ b/tests/unit/health/test_hidden_coupling.py
@@ -9,32 +9,43 @@ from repowise.core.analysis.health.biomarkers.hidden_coupling import (
HiddenCouplingDetector,
)
from repowise.core.analysis.health.models import Severity
+from repowise.core.co_change import (
+ STRUCTURAL_CORROBORATED,
+ STRUCTURAL_NOT_APPLICABLE,
+ STRUCTURAL_UNEXPLAINED,
+)
-class _FakeGraph:
- """Minimal ``HasEdge`` fake for unit tests."""
-
- def __init__(self, edges: set[tuple[str, str, str]] | None = None) -> None:
- # (src, dst, edge_type)
- self._edges = edges or set()
-
- def has_edge(self, src: str, dst: str, key: str = "imports") -> bool:
- return (src, dst, key) in self._edges
-
-
-def _partners(d: dict[str, float]) -> str:
- return json.dumps([{"file_path": p, "co_change_count": c} for p, c in d.items()])
+def _partners(
+ d: dict[str, int],
+ *,
+ self_commits: int,
+ repo_commits: dict[str, int],
+ structural: str = STRUCTURAL_UNEXPLAINED,
+) -> str:
+ return json.dumps(
+ [
+ {
+ "file_path": p,
+ "co_change_count": float(support),
+ "frequency": support,
+ "self_commits": self_commits,
+ "partner_commits": repo_commits.get(p, 0),
+ "structural": structural,
+ }
+ for p, support in d.items()
+ ]
+ )
def _ctx(
path: str,
*,
- partners: dict[str, float],
+ partners: dict[str, int],
self_commits: int,
repo_commits: dict[str, int],
- graph: _FakeGraph | None = None,
+ structural: str = STRUCTURAL_UNEXPLAINED,
) -> FileContext:
- repo_commits = {**repo_commits, path: self_commits}
return FileContext(
file_path=path,
language="python",
@@ -44,11 +55,14 @@ def _ctx(
function_metrics={},
git_meta={
"commit_count_total": self_commits,
- "co_change_partners_json": _partners(partners),
+ "co_change_partners_json": _partners(
+ partners,
+ self_commits=self_commits,
+ repo_commits=repo_commits,
+ structural=structural,
+ ),
},
dependents_count=0,
- graph_view=graph,
- repo_commit_counts=repo_commits,
)
@@ -62,7 +76,7 @@ def test_positive_python_pair_no_import_edge():
out = HiddenCouplingDetector().detect(ctx)
assert len(out) == 1
assert out[0].details["partner"] == "src/billing.py"
- # 18 / min(20, 22) = 0.9 → CRITICAL
+ # 18 / min(20, 22) = 0.9 -> CRITICAL
assert out[0].severity == Severity.CRITICAL
@@ -75,18 +89,63 @@ def test_positive_ts_pair_at_medium():
)
out = HiddenCouplingDetector().detect(ctx)
assert len(out) == 1
- # 6 / min(10, 12) = 0.6 → HIGH (>= 0.5, < 0.65 is MEDIUM; 0.6 -> MEDIUM)
+ # 6 / min(10, 12) = 0.6, below the HIGH band.
assert out[0].severity == Severity.MEDIUM
-def test_negative_explicit_import_edge_suppresses():
- graph = _FakeGraph({("src/payments.py", "src/billing.py", "imports")})
+def test_negative_corroborated_pair_suppresses():
+ """A pair the dependency graph already accounts for is not a finding."""
ctx = _ctx(
"src/payments.py",
partners={"src/billing.py": 18},
self_commits=20,
repo_commits={"src/billing.py": 22},
- graph=graph,
+ structural=STRUCTURAL_CORROBORATED,
+ )
+ assert HiddenCouplingDetector().detect(ctx) == []
+
+
+def test_pair_outside_the_graph_is_not_a_finding():
+ """A lockfile against a manifest co-changes constantly and imports nothing.
+
+ Neither is a graph node, so there is no edge to look for and the absence of
+ one says nothing. Scoring it would put release plumbing at the top of the
+ list ahead of every real pair.
+ """
+ ctx = _ctx(
+ "pyproject.toml",
+ partners={"uv.lock": 40},
+ self_commits=42,
+ repo_commits={"uv.lock": 41},
+ structural=STRUCTURAL_NOT_APPLICABLE,
+ )
+ assert HiddenCouplingDetector().detect(ctx) == []
+
+
+def test_unlabelled_partner_is_not_a_finding():
+ """An index written before the label existed cannot claim a pair is hidden."""
+ ctx = FileContext(
+ file_path="src/payments.py",
+ language="python",
+ nloc=120,
+ has_test_file=False,
+ module=None,
+ function_metrics={},
+ git_meta={
+ "commit_count_total": 20,
+ "co_change_partners_json": json.dumps(
+ [
+ {
+ "file_path": "src/billing.py",
+ "co_change_count": 18.0,
+ "frequency": 18,
+ "self_commits": 20,
+ "partner_commits": 22,
+ }
+ ]
+ ),
+ },
+ dependents_count=0,
)
assert HiddenCouplingDetector().detect(ctx) == []
@@ -112,7 +171,7 @@ def test_negative_partner_below_noise_floor():
def test_essential_tier_empty_partners_short_circuits():
- """Plan §1.2.1: ESSENTIAL git tier leaves co_change_partners_json empty."""
+ """The ESSENTIAL git tier leaves co_change_partners_json empty."""
ctx = FileContext(
file_path="src/payments.py",
language="python",
@@ -122,7 +181,6 @@ def test_essential_tier_empty_partners_short_circuits():
function_metrics={},
git_meta={"commit_count_total": 100, "co_change_partners_json": "[]"},
dependents_count=0,
- repo_commit_counts={"src/payments.py": 100, "src/billing.py": 100},
)
assert HiddenCouplingDetector().detect(ctx) == []
# Also defend the literal absence of the field.
@@ -141,12 +199,11 @@ def test_test_to_production_pair_is_filtered():
def test_test_support_is_test_material_when_paired_with_production():
- """``conftest.py`` against a production file is an expected test/production
- pairing, so it is filtered like any test would be.
+ """``conftest.py`` against a production file is an expected pairing.
Both ends go through the one shared classifier, which counts fixture plugins
- as test material (#1103). Two *test-material* files are a different case and
- still score — the rule only skips the asymmetric pairing.
+ as test material. Two *test-material* files are a different case and still
+ score -- the rule only skips the asymmetric pairing.
"""
ctx = _ctx(
"tests/conftest.py",
@@ -160,7 +217,7 @@ def test_test_support_is_test_material_when_paired_with_production():
def test_production_path_containing_the_word_test_is_not_test_material():
"""``src/latest/`` is production on both ends, so the pair is still scored.
- An unanchored ``test[s_/]`` match would classify ``src/latest/api.py`` as a
+ An unanchored test-directory match would classify ``src/latest/api.py`` as a
test and filter this pair away as an expected test/production pairing.
"""
ctx = _ctx(
@@ -189,7 +246,7 @@ def test_findings_capped_at_top_three_partners():
)
out = HiddenCouplingDetector().detect(ctx)
assert len(out) == 3
- # Sorted by correlation desc — top three are the highest counts.
+ # Sorted by correlation desc -- top three are the highest counts.
assert [f.details["partner"] for f in out] == ["src/a.py", "src/b.py", "src/c.py"]
@@ -217,27 +274,21 @@ def test_pair_dedupes_naturally_by_frozenset():
assert pairs == {frozenset({"src/a.py", "src/b.py"})}
-def test_fractional_weight_is_not_truncated_before_the_correlation():
- """The weight is a decayed sum, and the correlation divides by it. Dropping
- the fraction moves 8.9/11 from 0.81 to 0.73 -- across the critical band."""
- ctx = _ctx(
- "src/payments.py",
- partners={"src/billing.py": 8.9},
- self_commits=11,
- repo_commits={"src/billing.py": 11},
- )
- (finding,) = HiddenCouplingDetector().detect(ctx)
- assert finding.severity is Severity.CRITICAL
- assert finding.details["co_change_count"] == 8.9
+def test_ratio_reads_the_record_not_the_repo_wide_commit_total():
+ """The denominator comes from the co-change walk, not ``commit_count_total``.
-
-def test_fractional_weight_can_be_the_whole_finding():
- """5.9/11 is 0.54 and clears the correlation floor; truncated to 5 it is
- 0.45 and the finding disappears entirely."""
+ That column is collected over a shorter window and only for files with a
+ code extension, so a pair whose partner is missing from it used to score
+ zero. Here the repo-wide map disagrees with the record and the record wins.
+ """
ctx = _ctx(
"src/payments.py",
- partners={"src/billing.py": 5.9},
- self_commits=11,
- repo_commits={"src/billing.py": 11},
+ partners={"src/billing.py": 9},
+ self_commits=10,
+ repo_commits={"src/billing.py": 10},
)
- assert len(HiddenCouplingDetector().detect(ctx)) == 1
+ ctx.git_meta["commit_count_total"] = 0 # as if it never reached that column
+ (finding,) = HiddenCouplingDetector().detect(ctx)
+ assert finding.details["self_commits"] == 10
+ assert finding.details["partner_commits"] == 10
+ assert finding.details["correlation"] == 0.9
diff --git a/tests/unit/health/test_organizational_biomarkers.py b/tests/unit/health/test_organizational_biomarkers.py
index 6f7b53aa4..b53f115d3 100644
--- a/tests/unit/health/test_organizational_biomarkers.py
+++ b/tests/unit/health/test_organizational_biomarkers.py
@@ -386,7 +386,10 @@ def test_change_entropy_silent_without_signal():
def _partners(*pairs: tuple[str, float]) -> str:
- return json.dumps([{"file_path": p, "co_change_count": c} for p, c in pairs])
+ # The scatter count reads shared commits, so the record needs one.
+ return json.dumps(
+ [{"file_path": p, "co_change_count": c, "frequency": int(c)} for p, c in pairs]
+ )
def test_co_change_scatter_fires_on_broad_coupling():
@@ -410,13 +413,15 @@ def test_co_change_scatter_high_severity_on_heavy_coupling():
assert out[0].severity == "high" # scatter >= 15
-def test_co_change_scatter_ignores_weak_partners():
- # Many partners, but all below the 2.0 weight floor → scatter == 0.
+def test_co_change_scatter_counts_every_recorded_partner():
+ """The indexer already dropped pairs sharing too few commits, so a second
+ cutoff here would only disagree with it."""
meta = {
- "co_change_partners_json": _partners(*[(f"m{i}.py", 1.0) for i in range(12)]),
+ "co_change_partners_json": _partners(*[(f"m{i}.py", 0.04) for i in range(12)]),
"commit_count_90d": 5,
}
- assert CoChangeScatterDetector().detect(_ctx(meta)) == []
+ (finding,) = CoChangeScatterDetector().detect(_ctx(meta))
+ assert finding.details["scatter"] == 12
def test_co_change_scatter_skips_low_activity():
diff --git a/tests/unit/ingestion/test_co_change_edges.py b/tests/unit/ingestion/test_co_change_edges.py
index fde9e8484..1d9a40f32 100644
--- a/tests/unit/ingestion/test_co_change_edges.py
+++ b/tests/unit/ingestion/test_co_change_edges.py
@@ -7,7 +7,9 @@ from pathlib import Path
import pytest
+from repowise.core.co_change import parse_partners
from repowise.core.ingestion.graph import GraphBuilder
+from repowise.core.pipeline.phases.git import label_co_change_structure
@pytest.fixture
@@ -24,7 +26,7 @@ def _meta(partners: object) -> dict:
def test_a_bare_string_partner_does_not_crash_the_pass(builder: GraphBuilder) -> None:
b = builder
- meta = {"a.py": _meta(["b.py", {"file_path": "b.py", "co_change_count": 9}])}
+ meta = {"a.py": _meta(["b.py", {"file_path": "b.py", "co_change_count": 9, "frequency": 9}])}
assert b.add_co_change_edges(meta) == 1
edge = b._graph.edges["a.py", "b.py"]
assert edge["edge_type"] == "co_changes"
@@ -33,14 +35,113 @@ def test_a_bare_string_partner_does_not_crash_the_pass(builder: GraphBuilder) ->
def test_a_non_numeric_weight_does_not_crash_the_pass(builder: GraphBuilder) -> None:
b = builder
- meta = {"a.py": _meta([{"file_path": "b.py", "co_change_count": "lots"}])}
+ meta = {"a.py": _meta([{"file_path": "b.py", "co_change_count": "lots", "frequency": 9}])}
assert b.add_co_change_edges(meta) == 0
def test_the_pair_is_added_once_from_either_side(builder: GraphBuilder) -> None:
b = builder
meta = {
- "a.py": _meta([{"file_path": "b.py", "co_change_count": 9}]),
- "b.py": _meta([{"file_path": "a.py", "co_change_count": 9}]),
+ "a.py": _meta([{"file_path": "b.py", "co_change_count": 9, "frequency": 9}]),
+ "b.py": _meta([{"file_path": "a.py", "co_change_count": 9, "frequency": 9}]),
}
assert b.add_co_change_edges(meta) == 1
+
+
+def test_a_pair_seen_once_is_not_an_edge(builder: GraphBuilder) -> None:
+ """The gate counts shared commits, so a heavy but rare pair is still rare."""
+ b = builder
+ meta = {"a.py": _meta([{"file_path": "b.py", "co_change_count": 99, "frequency": 1}])}
+ assert b.add_co_change_edges(meta) == 0
+
+
+class TestStructuralLabel:
+ """``label_co_change_structure`` over the same graph the edges come from."""
+
+ def test_an_import_edge_corroborates_the_pair(self, builder: GraphBuilder) -> None:
+ builder._graph.add_edge("a.py", "b.py", edge_type="imports")
+ partners = {"a.py": [{"file_path": "b.py", "frequency": 9}]}
+ assert builder.label_co_change_structure(partners) == 0
+ assert partners["a.py"][0]["structural"] == "corroborated"
+
+ def test_a_type_reference_corroborates_it_too(self, builder: GraphBuilder) -> None:
+ """Six of the seven dependency edge types used to be invisible here, so
+ a pair the graph plainly explained was reported as hidden."""
+ builder._graph.add_edge("a.py", "b.py", edge_type="type_use")
+ partners = {"a.py": [{"file_path": "b.py", "frequency": 9}]}
+ assert builder.label_co_change_structure(partners) == 0
+ assert partners["a.py"][0]["structural"] == "corroborated"
+
+ def test_an_edge_the_other_way_still_corroborates(self, builder: GraphBuilder) -> None:
+ builder._graph.add_edge("b.py", "a.py", edge_type="imports")
+ partners = {"a.py": [{"file_path": "b.py", "frequency": 9}]}
+ builder.label_co_change_structure(partners)
+ assert partners["a.py"][0]["structural"] == "corroborated"
+
+ def test_a_co_change_edge_does_not_corroborate_itself(self, builder: GraphBuilder) -> None:
+ builder._graph.add_edge("a.py", "b.py", edge_type="co_changes")
+ partners = {"a.py": [{"file_path": "b.py", "frequency": 9}]}
+ assert builder.label_co_change_structure(partners) == 1
+ assert partners["a.py"][0]["structural"] == "unexplained"
+
+ def test_two_graph_nodes_with_no_edge_are_unexplained(self, builder: GraphBuilder) -> None:
+ partners = {"a.py": [{"file_path": "b.py", "frequency": 9}]}
+ assert builder.label_co_change_structure(partners) == 1
+ assert partners["a.py"][0]["structural"] == "unexplained"
+
+ def test_a_file_outside_the_graph_is_not_applicable(self, builder: GraphBuilder) -> None:
+ """A lockfile is tracked and co-changes, but is never parsed, so it has
+ no edge to find and its absence is not evidence of anything."""
+ partners = {"a.py": [{"file_path": "uv.lock", "frequency": 40}]}
+ assert builder.label_co_change_structure(partners) == 0
+ assert partners["a.py"][0]["structural"] == "not_applicable"
+
+ def test_both_sides_outside_the_graph_is_not_applicable(self, builder: GraphBuilder) -> None:
+ partners = {"pyproject.toml": [{"file_path": "uv.lock", "frequency": 40}]}
+ assert builder.label_co_change_structure(partners) == 0
+ assert partners["pyproject.toml"][0]["structural"] == "not_applicable"
+
+ def test_a_malformed_record_is_skipped_not_raised(self, builder: GraphBuilder) -> None:
+ partners = {"a.py": ["b.py", {"nope": 1}, {"file_path": "b.py", "frequency": 9}]}
+ assert builder.label_co_change_structure(partners) == 1
+
+
+class TestLabelPersistence:
+ """``label_co_change_structure`` writes through the JSON column.
+
+ The label is derived where the graph exists but consumed after a database
+ round-trip, so the write-back is the part that can silently do nothing.
+ """
+
+ def test_the_label_survives_the_column_round_trip(self, builder: GraphBuilder) -> None:
+ builder._graph.add_edge("a.py", "b.py", edge_type="framework")
+ git_meta_map = {
+ "a.py": _meta(
+ [
+ {"file_path": "b.py", "co_change_count": 5.0, "frequency": 9},
+ {"file_path": "uv.lock", "co_change_count": 5.0, "frequency": 9},
+ ]
+ )
+ }
+
+ assert label_co_change_structure(builder, git_meta_map) == 0
+
+ # Re-read the way every consumer does, not from the in-memory records.
+ labels = {
+ p.file_path: p.structural
+ for p in parse_partners(git_meta_map["a.py"]["co_change_partners_json"])
+ }
+ assert labels == {"b.py": "corroborated", "uv.lock": "not_applicable"}
+
+ def test_a_file_with_no_partners_is_left_alone(self, builder: GraphBuilder) -> None:
+ git_meta_map = {"a.py": {"co_change_partners_json": None}}
+ assert label_co_change_structure(builder, git_meta_map) == 0
+ assert git_meta_map["a.py"]["co_change_partners_json"] is None
+
+ def test_an_empty_graph_leaves_existing_labels_alone(self, tmp_path: Path) -> None:
+ """A run that rehydrated no graph must not relabel everything as
+ not-applicable, which would erase what an earlier run established."""
+ empty = GraphBuilder(repo_path=tmp_path)
+ partners = {"a.py": [{"file_path": "b.py", "frequency": 9, "structural": "unexplained"}]}
+ assert empty.label_co_change_structure(partners) == 0
+ assert partners["a.py"][0]["structural"] == "unexplained"
diff --git a/tests/unit/server/test_coupling.py b/tests/unit/server/test_coupling.py
index d62165972..b62de664f 100644
--- a/tests/unit/server/test_coupling.py
+++ b/tests/unit/server/test_coupling.py
@@ -1,4 +1,4 @@
-"""Wire-shape tests for the coupling router serializers.
+"""Wire-shape tests for the coupling response models.
The graph assembly itself is covered by ``tests/unit/coupling/test_graph.py``;
here we lock the JSON keys the endpoint emits so the wire contract (mirrored in
@@ -8,12 +8,12 @@ here we lock the JSON keys the endpoint emits so the wire contract (mirrored in
from __future__ import annotations
from repowise.core.analysis.coupling import CouplingEdge, CouplingNode
-from repowise.server.routers.coupling import _edge_to_dict, _node_to_dict
+from repowise.server.schemas import CouplingEdgeResponse, CouplingNodeResponse
-def test_node_to_dict_wire_shape() -> None:
+def test_node_wire_shape() -> None:
n = CouplingNode(file_path="a.py", module="api", score=3.4, nloc=420)
- assert _node_to_dict(n) == {
+ assert CouplingNodeResponse(**vars(n)).model_dump() == {
"file_path": "a.py",
"module": "api",
"score": 3.4,
@@ -21,9 +21,9 @@ def test_node_to_dict_wire_shape() -> None:
}
-def test_node_to_dict_null_score_module() -> None:
+def test_node_null_score_module() -> None:
n = CouplingNode(file_path="config.yaml", module=None, score=None, nloc=0)
- assert _node_to_dict(n) == {
+ assert CouplingNodeResponse(**vars(n)).model_dump() == {
"file_path": "config.yaml",
"module": None,
"score": None,
@@ -31,11 +31,39 @@ def test_node_to_dict_null_score_module() -> None:
}
-def test_edge_to_dict_wire_shape() -> None:
- e = CouplingEdge(source="a.py", target="b.py", strength=4.25, last_co_change="2026-06-01")
- assert _edge_to_dict(e) == {
+def test_edge_wire_shape() -> None:
+ e = CouplingEdge(
+ source="a.py",
+ target="b.py",
+ strength=4.25,
+ last_co_change="2026-06-01",
+ support=9,
+ confidence_ab=0.9,
+ confidence_ba=0.1,
+ structural="unexplained",
+ )
+ assert CouplingEdgeResponse(**vars(e)).model_dump() == {
"source": "a.py",
"target": "b.py",
"strength": 4.25,
"last_co_change": "2026-06-01",
+ "support": 9,
+ "confidence_ab": 0.9,
+ "confidence_ba": 0.1,
+ "structural": "unexplained",
+ }
+
+
+def test_an_edge_from_an_older_index_still_serializes() -> None:
+ """A repo indexed before the new fields existed must not 500 the endpoint."""
+ e = CouplingEdge(source="a.py", target="b.py", strength=4.25, last_co_change=None)
+ assert CouplingEdgeResponse(**vars(e)).model_dump() == {
+ "source": "a.py",
+ "target": "b.py",
+ "strength": 4.25,
+ "last_co_change": None,
+ "support": 0,
+ "confidence_ab": None,
+ "confidence_ba": None,
+ "structural": None,
}
diff --git a/tests/unit/server/test_git.py b/tests/unit/server/test_git.py
index 7508aa659..0769e95dc 100644
--- a/tests/unit/server/test_git.py
+++ b/tests/unit/server/test_git.py
@@ -31,7 +31,7 @@ async def _insert_git_metadata(session_factory, repo_id: str) -> None:
top_authors_json=json.dumps([{"name": "Alice", "commits": 30}]),
significant_commits_json=json.dumps([{"sha": "abc", "message": "init"}]),
co_change_partners_json=json.dumps(
- [{"file_path": "src/utils.py", "co_change_count": 5}]
+ [{"file_path": "src/utils.py", "co_change_count": 5, "frequency": 5}]
),
is_hotspot=True,
is_stable=False,
diff --git a/tests/unit/test_co_change.py b/tests/unit/test_co_change.py
index f6cf1ac82..19a4771a3 100644
--- a/tests/unit/test_co_change.py
+++ b/tests/unit/test_co_change.py
@@ -95,3 +95,51 @@ class TestRawRecord:
a = parse_partners(json.dumps([{"file_path": "a.py", "count": 1, "extra": 1}]))
b = parse_partners(json.dumps([{"file_path": "a.py", "count": 1}]))
assert a == b
+
+
+class TestSupportAndConfidence:
+ def test_reads_the_support_count_and_both_commit_totals(self) -> None:
+ raw = json.dumps(
+ [
+ {
+ "file_path": "a.py",
+ "co_change_count": 4.25,
+ "frequency": 9,
+ "self_commits": 10,
+ "partner_commits": 30,
+ }
+ ]
+ )
+ (p,) = parse_partners(raw)
+ assert p.support == 9
+ assert (p.self_commits, p.partner_commits) == (10, 30)
+
+ def test_counts_missing_or_malformed_read_as_zero(self) -> None:
+ (p,) = parse_partners(
+ json.dumps([{"file_path": "a.py", "count": 1, "frequency": "many"}])
+ )
+ assert p.support == 0
+
+ def test_weight_keeps_its_fraction(self) -> None:
+ """The weight is a decayed sum, so truncating it moves severity bands."""
+ (p,) = parse_partners(json.dumps([{"file_path": "a.py", "co_change_count": 8.9}]))
+ assert p.weight == 8.9
+
+
+class TestStructuralLabel:
+ def test_reads_the_label(self) -> None:
+ (p,) = parse_partners(
+ json.dumps([{"file_path": "a.py", "count": 1, "structural": "unexplained"}])
+ )
+ assert p.structural == "unexplained"
+
+ def test_an_unlabelled_record_is_none_not_unexplained(self) -> None:
+ """An older index must not have its silence read as a finding."""
+ (p,) = parse_partners(json.dumps([{"file_path": "a.py", "count": 1}]))
+ assert p.structural is None
+
+ def test_a_non_string_label_is_none(self) -> None:
+ (p,) = parse_partners(
+ json.dumps([{"file_path": "a.py", "count": 1, "structural": 3}])
+ )
+ assert p.structural is None
diff --git a/tests/unit/test_git_indexer.py b/tests/unit/test_git_indexer.py
index a3ea84ab0..874cad7cb 100644
--- a/tests/unit/test_git_indexer.py
+++ b/tests/unit/test_git_indexer.py
@@ -152,7 +152,7 @@ class TestSignificantCommitFilter:
class TestCoChangeDetection:
- """Files changed together >= 3 times are detected as co-change partners."""
+ """Files changed together are detected as co-change partners."""
def test_co_change_detection(self) -> None:
mock_repo = MagicMock()
@@ -173,11 +173,9 @@ class TestCoChangeDetection:
)
mock_repo.git.log.return_value = raw_log
- result, _entropy = compute_co_changes_and_entropy(
- mock_repo, all_files, commit_limit=500, min_count=3
- )
+ result, _entropy = compute_co_changes_and_entropy(mock_repo, all_files, commit_limit=500)
- # a.py <-> b.py should appear (co-changed 4 times, >= min_count=3)
+ # a.py <-> b.py should appear (co-changed 4 times)
assert "a.py" in result
partner_paths = [p["file_path"] for p in result["a.py"]]
assert "b.py" in partner_paths
@@ -186,9 +184,16 @@ class TestCoChangeDetection:
partner_paths_b = [p["file_path"] for p in result["b.py"]]
assert "a.py" in partner_paths_b
- # With temporal decay, score is close to 4 (all commits very recent)
+ # Three of the four commits are the pair alone, so each contributes its
+ # full weight; the three-file commit contributes half.
co_count = next(p["co_change_count"] for p in result["a.py"] if p["file_path"] == "b.py")
- assert co_count >= 3.9 # decay-weighted, very recent → near 4.0
+ assert 3.4 <= co_count <= 3.6
+
+ # The plain count is undecayed and unsplit.
+ entry_b = next(p for p in result["a.py"] if p["file_path"] == "b.py")
+ assert entry_b["frequency"] == 4
+ assert entry_b["self_commits"] == 4
+ assert entry_b["partner_commits"] == 4
# Verify last_co_change date is present
entry = next(p for p in result["a.py"] if p["file_path"] == "b.py")
@@ -956,30 +961,26 @@ class TestGitUnavailableGraceful:
class TestCoChangeBelowThresholdSkipped:
- """Pairs with co-change count < min_count are not stored."""
+ """A pair is kept on shared commits, not on the decayed weight."""
- def test_co_change_below_threshold_skipped(self) -> None:
+ def test_an_old_pair_survives_where_a_weight_cutoff_would_drop_it(self) -> None:
+ """Three co-changes two years ago decay to a weight under any useful
+ cutoff, but they are still three co-changes and the pair is real."""
mock_repo = MagicMock()
- all_files = {"x.py", "y.py", "z.py"}
-
- # Only 2 commits with x.py + y.py together (below default min_count=3)
- # 1 commit with x.py + z.py (also below min_count=3)
import time
- now = int(time.time())
- raw_log = (
- f"\x00{now}\nx.py\ny.py\n"
- f"\x00{now - 86400}\nx.py\ny.py\n"
- f"\x00{now - 172800}\nx.py\nz.py\n"
+ old = int(time.time()) - 730 * 86400
+ mock_repo.git.log.return_value = "".join(
+ f"\x00{old - i * 86400}\np.py\nq.py\n" for i in range(3)
)
- mock_repo.git.log.return_value = raw_log
result, _entropy = compute_co_changes_and_entropy(
- mock_repo, all_files, commit_limit=500, min_count=3
+ mock_repo, {"p.py", "q.py"}, commit_limit=500
)
- # No pairs should appear since none reach min_count=3
- assert result == {}
+ (partner,) = result["p.py"]
+ assert partner["frequency"] == 3
+ assert partner["co_change_count"] < 0.1
# ---------------------------------------------------------------------------
@@ -1021,7 +1022,7 @@ class TestChangeEntropy:
mock_repo.git.log.return_value = "".join(blocks)
_co, entropy = compute_co_changes_and_entropy(
- mock_repo, all_files, commit_limit=2000, min_count=2
+ mock_repo, all_files, commit_limit=2000
)
# Focused file changed alone → no entropy entry.
@@ -1117,3 +1118,103 @@ class TestExcludePatterns:
result = indexer._get_tracked_files(fake_repo)
assert result == ["src/main.py", ".claude/config.yml"]
+
+
+class TestCoChangeCommitWidth:
+ """A pair's weight is split across the commit that produced it."""
+
+ @staticmethod
+ def _log(now: int, *commits: tuple[str, ...]) -> str:
+ return "".join(
+ f"\x00{now - i * 86400}\n" + "".join(f"{p}\n" for p in files)
+ for i, files in enumerate(commits)
+ )
+
+ def test_a_wide_commit_is_weaker_evidence_than_a_narrow_one(self) -> None:
+ """Both pairs share two commits. The pair seen alone is the real one."""
+ import time
+
+ now = int(time.time())
+ wide = tuple(f"w{i}.py" for i in range(20))
+ all_files = {"a.py", "b.py", *wide}
+ mock_repo = MagicMock()
+ mock_repo.git.log.return_value = self._log(
+ now,
+ ("a.py", "b.py"),
+ ("a.py", "b.py"),
+ wide,
+ wide,
+ )
+
+ result, _entropy = compute_co_changes_and_entropy(
+ mock_repo, all_files, commit_limit=500
+ )
+
+ narrow = next(p for p in result["a.py"] if p["file_path"] == "b.py")
+ broad = next(p for p in result["w0.py"] if p["file_path"] == "w1.py")
+ assert narrow["frequency"] == broad["frequency"] == 2
+ assert narrow["co_change_count"] > broad["co_change_count"] * 10
+
+ def test_per_file_partner_list_is_capped(self) -> None:
+ import time
+
+ from repowise.core.co_change import MAX_PARTNERS_PER_FILE
+
+ now = int(time.time())
+ others = tuple(f"f{i}.py" for i in range(MAX_PARTNERS_PER_FILE + 10))
+ all_files = {"hub.py", *others}
+ # Every partner shares two commits with the hub, so support alone
+ # cannot trim the list.
+ mock_repo = MagicMock()
+ mock_repo.git.log.return_value = self._log(
+ now, ("hub.py", *others), ("hub.py", *others)
+ )
+
+ result, _entropy = compute_co_changes_and_entropy(
+ mock_repo, all_files, commit_limit=500
+ )
+
+ assert len(result["hub.py"]) == MAX_PARTNERS_PER_FILE
+
+ def test_partner_records_carry_each_side_own_commit_total(self) -> None:
+ """The two totals differ, which is what makes confidence directional."""
+ import time
+
+ now = int(time.time())
+ mock_repo = MagicMock()
+ mock_repo.git.log.return_value = self._log(
+ now,
+ ("readme.md", "bench.md"),
+ ("readme.md", "bench.md"),
+ ("readme.md", "other.md"),
+ ("readme.md", "other.md"),
+ )
+
+ result, _entropy = compute_co_changes_and_entropy(
+ mock_repo, {"readme.md", "bench.md", "other.md"}, commit_limit=500
+ )
+
+ bench = next(p for p in result["readme.md"] if p["file_path"] == "bench.md")
+ assert bench["self_commits"] == 4
+ assert bench["partner_commits"] == 2
+
+ def test_a_files_solo_commits_count_toward_its_total(self) -> None:
+ """Otherwise the denominator is "commits shared with someone", and a
+ file that mostly changes alone reports full confidence in its partner.
+ """
+ import time
+
+ now = int(time.time())
+ shared = ("config.py", "loader.py")
+ alone = ("config.py",)
+ mock_repo = MagicMock()
+ mock_repo.git.log.return_value = self._log(now, shared, shared, *([alone] * 9))
+
+ result, _entropy = compute_co_changes_and_entropy(
+ mock_repo, {"config.py", "loader.py"}, commit_limit=500
+ )
+
+ (partner,) = result["config.py"]
+ assert partner["frequency"] == 2
+ assert partner["self_commits"] == 11 # 2 shared + 9 alone
+ assert partner["partner_commits"] == 2