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.

refactor(co-change): read co-change records in one place (#1967)

Raghav Chamadiya5bb7c4bc2388
diff --git a/docs/reference/COMPUTED_GLOSSARY.md b/docs/reference/COMPUTED_GLOSSARY.md
index cabe2ccfd..fc7699b0f 100644
--- a/docs/reference/COMPUTED_GLOSSARY.md
+++ b/docs/reference/COMPUTED_GLOSSARY.md
@@ -136,7 +136,7 @@ workspace overlays, MCP responses, and CLI output.
| Churn percentile | Rank percentile among indexed files by temporal hotspot score, with 90-day commits as tiebreak. | `_compute_percentiles()` | `0.88` |
| Hotspot flag | Top churn file: percentile >= 0.75 and has recent commits. | `_compute_percentiles()` | `is_hotspot: true` |
| Stable file flag | File with more than 10 total commits and no recent 90-day commits. | `_index_file()` | `is_stable: true` |
-| Co-change partner | File historically changed in the same commits, with temporal decay. | `_compute_co_changes()` | `{file_path: "src/schema.py", co_change_count: 3.72, last_co_change: "2026-04-14"}` |
+| Co-change partner | File historically changed in the same commits, with temporal decay. | `compute_co_changes_and_entropy()` | `{file_path: "src/schema.py", co_change_count: 3.72, last_co_change: "2026-04-14"}` |
| Agent provenance (commit) | Which coding agent (if any) authored a commit, from local-git channels only (identity fields, message footers, co-author trailers); tier 1 = near-autonomous bot account, 2 = human-driven agent, 3 = assisted. | `agent_provenance.AgentProvenanceClassifier.classify()` | `{agent_name: "claude", agent_autonomy_tier: 2, agent_channel: "message_footer", agent_confidence: "high"}` |
| Agent-authored share (file) | Fraction of a file's indexed commits that are agent-attributed, with per-tier counts. | `_index_file()` | `{agent_authored_pct: 0.42, agent_commit_count: 21, agent_tier_counts: {"2": 18, "3": 3}}` |
| Git index summary | Repo-level indexing result. | `GitIndexSummary` | `{files_indexed: 420, hotspots: 38, stable_files: 71, duration_seconds: 12.4}` |
diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/decision_inject.py b/packages/cli/src/repowise/cli/commands/augment_cmd/decision_inject.py
index c206d8e25..a03822154 100644
--- a/packages/cli/src/repowise/cli/commands/augment_cmd/decision_inject.py
+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/decision_inject.py
@@ -32,6 +32,8 @@ import re
import sqlite3
from pathlib import Path
+from repowise.core.co_change import parse_partners
+
# --- SessionStart tunables -------------------------------------------------
#: Hard budget for the whole injected block, in estimated tokens (chars/4).
@@ -275,16 +277,9 @@ def _expand_one_hop(conn: sqlite3.Connection, seeds: list[str]) -> set[str]:
tuple(seeds),
).fetchall()
for (raw,) in rows:
- try:
- partners = json.loads(raw or "[]")
- except (TypeError, ValueError):
- continue
- if not isinstance(partners, list):
- continue
- for p in partners:
- path = p.get("file_path") if isinstance(p, dict) else None
- if isinstance(path, str) and path and path not in seeds:
- hop.add(path)
+ for partner in parse_partners(raw):
+ if partner.file_path not in seeds:
+ hop.add(partner.file_path)
if len(hop) >= _MAX_HOP:
return hop
return hop
diff --git a/packages/core/src/repowise/core/analysis/coupling/graph.py b/packages/core/src/repowise/core/analysis/coupling/graph.py
index cea506d83..e924f25be 100644
--- a/packages/core/src/repowise/core/analysis/coupling/graph.py
+++ b/packages/core/src/repowise/core/analysis/coupling/graph.py
@@ -17,7 +17,8 @@ Honesty rules:
* Co-change is a *temporal* hint (files committed together), not a verified
code dependency -- the strength is the decay-weighted count the indexer
- already thresholds (``>= 0.5``); we surface it verbatim and never invent one.
+ already thresholds (``MIN_CO_CHANGE_WEIGHT``); we surface it verbatim and
+ never invent one.
* We do **not** fabricate a "strengthening / weakening" trend: co-change history
is not snapshotted, so a trend is not derivable. ``strength`` (magnitude) and
``last_co_change`` (recency) are the only honest encodings.
@@ -28,10 +29,11 @@ Honesty rules:
from __future__ import annotations
-import json
from dataclasses import dataclass
from typing import Protocol
+from ...co_change import canonical_pair, parse_partners
+
class MetricLike(Protocol):
"""The health-metric fields the graph reads (duck-typed).
@@ -99,21 +101,6 @@ class CouplingGraph:
total_edges: int
-def _parse_partners(raw: str | None) -> list[dict]:
- """Parse a ``co_change_partners_json`` cell, tolerating absent/bad JSON.
-
- Mirrors the defensive parsing in :mod:`analysis.health.trends`: a malformed
- cell yields no partners rather than raising.
- """
- if not raw:
- return []
- try:
- parsed = json.loads(raw)
- except (ValueError, TypeError):
- return []
- return parsed if isinstance(parsed, list) else []
-
-
def coupling_graph(
metrics: list[MetricLike],
git_meta_by_path: dict[str, GitMetaLike],
@@ -138,18 +125,12 @@ def coupling_graph(
# Deduplicate symmetric partner records into undirected edges.
best: dict[tuple[str, str], tuple[float, str | None]] = {}
for src, meta in git_meta_by_path.items():
- for partner in _parse_partners(meta.co_change_partners_json):
- dst = partner.get("file_path")
- if not dst or dst == src:
- continue
- try:
- strength = float(partner.get("co_change_count") or 0.0)
- except (ValueError, TypeError):
- continue
- if strength <= 0:
+ for partner in parse_partners(meta.co_change_partners_json):
+ dst = partner.file_path
+ if dst == src or partner.weight <= 0:
continue
- last = partner.get("last_co_change")
- key = (src, dst) if src < dst else (dst, src)
+ strength, last = partner.weight, partner.last_co_change
+ key = canonical_pair(src, dst)
prev = best.get(key)
if prev is None:
best[key] = (strength, last)
diff --git a/packages/core/src/repowise/core/analysis/graph_view.py b/packages/core/src/repowise/core/analysis/graph_view.py
new file mode 100644
index 000000000..ecfa18bec
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/graph_view.py
@@ -0,0 +1,49 @@
+"""The narrow graph view analyses use to ask about an edge between two files.
+
+Analyses that only need "is there an edge from A to B, of this type?" should
+not pull NetworkX into their signature, because that makes every one of their
+tests build a real graph to say no. :class:`HasEdge` is the contract and
+:class:`ImportEdgeView` is the adapter over the real ``DiGraph``.
+
+It lives under ``analysis/`` rather than beside any one consumer because more
+than one of them needs it, and a view of the graph belongs to none of them.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Protocol
+
+__all__ = ["HasEdge", "ImportEdgeView"]
+
+
+class HasEdge(Protocol):
+ """Minimal graph view: does an edge of some type join these two files?"""
+
+ def has_edge(self, src: str, dst: str, key: str = "imports") -> bool: ...
+
+
+class ImportEdgeView:
+ """``HasEdge`` over a NetworkX DiGraph, matched on the ``edge_type`` attribute.
+
+ The graph stores one edge between any two file nodes and records its kind as
+ an attribute, so *key* is compared against that rather than being a
+ multigraph key. A missing graph answers ``False`` to everything, which lets
+ a caller pass ``None`` instead of branching.
+ """
+
+ __slots__ = ("_graph",)
+
+ def __init__(self, graph: Any) -> None:
+ self._graph = graph
+
+ def has_edge(self, src: str, dst: str, key: str = "imports") -> 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") == key
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 554458d3c..69ead053c 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/base.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/base.py
@@ -6,21 +6,12 @@ from dataclasses import dataclass, field
from typing import Any, Protocol
from ....ingestion.git_indexer.function_blame import BlameIndex
+from ...graph_view import HasEdge
from ..complexity import ClassComplexity, ErrorHandlingHit, FunctionComplexity, PerfHit
from ..duplication import ClonePair
from ..models import Severity
-class HasEdge(Protocol):
- """Minimal graph view for biomarkers that need to ask "is there an
- edge between these two files?" without depending on NetworkX in
- tests. ``engine.py`` wraps the real ``DiGraph`` in an adapter that
- implements this protocol.
- """
-
- def has_edge(self, src: str, dst: str, key: str = "imports") -> bool: ...
-
-
@dataclass
class FileContext:
"""All inputs a biomarker may need to evaluate a file.
@@ -76,8 +67,8 @@ class FileContext:
# is the percent of NLOC covered by clones.
clones: list[ClonePair] = field(default_factory=list)
duplication_pct: float | None = None
- # Thin graph view exposing only ``has_edge`` — see ``HasEdge`` above.
- # ``None`` on test fixtures that never construct a graph.
+ # 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
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 c34f373cd..2d1506838 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
@@ -22,9 +22,9 @@ detector emits nothing.
from __future__ import annotations
-import json
from typing import Any
+from ....co_change import parse_partners
from ..models import Severity
from .base import BiomarkerResult, FileContext
@@ -35,24 +35,8 @@ _MIN_COMMITS_90D = 3
def _count_scatter(meta: dict[str, Any]) -> int:
- raw = meta.get("co_change_partners_json")
- if not raw:
- return 0
- try:
- partners = json.loads(raw)
- except (TypeError, ValueError):
- return 0
- scatter = 0
- for p in partners:
- if not isinstance(p, dict):
- continue
- weight = p.get("co_change_count") or p.get("count") or 0
- try:
- if float(weight) >= _MIN_PARTNER_WEIGHT:
- scatter += 1
- except (TypeError, ValueError):
- continue
- return scatter
+ partners = parse_partners(meta.get("co_change_partners_json"))
+ return sum(1 for p in partners if p.weight >= _MIN_PARTNER_WEIGHT)
def _as_int(value: object, default: int = 0) -> int:
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/dry_violation.py b/packages/core/src/repowise/core/analysis/health/biomarkers/dry_violation.py
index 1884c7c90..5b7ccade7 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/dry_violation.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/dry_violation.py
@@ -68,12 +68,16 @@ class DryViolationDetector:
"clone_pair_count": len(ctx.clones),
"worst_clone_lines": worst_lines,
"worst_clone_partner": partner,
- "worst_clone_co_change": worst.co_change_count,
+ "worst_clone_co_change": round(worst.co_change_count, 2),
},
reason=(
f"{dup_pct:.0f}% of file duplicated; worst clone shares "
f"{worst_lines} lines with {partner}"
- + (f" (co-changed {worst.co_change_count}x)" if worst.co_change_count else "")
+ + (
+ f" (co-changed {round(worst.co_change_count, 2)}x)"
+ if worst.co_change_count
+ else ""
+ )
),
)
]
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 9e1265e45..aae488f38 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
@@ -16,16 +16,14 @@ Fires when:
co-change)
Tier-aware: when ``co_change_partners_json`` is empty (ESSENTIAL git
-tier, plan §1.2.1) the detector short-circuits to zero findings. The
-empty short-circuit is explicit so backfill behavior is testable.
+tier) the detector short-circuits to zero findings. The empty
+short-circuit is explicit so backfill behavior is testable.
"""
from __future__ import annotations
-import json
-from typing import Any
-
-from ....test_paths import is_test_related_path
+from ....co_change import parse_partners
+from ....test_paths import is_test_to_production_pair
from ..models import Severity
from .base import BiomarkerResult, FileContext
@@ -43,29 +41,6 @@ _MAX_FINDINGS_PER_FILE = 3
_MIN_CO_CHANGE_FOR_HIGH = 8
-def _parse_partners(meta: dict[str, Any]) -> dict[str, int]:
- raw = meta.get("co_change_partners_json")
- if not raw:
- return {}
- try:
- partners = json.loads(raw)
- except (TypeError, ValueError):
- return {}
- out: dict[str, int] = {}
- for p in partners:
- if not isinstance(p, dict):
- continue
- path = p.get("file_path") or p.get("path")
- count = p.get("co_change_count") or p.get("count") or 0
- if not path:
- continue
- try:
- out[str(path)] = int(count)
- except (TypeError, ValueError):
- continue
- return out
-
-
def _as_int(value: object, default: int = 0) -> int:
try:
return int(value or 0) # type: ignore[arg-type]
@@ -73,7 +48,7 @@ def _as_int(value: object, default: int = 0) -> int:
return default
-def _severity_for(correlation: float, co_count: int) -> Severity:
+def _severity_for(correlation: float, co_count: float) -> 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:
@@ -91,8 +66,8 @@ class HiddenCouplingDetector:
def detect(self, ctx: FileContext) -> list[BiomarkerResult]:
meta = ctx.git_meta or {}
- partners = _parse_partners(meta)
- # Explicit ESSENTIAL-tier short-circuit (plan §1.2.1).
+ partners = parse_partners(meta.get("co_change_partners_json"))
+ # Explicit ESSENTIAL-tier short-circuit.
if not partners:
return []
@@ -100,12 +75,12 @@ class HiddenCouplingDetector:
if total_self < _MIN_COMMITS:
return []
- self_is_test = is_test_related_path(ctx.file_path, ctx.language)
graph = ctx.graph_view
counts = ctx.repo_commit_counts or {}
- candidates: list[tuple[float, str, int]] = []
- for partner_path, co_count in partners.items():
+ candidates: list[tuple[float, str, float]] = []
+ for partner in partners:
+ partner_path, co_count = partner.file_path, partner.weight
if partner_path == ctx.file_path:
continue
partner_total = counts.get(partner_path, 0)
@@ -117,11 +92,11 @@ class HiddenCouplingDetector:
correlation = co_count / denom
if correlation < _MIN_CORRELATION:
continue
- # Skip test ↔ production pairings — expected to co-change. The
- # partner is a bare path from the co-change record and ``graph_view``
- # exposes only ``has_edge``, so there is no node to read its stored
- # flag from and no language to pass; the path rules are all we have.
- if self_is_test ^ is_test_related_path(partner_path):
+ # Test ↔ production pairs are expected to co-change, so they carry
+ # no finding.
+ if is_test_to_production_pair(
+ ctx.file_path, partner_path, code_language=ctx.language
+ ):
continue
# Skip when an explicit import edge already documents the
# coupling.
@@ -150,13 +125,13 @@ class HiddenCouplingDetector:
details={
"partner": partner_path,
"correlation": round(correlation, 3),
- "co_change_count": co_count,
+ "co_change_count": round(co_count, 2),
"self_commits": total_self,
"partner_commits": counts.get(partner_path, 0),
},
reason=(
f"{partner_path} co-changes with this file "
- f"{co_count} times ({correlation:.0%} of shared "
+ f"{round(co_count, 2)} times ({correlation:.0%} of shared "
"commits) 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 42580ab72..fd1574dad 100644
--- a/packages/core/src/repowise/core/analysis/health/duplication/detector.py
+++ b/packages/core/src/repowise/core/analysis/health/duplication/detector.py
@@ -20,7 +20,6 @@ size.
from __future__ import annotations
-import json
import time
from collections import defaultdict
from collections.abc import Iterable
@@ -31,6 +30,7 @@ from typing import Any
import structlog
from repowise.core.cancellation import check_cancelled
+from repowise.core.co_change import parse_partners
from .limits import DuplicationDiagnostics, DuplicationLimits, looks_minified
from .rabin_karp import WindowHash, index_by_hash, rolling_hashes
@@ -56,7 +56,7 @@ class ClonePair:
b_start_line: int
b_end_line: int
token_count: int
- co_change_count: int = 0 # 0 when files don't share co-change history
+ co_change_count: float = 0.0 # 0 when files don't share co-change history
@property
def is_intra_file(self) -> bool:
@@ -93,42 +93,25 @@ def _read_source(abs_path: str) -> bytes | None:
return None
-def _parse_co_change_partners(meta: dict[str, Any]) -> dict[str, int]:
- raw = meta.get("co_change_partners_json")
- if not raw:
- return {}
- try:
- partners = json.loads(raw)
- except (TypeError, ValueError):
- return {}
- out: dict[str, int] = {}
- for p in partners:
- if not isinstance(p, dict):
- continue
- path = p.get("file_path") or p.get("path")
- count = p.get("co_change_count") or p.get("count") or 0
- if not path:
- continue
- try:
- out[str(path)] = int(count)
- except (TypeError, ValueError):
- continue
- return out
+def _partner_weight(meta: dict[str, Any], partner_path: str) -> float:
+ """The decayed co-change weight *meta*'s file carries for *partner_path*."""
+ for p in parse_partners(meta.get("co_change_partners_json")):
+ if p.file_path == partner_path:
+ return p.weight
+ return 0.0
def _co_change_score(
file_a: str,
file_b: str,
git_meta_map: dict[str, dict[str, Any]],
-) -> int:
+) -> float:
"""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."""
a_meta = git_meta_map.get(file_a, {}) or {}
b_meta = git_meta_map.get(file_b, {}) or {}
- from_a = _parse_co_change_partners(a_meta).get(file_b, 0)
- from_b = _parse_co_change_partners(b_meta).get(file_a, 0)
- return max(from_a, from_b)
+ return max(_partner_weight(a_meta, file_b), _partner_weight(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 f62b67c65..37c653ec7 100644
--- a/packages/core/src/repowise/core/analysis/health/engine.py
+++ b/packages/core/src/repowise/core/analysis/health/engine.py
@@ -37,9 +37,9 @@ from ...ingestion.git_indexer.function_blame import (
from ...ingestion.package_roots import module_for as _module_for
from ...ingestion.package_roots import package_roots_from_paths as _package_roots
from ...ingestion.package_roots import scan_package_roots as _scan_package_roots
+from ..graph_view import HasEdge, ImportEdgeView
from ..test_reachability import files_reached_by_tests
from .biomarkers import FileContext, detect_all
-from .biomarkers.base import HasEdge
from .complexity import FileComplexity, FunctionComplexity, walk_file
from .coverage import is_test_file as _coverage_is_test_file
from .dataflow import FileDataflowCache
@@ -152,32 +152,6 @@ def _read_source_lines(abs_path: str) -> list[str] | None:
return text.splitlines()
-class _ImportEdgeView:
- """Thin ``HasEdge`` adapter over a NetworkX DiGraph.
-
- The graph stores ``edge_type`` as an attribute on each (single)
- edge between two file nodes. We look it up directly rather than
- pulling NetworkX into the biomarker test surface.
- """
-
- __slots__ = ("_graph",)
-
- def __init__(self, graph: Any) -> None:
- self._graph = graph
-
- def has_edge(self, src: str, dst: str, key: str = "imports") -> 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") == key
-
-
def _percentile_p80(counts: list[int]) -> int | None:
"""80th percentile of *counts* using the inclusive-lower convention
already used by ``churn_percentile`` in ``enrich.compute_percentiles``.
@@ -463,7 +437,7 @@ class HealthAnalyzer:
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
+ 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
# its clone list. Cheap when the repo is small; when disabled
@@ -647,7 +621,7 @@ class HealthAnalyzer:
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
+ 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
# overlap with the pre-walk instead of blocking it — on large
diff --git a/packages/core/src/repowise/core/analysis/pr_blast.py b/packages/core/src/repowise/core/analysis/pr_blast.py
index abbdb39e5..6548681bd 100644
--- a/packages/core/src/repowise/core/analysis/pr_blast.py
+++ b/packages/core/src/repowise/core/analysis/pr_blast.py
@@ -14,7 +14,6 @@ co_change_partners_json field stored in git_metadata rows.
from __future__ import annotations
-import json
import math
import os
from collections import Counter, defaultdict
@@ -25,6 +24,7 @@ from sqlalchemy import select, text
from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.analysis.risk_semantics import structural_impact_contract
+from repowise.core.co_change import parse_partners
from repowise.core.exclusion import build_exclude_spec, is_excluded
from repowise.core.ingestion.models import FILE_DEPENDENCY_EDGE_TYPES
from repowise.core.persistence.models import GitMetadata, GraphNode, Repository
@@ -318,11 +318,9 @@ class PRBlastRadiusAnalyzer:
warnings = []
for meta in res.scalars().all():
- partners = json.loads(meta.co_change_partners_json or "[]")
- for partner in partners:
- partner_path = partner.get("file_path") or partner.get("path") or ""
- score = float(partner.get("co_change_count") or partner.get("count") or 0)
- if partner_path and partner_path not in changed_set:
+ for partner in parse_partners(meta.co_change_partners_json):
+ partner_path, score = partner.file_path, partner.weight
+ if partner_path not in changed_set:
warnings.append(
{
"changed": meta.file_path,
@@ -333,8 +331,8 @@ class PRBlastRadiusAnalyzer:
"evidence_kind": "historical",
"provenance": "git_history",
**(
- {"support": partner["frequency"]}
- if partner.get("frequency") is not None
+ {"support": partner.record["frequency"]}
+ if partner.record.get("frequency") is not None
else {}
),
}
diff --git a/packages/core/src/repowise/core/co_change.py b/packages/core/src/repowise/core/co_change.py
new file mode 100644
index 000000000..d5b05a188
--- /dev/null
+++ b/packages/core/src/repowise/core/co_change.py
@@ -0,0 +1,113 @@
+"""Single home for reading persisted co-change records.
+
+``GitMetadata.co_change_partners_json`` is written in one place
+(:mod:`ingestion.git_indexer.co_change`) and read in seventeen. Every reader
+used to re-derive the format for itself, and they disagreed: on which key
+aliases to accept, on whether the weight was an int or a float, and on whether
+a malformed cell should raise. Two of them read a partner record without first
+checking it is a record, which turned one bad row into an ``AttributeError``
+out of a REST handler.
+
+This module sits beside :mod:`test_paths` and :mod:`support_paths`, and for the
+same reason those do: the column is read during ingestion, during analysis, and
+at query time, so the one answer cannot live under ``ingestion/`` without the
+server importing across a layer to reach it.
+
+**One reader.** :func:`parse_partners` is it. Callers that must put the record
+back on the wire, or that read a field this module does not model, take it from
+:attr:`CoChangePartner.record` rather than decoding the cell a second time.
+
+**Weights are floats.** The producer rounds to 2dp because the value is a
+recency-decayed sum, not a count of commits. Truncating it to ``int`` loses the
+part that decides a severity band.
+"""
+
+from __future__ import annotations
+
+import json
+from dataclasses import dataclass, field
+
+__all__ = [
+ "CO_CHANGE_DECAY_TAU",
+ "MIN_CO_CHANGE_WEIGHT",
+ "CoChangePartner",
+ "canonical_pair",
+ "parse_partners",
+]
+
+
+# Tau in ``exp(-age_days / tau)``, which puts the half-life near 125 days.
+# Defined here rather than in the indexer because two independent producers
+# apply it (per-repo history and the cross-repo session miner), and a drift
+# 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
+
+
+@dataclass(frozen=True)
+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.
+ """
+
+ file_path: str
+ weight: float
+ last_co_change: str | None = None
+ record: dict = field(default_factory=dict, compare=False, repr=False)
+
+
+def parse_partners(raw: object) -> list[CoChangePartner]:
+ """Partners from a ``co_change_partners_json`` cell, strongest first.
+
+ Tolerates an absent cell, malformed JSON, a non-list document, and non-record
+ 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``.
+ """
+ if not raw:
+ return []
+ if isinstance(raw, (str, bytes)):
+ try:
+ parsed: object = json.loads(raw)
+ except (TypeError, ValueError):
+ return []
+ else:
+ parsed = raw
+ if not isinstance(parsed, list):
+ return []
+
+ out: list[CoChangePartner] = []
+ for record in parsed:
+ if not isinstance(record, dict):
+ continue
+ path = record.get("file_path") or record.get("path")
+ if not path:
+ continue
+ try:
+ weight = float(record.get("co_change_count") or record.get("count") or 0.0)
+ except (TypeError, ValueError):
+ continue
+ last = record.get("last_co_change")
+ out.append(
+ CoChangePartner(
+ file_path=str(path),
+ weight=weight,
+ last_co_change=last if isinstance(last, str) else None,
+ record=record,
+ )
+ )
+ out.sort(key=lambda p: -p.weight)
+ return out
+
+
+def canonical_pair(a: str, b: str) -> tuple[str, str]:
+ """The two paths in a stable order, so an undirected pair deduplicates."""
+ return (a, b) if a < b else (b, a)
diff --git a/packages/core/src/repowise/core/generation/context/assembler.py b/packages/core/src/repowise/core/generation/context/assembler.py
index e2bffafa0..44c8dc57c 100644
--- a/packages/core/src/repowise/core/generation/context/assembler.py
+++ b/packages/core/src/repowise/core/generation/context/assembler.py
@@ -18,6 +18,7 @@ from repowise.core.analysis.dead_code.file_reachability import (
from repowise.core.ids import file_path_of, is_external
from repowise.core.ingestion.models import ParsedFile, RepoStructure, Symbol
+from ...co_change import parse_partners
from ..categories import file_category
from ..entry_points import orientation_entry_points, rank_entry_point_paths
from ..models import GenerationConfig
@@ -630,7 +631,6 @@ class ContextAssembler:
empty when there is no git metadata, so a repository indexed without
history renders none of it rather than a fabricated health line.
"""
- import json as _json
from collections import Counter
if not git_meta_map:
@@ -651,22 +651,11 @@ class ContextAssembler:
# another module. History coupling the import graph never shows.
coupled: Counter[str] = Counter()
for m in metas:
- raw = m.get("co_change_partners_json") or "[]"
- try:
- partners = _json.loads(raw) if isinstance(raw, str) else raw
- except Exception:
- partners = []
- for p in partners:
- # Co-change entries are dicts keyed by ``file_path`` (see
- # git_indexer/co_change.py); tolerate a bare string too.
- partner_path = (p.get("file_path") or p.get("path")) if isinstance(p, dict) else p
- if (
- isinstance(partner_path, str)
- and partner_path
- and partner_path not in member_set
- ):
- module = partner_path.rsplit("/", 1)[0] if "/" in partner_path else partner_path
- coupled[module] += 1
+ for p in parse_partners(m.get("co_change_partners_json")):
+ if p.file_path in member_set:
+ continue
+ module = p.file_path.rsplit("/", 1)[0] if "/" in p.file_path else p.file_path
+ coupled[module] += 1
coupled_modules = [{"path": path, "count": count} for path, count in coupled.most_common(5)]
bugfix_total = sum(int(m.get("prior_defect_count") or 0) for m in metas)
@@ -1031,12 +1020,7 @@ class ContextAssembler:
if len(sig_commits) >= 8:
return "thorough"
- co_json = git_meta.get("co_change_partners_json", "[]")
- try:
- co_partners = _json.loads(co_json) if isinstance(co_json, str) else co_json
- except Exception:
- co_partners = []
- if co_partners:
+ if parse_partners(git_meta.get("co_change_partners_json")):
return "thorough"
# Downgrade conditions
diff --git a/packages/core/src/repowise/core/generation/related_pages.py b/packages/core/src/repowise/core/generation/related_pages.py
index 515cd1ce4..c677512c8 100644
--- a/packages/core/src/repowise/core/generation/related_pages.py
+++ b/packages/core/src/repowise/core/generation/related_pages.py
@@ -13,12 +13,12 @@ prose never names its collaborators is still connected to them.
from __future__ import annotations
-import json
from collections import Counter
from typing import Any
import structlog
+from ..co_change import parse_partners
from .interlinking import FILE_BACKED_PAGE_TYPES as _FILE_BACKED
from .interlinking import LinkIndex
from .models import GeneratedPage
@@ -37,21 +37,8 @@ def _co_change_partners(git_meta: dict | None) -> list[tuple[str, float]]:
"""``(partner_path, co_change_count)`` pairs, strongest first."""
if not git_meta:
return []
- raw = git_meta.get("co_change_partners_json") or "[]"
- try:
- partners = json.loads(raw)
- except (TypeError, ValueError):
- return []
- out: list[tuple[str, float]] = []
- for p in partners:
- if not isinstance(p, dict):
- continue
- path = p.get("file_path")
- if not path:
- continue
- out.append((path, float(p.get("co_change_count") or 0.0)))
- out.sort(key=lambda t: -t[1])
- return out
+ partners = parse_partners(git_meta.get("co_change_partners_json"))
+ return [(p.file_path, p.weight) for p in partners]
def _module_siblings(
diff --git a/packages/core/src/repowise/core/ingestion/git_commit_index.py b/packages/core/src/repowise/core/ingestion/git_commit_index.py
index 809cbc229..8db6a6279 100644
--- a/packages/core/src/repowise/core/ingestion/git_commit_index.py
+++ b/packages/core/src/repowise/core/ingestion/git_commit_index.py
@@ -7,7 +7,7 @@ made the git phase dominate the total ``repowise init`` wall-clock.
This module replaces the fan-out with one repo-wide ``git log`` pass
and an in-memory bucketing step. The shape mirrors what
-``_compute_co_changes`` already does — one subprocess, fan-out via
+``compute_co_changes_and_entropy`` already does — one subprocess, fan-out via
Python dicts — so any future debugging only has one log format to
understand.
diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/README.md b/packages/core/src/repowise/core/ingestion/git_indexer/README.md
index c137bf5ff..bb737b703 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/README.md
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/README.md
@@ -49,7 +49,7 @@ Imported via `repowise.core.ingestion.git_indexer`:
- `backfill_full_tier(indexer, repo_id, *, job_store=None)` — promote an
ESSENTIAL index to FULL as a resumable phase.
- Module-level building blocks (unit-tested directly): `index_file`,
- `compute_co_changes`, `compute_co_changes_and_entropy`, `compute_percentiles`,
+ `compute_co_changes_and_entropy`, `compute_percentiles`,
`compute_prior_defects`, `get_blame_ownership`, `is_significant_commit`,
`detect_original_path`, `is_fix_commit`.
@@ -166,7 +166,7 @@ and a per-file rollup on `git_metadata` (`agent_commit_count`,
| `file_history.py` | `index_file` — per-file parse + base metrics (blame gated by tier) |
| `enrich.py` | blame ownership, commit significance, rename detection, percentiles |
| `function_blame.py` | per-line blame index → per-function modification counts + line age (FULL tier; feeds `function_hotspot` / `code_age_volatility`) |
-| `co_change.py` | `compute_co_changes` / `compute_co_changes_and_entropy` — repo-wide decay-weighted pair walk + Hassan HCM |
+| `co_change.py` | `compute_co_changes_and_entropy` — repo-wide decay-weighted pair walk + Hassan HCM |
| `prior_defects.py` | `compute_prior_defects` — windowed bug-fix count per file (leakage-aware, benchmark-mirroring) |
| `indexer.py` | `GitIndexer` class wiring the above; merges co-change/entropy/prior-defects into per-file metadata; back-compat instance shims |
| `backfill.py` | `backfill_full_tier` resumable ESSENTIAL→FULL promotion |
diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/__init__.py b/packages/core/src/repowise/core/ingestion/git_indexer/__init__.py
index 88fe52a3f..dbc0f3bce 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/__init__.py
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/__init__.py
@@ -26,7 +26,7 @@ from .agent_provenance import (
classifier_from_repo_config,
)
from .backfill import BACKFILL_PHASE, backfill_full_tier
-from .co_change import compute_co_changes, compute_co_changes_and_entropy
+from .co_change import compute_co_changes_and_entropy
from .enrich import (
compute_percentiles,
count_active_contributors,
@@ -86,7 +86,6 @@ __all__ = [
"classifier_from_repo_config",
"classify_fix_shape",
"collect_fix_commits",
- "compute_co_changes",
"compute_co_changes_and_entropy",
"compute_percentiles",
"compute_prior_defects",
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 4bcdc776f..eaabf5bdf 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/_constants.py
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/_constants.py
@@ -10,6 +10,7 @@ import contextlib
import re
from typing import Any
+from ...co_change import CO_CHANGE_DECAY_TAU, MIN_CO_CHANGE_WEIGHT
from ..languages.registry import REGISTRY as _LANG_REGISTRY
# Silence GitPython's _CatFileContentStream.__del__ ValueError spam.
@@ -143,7 +144,7 @@ _DEFAULT_CO_CHANGE_COMMIT_LIMIT: int = 2000
# 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 = 2
+_DEFAULT_CO_CHANGE_MIN_COUNT: int = MIN_CO_CHANGE_WEIGHT
# Commits that touch a very large number of files (mass renames,
# copyright header sweeps, code-mod runs) produce O(N^2) pairs and
@@ -336,7 +337,7 @@ def classify_commit_category(subject: str) -> str:
# Co-change temporal decay: half-life ~125 days (lambda for exp(-t/tau)).
-_CO_CHANGE_DECAY_TAU: float = 180.0
+_CO_CHANGE_DECAY_TAU: float = CO_CHANGE_DECAY_TAU
# Hotspot temporal decay: half-life for exponentially weighted churn score.
HOTSPOT_HALFLIFE_DAYS: float = 180.0
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 adcea0c92..77b6504bb 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
@@ -32,7 +32,7 @@ from ._constants import (
logger = structlog.get_logger(__name__)
-__all__ = ["compute_co_changes", "compute_co_changes_and_entropy"]
+__all__ = ["compute_co_changes_and_entropy"]
def compute_co_changes_and_entropy(
@@ -187,23 +187,3 @@ def compute_co_changes_and_entropy(
)
return dict(result), entropy
-
-
-def compute_co_changes(
- repo: Any,
- all_files: set[str],
- commit_limit: int = _DEFAULT_CO_CHANGE_COMMIT_LIMIT,
- min_count: int = _DEFAULT_CO_CHANGE_MIN_COUNT,
- on_commit_done: Callable[[], None] | None = None,
- on_co_change_start: Callable[[int], None] | None = None,
-) -> dict[str, list[dict]]:
- """Co-change-only wrapper over :func:`compute_co_changes_and_entropy`.
-
- Preserves the historical signature for the instance shim and existing
- tests. Production indexing calls the combined function directly so the
- single ``git log`` walk feeds both signals.
- """
- co_changes, _entropy = compute_co_changes_and_entropy(
- repo, all_files, commit_limit, min_count, on_commit_done, on_co_change_start
- )
- return co_changes
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 716d1fe47..8a7c8b736 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py
@@ -28,7 +28,7 @@ from ._constants import (
_DEFAULT_COMMIT_LIMIT,
_FILE_INDEX_TIMEOUT_SECS,
)
-from .co_change import compute_co_changes, compute_co_changes_and_entropy
+from .co_change import compute_co_changes_and_entropy
from .enrich import compute_percentiles
from .file_history import DECAY_REFRESH_KEYS, index_file
from .prior_defects import FixWalk, PriorDefects, collect_fix_commits, compute_prior_defects
@@ -1052,19 +1052,6 @@ class GitIndexer:
return is_significant_commit(message, author)
- def _compute_co_changes(
- self,
- repo: Any,
- all_files: set[str],
- commit_limit: int = _DEFAULT_CO_CHANGE_COMMIT_LIMIT,
- min_count: int = _DEFAULT_CO_CHANGE_MIN_COUNT,
- on_commit_done: Callable[[], None] | None = None,
- on_co_change_start: Callable[[int], None] | None = None,
- ) -> dict[str, list[dict]]:
- return compute_co_changes(
- repo, all_files, commit_limit, min_count, on_commit_done, on_co_change_start
- )
-
@staticmethod
def _compute_percentiles(metadata_list: list[dict]) -> None:
compute_percentiles(metadata_list)
diff --git a/packages/core/src/repowise/core/ingestion/graph/_edges.py b/packages/core/src/repowise/core/ingestion/graph/_edges.py
index 98246b118..de1bd4332 100644
--- a/packages/core/src/repowise/core/ingestion/graph/_edges.py
+++ b/packages/core/src/repowise/core/ingestion/graph/_edges.py
@@ -7,10 +7,9 @@ framework-mediated wiring.
from __future__ import annotations
-import json
-
import structlog
+from ...co_change import 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
@@ -27,24 +26,14 @@ class EdgesMixin:
seen: set[tuple[str, str]] = set()
for file_path, meta in git_meta_map.items():
- co_json = meta.get("co_change_partners_json", "[]")
- if isinstance(co_json, str):
- try:
- partners = json.loads(co_json)
- except Exception:
- partners = []
- else:
- partners = co_json
-
- for partner in partners:
- partner_path = partner.get("file_path", "")
- co_count = partner.get("co_change_count", 0)
+ 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:
continue
if partner_path not in self._graph:
continue
- pair = tuple(sorted([file_path, partner_path]))
+ pair = canonical_pair(file_path, partner_path)
if pair in seen:
continue
seen.add(pair)
diff --git a/packages/core/src/repowise/core/test_paths.py b/packages/core/src/repowise/core/test_paths.py
index fb81234d5..e1faba020 100644
--- a/packages/core/src/repowise/core/test_paths.py
+++ b/packages/core/src/repowise/core/test_paths.py
@@ -297,3 +297,16 @@ def is_test_related_path(path: str, language: str | None = None) -> bool:
search should prefer :func:`is_test_path`, so fixtures stay findable.
"""
return _classify(path, language) != ""
+
+
+def is_test_to_production_pair(
+ code_path: str, partner_path: str, *, code_language: str | None = None
+) -> bool:
+ """Whether exactly one of the two paths is test material.
+
+ A test and the code it covers are supposed to change together, so a signal
+ derived from history has nothing to say about such a pair. *partner_path*
+ takes no language because callers reach this from a bare path recorded
+ against another file, with no node to read a stored flag from.
+ """
+ return is_test_related_path(code_path, code_language) ^ is_test_related_path(partner_path)
diff --git a/packages/core/src/repowise/core/workspace/cross_repo.py b/packages/core/src/repowise/core/workspace/cross_repo.py
index ba2202b95..d2fe489a9 100644
--- a/packages/core/src/repowise/core/workspace/cross_repo.py
+++ b/packages/core/src/repowise/core/workspace/cross_repo.py
@@ -22,6 +22,7 @@ from datetime import UTC, datetime
from pathlib import Path, PurePosixPath
from typing import Any
+from ..co_change import CO_CHANGE_DECAY_TAU
from ..fsutils import atomic_write_text
from .config import WorkspaceConfig, ensure_workspace_data_dir
@@ -38,9 +39,6 @@ CROSS_REPO_EDGES_FILENAME = "cross_repo_edges.json"
# the new semantics (v2: strength became a bounded [0,1) session share).
_OVERLAY_VERSION: int = 2
-# Same decay constant as intra-repo co-change (git_indexer.py)
-_CO_CHANGE_DECAY_TAU: float = 180.0
-
_DEFAULT_TIME_WINDOW_HOURS: int = 24
_DEFAULT_COMMIT_LIMIT: int = 500
# Strength is a bounded [0, 1) share (see detect_cross_repo_co_changes), so
@@ -467,7 +465,7 @@ def detect_cross_repo_co_changes(
for session in _build_sessions(tagged_commits, window_seconds):
last_ts = max(c.timestamp for _, c in session)
age_days = max((now_ts - last_ts) / 86400.0, 0.0)
- weight = math.exp(-age_days / _CO_CHANGE_DECAY_TAU)
+ weight = math.exp(-age_days / CO_CHANGE_DECAY_TAU)
# Files per repo for this session, with how many of the
# session's commits touched each one
diff --git a/packages/server/src/repowise/server/mcp_server/tool_dependency.py b/packages/server/src/repowise/server/mcp_server/tool_dependency.py
index 06b15fef5..829749a18 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_dependency.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_dependency.py
@@ -2,11 +2,11 @@
from __future__ import annotations
-import json
from typing import Any
from sqlalchemy import select
+from repowise.core.co_change import parse_partners
from repowise.core.ingestion.models import TEMPORAL_EDGE_TYPES
from repowise.core.persistence.database import get_session
from repowise.core.persistence.models import (
@@ -142,14 +142,12 @@ async def get_dependency_path(source: str, target: str, repo: str | None = None)
)
)
src_meta = src_res.scalar_one_or_none()
- if src_meta and src_meta.co_change_partners_json:
- partners = json.loads(src_meta.co_change_partners_json)
- for p in partners:
- partner_path = p.get("file_path", "")
- if partner_path == target:
+ if src_meta:
+ for p in parse_partners(src_meta.co_change_partners_json):
+ if p.file_path == target:
result_data["co_change_signal"] = {
- "co_change_count": p.get("co_change_count", 0),
- "last_co_change": p.get("last_co_change"),
+ "co_change_count": p.weight,
+ "last_co_change": p.last_co_change,
"note": (
"No import dependency, but these files co-change "
"frequently — likely logical coupling."
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 6731b738d..c033939de 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
@@ -11,6 +11,7 @@ from sqlalchemy import select, text
from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.analysis.health.engine import _has_paired_test_file, _path_basenames
+from repowise.core.co_change import parse_partners
from repowise.core.persistence.models import (
GitMetadata,
GraphNode,
@@ -318,22 +319,17 @@ def _build_co_changes(
is a recency-decayed sum (``exp(-age_days / tau)`` per shared commit), so it
is fractional. Named ``count`` it read as "5.52 co-changes" to every agent.
"""
- partners = json.loads(meta.co_change_partners_json)
- partners_sorted = sorted(
- partners,
- key=lambda p: p.get("co_change_count", p.get("count", 0)) or 0,
- reverse=True,
- )
+ partners_sorted = parse_partners(meta.co_change_partners_json)
relation_types = structural_related if isinstance(structural_related, dict) else {}
related_paths = set(structural_related)
rows = []
for partner in partners_sorted:
- path = partner.get("file_path", partner.get("path", ""))
+ path = partner.file_path
types = sorted(relation_types.get(path, ()))
row = {
"file_path": path,
- "weight": partner.get("co_change_count", partner.get("count", 0)),
- "last_co_change": partner.get("last_co_change"),
+ "weight": partner.weight,
+ "last_co_change": partner.last_co_change,
"relationship_type": "co_change",
"direction": "undirected",
"evidence_kind": "historical",
@@ -345,7 +341,7 @@ def _build_co_changes(
}
if types:
row["structural_relationship_types"] = types
- support = partner.get("frequency", partner.get("shared_commit_count"))
+ support = partner.record.get("frequency", partner.record.get("shared_commit_count"))
if support is not None:
row["support"] = support
rows.append(row)
diff --git a/packages/server/src/repowise/server/routers/git.py b/packages/server/src/repowise/server/routers/git.py
index e5163c0fd..301f1670e 100644
--- a/packages/server/src/repowise/server/routers/git.py
+++ b/packages/server/src/repowise/server/routers/git.py
@@ -33,6 +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.ingestion.git_indexer._constants import (
EVOLUTION_CATEGORIES,
classify_commit_category,
@@ -609,8 +610,11 @@ async def get_co_changes(
if meta is None:
raise HTTPException(status_code=404, detail="Git metadata not found")
- partners = json.loads(meta.co_change_partners_json)
- filtered = [p for p in partners if p.get("co_change_count", 0) >= min_count]
+ filtered = [
+ p.record
+ for p in parse_partners(meta.co_change_partners_json)
+ if p.weight >= min_count
+ ]
return {
"file_path": file_path,
diff --git a/packages/server/src/repowise/server/routers/stats.py b/packages/server/src/repowise/server/routers/stats.py
index 1b77e0cc6..349c2d50f 100644
--- a/packages/server/src/repowise/server/routers/stats.py
+++ b/packages/server/src/repowise/server/routers/stats.py
@@ -17,7 +17,6 @@ to ``None`` / empty rather than 500-ing the page.
from __future__ import annotations
-import json
import re
from datetime import UTC, datetime, timedelta
from itertools import pairwise
@@ -27,6 +26,7 @@ from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy import Integer, func, select
from sqlalchemy.ext.asyncio import AsyncSession
+from repowise.core.co_change import parse_partners
from repowise.core.ingestion.git_indexer import build_identity_resolver
from repowise.core.ingestion.git_indexer.agent_provenance import agent_from_identity
from repowise.core.persistence import crud
@@ -728,15 +728,9 @@ async def _records(
# Strongest hidden coupling pair (max co-change count across files)
best_pair: dict[str, Any] | None = None
for m in all_meta:
- try:
- partners = json.loads(m.co_change_partners_json or "[]")
- except Exception:
- continue
- for p in partners:
- count = p.get("co_change_count", 0)
- other = p.get("file_path") or p.get("partner")
- if other and (best_pair is None or count > best_pair["count"]):
- best_pair = {"a": m.file_path, "b": other, "count": count}
+ 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 and best_pair["count"] > 0:
out["strongest_coupling"] = best_pair
diff --git a/packages/server/src/repowise/server/schemas/git.py b/packages/server/src/repowise/server/schemas/git.py
index dd8b2ed01..34e48fd64 100644
--- a/packages/server/src/repowise/server/schemas/git.py
+++ b/packages/server/src/repowise/server/schemas/git.py
@@ -7,6 +7,7 @@ from datetime import datetime
from pydantic import BaseModel
+from repowise.core.co_change import parse_partners
from repowise.server.schemas.risk_semantics import RiskAuthority
@@ -78,7 +79,10 @@ class GitMetadataResponse(BaseModel):
recent_owner_commit_pct=obj.recent_owner_commit_pct, # type: ignore[attr-defined]
top_authors=json.loads(obj.top_authors_json), # type: ignore[attr-defined]
significant_commits=json.loads(obj.significant_commits_json), # type: ignore[attr-defined]
- co_change_partners=json.loads(obj.co_change_partners_json), # type: ignore[attr-defined]
+ co_change_partners=[
+ p.record
+ for p in parse_partners(obj.co_change_partners_json) # type: ignore[attr-defined]
+ ],
is_hotspot=obj.is_hotspot, # type: ignore[attr-defined]
is_stable=obj.is_stable, # type: ignore[attr-defined]
# Normalize 0-1 -> 0-100 to match the rest of the HTTP API.
diff --git a/packages/server/src/repowise/server/services/reviewer_suggestions.py b/packages/server/src/repowise/server/services/reviewer_suggestions.py
index 7103cfba1..eed44d43c 100644
--- a/packages/server/src/repowise/server/services/reviewer_suggestions.py
+++ b/packages/server/src/repowise/server/services/reviewer_suggestions.py
@@ -22,6 +22,7 @@ from collections import defaultdict
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
+from repowise.core.co_change import parse_partners
from repowise.core.persistence.models import GitMetadata
from repowise.server.schemas import ReviewerSuggestion
@@ -56,16 +57,9 @@ async def suggest_reviewers(
cochange_paths: set[str] = set()
cochange_partners: dict[str, list[str]] = defaultdict(list)
for m in direct_rows:
- try:
- partners = json.loads(m.co_change_partners_json or "[]")
- except json.JSONDecodeError:
- partners = []
- partners.sort(key=lambda p: p.get("co_change_count", 0), reverse=True)
- for p in partners[:5]:
- other = p.get("file_path")
- if other:
- cochange_paths.add(other)
- cochange_partners[other].append(m.file_path)
+ for p in parse_partners(m.co_change_partners_json)[:5]:
+ cochange_paths.add(p.file_path)
+ cochange_partners[p.file_path].append(m.file_path)
cochange_rows = []
if cochange_paths:
diff --git a/tests/unit/coupling/test_graph.py b/tests/unit/coupling/test_graph.py
index 345ffbb02..8c03db8ed 100644
--- a/tests/unit/coupling/test_graph.py
+++ b/tests/unit/coupling/test_graph.py
@@ -131,3 +131,17 @@ def test_empty_inputs() -> None:
assert g.nodes == []
assert g.edges == []
assert g.total_edges == 0
+
+
+def test_a_bare_string_partner_does_not_crash_the_join() -> None:
+ """A non-record element must not reach ``.get`` and raise out of the route."""
+ metrics = [_Metric("a.py"), _Metric("b.py")]
+ git = {
+ "a.py": _Git(
+ co_change_partners_json=json.dumps(
+ ["b.py", {"file_path": "b.py", "co_change_count": 4.0, "last_co_change": None}]
+ )
+ )
+ }
+ g = coupling_graph(metrics, git)
+ assert g.edges == [CouplingEdge("a.py", "b.py", 4.0, None)]
diff --git a/tests/unit/generation/test_related_pages.py b/tests/unit/generation/test_related_pages.py
index c4bff9ea9..148444fe2 100644
--- a/tests/unit/generation/test_related_pages.py
+++ b/tests/unit/generation/test_related_pages.py
@@ -391,3 +391,27 @@ def test_bad_co_change_json_tolerated():
attach_related_pages(pages, import_edges=[("a.py", "b.py")], git_meta_map=git_meta)
assert [r["reason"] for r in _related(pages[0])] == ["imports"]
+
+
+def test_malformed_co_change_records_do_not_raise():
+ """The column is untrusted: a bare string, a missing path, and a
+ non-numeric weight must each drop their record rather than raise."""
+ pages = [_make_page("file_page", "a.py"), _make_page("file_page", "b.py")]
+ git_meta = {
+ "a.py": {
+ "co_change_partners_json": json.dumps(
+ [
+ "b.py",
+ {"co_change_count": 5},
+ {"file_path": "b.py", "co_change_count": "many"},
+ {"file_path": "b.py", "co_change_count": 4},
+ ]
+ )
+ }
+ }
+
+ attach_related_pages(pages, git_meta_map=git_meta)
+
+ rel = _related(pages[0])
+ assert [r["target_page_id"] for r in rel] == ["file_page:b.py"]
+ assert rel[0]["weight"] == 4.0
diff --git a/tests/unit/health/test_hidden_coupling.py b/tests/unit/health/test_hidden_coupling.py
index e7cb4710b..f3ce839cf 100644
--- a/tests/unit/health/test_hidden_coupling.py
+++ b/tests/unit/health/test_hidden_coupling.py
@@ -22,14 +22,14 @@ class _FakeGraph:
return (src, dst, key) in self._edges
-def _partners(d: dict[str, int]) -> str:
+def _partners(d: dict[str, float]) -> str:
return json.dumps([{"file_path": p, "co_change_count": c} for p, c in d.items()])
def _ctx(
path: str,
*,
- partners: dict[str, int],
+ partners: dict[str, float],
self_commits: int,
repo_commits: dict[str, int],
graph: _FakeGraph | None = None,
@@ -215,3 +215,29 @@ def test_pair_dedupes_naturally_by_frozenset():
frozenset({b.file_path, out_b[0].details["partner"]}),
}
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_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."""
+ ctx = _ctx(
+ "src/payments.py",
+ partners={"src/billing.py": 5.9},
+ self_commits=11,
+ repo_commits={"src/billing.py": 11},
+ )
+ assert len(HiddenCouplingDetector().detect(ctx)) == 1
diff --git a/tests/unit/ingestion/test_co_change_edges.py b/tests/unit/ingestion/test_co_change_edges.py
new file mode 100644
index 000000000..fde9e8484
--- /dev/null
+++ b/tests/unit/ingestion/test_co_change_edges.py
@@ -0,0 +1,46 @@
+"""``add_co_change_edges``: the co-change records it reads are untrusted."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from repowise.core.ingestion.graph import GraphBuilder
+
+
+def builder(tmp_path: Path) -> GraphBuilder:
+ """A real builder holding two file nodes and nothing else."""
+ gb = GraphBuilder(repo_path=tmp_path)
+ gb._graph.add_nodes_from(("a.py", "b.py"))
+ return gb
+
+
+def _meta(partners: object) -> dict:
+ return {"co_change_partners_json": json.dumps(partners)}
+
+
+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}])}
+ assert b.add_co_change_edges(meta) == 1
+ edge = b._graph.edges["a.py", "b.py"]
+ assert edge["edge_type"] == "co_changes"
+ assert edge["weight"] == 9.0
+
+
+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"}])}
+ 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}]),
+ }
+ assert b.add_co_change_edges(meta) == 1
diff --git a/tests/unit/ingestion/test_git_indexer_tiers.py b/tests/unit/ingestion/test_git_indexer_tiers.py
index f47fcd3b8..68813340b 100644
--- a/tests/unit/ingestion/test_git_indexer_tiers.py
+++ b/tests/unit/ingestion/test_git_indexer_tiers.py
@@ -123,7 +123,7 @@ def test_index_file_full_consults_blame(tmp_path) -> None:
async def test_index_repo_essential_skips_co_change(tmp_path) -> None:
- """ESSENTIAL tier must not invoke compute_co_changes and must leave
+ """ESSENTIAL tier must not invoke the co-change walk and must leave
co_change_partners empty, while still producing per-file metadata.
"""
import git as gitpython
@@ -141,18 +141,18 @@ async def test_index_repo_essential_skips_co_change(tmp_path) -> None:
co_change_seen = {"called": False}
import repowise.core.ingestion.git_indexer.indexer as indexer_mod
- orig = indexer_mod.compute_co_changes
+ orig = indexer_mod.compute_co_changes_and_entropy
- def _spy(*args, **kwargs): # pragma: no cover - should not run
+ def _spy(*args, **kwargs):
co_change_seen["called"] = True
return orig(*args, **kwargs)
- indexer_mod.compute_co_changes = _spy
+ indexer_mod.compute_co_changes_and_entropy = _spy
try:
idx = GitIndexer(tmp_path, tier=GitIndexTier.ESSENTIAL)
summary, results = await idx.index_repo("repo1")
finally:
- indexer_mod.compute_co_changes = orig
+ indexer_mod.compute_co_changes_and_entropy = orig
assert co_change_seen["called"] is False
assert summary.files_indexed >= 1
diff --git a/tests/unit/server/test_git_schema_partners.py b/tests/unit/server/test_git_schema_partners.py
new file mode 100644
index 000000000..cd1dec69c
--- /dev/null
+++ b/tests/unit/server/test_git_schema_partners.py
@@ -0,0 +1,71 @@
+"""``GitMetadataResponse.from_orm`` must survive a malformed partners cell.
+
+The column is written by the indexer and read here with no validation in
+between, so one bad row used to fail the whole response.
+"""
+
+from __future__ import annotations
+
+import json
+from datetime import UTC, datetime
+from types import SimpleNamespace
+
+from repowise.server.schemas.git import GitMetadataResponse
+
+
+def _row(co_change_partners_json: str) -> SimpleNamespace:
+ return SimpleNamespace(
+ file_path="a.py",
+ commit_count_total=3,
+ commit_count_90d=2,
+ commit_count_30d=1,
+ first_commit_at=datetime(2026, 1, 1, tzinfo=UTC),
+ last_commit_at=datetime(2026, 2, 1, tzinfo=UTC),
+ primary_owner_name=None,
+ primary_owner_email=None,
+ primary_owner_commit_pct=None,
+ recent_owner_name=None,
+ recent_owner_commit_pct=None,
+ top_authors_json="[]",
+ significant_commits_json="[]",
+ co_change_partners_json=co_change_partners_json,
+ is_hotspot=False,
+ is_stable=True,
+ churn_percentile=0.5,
+ age_days=10,
+ bus_factor=1,
+ contributor_count=1,
+ lines_added_90d=0,
+ lines_deleted_90d=0,
+ avg_commit_size=1.0,
+ commit_categories_json="{}",
+ merge_commit_count_90d=0,
+ change_entropy=0.0,
+ change_entropy_pct=0.0,
+ prior_defect_count=0,
+ fix_symbol_counts_json="{}",
+ bug_magnet=False,
+ last_fix_at=None,
+ temporal_hotspot_score=None,
+ commit_count_capped=False,
+ original_path=None,
+ test_gap=None,
+ agent_commit_count=0,
+ agent_authored_pct=None,
+ agent_tier_counts_json="{}",
+ )
+
+
+def test_well_formed_partners_pass_through() -> None:
+ raw = json.dumps([{"file_path": "b.py", "co_change_count": 4.25}])
+ out = GitMetadataResponse.from_orm(_row(raw))
+ assert out.co_change_partners == [{"file_path": "b.py", "co_change_count": 4.25}]
+
+
+def test_malformed_partners_yield_an_empty_list_not_an_error() -> None:
+ assert GitMetadataResponse.from_orm(_row("not json")).co_change_partners == []
+
+
+def test_non_record_elements_are_dropped() -> None:
+ raw = json.dumps(["b.py", {"file_path": "c.py"}])
+ assert GitMetadataResponse.from_orm(_row(raw)).co_change_partners == [{"file_path": "c.py"}]
diff --git a/tests/unit/test_co_change.py b/tests/unit/test_co_change.py
new file mode 100644
index 000000000..f6cf1ac82
--- /dev/null
+++ b/tests/unit/test_co_change.py
@@ -0,0 +1,97 @@
+"""The shared co-change record reader."""
+
+from __future__ import annotations
+
+import json
+
+from repowise.core.co_change import canonical_pair, parse_partners
+from repowise.core.test_paths import is_test_to_production_pair
+
+
+class TestTolerance:
+ def test_absent_and_malformed_cells_yield_nothing(self) -> None:
+ for raw in (None, "", "not json", "{", b"nope"):
+ assert parse_partners(raw) == []
+
+ def test_non_list_document_yields_nothing(self) -> None:
+ assert parse_partners('{"file_path": "a.py"}') == []
+ assert parse_partners("5") == []
+
+ def test_accepts_an_already_decoded_list(self) -> None:
+ (p,) = parse_partners([{"file_path": "a.py", "co_change_count": 1}])
+ assert p.file_path == "a.py"
+
+
+class TestParsePartners:
+ def test_reads_the_canonical_field_names(self) -> None:
+ raw = json.dumps(
+ [{"file_path": "a.py", "co_change_count": 4.25, "last_co_change": "2026-01-02"}]
+ )
+ (p,) = parse_partners(raw)
+ assert (p.file_path, p.weight, p.last_co_change) == ("a.py", 4.25, "2026-01-02")
+
+ def test_reads_the_path_and_count_aliases(self) -> None:
+ (p,) = parse_partners(json.dumps([{"path": "a.py", "count": 3}]))
+ assert (p.file_path, p.weight) == ("a.py", 3.0)
+
+ def test_keeps_the_fractional_weight(self) -> None:
+ # The producer rounds to 2dp because the weight is a decayed sum, so
+ # truncating it would move a pair across a severity threshold.
+ (p,) = parse_partners(json.dumps([{"file_path": "a.py", "co_change_count": 7.9}]))
+ assert p.weight == 7.9
+
+ def test_drops_records_with_no_path_or_a_bad_weight(self) -> None:
+ raw = json.dumps(
+ [
+ {"co_change_count": 5},
+ {"file_path": "", "co_change_count": 5},
+ {"file_path": "a.py", "co_change_count": "many"},
+ {"file_path": "b.py", "co_change_count": 1},
+ ]
+ )
+ assert [p.file_path for p in parse_partners(raw)] == ["b.py"]
+
+ def test_a_bare_string_partner_does_not_raise(self) -> None:
+ raw = json.dumps(["a.py", {"file_path": "b.py", "co_change_count": 2}])
+ assert [p.file_path for p in parse_partners(raw)] == ["b.py"]
+
+ def test_orders_strongest_first(self) -> None:
+ raw = json.dumps(
+ [
+ {"file_path": "a.py", "co_change_count": 1},
+ {"file_path": "b.py", "co_change_count": 9},
+ {"file_path": "c.py", "co_change_count": 5},
+ ]
+ )
+ assert [p.file_path for p in parse_partners(raw)] == ["b.py", "c.py", "a.py"]
+
+ def test_a_non_string_date_becomes_none(self) -> None:
+ (p,) = parse_partners(json.dumps([{"file_path": "a.py", "count": 1, "last_co_change": 7}]))
+ assert p.last_co_change is None
+
+
+class TestCanonicalPair:
+ def test_orders_the_pair_the_same_way_from_either_side(self) -> None:
+ assert canonical_pair("b.py", "a.py") == canonical_pair("a.py", "b.py") == ("a.py", "b.py")
+
+
+class TestIsTestToProductionPair:
+ def test_a_test_and_its_subject_are_a_pair(self) -> None:
+ assert is_test_to_production_pair("tests/unit/test_a.py", "src/a.py")
+
+ def test_two_production_files_are_not(self) -> None:
+ assert not is_test_to_production_pair("src/a.py", "src/b.py")
+
+ def test_two_tests_are_not(self) -> None:
+ assert not is_test_to_production_pair("tests/unit/test_a.py", "tests/unit/test_b.py")
+
+
+class TestRawRecord:
+ def test_carries_the_verbatim_record_for_fields_not_modelled(self) -> None:
+ (p,) = parse_partners(json.dumps([{"file_path": "a.py", "count": 1, "frequency": 12}]))
+ assert p.record["frequency"] == 12
+
+ def test_the_record_is_excluded_from_equality(self) -> None:
+ 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
diff --git a/tests/unit/test_git_indexer.py b/tests/unit/test_git_indexer.py
index 4bcc268d8..a3ea84ab0 100644
--- a/tests/unit/test_git_indexer.py
+++ b/tests/unit/test_git_indexer.py
@@ -8,6 +8,7 @@ from unittest.mock import MagicMock, patch
import pytest
from repowise.core.ingestion.git_indexer import GitIndexer
+from repowise.core.ingestion.git_indexer.co_change import compute_co_changes_and_entropy
# ---------------------------------------------------------------------------
# Helpers
@@ -154,8 +155,6 @@ class TestCoChangeDetection:
"""Files changed together >= 3 times are detected as co-change partners."""
def test_co_change_detection(self) -> None:
- indexer = GitIndexer("/tmp/repo")
-
mock_repo = MagicMock()
all_files = {"a.py", "b.py", "c.py"}
@@ -174,7 +173,9 @@ class TestCoChangeDetection:
)
mock_repo.git.log.return_value = raw_log
- result = indexer._compute_co_changes(mock_repo, all_files, commit_limit=500, min_count=3)
+ result, _entropy = compute_co_changes_and_entropy(
+ mock_repo, all_files, commit_limit=500, min_count=3
+ )
# a.py <-> b.py should appear (co-changed 4 times, >= min_count=3)
assert "a.py" in result
@@ -958,8 +959,6 @@ class TestCoChangeBelowThresholdSkipped:
"""Pairs with co-change count < min_count are not stored."""
def test_co_change_below_threshold_skipped(self) -> None:
- indexer = GitIndexer("/tmp/repo")
-
mock_repo = MagicMock()
all_files = {"x.py", "y.py", "z.py"}
@@ -975,7 +974,9 @@ class TestCoChangeBelowThresholdSkipped:
)
mock_repo.git.log.return_value = raw_log
- result = indexer._compute_co_changes(mock_repo, all_files, commit_limit=500, min_count=3)
+ result, _entropy = compute_co_changes_and_entropy(
+ mock_repo, all_files, commit_limit=500, min_count=3
+ )
# No pairs should appear since none reach min_count=3
assert result == {}