Skip to content

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

feat(workspace): surface supporting evidence for cross-repo co-change pairs (#2041)

Nehal Kb266ee594e11
diff --git a/packages/api-client/src/types/workspace.ts b/packages/api-client/src/types/workspace.ts
index 67c9baf33..54c056fb5 100644
--- a/packages/api-client/src/types/workspace.ts
+++ b/packages/api-client/src/types/workspace.ts
@@ -167,6 +167,20 @@ export interface WorkspaceContractDetail {
unmatched_reason: string | null;
}
+export interface WorkspaceCoChangeEvidence {
+ /** Distinct author emails behind the pair (bounded sample). */
+ authors: string[];
+ /** Example matched commit pairs: short SHAs, date, time gap in hours. */
+ commit_pairs: {
+ source_sha: string;
+ target_sha: string;
+ date: string;
+ gap_hours: number;
+ }[];
+ /** Largest time gap between the sampled paired commits, hours. */
+ max_gap_hours: number;
+}
+
export interface WorkspaceCoChangeEntry {
source_repo: string;
source_file: string;
@@ -175,6 +189,8 @@ export interface WorkspaceCoChangeEntry {
strength: number;
frequency: number;
last_date: string;
+ /** Bounded supporting evidence (#483); null for pre-evidence overlays. */
+ evidence: WorkspaceCoChangeEvidence | null;
}
export interface WorkspaceCoChangesResponse {
diff --git a/packages/core/src/repowise/core/workspace/cross_repo.py b/packages/core/src/repowise/core/workspace/cross_repo.py
index f6af98c1a..e96ac482f 100644
--- a/packages/core/src/repowise/core/workspace/cross_repo.py
+++ b/packages/core/src/repowise/core/workspace/cross_repo.py
@@ -43,8 +43,10 @@ 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
+# the new semantics (v2: strength became a bounded [0,1) session share;
+# v3: co-change rows gained bounded supporting evidence — authors, example
+# commit pairs, max time gap — issue #483).
+_OVERLAY_VERSION: int = 3
_DEFAULT_TIME_WINDOW_HOURS: int = 24
_CROSS_REPO_COMMIT_LIMIT: int = 500
@@ -75,6 +77,11 @@ 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
+# Evidence capture (#483): how many example matched commit pairs survive per
+# co-change pair, and how many distinct authors are recorded. Bounded so a
+# pair backed by hundreds of commit pairs cannot bloat the persisted overlay.
+_MAX_EVIDENCE_COMMIT_PAIRS: int = 3
+_MAX_EVIDENCE_AUTHORS: int = 5
# ---------------------------------------------------------------------------
# Noise-file filtering
@@ -168,6 +175,21 @@ def _is_noise_path(path: str) -> bool:
# ---------------------------------------------------------------------------
+@dataclass
+class CoChangeEvidence:
+ """Bounded supporting evidence for one cross-repo co-change pair (#483).
+
+ A pair is a temporal, same-author hint; the evidence is what lets a user
+ judge whether the relationship is meaningful. The sample is capped —
+ ``_MAX_EVIDENCE_COMMIT_PAIRS`` example matched commit pairs per pair, so
+ the overlay cannot bloat on pairs backed by hundreds of commit pairs.
+ """
+
+ authors: list[str] # distinct author emails, dedup, insertion order
+ commit_pairs: list[dict] # capped [{source_sha, target_sha, date, gap_hours}]
+ max_gap_hours: float # largest time gap between a matched commit pair
+
+
@dataclass
class CrossRepoCoChange:
source_repo: str
@@ -177,6 +199,7 @@ class CrossRepoCoChange:
strength: float # bounded [0, 1) recency-weighted share of co-sessions
frequency: int # distinct work sessions in which both files changed
last_date: str # ISO date of most recent co-change
+ evidence: CoChangeEvidence | None = None # bounded sample, None pre-#483 overlays
@dataclass
@@ -211,7 +234,27 @@ class CrossRepoOverlay:
@classmethod
def from_dict(cls, data: dict) -> CrossRepoOverlay:
- co_changes = [CrossRepoCoChange(**c) for c in data.get("co_changes", [])]
+ def _co_change(c: dict) -> CrossRepoCoChange:
+ ev = c.get("evidence")
+ evidence = None
+ if isinstance(ev, dict) and (ev.get("commit_pairs") or ev.get("authors")):
+ evidence = CoChangeEvidence(
+ authors=list(ev.get("authors") or []),
+ commit_pairs=list(ev.get("commit_pairs") or []),
+ max_gap_hours=float(ev.get("max_gap_hours", 0.0)),
+ )
+ return CrossRepoCoChange(
+ source_repo=c["source_repo"],
+ source_file=c["source_file"],
+ target_repo=c["target_repo"],
+ target_file=c["target_file"],
+ strength=float(c["strength"]),
+ frequency=int(c["frequency"]),
+ last_date=c.get("last_date", ""),
+ evidence=evidence,
+ )
+
+ co_changes = [_co_change(c) for c in data.get("co_changes", [])]
return cls(
version=data.get("version", 1),
generated_at=data.get("generated_at", ""),
@@ -240,6 +283,7 @@ class _GitCommit:
timestamp: int # Unix epoch
files: list[str] = field(default_factory=list)
author_name: str = ""
+ sha: str = "" # full commit SHA (%H)
@property
def author_identity(self) -> str:
@@ -271,7 +315,7 @@ def _parse_git_log(
"log",
f"-{commit_limit}",
# %x01 separator: author names may contain "|"
- "--format=%x00%ae%x01%an%x01%ct",
+ "--format=%x00%ae%x01%an%x01%ct%x01%H",
"--name-only",
"--no-merges",
],
@@ -298,18 +342,20 @@ def _parse_git_log(
commits.append(current)
header = line.lstrip("\x00").strip()
- parts = header.split("\x01", 2)
- if len(parts) == 3:
+ parts = header.split("\x01", 3)
+ if len(parts) >= 3:
email = parts[0].strip()
name = parts[1].strip()
try:
ts = int(parts[2].strip())
except (ValueError, TypeError):
ts = 0
+ sha = parts[3].strip() if len(parts) == 4 else ""
current = _GitCommit(
author_email=email,
timestamp=ts,
author_name=name,
+ sha=sha,
)
else:
current = None
@@ -469,6 +515,10 @@ def detect_cross_repo_co_changes(
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] = {}
+ # Evidence capture (#483): per-pair bounded sample of matched commits.
+ pair_evidence: dict[tuple[str, str, str, str], dict] = defaultdict(
+ lambda: {"authors": [], "commit_pairs": [], "max_gap_hours": 0.0}
+ )
for tagged_commits in author_commits.values():
tagged_commits.sort(key=lambda x: x[1].timestamp)
@@ -521,6 +571,41 @@ def detect_cross_repo_co_changes(
pair_freq[key] += 1
if key not in pair_last_ts or last_ts > pair_last_ts[key]:
pair_last_ts[key] = last_ts
+ # Evidence (#483): one example matched commit pair
+ # per session — the commits in each repo that
+ # touched the two files — capped per pair and
+ # deduped by (source_sha, target_sha).
+ ev = pair_evidence[key]
+ src_commit = next(
+ (c for _, c in session if c.sha and fa in c.files),
+ None,
+ )
+ tgt_commit = next(
+ (c for _, c in session if c.sha and fb in c.files),
+ None,
+ )
+ if src_commit is not None and tgt_commit is not None:
+ gap = abs(src_commit.timestamp - tgt_commit.timestamp) / 3600.0
+ ev["max_gap_hours"] = max(ev["max_gap_hours"], gap)
+ for email in (src_commit.author_email, tgt_commit.author_email):
+ if email and email not in ev["authors"]:
+ ev["authors"].append(email)
+ pair = (src_commit.sha, tgt_commit.sha)
+ if len(ev["commit_pairs"]) < _MAX_EVIDENCE_COMMIT_PAIRS and not any(
+ p["source_sha"] == pair[0] and p["target_sha"] == pair[1]
+ for p in ev["commit_pairs"]
+ ):
+ ev["commit_pairs"].append(
+ {
+ "source_sha": pair[0][:8],
+ "target_sha": pair[1][:8],
+ "date": datetime.fromtimestamp(
+ last_ts, tz=UTC
+ ).strftime("%Y-%m-%d"),
+ "gap_hours": round(gap, 1),
+ }
+ )
+ ev["authors"] = ev["authors"][:_MAX_EVIDENCE_AUTHORS]
# Step 5+6: Normalize to a bounded share, filter, and build results
results: list[CrossRepoCoChange] = []
@@ -542,6 +627,14 @@ def detect_cross_repo_co_changes(
last_date = (
datetime.fromtimestamp(last_ts, tz=UTC).strftime("%Y-%m-%d") if last_ts > 0 else ""
)
+ ev = pair_evidence.get((src_repo, src_file, tgt_repo, tgt_file))
+ evidence = None
+ if ev and (ev["commit_pairs"] or ev["authors"]):
+ evidence = CoChangeEvidence(
+ authors=ev["authors"][:_MAX_EVIDENCE_AUTHORS],
+ commit_pairs=ev["commit_pairs"][:_MAX_EVIDENCE_COMMIT_PAIRS],
+ max_gap_hours=round(ev["max_gap_hours"], 1),
+ )
results.append(
CrossRepoCoChange(
source_repo=src_repo,
@@ -551,6 +644,7 @@ def detect_cross_repo_co_changes(
strength=round(strength, 3),
frequency=freq,
last_date=last_date,
+ evidence=evidence,
)
)
diff --git a/packages/core/src/repowise/core/workspace/reads.py b/packages/core/src/repowise/core/workspace/reads.py
index b30a7ec43..44b54dd2d 100644
--- a/packages/core/src/repowise/core/workspace/reads.py
+++ b/packages/core/src/repowise/core/workspace/reads.py
@@ -307,6 +307,9 @@ def list_co_changes(
"strength": cc.get("strength", 0.0),
"frequency": cc.get("frequency", 0),
"last_date": cc.get("last_date", ""),
+ # Bounded sample, absent on pre-#483 overlays. Passed through
+ # as stored: the miner already capped and deduped it.
+ "evidence": cc.get("evidence"),
}
for cc in pairs[:limit]
],
diff --git a/packages/server/src/repowise/server/routers/workspace.py b/packages/server/src/repowise/server/routers/workspace.py
index 2806fdaca..ad1ba4d67 100644
--- a/packages/server/src/repowise/server/routers/workspace.py
+++ b/packages/server/src/repowise/server/routers/workspace.py
@@ -310,8 +310,7 @@ async def get_co_change_structure(
source_file=source_file,
target_repo=target_repo,
target_file=target_file,
- )
- )
+ ) )
# ---------------------------------------------------------------------------
diff --git a/packages/server/src/repowise/server/schemas/__init__.py b/packages/server/src/repowise/server/schemas/__init__.py
index db6b3a178..78b1ca04a 100644
--- a/packages/server/src/repowise/server/schemas/__init__.py
+++ b/packages/server/src/repowise/server/schemas/__init__.py
@@ -303,6 +303,7 @@ if TYPE_CHECKING:
WorkspaceBreakingChange,
WorkspaceBreakingChangesResponse,
WorkspaceCoChangeEntry,
+ WorkspaceCoChangeEvidence,
WorkspaceCoChangesResponse,
WorkspaceCoChangeStructure,
WorkspaceConformanceResponse,
@@ -612,6 +613,7 @@ _EXPORTS: dict[str, tuple[str, ...]] = {
"WorkspaceBreakingChange",
"WorkspaceBreakingChangesResponse",
"WorkspaceCoChangeEntry",
+ "WorkspaceCoChangeEvidence",
"WorkspaceCoChangesResponse",
"WorkspaceCoChangeStructure",
"WorkspaceConformanceResponse",
@@ -671,7 +673,6 @@ if not TYPE_CHECKING:
def __dir__() -> list[str]:
return sorted({*globals(), *__all__})
-
__all__ = [
"ActiveProviderSelection",
"AgentTrendBucket",
@@ -919,6 +920,7 @@ __all__ = [
"WorkspaceBreakingChange",
"WorkspaceBreakingChangesResponse",
"WorkspaceCoChangeEntry",
+ "WorkspaceCoChangeEvidence",
"WorkspaceCoChangeStructure",
"WorkspaceCoChangesResponse",
"WorkspaceConformanceResponse",
diff --git a/packages/server/src/repowise/server/schemas/workspace.py b/packages/server/src/repowise/server/schemas/workspace.py
index 1f8cab1e8..439bedb42 100644
--- a/packages/server/src/repowise/server/schemas/workspace.py
+++ b/packages/server/src/repowise/server/schemas/workspace.py
@@ -178,6 +178,14 @@ class WorkspaceContractDetail(BaseModel):
unmatched_reason: str | None = None
+class WorkspaceCoChangeEvidence(BaseModel):
+ """Bounded supporting evidence for one co-change pair (#483)."""
+
+ authors: list[str] = []
+ commit_pairs: list[dict] = []
+ max_gap_hours: float = 0.0
+
+
class WorkspaceCoChangeEntry(BaseModel):
source_repo: str
source_file: str
@@ -186,6 +194,7 @@ class WorkspaceCoChangeEntry(BaseModel):
strength: float
frequency: int
last_date: str
+ evidence: WorkspaceCoChangeEvidence | None = None
class WorkspacePackageDepEntry(BaseModel):
diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.ts
index 2770071eb..147b776ac 100644
--- a/packages/types/src/generated/http.ts
+++ b/packages/types/src/generated/http.ts
@@ -4644,6 +4644,14 @@ export interface WorkspaceCoChangeEntry {
strength: number;
frequency: number;
last_date: string;
+ evidence?: WorkspaceCoChangeEvidence | null;
+}
+
+/** Bounded supporting evidence for one co-change pair (#483). */
+export interface WorkspaceCoChangeEvidence {
+ authors?: string[];
+ commit_pairs?: Record<string, unknown>[];
+ max_gap_hours?: number;
}
/** What declared structure connects one co-changing file pair. */
diff --git a/packages/types/src/workspace.ts b/packages/types/src/workspace.ts
index bd9a9879c..c4734aa58 100644
--- a/packages/types/src/workspace.ts
+++ b/packages/types/src/workspace.ts
@@ -111,6 +111,20 @@ export interface WorkspaceContractLinkEntry {
consumer_contract_id?: string | null;
}
+export interface WorkspaceCoChangeEvidence {
+ /** Distinct author emails behind the pair (bounded sample). */
+ authors: string[];
+ /** Example matched commit pairs: short SHAs, date, time gap in hours. */
+ commit_pairs: Array<{
+ source_sha: string;
+ target_sha: string;
+ date: string;
+ gap_hours: number;
+ }>;
+ /** Largest time gap between a matched commit pair, in hours. */
+ max_gap_hours: number;
+}
+
/**
* Which way a link between two services runs: `a_to_b` when `a` is the consumer
* or dependent, `both` for a co-change (it has no direction).
@@ -172,6 +186,8 @@ export interface WorkspaceCoChangeEntry {
strength: number;
frequency: number;
last_date: string;
+ /** Bounded supporting evidence (#483); null for pre-evidence overlays. */
+ evidence: WorkspaceCoChangeEvidence | null;
}
export interface WorkspacePackageDepEntry {
diff --git a/packages/ui/__tests__/workspace/co-change-ai-prompt.test.ts b/packages/ui/__tests__/workspace/co-change-ai-prompt.test.ts
index 409dccf1e..8bb3c34f1 100644
--- a/packages/ui/__tests__/workspace/co-change-ai-prompt.test.ts
+++ b/packages/ui/__tests__/workspace/co-change-ai-prompt.test.ts
@@ -16,6 +16,7 @@ function pair(overrides: Partial<WorkspaceCoChangeEntry> = {}): WorkspaceCoChang
strength: 0.694,
frequency: 3,
last_date: "2026-09-01",
+ evidence: null,
...overrides,
};
}
diff --git a/packages/ui/__tests__/workspace/co-change-pair-drawer.test.tsx b/packages/ui/__tests__/workspace/co-change-pair-drawer.test.tsx
index 6578545ef..c9c4d6d52 100644
--- a/packages/ui/__tests__/workspace/co-change-pair-drawer.test.tsx
+++ b/packages/ui/__tests__/workspace/co-change-pair-drawer.test.tsx
@@ -16,6 +16,7 @@ const PAIR: WorkspaceCoChangeEntry = {
strength: 0.69,
frequency: 3,
last_date: "2026-09-01",
+ evidence: null,
};
function history(sha: string, date: string): Loadable<CoChangeFileHistory> {
diff --git a/packages/ui/__tests__/workspace/co-change-table.test.tsx b/packages/ui/__tests__/workspace/co-change-table.test.tsx
index a1884c7ea..d1eeb2434 100644
--- a/packages/ui/__tests__/workspace/co-change-table.test.tsx
+++ b/packages/ui/__tests__/workspace/co-change-table.test.tsx
@@ -9,6 +9,7 @@ function cc(
targetRepo: string,
targetFile: string,
strength = 0.5,
+ evidence: WorkspaceCoChangeEntry["evidence"] = null,
): WorkspaceCoChangeEntry {
return {
source_repo: sourceRepo,
@@ -18,6 +19,7 @@ function cc(
strength,
frequency: 3,
last_date: "2026-06-01",
+ evidence,
};
}
@@ -61,4 +63,27 @@ describe("CoChangeTable", () => {
render(<CoChangeTable coChanges={[]} />);
expect(screen.getByText(/no cross-repo co-changes/i)).toBeInTheDocument();
});
+
+ it("collapses the evidence behind a disclosure that names the sample size", () => {
+ const row = cc("api", "api/a.py", "core", "core/b.py", 0.8, {
+ authors: ["[email protected]"],
+ commit_pairs: [
+ { source_sha: "abc12345", target_sha: "def67890", date: "2026-06-01", gap_hours: 3.5 },
+ ],
+ max_gap_hours: 3.5,
+ });
+ render(<CoChangeTable coChanges={[row]} />);
+ const summary = screen.getByText("1 commit pair");
+ expect(summary).toBeInTheDocument();
+ // Collapsed: the author and the shas are in the DOM but not yet shown.
+ expect(screen.getByText("[email protected]")).not.toBeVisible();
+ fireEvent.click(summary);
+ expect(screen.getByText("[email protected]")).toBeVisible();
+ expect(screen.getByText("abc12345")).toBeVisible();
+ });
+
+ it("renders a dash for a pair with no evidence recorded", () => {
+ render(<CoChangeTable coChanges={[cc("api", "a.py", "core", "b.py")]} />);
+ expect(screen.getByText("—")).toBeInTheDocument();
+ });
});
diff --git a/packages/ui/src/workspace/co-change-table.tsx b/packages/ui/src/workspace/co-change-table.tsx
index 19e03a95b..5e899ebbd 100644
--- a/packages/ui/src/workspace/co-change-table.tsx
+++ b/packages/ui/src/workspace/co-change-table.tsx
@@ -9,7 +9,7 @@ import { cn } from "../lib/cn";
import { formatDate, formatDateTime } from "../lib/format";
import { PAIR_MICRO as MICRO } from "../coupling/pair-drawer-parts";
import { SESSIONS_DEFINITION, STRENGTH_DEFINITION } from "./co-change-facts";
-import type { WorkspaceCoChangeEntry } from "@repowise-dev/types/workspace";
+import type { WorkspaceCoChangeEvidence, WorkspaceCoChangeEntry } from "@repowise-dev/types/workspace";
interface CoChangeTableProps {
coChanges: WorkspaceCoChangeEntry[];
@@ -36,6 +36,47 @@ export function coChangeKey(cc: WorkspaceCoChangeEntry): string {
// files and the strength stay at every width.
const HIDE_BELOW_MD = "max-md:hidden";
+/**
+ * The bounded sample behind one pair: which authors, which matched commits, and
+ * how far apart they landed. Collapsed by default, so a reader scans the list
+ * and opens only the pair they doubt. The counts are small by construction
+ * (`_MAX_EVIDENCE_COMMIT_PAIRS`, `_MAX_EVIDENCE_AUTHORS` in the miner), so this
+ * never renders an unbounded block.
+ */
+function EvidenceCell({ evidence }: { evidence: WorkspaceCoChangeEvidence }) {
+ const authors = evidence.authors ?? [];
+ const pairs = evidence.commit_pairs ?? [];
+ if (authors.length === 0 && pairs.length === 0) {
+ return <span className="text-[var(--color-text-tertiary)]">none recorded</span>;
+ }
+ return (
+ <details className="group">
+ <summary className="flex cursor-pointer list-none items-center justify-end gap-1 text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]">
+ <span className="inline-block transition-transform group-open:rotate-90" aria-hidden>
+ ▸
+ </span>
+ <span className="tabular-nums">
+ {pairs.length > 0 ? `${pairs.length} commit pair${pairs.length === 1 ? "" : "s"}` : "evidence"}
+ </span>
+ </summary>
+ <div className="mt-1.5 flex flex-col items-end gap-1 text-[var(--color-text-tertiary)]">
+ {authors.length > 0 ? <span className="whitespace-nowrap">{authors.join(", ")}</span> : null}
+ {pairs.map((pair) => (
+ <span key={`${pair.source_sha}|${pair.target_sha}`} className="whitespace-nowrap font-mono">
+ <span className="tabular-nums">{pair.source_sha}</span>
+ <span aria-hidden> → </span>
+ <span className="tabular-nums">{pair.target_sha}</span>
+ <span>{` · ${pair.gap_hours}h`}</span>
+ </span>
+ ))}
+ {evidence.max_gap_hours > 0 ? (
+ <span>{`max gap ${evidence.max_gap_hours}h`}</span>
+ ) : null}
+ </div>
+ </details>
+ );
+}
+
/**
* A repository as a quiet micro-label over its path. In a row the file name
* leads and the directory clips; with `wrap`, where the exact file must be
@@ -101,6 +142,13 @@ const CoChangeRow = React.memo(function CoChangeRow({ cc, compact, selected, onS
{cc.last_date ? formatDate(cc.last_date) : "unknown"}
</span>
</td>
+ <td className={`px-3 py-2.5 text-right align-middle text-xs ${HIDE_BELOW_MD}`}>
+ {cc.evidence ? (
+ <EvidenceCell evidence={cc.evidence} />
+ ) : (
+ <span className="text-[var(--color-text-tertiary)]">—</span>
+ )}
+ </td>
</>
)}
</tr>
@@ -153,6 +201,15 @@ export function CoChangeTable({ coChanges, compact = false, onSelect, selectedKe
<th className={cn(MICRO, "px-3 py-2 text-right font-normal", HIDE_BELOW_MD)}>
Last together
</th>
+ <th className={cn(MICRO, "px-3 py-2 text-right font-normal", HIDE_BELOW_MD)}>
+ <span className="inline-flex items-center gap-1">
+ Evidence
+ <InfoTip
+ content="Supporting evidence for the pair: authors, example matched commit pairs, and the time gap between them. Sampled and capped, so a pair backed by hundreds of commits shows a few examples."
+ label="What the evidence column shows"
+ />
+ </span>
+ </th>
</>
)}
</tr>
diff --git a/tests/unit/workspace/test_cross_repo.py b/tests/unit/workspace/test_cross_repo.py
index 8f2a7708f..21fa0ca67 100644
--- a/tests/unit/workspace/test_cross_repo.py
+++ b/tests/unit/workspace/test_cross_repo.py
@@ -98,6 +98,14 @@ def _make_commits(alias: str, entries: list[tuple[str, int, list[str]]]) -> list
return [_GitCommit(author_email=e, timestamp=ts, files=files) for e, ts, files in entries]
+def _make_commits_with_sha(alias: str, entries: list[tuple[str, int, list[str], str]]) -> list[_GitCommit]:
+ """Helper: (email, ts, files, sha) tuples for evidence capture tests."""
+ return [
+ _GitCommit(author_email=e, timestamp=ts, files=files, sha=sha)
+ for e, ts, files, sha in entries
+ ]
+
+
class TestCrossRepoCoChanges:
def _detect_with_mocked_logs(
self, repo_commits: dict[str, list[_GitCommit]], **kwargs
@@ -410,6 +418,69 @@ class TestCrossRepoCoChanges:
assert len(ac_edges) == 1, "weaker pair still present"
+ def test_evidence_captured_for_co_change_pair(self) -> None:
+ """A matched commit pair in a co-session leaves authors + commit pair
+ evidence on the edge (#483)."""
+ now = int(time.time())
+ results = self._detect_with_mocked_logs(
+ {
+ "a": _make_commits_with_sha(
+ "a",
+ [
+ ("[email protected]", now - 3600, ["f1.py"], "aaaa1111"),
+ ],
+ ),
+ "b": _make_commits_with_sha(
+ "b",
+ [
+ ("[email protected]", now - 7200, ["f2.py"], "bbbb2222"),
+ ],
+ ),
+ },
+ min_score=0.0,
+ min_sessions=1,
+ )
+ assert len(results) == 1
+ r = results[0]
+ assert r.evidence is not None
+ assert r.evidence.authors == ["[email protected]"]
+ assert len(r.evidence.commit_pairs) == 1
+ pair = r.evidence.commit_pairs[0]
+ assert pair["source_sha"] == "aaaa1111"
+ assert pair["target_sha"] == "bbbb2222"
+ assert pair["gap_hours"] == 1.0 # 3600s apart = 1h
+ assert r.evidence.max_gap_hours == 1.0
+
+ def test_evidence_commit_pairs_capped(self) -> None:
+ """A pair backed by many co-sessions keeps at most the capped sample."""
+ now = int(time.time())
+ a_commits = [
+ _GitCommit(
+ author_email=f"x{i}@co.com",
+ timestamp=now - (i + 1) * 3600,
+ files=["f1.py"],
+ sha=f"aaaa{i:04d}",
+ )
+ for i in range(10)
+ ]
+ b_commits = [
+ _GitCommit(
+ author_email=f"x{i}@co.com",
+ timestamp=now - (i + 1) * 3600 - 600,
+ files=["f2.py"],
+ sha=f"bbbb{i:04d}",
+ )
+ for i in range(10)
+ ]
+ results = self._detect_with_mocked_logs(
+ {"a": a_commits, "b": b_commits},
+ min_score=0.0,
+ min_sessions=1,
+ )
+ assert len(results) >= 1
+ assert len(results[0].evidence.commit_pairs) <= 3 # _MAX_EVIDENCE_COMMIT_PAIRS
+
+
class TestCoChangeTruncationTotals:
"""The caps must report what they dropped, not just drop it."""
@@ -761,6 +832,43 @@ class TestOverlayPersistence:
assert path.is_file()
assert (tmp_path / ".repowise-workspace").is_dir()
+ def test_load_overlay_round_trips_evidence(self, tmp_path: Path) -> None:
+ """Evidence survives save -> load round trip."""
+ from repowise.core.workspace.cross_repo import (
+ CoChangeEvidence,
+ CrossRepoCoChange,
+ CrossRepoOverlay,
+ load_overlay,
+ save_overlay,
+ )
+
+ cc = CrossRepoCoChange(
+ source_repo="a",
+ source_file="f1.py",
+ target_repo="b",
+ target_file="f2.py",
+ strength=0.5,
+ frequency=2,
+ last_date="2026-06-01",
+ evidence=CoChangeEvidence(
+ authors=["[email protected]"],
+ commit_pairs=[
+ {
+ "source_sha": "aaaa1111",
+ "target_sha": "bbbb2222",
+ "date": "2026-06-01",
+ "gap_hours": 2.0,
+ }
+ ],
+ max_gap_hours=2.0,
+ ),
+ )
+ save_overlay(CrossRepoOverlay(co_changes=[cc]), tmp_path)
+ loaded = load_overlay(tmp_path)
+ assert loaded is not None
+ assert loaded.co_changes[0].evidence is not None
+ assert loaded.co_changes[0].evidence.authors == ["[email protected]"]
+ assert loaded.co_changes[0].evidence.commit_pairs[0]["source_sha"] == "aaaa1111"
# ---------------------------------------------------------------------------
# run_cross_repo_analysis with no repo changed