Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(workspace): make cross-repo co-change a bounded session-share signal (#758)
Raghav Chamadiyadbc92a666492
diff --git a/packages/cli/src/repowise/cli/commands/claude_md_cmd.py b/packages/cli/src/repowise/cli/commands/claude_md_cmd.pyindex 7cab039c4..b5893648d 100644--- a/packages/cli/src/repowise/cli/commands/claude_md_cmd.py+++ b/packages/cli/src/repowise/cli/commands/claude_md_cmd.py@@ -203,8 +203,8 @@ def _generate_workspace(WORKSPACE_DATA_DIR,WorkspaceConfig,)- from repowise.core.workspace.cross_repo import CROSS_REPO_EDGES_FILENAMEfrom repowise.core.workspace.contracts import CONTRACTS_FILENAME+ from repowise.core.workspace.cross_repo import load_overlayws_root = find_workspace_root(start_path)if ws_root is None:@@ -220,14 +220,14 @@ def _generate_workspace(# ------------------------------------------------------------------co_changes: list[dict] = []package_deps: list[dict] = []- edges_file = data_dir / CROSS_REPO_EDGES_FILENAME- if edges_file.exists():- try:- overlay = json.loads(edges_file.read_text(encoding="utf-8"))- co_changes = overlay.get("co_changes", [])- package_deps = overlay.get("package_deps", [])- except Exception:- pass # non-fatal; workspace data may not exist yet+ overlay_summaries: dict[str, dict] = {}+ overlay = load_overlay(ws_root) # None when absent, corrupt, or stale-versioned+ if overlay is not None:+ from dataclasses import asdict++ co_changes = [asdict(c) for c in overlay.co_changes]+ package_deps = [asdict(d) for d in overlay.package_deps]+ overlay_summaries = overlay.repo_summaries# Sort co-changes by frequency descending so the top entries are most usefulco_changes = sorted(co_changes, key=lambda c: c.get("frequency", 0), reverse=True)@@ -257,25 +257,9 @@ def _generate_workspace(abs_path = (ws_root / entry.path).resolve()file_count, symbol_count = _query_repo_counts(abs_path)- # Hotspot count: try to read from the overlay's repo_summaries if available- hotspot_count = 0- if edges_file.exists():- try:- overlay_data = json.loads(edges_file.read_text(encoding="utf-8"))- repo_sum = overlay_data.get("repo_summaries", {}).get(entry.alias, {})- hotspot_count = repo_sum.get("hotspot_count", 0)- except Exception:- pass-- # Entry points: read from overlay repo_summaries if present, else empty- entry_points: list[str] = []- if edges_file.exists():- try:- overlay_data = json.loads(edges_file.read_text(encoding="utf-8"))- repo_sum = overlay_data.get("repo_summaries", {}).get(entry.alias, {})- entry_points = repo_sum.get("entry_points", [])- except Exception:- pass+ repo_sum = overlay_summaries.get(entry.alias, {})+ hotspot_count = repo_sum.get("hotspot_count", 0)+ entry_points = repo_sum.get("entry_points", [])repo_summaries.append(WorkspaceRepoSummary(diff --git a/packages/core/src/repowise/core/workspace/cross_repo.py b/packages/core/src/repowise/core/workspace/cross_repo.pyindex ec09b7d72..54d4d44a1 100644--- a/packages/core/src/repowise/core/workspace/cross_repo.py+++ b/packages/core/src/repowise/core/workspace/cross_repo.py@@ -13,13 +13,13 @@ import fnmatchimport jsonimport loggingimport math+import reimport subprocessimport timefrom collections import defaultdictfrom dataclasses import asdict, dataclass, field-from datetime import datetime, timezone+from datetime import UTC, datetimefrom pathlib import Path, PurePosixPath-from typing import Anyfrom .config import WorkspaceConfig, ensure_workspace_data_dir@@ -31,16 +31,42 @@ _log = logging.getLogger("repowise.workspace.cross_repo")CROSS_REPO_EDGES_FILENAME = "cross_repo_edges.json"+# Bump when the meaning of the persisted fields changes; ``load_overlay``+# discards older versions so stale scores never reach consumers that assume+# 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-# Threshold lowered from 1.0 when commit-size normalization was added: dividing-# each pair's weight by sqrt(files_a * files_b) shrinks raw scores, so the old-# 1.0 floor would have silently dropped legitimate (slightly aged) co-changes.-_MIN_CROSS_REPO_SCORE: float = 0.5+# Strength is a bounded [0, 1) share (see detect_cross_repo_co_changes), so+# the floor is a ratio: pairs that co-occur in under ~20% of the less-active+# file's sessions are coincidence, not coupling.+_MIN_CROSS_REPO_SCORE: float = 0.2+# A pair must co-occur in at least this many distinct work sessions. A single+# session proves nothing — one afternoon of unrelated commits in two repos+# would otherwise mint 100%-strength edges.+_MIN_CO_SESSIONS: int = 2+# Files changed in more than this share of a repo's scanned commits are+# ambient (progress diaries, changelogs, version stamps): they ride along+# with everything and carry no pairing signal. 0.20 leaves headroom above+# genuinely hot files (observed maxima sit near 15% in active repos), and+# the filter is skipped entirely for short histories where shares are noise.+_UBIQUITY_MAX_COMMIT_SHARE: float = 0.20+_UBIQUITY_MIN_HISTORY: int = 30+# Laplace-style smoothing added to the strength denominator so a pair seen in+# 2-of-2 sessions (67% after smoothing) cannot outrank sustained coupling+# like 30-of-40 (73%).+_STRENGTH_SMOOTHING: float = 1.0_MAX_EDGES: int = 200+# One hyperactive repo pair must not consume the whole edge budget and starve+# the other pairs out of the overlay.+_MAX_EDGES_PER_REPO_PAIR: int = 50+# Per-session cap on files paired per side, guarding the O(N*M) cross-product+# against sprawling release/codemod sessions.+_MAX_FILES_PER_SESSION_SIDE: int = 20# ---------------------------------------------------------------------------@@ -85,6 +111,10 @@ _NOISE_FILE_PATTERNS: tuple[str, ...] = (# Localization resource files"*.po","*.mo",+ # Release ritual: changelogs ride along with every release session and+ # pair with whatever else shipped that day+ "CHANGELOG*",+ "changelog*",# Binary / asset metadata (Unity and similar engines)"*.prefab","*.meta",@@ -93,19 +123,21 @@ _NOISE_FILE_PATTERNS: tuple[str, ...] = (# Path segments (case-insensitive) that mark a file as generated/vendored/noise# wherever they appear in the path.-_NOISE_DIR_SEGMENTS: frozenset[str] = frozenset({- "node_modules",- "dist",- "build",- "vendor",- "generated",- "__generated__",- "locales",- "locale",- "localization",- "i18n",- "translations",-})+_NOISE_DIR_SEGMENTS: frozenset[str] = frozenset(+ {+ "node_modules",+ "dist",+ "build",+ "vendor",+ "generated",+ "__generated__",+ "locales",+ "locale",+ "localization",+ "i18n",+ "translations",+ }+)def _is_noise_path(path: str) -> bool:@@ -135,8 +167,8 @@ class CrossRepoCoChange:source_file: strtarget_repo: strtarget_file: str- strength: float # decay-weighted co-change score- frequency: int # raw count of temporally-correlated commit pairs+ strength: float # bounded [0, 1) recency-weighted share of co-sessions+ frequency: int # distinct work sessions in which both files changedlast_date: str # ISO date of most recent co-change@@ -150,7 +182,7 @@ class CrossRepoPackageDep:@dataclassclass CrossRepoOverlay:- version: int = 1+ version: int = _OVERLAY_VERSIONgenerated_at: str = ""co_changes: list[CrossRepoCoChange] = field(default_factory=list)package_deps: list[CrossRepoPackageDep] = field(default_factory=list)@@ -170,12 +202,8 @@ class CrossRepoOverlay:return cls(version=data.get("version", 1),generated_at=data.get("generated_at", ""),- co_changes=[- CrossRepoCoChange(**c) for c in data.get("co_changes", [])- ],- package_deps=[- CrossRepoPackageDep(**d) for d in data.get("package_deps", [])- ],+ co_changes=[CrossRepoCoChange(**c) for c in data.get("co_changes", [])],+ package_deps=[CrossRepoPackageDep(**d) for d in data.get("package_deps", [])],repo_summaries=data.get("repo_summaries", {}),)@@ -190,6 +218,20 @@ class _GitCommit:author_email: strtimestamp: int # Unix epochfiles: list[str] = field(default_factory=list)+ author_name: str = ""++ @property+ def author_identity(self) -> str:+ """Best-effort cross-repo identity for this author.++ The same person routinely commits with different emails per clone+ (work vs personal vs GitHub noreply), which would make their own+ repos invisible to each other under email-keyed matching. A+ normalized author name ("Raghav Chamadiya" == "RaghavChamadiya")+ bridges those configs; the email remains the fallback.+ """+ normalized = re.sub(r"[^a-z0-9]", "", self.author_name.lower())+ return normalized or self.author_email.lower()def _parse_git_log(@@ -204,9 +246,11 @@ def _parse_git_log(try:result = subprocess.run([- "git", "log",+ "git",+ "log",f"-{commit_limit}",- "--format=%x00%ae|%ct",+ # %x01 separator: author names may contain "|"+ "--format=%x00%ae%x01%an%x01%ct","--name-only","--no-merges",],@@ -233,14 +277,19 @@ def _parse_git_log(commits.append(current)header = line.lstrip("\x00").strip()- parts = header.split("|", 1)- if len(parts) == 2:+ parts = header.split("\x01", 2)+ if len(parts) == 3:email = parts[0].strip()+ name = parts[1].strip()try:- ts = int(parts[1].strip())+ ts = int(parts[2].strip())except (ValueError, TypeError):ts = 0- current = _GitCommit(author_email=email, timestamp=ts)+ current = _GitCommit(+ author_email=email,+ timestamp=ts,+ author_name=name,+ )else:current = Noneelif current is not None:@@ -260,25 +309,98 @@ def _parse_git_log(# ---------------------------------------------------------------------------+def _drop_ubiquitous_files(+ repo_commits: dict[str, list[_GitCommit]],+) -> dict[str, list[_GitCommit]]:+ """Remove files that appear in an outsized share of a repo's commits.++ A progress diary or changelog edited alongside nearly every commit rides+ into every temporal pairing and, before this filter existed, produced the+ top cross-repo "couplings" in real workspaces. Ubiquity is measured per+ repo over the scanned window, so the filter adapts to any repo's habits+ without a hardcoded filename list.+ """+ filtered: dict[str, list[_GitCommit]] = {}+ for alias, commits in repo_commits.items():+ if len(commits) < _UBIQUITY_MIN_HISTORY:+ filtered[alias] = commits+ continue+ file_counts: dict[str, int] = defaultdict(int)+ for c in commits:+ for f in c.files:+ file_counts[f] += 1+ threshold = _UBIQUITY_MAX_COMMIT_SHARE * len(commits)+ ubiquitous = {f for f, n in file_counts.items() if n > threshold}+ kept: list[_GitCommit] = []+ for c in commits:+ c.files = [f for f in c.files if f not in ubiquitous]+ if c.files:+ kept.append(c)+ if kept:+ filtered[alias] = kept+ return filtered+++def _build_sessions(+ tagged_commits: list[tuple[str, _GitCommit]],+ window_seconds: int,+) -> list[list[tuple[str, _GitCommit]]]:+ """Chain one author's commits (sorted by timestamp) into work sessions.++ A new session starts when the gap to the previous commit exceeds the+ window, or when the session's total span would exceed it: without the+ span cap, an author who commits every day never has a >24h gap and+ months of history would chain into one mega-session. Chaining (rather+ than pairing every commit against every other commit in range) is what+ keeps a busy day from counting quadratically: one session contributes+ exactly once per file pair.+ """+ sessions: list[list[tuple[str, _GitCommit]]] = []+ current: list[tuple[str, _GitCommit]] = []+ session_start_ts: int | None = None+ prev_ts: int | None = None+ for alias, commit in tagged_commits:+ if prev_ts is not None and (+ commit.timestamp - prev_ts > window_seconds+ or commit.timestamp - (session_start_ts or prev_ts) > window_seconds+ ):+ sessions.append(current)+ current = []+ session_start_ts = commit.timestamp+ elif session_start_ts is None:+ session_start_ts = commit.timestamp+ current.append((alias, commit))+ prev_ts = commit.timestamp+ if current:+ sessions.append(current)+ return sessions++def detect_cross_repo_co_changes(repo_paths: dict[str, Path],*,time_window_hours: int = _DEFAULT_TIME_WINDOW_HOURS,commit_limit: int = _DEFAULT_COMMIT_LIMIT,min_score: float = _MIN_CROSS_REPO_SCORE,+ min_sessions: int = _MIN_CO_SESSIONS,) -> list[CrossRepoCoChange]:- """Find files across repos committed by same author within *time_window*.+ """Find files across repos that the same author changes in the same+ work sessions.Algorithm:1. Parse git logs for all repos- 2. Drop noise files (CI, lockfiles, generated, localization, assets)- 3. Group commits by author email- 4. For same author, find commit pairs from different repos within window- 5. All (signal) files from correlated commits are co-change partners,- with each pair's weight divided by sqrt(files_a * files_b) so large- release/CI commits cannot dominate the ranking- 6. Apply temporal decay (same as intra-repo)- 7. Filter by min_score, cap at MAX_EDGES+ 2. Drop noise files (CI, lockfiles, generated, localization, assets),+ then files present in an outsized share of a repo's commits+ 3. Chain each author's commits into work sessions (gap > window starts+ a new session); a session touching >=2 repos is a co-session+ 4. Each co-session credits every cross-repo file pair once with the+ session's recency decay weight; every session (co- or not) credits+ each of its files' activity totals with the same weight+ 5. strength = co-session weight / (less-active file's session weight+ + smoothing) — a bounded [0, 1) "share of the less-active file's+ recent work that also touched the partner"+ 6. Keep pairs with >= min_sessions co-sessions and strength >= min_score,+ cap per repo pair, then globally"""if len(repo_paths) < 2:return []@@ -293,7 +415,8 @@ def detect_cross_repo_co_changes(if commits:repo_commits[alias] = commits- # Step 2: Drop noise files, then commits that are left with nothing+ # Step 2: Drop noise files, then commits left with nothing, then+ # ambient files that ride along with everythingfiltered: dict[str, list[_GitCommit]] = {}for alias, commits in repo_commits.items():kept: list[_GitCommit] = []@@ -303,98 +426,124 @@ def detect_cross_repo_co_changes(kept.append(c)if kept:filtered[alias] = kept- repo_commits = filtered+ repo_commits = _drop_ubiquitous_files(filtered)if len(repo_commits) < 2:return []- # Step 3: Group all commits by author, tagged with repo alias+ # Step 3: Group all commits by author identity, tagged with repo aliasauthor_commits: dict[str, list[tuple[str, _GitCommit]]] = defaultdict(list)for alias, commits in repo_commits.items():for c in commits:- author_commits[c.author_email].append((alias, c))+ author_commits[c.author_identity].append((alias, c))- # Step 4: For each author, find temporally-correlated cross-repo pairs- # Accumulate (src_repo, src_file, tgt_repo, tgt_file) -> (score, frequency, last_ts)+ # Step 4: Walk each author's sessions, accumulating per-file activity+ # (the strength denominator) and per-pair co-session weight/count.+ file_activity: dict[tuple[str, str], float] = defaultdict(float)pair_scores: dict[tuple[str, str, str, str], float] = defaultdict(float)pair_freq: dict[tuple[str, str, str, str], int] = defaultdict(int)pair_last_ts: dict[tuple[str, str, str, str], int] = {}- for author, tagged_commits in author_commits.items():- if len(tagged_commits) < 2:- continue-- # Sort by timestamp+ for tagged_commits in author_commits.values():tagged_commits.sort(key=lambda x: x[1].timestamp)- # Sliding window: for each commit, look ahead for commits from- # different repos within the time window- for i in range(len(tagged_commits)):- repo_a, commit_a = tagged_commits[i]- for j in range(i + 1, len(tagged_commits)):- repo_b, commit_b = tagged_commits[j]-- time_diff = commit_b.timestamp - commit_a.timestamp- if time_diff > window_seconds:- break # Past window — no more matches for commit_a-- if repo_a == repo_b:- continue # Same repo — skip-- # Cross-repo match found- age_days = max((now_ts - commit_b.timestamp) / 86400.0, 0.0)- decay = math.exp(-age_days / _CO_CHANGE_DECAY_TAU)-- # Down-weight by commit breadth (tf-idf style): a focused- # 2-file commit carries far more signal per pair than a sprawling- # release commit, so divide by sqrt(files_a * files_b). A- # single-file/single-file pair keeps the full decay weight.- na = len(commit_a.files)- nb = len(commit_b.files)- weight = decay / math.sqrt(na * nb)-- # Create file pairs (limit to avoid O(N*M) explosion on huge commits)- files_a = commit_a.files[:20]- files_b = commit_b.files[:20]-- for fa in files_a:- for fb in files_b:- # Normalize key ordering to avoid symmetric duplicates- if (repo_a, fa) > (repo_b, fb):- key = (repo_b, fb, repo_a, fa)- else:+ 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)++ # Files per repo for this session, with how many of the+ # session's commits touched each one+ session_files: dict[str, dict[str, int]] = defaultdict(lambda: defaultdict(int))+ for alias, commit in session:+ for f in commit.files:+ session_files[alias][f] += 1++ # Every session counts toward its files' activity totals, so a+ # file's denominator reflects all its work — including sessions+ # confined to one repo. This is what bounds strength below 1.+ for alias, files in session_files.items():+ for f in files:+ file_activity[(alias, f)] += weight++ if len(session_files) < 2:+ continue++ # Cap each side by session centrality (files touched by the most+ # commits in the session first): an alphabetical cut would+ # systematically evict late-sorting paths like src/** from busy+ # sessions while keeping __tests__/** and content/** noise.+ capped_files = {+ alias: [+ f+ for f, _ in sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))[+ :_MAX_FILES_PER_SESSION_SIDE+ ]+ ]+ for alias, counts in session_files.items()+ }+ aliases = sorted(capped_files)+ for ai in range(len(aliases)):+ for bi in range(ai + 1, len(aliases)):+ repo_a, repo_b = aliases[ai], aliases[bi]+ files_a = capped_files[repo_a]+ files_b = capped_files[repo_b]+ for fa in files_a:+ for fb in files_b:key = (repo_a, fa, repo_b, fb)- pair_scores[key] += weight- pair_freq[key] += 1- ts = max(commit_a.timestamp, commit_b.timestamp)- if key not in pair_last_ts or ts > pair_last_ts[key]:- pair_last_ts[key] = ts+ pair_scores[key] += weight+ pair_freq[key] += 1+ if key not in pair_last_ts or last_ts > pair_last_ts[key]:+ pair_last_ts[key] = last_ts- # Step 7: Filter and build results+ # Step 5+6: Normalize to a bounded share, filter, and build resultsresults: list[CrossRepoCoChange] = []for (src_repo, src_file, tgt_repo, tgt_file), score in pair_scores.items():- if score < min_score:- continuefreq = pair_freq[(src_repo, src_file, tgt_repo, tgt_file)]+ if freq < min_sessions:+ continue+ denom = (+ min(+ file_activity[(src_repo, src_file)],+ file_activity[(tgt_repo, tgt_file)],+ )+ + _STRENGTH_SMOOTHING+ )+ strength = score / denom+ if strength < min_score:+ continuelast_ts = pair_last_ts.get((src_repo, src_file, tgt_repo, tgt_file), 0)last_date = (- datetime.fromtimestamp(last_ts, tz=timezone.utc).strftime("%Y-%m-%d")+ datetime.fromtimestamp(last_ts, tz=UTC).strftime("%Y-%m-%d")if last_ts > 0else "")- results.append(CrossRepoCoChange(- source_repo=src_repo,- source_file=src_file,- target_repo=tgt_repo,- target_file=tgt_file,- strength=round(score, 2),- frequency=freq,- last_date=last_date,- ))+ results.append(+ CrossRepoCoChange(+ source_repo=src_repo,+ source_file=src_file,+ target_repo=tgt_repo,+ target_file=tgt_file,+ strength=round(strength, 3),+ frequency=freq,+ last_date=last_date,+ )+ )- # Sort by strength descending and cap- results.sort(key=lambda x: -x.strength)- return results[:_MAX_EDGES]+ # Sort by strength (frequency breaking ties), cap per repo pair so one+ # hyperactive pair cannot starve the rest, then cap globally.+ results.sort(key=lambda x: (-x.strength, -x.frequency))+ per_pair: dict[tuple[str, str], int] = defaultdict(int)+ capped: list[CrossRepoCoChange] = []+ for r in results:+ pair_key = (r.source_repo, r.target_repo)+ if per_pair[pair_key] >= _MAX_EDGES_PER_REPO_PAIR:+ continue+ per_pair[pair_key] += 1+ capped.append(r)+ if len(capped) >= _MAX_EDGES:+ break+ return capped# ---------------------------------------------------------------------------@@ -445,12 +594,14 @@ def _scan_package_json(rel_path = version[5:] # strip "file:"target = _resolve_target_repo(rel_path, repo_path, repo_paths)if target and target != alias:- results.append(CrossRepoPackageDep(- source_repo=alias,- target_repo=target,- source_manifest="package.json",- kind="npm_local_path",- ))+ results.append(+ CrossRepoPackageDep(+ source_repo=alias,+ target_repo=target,+ source_manifest="package.json",+ kind="npm_local_path",+ )+ )# Check workspaces fieldworkspaces = data.get("workspaces", [])@@ -461,12 +612,14 @@ def _scan_package_json(if isinstance(ws, str) and ".." in ws:target = _resolve_target_repo(ws.rstrip("/*"), repo_path, repo_paths)if target and target != alias:- results.append(CrossRepoPackageDep(- source_repo=alias,- target_repo=target,- source_manifest="package.json",- kind="npm_workspace",- ))+ results.append(+ CrossRepoPackageDep(+ source_repo=alias,+ target_repo=target,+ source_manifest="package.json",+ kind="npm_workspace",+ )+ )return results@@ -494,19 +647,19 @@ def _scan_pyproject_toml(return results# Poetry path dependencies- poetry_deps = (- data.get("tool", {}).get("poetry", {}).get("dependencies", {})- )+ poetry_deps = data.get("tool", {}).get("poetry", {}).get("dependencies", {})for _name, spec in poetry_deps.items() if isinstance(poetry_deps, dict) else []:if isinstance(spec, dict) and "path" in spec:target = _resolve_target_repo(spec["path"], repo_path, repo_paths)if target and target != alias:- results.append(CrossRepoPackageDep(- source_repo=alias,- target_repo=target,- source_manifest="pyproject.toml",- kind="pip_path",- ))+ results.append(+ CrossRepoPackageDep(+ source_repo=alias,+ target_repo=target,+ source_manifest="pyproject.toml",+ kind="pip_path",+ )+ )# PEP 621 dependencies with path (uncommon but possible via tool configs)for group_key in ("dependencies", "optional-dependencies"):@@ -516,12 +669,14 @@ def _scan_pyproject_toml(if isinstance(spec, dict) and "path" in spec:target = _resolve_target_repo(spec["path"], repo_path, repo_paths)if target and target != alias:- results.append(CrossRepoPackageDep(- source_repo=alias,- target_repo=target,- source_manifest="pyproject.toml",- kind="pip_path",- ))+ results.append(+ CrossRepoPackageDep(+ source_repo=alias,+ target_repo=target,+ source_manifest="pyproject.toml",+ kind="pip_path",+ )+ )return results@@ -553,12 +708,14 @@ def _scan_cargo_toml(if isinstance(spec, dict) and "path" in spec:target = _resolve_target_repo(spec["path"], repo_path, repo_paths)if target and target != alias:- results.append(CrossRepoPackageDep(- source_repo=alias,- target_repo=target,- source_manifest="Cargo.toml",- kind="cargo_path",- ))+ results.append(+ CrossRepoPackageDep(+ source_repo=alias,+ target_repo=target,+ source_manifest="Cargo.toml",+ kind="cargo_path",+ )+ )return results@@ -598,12 +755,14 @@ def _scan_go_mod(if target_path.startswith("..") or target_path.startswith("./"):target = _resolve_target_repo(target_path, repo_path, repo_paths)if target and target != alias:- results.append(CrossRepoPackageDep(- source_repo=alias,- target_repo=target,- source_manifest="go.mod",- kind="go_replace",- ))+ results.append(+ CrossRepoPackageDep(+ source_repo=alias,+ target_repo=target,+ source_manifest="go.mod",+ kind="go_replace",+ )+ )return results@@ -784,6 +943,17 @@ def load_overlay(workspace_root: Path) -> CrossRepoOverlay | None:return Nonetry:data = json.loads(path.read_text(encoding="utf-8"))+ if data.get("version", 1) < _OVERLAY_VERSION:+ # Older overlays used unbounded strength values; consumers now+ # assume the bounded [0, 1) share, so treat them as absent until+ # the next workspace update regenerates the file.+ _log.info(+ "Ignoring cross-repo overlay at %s (version %s < %s)",+ path,+ data.get("version", 1),+ _OVERLAY_VERSION,+ )+ return Nonereturn CrossRepoOverlay.from_dict(data)except Exception:_log.warning("Failed to load cross-repo overlay from %s", path, exc_info=True)@@ -831,21 +1001,17 @@ async def run_cross_repo_analysis(# Co-change detection (CPU-bound git subprocess calls)import asyncio- co_changes = await asyncio.to_thread(- detect_cross_repo_co_changes, repo_paths- )+ co_changes = await asyncio.to_thread(detect_cross_repo_co_changes, repo_paths)# Package dependency detection (file I/O)- package_deps = await asyncio.to_thread(- detect_package_dependencies, repo_paths- )+ package_deps = await asyncio.to_thread(detect_package_dependencies, repo_paths)# Build summariesrepo_summaries = _build_repo_summaries(repo_paths, co_changes, package_deps)overlay = CrossRepoOverlay(- version=1,- generated_at=datetime.now(timezone.utc).isoformat(),+ version=_OVERLAY_VERSION,+ generated_at=datetime.now(UTC).isoformat(),co_changes=co_changes,package_deps=package_deps,repo_summaries=repo_summaries,diff --git a/packages/server/src/repowise/server/mcp_server/_enrichment.py b/packages/server/src/repowise/server/mcp_server/_enrichment.pyindex c536fc83e..af66e7ab6 100644--- a/packages/server/src/repowise/server/mcp_server/_enrichment.py+++ b/packages/server/src/repowise/server/mcp_server/_enrichment.py@@ -82,6 +82,17 @@ class CrossRepoEnricher:_log.warning("Failed to parse cross-repo data at %s", data_path, exc_info=True)return+ if data.get("version", 1) < 2:+ # v1 overlays carry unbounded strength values; everything+ # downstream now assumes the bounded [0, 1) session share, so+ # skip stale files until a workspace update regenerates them.+ _log.info(+ "Ignoring cross-repo data at %s (version %s < 2)",+ data_path,+ data.get("version", 1),+ )+ return+self._co_changes = data.get("co_changes", [])self._package_deps = data.get("package_deps", [])self._repo_summaries = data.get("repo_summaries", {})diff --git a/packages/ui/src/workspace/co-change-table.tsx b/packages/ui/src/workspace/co-change-table.tsxindex 45d70d66b..fbef91b10 100644--- a/packages/ui/src/workspace/co-change-table.tsx+++ b/packages/ui/src/workspace/co-change-table.tsx@@ -39,7 +39,7 @@ export function CoChangeTable({ coChanges, compact }: CoChangeTableProps) {<th className="px-3 py-2 text-left font-medium">Target</th><th className={`px-3 py-2 text-left font-medium w-32 ${HIDE_BELOW_MD}`}><span- title="Relative, recency-weighted frequency of same-author commits across these repos. Higher means more or more-recent shared activity. It is not a percentage or a verified dependency."+ title="Share of the less-active file's recent work sessions that also touched the partner file (same author, recency-weighted). 100% would mean they always change together. It is not a verified dependency."className="cursor-help underline decoration-dotted underline-offset-2">Strength@@ -77,11 +77,11 @@ export function CoChangeTable({ coChanges, compact }: CoChangeTableProps) {<div className="h-1.5 flex-1 rounded-full bg-[var(--color-bg-inset)] overflow-hidden"><divclassName="h-full rounded-full bg-[var(--color-accent-primary)] transition-all"- style={{ width: `${Math.min(Math.round(cc.strength * 10), 100)}%` }}+ style={{ width: `${Math.min(Math.round(cc.strength * 100), 100)}%` }}/></div><span className="text-xs text-[var(--color-text-tertiary)] tabular-nums w-8 text-right">- {Math.round(cc.strength * 10) / 10}+ {`${Math.round(cc.strength * 100)}%`}</span></div></td>diff --git a/packages/ui/src/workspace/repo-pair-table.tsx b/packages/ui/src/workspace/repo-pair-table.tsxindex 03d0daee7..e8f41b5e2 100644--- a/packages/ui/src/workspace/repo-pair-table.tsx+++ b/packages/ui/src/workspace/repo-pair-table.tsx@@ -82,11 +82,11 @@ export function RepoPairTable({ repoPairs, onSelectPair, selectedPairId }: RepoP<div className="h-1.5 flex-1 rounded-full bg-[var(--color-bg-inset)] overflow-hidden"><divclassName="h-full rounded-full bg-[var(--color-accent-primary)] transition-all"- style={{ width: `${Math.min(Math.round(p.maxStrength * 10), 100)}%` }}+ style={{ width: `${Math.min(Math.round(p.maxStrength * 100), 100)}%` }}/></div><span className="text-xs text-[var(--color-text-tertiary)] tabular-nums w-8 text-right">- {Math.round(p.maxStrength * 10) / 10}+ {`${Math.round(p.maxStrength * 100)}%`}</span></div></td>diff --git a/packages/web/src/app/workspace/co-changes/page.tsx b/packages/web/src/app/workspace/co-changes/page.tsxindex 55fc31c52..068a4f99e 100644--- a/packages/web/src/app/workspace/co-changes/page.tsx+++ b/packages/web/src/app/workspace/co-changes/page.tsx@@ -103,10 +103,11 @@ export default function CoChangesPage() {</div></div><p className="text-sm text-[var(--color-text-secondary)] mt-2">- Files the same author committed across repositories within a short time- window. This is a temporal work-pattern hint from git history, not a- verified technical dependency, so treat it as a starting point for- inspection rather than proof of coupling.+ Files the same author tends to change in the same work sessions across+ repositories. Strength is the share of the less-active file's recent+ sessions that also touched the partner. This is a temporal work-pattern+ hint from git history, not a verified technical dependency, so treat it+ as a starting point for inspection rather than proof of coupling.</p></div>@@ -126,11 +127,11 @@ export default function CoChangesPage() {label="Avg Strength"value={data?.co_changes && data.co_changes.length > 0- ? Math.round(+ ? `${Math.round((data.co_changes.reduce((sum, cc) => sum + cc.strength, 0) /data.co_changes.length) *- 10,- ) / 10+ 100,+ )}%`: "—"}icon={<GitMerge className="h-4 w-4 text-[var(--color-accent-primary)]" />}diff --git a/tests/unit/server/test_enrichment_contracts.py b/tests/unit/server/test_enrichment_contracts.pyindex 4a5349724..0d0ee4292 100644--- a/tests/unit/server/test_enrichment_contracts.py+++ b/tests/unit/server/test_enrichment_contracts.py@@ -20,7 +20,7 @@ def contracts_json(tmp_path: Path) -> Path:"""Write a minimal contracts.json and return its path."""path = tmp_path / "contracts.json"_write_json(path, {- "version": 1,+ "version": 2,"generated_at": "2026-04-12T12:00:00Z","contracts": [{@@ -64,7 +64,7 @@ def contracts_json(tmp_path: Path) -> Path:def empty_cross_repo(tmp_path: Path) -> Path:"""Empty cross_repo_edges.json (no co-changes or deps)."""path = tmp_path / "cross_repo_edges.json"- _write_json(path, {"version": 1, "co_changes": [], "package_deps": []})+ _write_json(path, {"version": 2, "co_changes": [], "package_deps": []})return pathdiff --git a/tests/unit/server/test_mcp_workspace.py b/tests/unit/server/test_mcp_workspace.pyindex e8400d9e7..55ef568be 100644--- a/tests/unit/server/test_mcp_workspace.py+++ b/tests/unit/server/test_mcp_workspace.py@@ -446,7 +446,7 @@ async def test_single_repo_mode_no_workspace():def enricher_data(tmp_path):"""Write a cross_repo_edges.json and return its path."""data = {- "version": 1,+ "version": 2,"generated_at": "2026-04-12T12:00:00Z","co_changes": [{diff --git a/tests/unit/server/test_workspace_router.py b/tests/unit/server/test_workspace_router.pyindex ee0cbac0a..a81757050 100644--- a/tests/unit/server/test_workspace_router.py+++ b/tests/unit/server/test_workspace_router.py@@ -80,7 +80,7 @@ def _make_enricher(tmp_path: Path) -> CrossRepoEnricher:_write_json(cross_repo_path,{- "version": 1,+ "version": 2,"co_changes": [{"source_repo": "backend",@@ -107,7 +107,7 @@ def _make_enricher(tmp_path: Path) -> CrossRepoEnricher:_write_json(contracts_path,{- "version": 1,+ "version": 2,"generated_at": "2026-04-12T12:00:00Z","contracts": [{diff --git a/tests/unit/workspace/test_cross_repo.py b/tests/unit/workspace/test_cross_repo.pyindex 07170669e..a63b3d7f7 100644--- a/tests/unit/workspace/test_cross_repo.py+++ b/tests/unit/workspace/test_cross_repo.py@@ -3,9 +3,7 @@from __future__ import annotationsimport json-import mathimport time-from datetime import datetime, timezonefrom pathlib import Pathfrom unittest.mock import patch@@ -25,7 +23,6 @@ from repowise.core.workspace.cross_repo import (save_overlay,)-# ---------------------------------------------------------------------------# _parse_git_log# ---------------------------------------------------------------------------@@ -35,38 +32,53 @@ class TestParseGitLog:def test_parses_standard_output(self, tmp_path: Path) -> None:"""Mock subprocess to return a known git log and verify parsing."""fake_output = (- "\[email protected]|1712900000\n"+ "\[email protected]\x01Alice\x011712900000\n""src/app.py\n""src/utils.py\n"- "\[email protected]|1712890000\n"+ "\[email protected]\x01Bob B\x011712890000\n""src/main.py\n")with patch("subprocess.run") as mock_run:- mock_run.return_value = type("R", (), {- "returncode": 0, "stdout": fake_output, "stderr": ""- })()+ mock_run.return_value = type(+ "R", (), {"returncode": 0, "stdout": fake_output, "stderr": ""}+ )()commits = _parse_git_log(tmp_path)assert len(commits) == 2assert commits[0].author_email == "[email protected]"+ assert commits[0].author_name == "Alice"assert commits[0].timestamp == 1712900000assert commits[0].files == ["src/app.py", "src/utils.py"]assert commits[1].author_email == "[email protected]"assert commits[1].files == ["src/main.py"]+ def test_author_identity_bridges_email_variants(self) -> None:+ """Same human, different git configs → one identity."""+ a = _GitCommit(+ author_email="[email protected]",+ timestamp=0,+ author_name="Jane Doe",+ )+ b = _GitCommit(+ author_email="[email protected]",+ timestamp=0,+ author_name="JaneDoe",+ )+ c = _GitCommit(author_email="[email protected]", timestamp=0, author_name="")+ assert a.author_identity == b.author_identity == "janedoe"+ assert c.author_identity == "[email protected]"+def test_handles_empty_repo(self, tmp_path: Path) -> None:with patch("subprocess.run") as mock_run:- mock_run.return_value = type("R", (), {- "returncode": 0, "stdout": "", "stderr": ""- })()+ mock_run.return_value = type("R", (), {"returncode": 0, "stdout": "", "stderr": ""})()commits = _parse_git_log(tmp_path)assert commits == []def test_handles_subprocess_failure(self, tmp_path: Path) -> None:with patch("subprocess.run") as mock_run:- mock_run.return_value = type("R", (), {- "returncode": 128, "stdout": "", "stderr": "fatal: not a git repo"- })()+ mock_run.return_value = type(+ "R", (), {"returncode": 128, "stdout": "", "stderr": "fatal: not a git repo"}+ )()commits = _parse_git_log(tmp_path)assert commits == []@@ -83,8 +95,7 @@ class TestParseGitLog:def _make_commits(alias: str, entries: list[tuple[str, int, list[str]]]) -> list[_GitCommit]:"""Helper: build _GitCommit list from (email, ts, files) tuples."""- return [_GitCommit(author_email=e, timestamp=ts, files=files)- for e, ts, files in entries]+ return [_GitCommit(author_email=e, timestamp=ts, files=files) for e, ts, files in entries]class TestCrossRepoCoChanges:@@ -106,14 +117,24 @@ class TestCrossRepoCoChanges:def test_same_author_within_window(self) -> None:"""Two repos, same author, commits <24h apart → edges found."""now = int(time.time())- results = self._detect_with_mocked_logs({- "backend": _make_commits("backend", [- ("[email protected]", now - 3600, ["src/api.py"]), # 1 hour ago- ]),- "frontend": _make_commits("frontend", [- ("[email protected]", now - 7200, ["src/client.ts"]), # 2 hours ago- ]),- }, min_score=0.0)+ results = self._detect_with_mocked_logs(+ {+ "backend": _make_commits(+ "backend",+ [+ ("[email protected]", now - 3600, ["src/api.py"]), # 1 hour ago+ ],+ ),+ "frontend": _make_commits(+ "frontend",+ [+ ("[email protected]", now - 7200, ["src/client.ts"]), # 2 hours ago+ ],+ ),+ },+ min_score=0.0,+ min_sessions=1,+ )assert len(results) >= 1edge = results[0]assert {edge.source_repo, edge.target_repo} == {"backend", "frontend"}@@ -121,43 +142,71 @@ class TestCrossRepoCoChanges:def test_different_authors_no_match(self) -> None:"""Same timestamps but different authors → no edges."""now = int(time.time())- results = self._detect_with_mocked_logs({- "backend": _make_commits("backend", [- ("[email protected]", now - 3600, ["src/api.py"]),- ]),- "frontend": _make_commits("frontend", [- ("[email protected]", now - 3600, ["src/client.ts"]),- ]),- }, min_score=0.0)+ results = self._detect_with_mocked_logs(+ {+ "backend": _make_commits(+ "backend",+ [+ ("[email protected]", now - 3600, ["src/api.py"]),+ ],+ ),+ "frontend": _make_commits(+ "frontend",+ [+ ("[email protected]", now - 3600, ["src/client.ts"]),+ ],+ ),+ },+ min_score=0.0,+ min_sessions=1,+ )assert len(results) == 0def test_outside_time_window(self) -> None:"""Same author, commits >24h apart → no edges."""now = int(time.time())- results = self._detect_with_mocked_logs({- "backend": _make_commits("backend", [- ("[email protected]", now, ["src/api.py"]),- ]),- "frontend": _make_commits("frontend", [- ("[email protected]", now - 100000, ["src/client.ts"]), # ~28h ago- ]),- }, min_score=0.0)+ results = self._detect_with_mocked_logs(+ {+ "backend": _make_commits(+ "backend",+ [+ ("[email protected]", now, ["src/api.py"]),+ ],+ ),+ "frontend": _make_commits(+ "frontend",+ [+ ("[email protected]", now - 100000, ["src/client.ts"]), # ~28h ago+ ],+ ),+ },+ min_score=0.0,+ min_sessions=1,+ )assert len(results) == 0def test_temporal_decay(self) -> None:"""Recent co-changes should have higher strength than old ones."""now = int(time.time())# Recent pair- recent = self._detect_with_mocked_logs({- "a": _make_commits("a", [("[email protected]", now - 100, ["f1.py"])]),- "b": _make_commits("b", [("[email protected]", now - 200, ["f2.py"])]),- }, min_score=0.0)+ recent = self._detect_with_mocked_logs(+ {+ "a": _make_commits("a", [("[email protected]", now - 100, ["f1.py"])]),+ "b": _make_commits("b", [("[email protected]", now - 200, ["f2.py"])]),+ },+ min_score=0.0,+ min_sessions=1,+ )# Old pair (6 months ago)- old = self._detect_with_mocked_logs({- "a": _make_commits("a", [("[email protected]", now - 15_000_000, ["f1.py"])]),- "b": _make_commits("b", [("[email protected]", now - 15_000_100, ["f2.py"])]),- }, min_score=0.0)+ old = self._detect_with_mocked_logs(+ {+ "a": _make_commits("a", [("[email protected]", now - 15_000_000, ["f1.py"])]),+ "b": _make_commits("b", [("[email protected]", now - 15_000_100, ["f2.py"])]),+ },+ min_score=0.0,+ min_sessions=1,+ )assert recent and oldassert recent[0].strength > old[0].strength@@ -165,37 +214,199 @@ class TestCrossRepoCoChanges:def test_min_score_filter(self) -> None:"""Low-strength edges are filtered by min_score."""now = int(time.time())- # Very old commit → low weight- results = self._detect_with_mocked_logs({- "a": _make_commits("a", [("[email protected]", now - 30_000_000, ["f1.py"])]),- "b": _make_commits("b", [("[email protected]", now - 30_000_100, ["f2.py"])]),- }, min_score=5.0)+ # Strength is bounded below 1, so a floor of 1.0 filters everything.+ results = self._detect_with_mocked_logs(+ {+ "a": _make_commits("a", [("[email protected]", now - 100, ["f1.py"])]),+ "b": _make_commits("b", [("[email protected]", now - 200, ["f2.py"])]),+ },+ min_score=1.0,+ min_sessions=1,+ )assert len(results) == 0def test_single_repo_returns_empty(self) -> None:"""Only one repo → no cross-repo edges."""now = int(time.time())- results = self._detect_with_mocked_logs({- "only": _make_commits("only", [- ("[email protected]", now, ["f1.py", "f2.py"]),- ]),- })+ results = self._detect_with_mocked_logs(+ {+ "only": _make_commits(+ "only",+ [+ ("[email protected]", now, ["f1.py", "f2.py"]),+ ],+ ),+ }+ )assert results == []def test_multiple_files_per_commit(self) -> None:- """N files in commit A × M files in commit B = N*M file pairs."""+ """N files in commit A x M files in commit B = N*M file pairs."""now = int(time.time())- results = self._detect_with_mocked_logs({- "a": _make_commits("a", [- ("[email protected]", now - 100, ["f1.py", "f2.py"]),- ]),- "b": _make_commits("b", [- ("[email protected]", now - 200, ["g1.py", "g2.py", "g3.py"]),- ]),- }, min_score=0.0)- # 2 × 3 = 6 unique file pairs+ results = self._detect_with_mocked_logs(+ {+ "a": _make_commits(+ "a",+ [+ ("[email protected]", now - 100, ["f1.py", "f2.py"]),+ ],+ ),+ "b": _make_commits(+ "b",+ [+ ("[email protected]", now - 200, ["g1.py", "g2.py", "g3.py"]),+ ],+ ),+ },+ min_score=0.0,+ min_sessions=1,+ )+ # 2 x 3 = 6 unique file pairsassert len(results) == 6+ def test_strength_bounded_below_one(self) -> None:+ """Strength is a share: always in (0, 1) no matter the volume."""+ now = int(time.time())+ # Many co-sessions of the same pair, 2 days apart each+ day = 86400+ entries_a = [("[email protected]", now - i * 2 * day, ["api.py"]) for i in range(10)]+ entries_b = [("[email protected]", now - i * 2 * day + 60, ["client.ts"]) for i in range(10)]+ results = self._detect_with_mocked_logs(+ {+ "a": _make_commits("a", entries_a),+ "b": _make_commits("b", entries_b),+ },+ min_score=0.0,+ )+ assert results+ for r in results:+ assert 0.0 < r.strength < 1.0++ def test_session_collapses_burst_of_commits(self) -> None:+ """A day of back-to-back commits is one session: frequency 1, not NxM."""+ now = int(time.time())+ results = self._detect_with_mocked_logs(+ {+ "a": _make_commits(+ "a",+ [+ ("[email protected]", now - 3600 * 1, ["api.py"]),+ ("[email protected]", now - 3600 * 2, ["api.py"]),+ ("[email protected]", now - 3600 * 3, ["api.py"]),+ ],+ ),+ "b": _make_commits(+ "b",+ [+ ("[email protected]", now - 3000, ["client.ts"]),+ ("[email protected]", now - 5000, ["client.ts"]),+ ("[email protected]", now - 9000, ["client.ts"]),+ ],+ ),+ },+ min_score=0.0,+ min_sessions=1,+ )+ assert len(results) == 1+ assert results[0].frequency == 1++ def test_single_session_pair_dropped_by_default(self) -> None:+ """One shared afternoon proves nothing: default needs >=2 co-sessions."""+ now = int(time.time())+ results = self._detect_with_mocked_logs(+ {+ "a": _make_commits("a", [("[email protected]", now - 100, ["f1.py"])]),+ "b": _make_commits("b", [("[email protected]", now - 200, ["f2.py"])]),+ },+ min_score=0.0,+ )+ assert results == []++ def test_ubiquitous_file_filtered(self) -> None:+ """A diary file touched in most commits never becomes an edge."""+ now = int(time.time())+ day = 86400+ # 30 backend sessions 2 days apart (enough history for the ubiquity+ # filter to engage); a diary rides along in every one.+ backend = []+ for i in range(30):+ files = ["docs/PROGRESS.md", f"src/other_{i}.py"]+ if i in (0, 2):+ files.append("src/api.py")+ backend.append(("[email protected]", now - i * 2 * day, files))+ frontend = [+ ("[email protected]", now - 0 * 2 * day + 60, ["src/client.ts"]),+ ("[email protected]", now - 2 * 2 * day + 60, ["src/client.ts"]),+ ]+ results = self._detect_with_mocked_logs(+ {+ "backend": _make_commits("backend", backend),+ "frontend": _make_commits("frontend", frontend),+ }+ )+ assert results, "the real api.py <-> client.ts coupling must survive"+ for r in results:+ assert "PROGRESS.md" not in r.source_file+ assert "PROGRESS.md" not in r.target_file+ pair_files = {(r.source_file, r.target_file) for r in results}+ assert ("src/api.py", "src/client.ts") in pair_files++ def test_sustained_coupling_outranks_coincidence(self) -> None:+ """5-of-6 sessions must outrank a 2-of-2 coincidence (smoothing)."""+ now = int(time.time())+ day = 86400+ a_entries = []+ b_entries = []+ # Sustained pair: co-occurs in 5 sessions, plus one solo session+ for i in range(5):+ a_entries.append(("[email protected]", now - i * 2 * day, ["sustained.py"]))+ b_entries.append(("[email protected]", now - i * 2 * day + 60, ["sustained.ts"]))+ a_entries.append(("[email protected]", now - 5 * 2 * day, ["sustained.py"]))+ # Coincidental pair: exists in exactly 2 sessions, both shared+ for i in range(2):+ a_entries.append(("[email protected]", now - i * 2 * day, ["coincidence.py"]))+ b_entries.append(("[email protected]", now - i * 2 * day + 60, ["coincidence.ts"]))+ results = self._detect_with_mocked_logs(+ {+ "a": _make_commits("a", a_entries),+ "b": _make_commits("b", b_entries),+ },+ min_score=0.0,+ )+ by_pair = {(r.source_file, r.target_file): r.strength for r in results}+ assert (+ by_pair[("sustained.py", "sustained.ts")]+ > by_pair[("coincidence.py", "coincidence.ts")]+ )++ def test_per_repo_pair_cap(self) -> None:+ """One hyperactive repo pair cannot starve others out of the results."""+ import repowise.core.workspace.cross_repo as cr++ now = int(time.time())+ day = 86400+ # a<->b: 4x4 files co-occurring in 2 recent sessions → 16 strong pairs+ ab_a = [("[email protected]", now - i * 2 * day, [f"a{n}.py" for n in range(4)]) for i in range(2)]+ ab_b = [+ ("[email protected]", now - i * 2 * day + 60, [f"b{n}.ts" for n in range(4)]) for i in range(2)+ ]+ # a<->c: one weaker (older) pair+ ac_a = [("[email protected]", now - (100 + i * 2) * day, ["shared.py"]) for i in range(2)]+ ac_c = [("[email protected]", now - (100 + i * 2) * day + 60, ["consumer.go"]) for i in range(2)]+ with patch.object(cr, "_MAX_EDGES_PER_REPO_PAIR", 5):+ results = self._detect_with_mocked_logs(+ {+ "a": _make_commits("a", ab_a + ac_a),+ "b": _make_commits("b", ab_b),+ "c": _make_commits("c", ac_c),+ },+ min_score=0.0,+ )+ ab_edges = [r for r in results if {r.source_repo, r.target_repo} == {"a", "b"}]+ ac_edges = [r for r in results if {r.source_repo, r.target_repo} == {"a", "c"}]+ assert len(ab_edges) == 5, "hyperactive pair capped"+ assert len(ac_edges) == 1, "weaker pair still present"+# ---------------------------------------------------------------------------# Noise-file filtering@@ -203,39 +414,47 @@ class TestCrossRepoCoChanges:class TestIsNoisePath:- @pytest.mark.parametrize("path", [- ".github/workflows/deploy.yml",- "sub/.github/workflows/build.yaml",- "package-lock.json",- "frontend/yarn.lock",- "Cargo.lock",- "go.sum",- "poetry.lock",- "uv.lock",- "app/static/bundle.min.js",- "styles/site.min.css",- "dist/index.js",- "node_modules/left-pad/index.js",- "src/generated/client.ts",- "Assets/Localization/en.json",- "web/locales/de.json",- "i18n/messages.fr.json",- "Assets/UI/Panels/InventoryPanel.prefab",- "api/proto/service.pb.go",- "svc/pb/thing_pb2.py",- "messages.po",- ])+ @pytest.mark.parametrize(+ "path",+ [+ ".github/workflows/deploy.yml",+ "sub/.github/workflows/build.yaml",+ "package-lock.json",+ "frontend/yarn.lock",+ "Cargo.lock",+ "go.sum",+ "poetry.lock",+ "uv.lock",+ "app/static/bundle.min.js",+ "styles/site.min.css",+ "dist/index.js",+ "node_modules/left-pad/index.js",+ "src/generated/client.ts",+ "Assets/Localization/en.json",+ "web/locales/de.json",+ "i18n/messages.fr.json",+ "Assets/UI/Panels/InventoryPanel.prefab",+ "api/proto/service.pb.go",+ "svc/pb/thing_pb2.py",+ "messages.po",+ "CHANGELOG.md",+ "docs/CHANGELOG.md",+ ],+ )def test_noise_paths_detected(self, path: str) -> None:assert _is_noise_path(path) is True- @pytest.mark.parametrize("path", [- "src/api.py",- "src/client.ts",- "backend/src/domain/manager.rs",- "config.json",- "README.md",- "packages/core/index.ts",- ])+ @pytest.mark.parametrize(+ "path",+ [+ "src/api.py",+ "src/client.ts",+ "backend/src/domain/manager.rs",+ "config.json",+ "README.md",+ "packages/core/index.ts",+ ],+ )def test_signal_paths_kept(self, path: str) -> None:assert _is_noise_path(path) is False@@ -261,14 +480,28 @@ class TestCrossRepoNoiseFiltering:def test_noise_files_excluded_from_pairs(self) -> None:"""Workflow/lockfile noise never appears in co-change results."""now = int(time.time())- results = self._detect_with_mocked_logs({- "backend": _make_commits("backend", [- ("[email protected]", now - 3600, ["src/api.py", ".github/workflows/deploy.yml"]),- ]),- "frontend": _make_commits("frontend", [- ("[email protected]", now - 7200, ["src/client.ts", "yarn.lock"]),- ]),- }, min_score=0.0)+ results = self._detect_with_mocked_logs(+ {+ "backend": _make_commits(+ "backend",+ [+ (+ "[email protected]",+ now - 3600,+ ["src/api.py", ".github/workflows/deploy.yml"],+ ),+ ],+ ),+ "frontend": _make_commits(+ "frontend",+ [+ ("[email protected]", now - 7200, ["src/client.ts", "yarn.lock"]),+ ],+ ),+ },+ min_score=0.0,+ min_sessions=1,+ )# Only the real src/api.py <-> src/client.ts pair survives.assert len(results) == 1files = {results[0].source_file, results[0].target_file}@@ -277,46 +510,50 @@ class TestCrossRepoNoiseFiltering:def test_commit_with_only_noise_dropped(self) -> None:"""A commit left empty after filtering produces no edges."""now = int(time.time())- results = self._detect_with_mocked_logs({- "backend": _make_commits("backend", [- ("[email protected]", now - 3600, [".github/workflows/deploy.yml"]),- ]),- "frontend": _make_commits("frontend", [- ("[email protected]", now - 7200, ["src/client.ts"]),- ]),- }, min_score=0.0)+ results = self._detect_with_mocked_logs(+ {+ "backend": _make_commits(+ "backend",+ [+ ("[email protected]", now - 3600, [".github/workflows/deploy.yml"]),+ ],+ ),+ "frontend": _make_commits(+ "frontend",+ [+ ("[email protected]", now - 7200, ["src/client.ts"]),+ ],+ ),+ },+ min_score=0.0,+ min_sessions=1,+ )assert results == []- def test_large_commit_does_not_dominate(self) -> None:- """A focused 1x1 cross-repo pair outranks pairs born from a wide commit.-- Same author, same recency: a small focused commit pairing should score- higher per-pair than pairs spun off a sprawling release commit.- """+ def test_wide_session_capped_per_side(self) -> None:+ """A sprawling release session pairs at most 20 files per side."""now = int(time.time())- focused_files = [f"focused_b{n}.py" for n in range(1)]- wide_files = [f"wide_b{n}.py" for n in range(40)]- results = self._detect_with_mocked_logs({- "a": _make_commits("a", [- ("[email protected]", now - 100, ["focused_a.py"]),- ("[email protected]", now - 50, ["wide_a.py"]),- ]),- "b": _make_commits("b", [- ("[email protected]", now - 120, focused_files),- ("[email protected]", now - 60, wide_files),- ]),- }, min_score=0.0)- by_pair = {(r.source_file, r.target_file): r.strength for r in results}- # The focused pair must outrank any pair generated from the wide commit.- focused_strength = max(- s for (sf, tf), s in by_pair.items()- if "focused" in sf or "focused" in tf- )- wide_strength = max(- s for (sf, tf), s in by_pair.items()- if "wide" in sf and "wide" in tf+ wide_files = [f"wide_b{n:02d}.py" for n in range(40)]+ results = self._detect_with_mocked_logs(+ {+ "a": _make_commits(+ "a",+ [+ ("[email protected]", now - 100, ["main.py"]),+ ],+ ),+ "b": _make_commits(+ "b",+ [+ ("[email protected]", now - 120, wide_files),+ ],+ ),+ },+ min_score=0.0,+ min_sessions=1,)- assert focused_strength > wide_strength+ # 1 x min(40, 20) = 20 pairs, not 40+ assert len(results) == 20# ---------------------------------------------------------------------------@@ -407,19 +644,24 @@ class TestManifestScanning:class TestOverlayPersistence:def test_save_and_load_round_trip(self, tmp_path: Path) -> None:overlay = CrossRepoOverlay(- version=1,generated_at="2026-04-12T12:00:00Z",co_changes=[CrossRepoCoChange(- source_repo="a", source_file="f1.py",- target_repo="b", target_file="f2.py",- strength=3.5, frequency=4, last_date="2026-04-10",+ source_repo="a",+ source_file="f1.py",+ target_repo="b",+ target_file="f2.py",+ strength=0.35,+ frequency=4,+ last_date="2026-04-10",),],package_deps=[CrossRepoPackageDep(- source_repo="b", target_repo="a",- source_manifest="package.json", kind="npm_local_path",+ source_repo="b",+ target_repo="a",+ source_manifest="package.json",+ kind="npm_local_path",),],repo_summaries={"a": {"cross_repo_edge_count": 1}},@@ -427,12 +669,18 @@ class TestOverlayPersistence:save_overlay(overlay, tmp_path)loaded = load_overlay(tmp_path)assert loaded is not None- assert loaded.version == 1+ assert loaded.version == overlay.versionassert len(loaded.co_changes) == 1- assert loaded.co_changes[0].strength == 3.5+ assert loaded.co_changes[0].strength == 0.35assert len(loaded.package_deps) == 1assert loaded.package_deps[0].kind == "npm_local_path"+ def test_load_stale_version_returns_none(self, tmp_path: Path) -> None:+ """v1 overlays carry unbounded strengths — treated as absent."""+ overlay = CrossRepoOverlay(version=1)+ save_overlay(overlay, tmp_path)+ assert load_overlay(tmp_path) is None+def test_load_missing_file_returns_none(self, tmp_path: Path) -> None:assert load_overlay(tmp_path) is None