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): open co-changing file pairs in a drawer, with search and cap reporting (#2499)

Raghav Chamadiya534e1a5816dc
diff --git a/packages/api-client/src/types/workspace.ts b/packages/api-client/src/types/workspace.ts
index cc960e2a2..746c511f4 100644
--- a/packages/api-client/src/types/workspace.ts
+++ b/packages/api-client/src/types/workspace.ts
@@ -177,6 +177,24 @@ export interface WorkspaceCoChangesResponse {
* before pairing, so some pairs are in neither number.
*/
total_mined: number;
+ /** Most pairs the miner keeps per repository pair. Optional for older servers. */
+ per_repo_pair_cap?: number | null;
+ /** Most pairs the miner keeps across the workspace. */
+ total_cap?: number | null;
+ /** Which cap trimmed the stored overlay; null when nothing was dropped. */
+ truncated_by?: "total" | "per_repo_pair" | null;
+}
+
+/** Declared structure behind one co-changing file pair. */
+export interface WorkspaceCoChangeStructure {
+ /** Contract links where one of the two files provides and the other consumes. */
+ pair_links: WorkspaceContractLinkEntry[];
+ /** Contract links between the two repositories through any files. */
+ repo_links_total: number;
+ repo_links_by_type: Record<string, number>;
+ /** Contract links touching each file, whatever the other end. */
+ source_file_links: number;
+ target_file_links: number;
}
export interface WorkspaceGraphNode {
diff --git a/packages/api-client/src/workspace.ts b/packages/api-client/src/workspace.ts
index 07517c521..cd0cf66c2 100644
--- a/packages/api-client/src/workspace.ts
+++ b/packages/api-client/src/workspace.ts
@@ -4,6 +4,7 @@ import type {
WorkspaceContractsResponse,
WorkspaceContractDetail,
WorkspaceCoChangesResponse,
+ WorkspaceCoChangeStructure,
WorkspaceGraphResponse,
WorkspaceRepoRemovedResponse,
WorkspaceSyncResponse,
@@ -77,6 +78,16 @@ export async function getWorkspaceCoChanges(opts?: {
return apiGet<WorkspaceCoChangesResponse>("/api/workspace/co-changes", params);
}
+/** Contract links behind one co-changing file pair, fetched when its drawer opens. */
+export async function getWorkspaceCoChangeStructure(pair: {
+ source_repo: string;
+ source_file: string;
+ target_repo: string;
+ target_file: string;
+}): Promise<WorkspaceCoChangeStructure> {
+ return apiGet<WorkspaceCoChangeStructure>("/api/workspace/co-changes/structure", pair);
+}
+
export async function getWorkspaceGraph(): Promise<WorkspaceGraphResponse> {
return apiGet<WorkspaceGraphResponse>("/api/workspace/graph");
}
diff --git a/packages/core/src/repowise/core/workspace/cross_repo.py b/packages/core/src/repowise/core/workspace/cross_repo.py
index b3bf37c48..b13147634 100644
--- a/packages/core/src/repowise/core/workspace/cross_repo.py
+++ b/packages/core/src/repowise/core/workspace/cross_repo.py
@@ -60,10 +60,11 @@ _UBIQUITY_MIN_HISTORY: int = 30
# 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
+# Public: the workspace API reports which of these caps trimmed the overlay.
+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
+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
@@ -206,7 +207,7 @@ class CrossRepoOverlay:
package_diagnostics: list[CrossRepoPackageDiagnostic] = field(default_factory=list)
repo_summaries: dict[str, dict] = field(default_factory=dict)
#: How many pairs cleared the strength/session thresholds before
- #: ``_MAX_EDGES`` / ``_MAX_EDGES_PER_REPO_PAIR`` trimmed ``co_changes``.
+ #: ``MAX_EDGES`` / ``MAX_EDGES_PER_REPO_PAIR`` trimmed ``co_changes``.
#: Equal to ``len(co_changes)`` when nothing was dropped. Not a count of
#: every pair in git history: ``_MAX_FILES_PER_SESSION_SIDE`` bounds each
#: session before pairing, so pairs involving an evicted file are in
@@ -579,19 +580,19 @@ def detect_cross_repo_co_changes(
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:
+ if per_pair[pair_key] >= MAX_EDGES_PER_REPO_PAIR:
continue
per_pair[pair_key] += 1
capped.append(r)
- if len(capped) >= _MAX_EDGES:
+ if len(capped) >= MAX_EDGES:
break
if len(capped) < len(results):
_log.info(
"Co-change mining kept %d of %d qualifying pairs (caps: %d total, %d per repo pair)",
len(capped),
len(results),
- _MAX_EDGES,
- _MAX_EDGES_PER_REPO_PAIR,
+ MAX_EDGES,
+ MAX_EDGES_PER_REPO_PAIR,
)
return capped, len(results)
diff --git a/packages/server/src/repowise/server/routers/workspace.py b/packages/server/src/repowise/server/routers/workspace.py
index 6fe21fd8e..094db2e24 100644
--- a/packages/server/src/repowise/server/routers/workspace.py
+++ b/packages/server/src/repowise/server/routers/workspace.py
@@ -14,6 +14,7 @@ from pathlib import Path
from fastapi import APIRouter, Depends, HTTPException, Query, Request
from repowise.core.docs_mode import resolve_docs_mode
+from repowise.core.workspace.cross_repo import MAX_EDGES, MAX_EDGES_PER_REPO_PAIR
from repowise.server.deps import (
get_cross_repo_enricher,
get_workspace_config,
@@ -26,6 +27,7 @@ from repowise.server.schemas import (
WorkspaceBreakingChangesResponse,
WorkspaceCoChangeEntry,
WorkspaceCoChangesResponse,
+ WorkspaceCoChangeStructure,
WorkspaceConformanceResponse,
WorkspaceContractDetail,
WorkspaceContractEntry,
@@ -519,6 +521,15 @@ async def get_co_changes(
co_changes = list(getattr(enricher, "_co_changes", []))
total_mined = getattr(enricher, "_total_co_changes", len(co_changes))
+ # Which cap trimmed the stored overlay, judged before any query filter. The
+ # miner walks pairs strongest first, so a full global budget means the
+ # workspace-wide cap stopped it (the per-pair cap may also have applied).
+ if total_mined <= len(co_changes):
+ truncated_by = None
+ elif len(co_changes) >= MAX_EDGES:
+ truncated_by = "total"
+ else:
+ truncated_by = "per_repo_pair"
if repo:
co_changes = [
@@ -550,6 +561,72 @@ async def get_co_changes(
],
total=total,
total_mined=total_mined,
+ # The constants name the rules the miner applied; the overlay does not
+ # store them.
+ per_repo_pair_cap=MAX_EDGES_PER_REPO_PAIR,
+ total_cap=MAX_EDGES,
+ truncated_by=truncated_by,
+ )
+
+
[email protected]("/co-changes/structure", response_model=WorkspaceCoChangeStructure)
+async def get_co_change_structure(
+ ws_config=Depends(get_workspace_config),
+ enricher=Depends(get_cross_repo_enricher),
+ source_repo: str = Query(...),
+ source_file: str = Query(...),
+ target_repo: str = Query(...),
+ target_file: str = Query(...),
+):
+ """Declared structure behind one co-changing pair: the contract links between
+ the two files, and between their repositories through any files.
+
+ Served per pair so the co-change drawer never downloads the whole link list.
+ """
+ _require_workspace(ws_config)
+ if enricher is None:
+ return WorkspaceCoChangeStructure(
+ pair_links=[],
+ repo_links_total=0,
+ repo_links_by_type={},
+ source_file_links=0,
+ target_file_links=0,
+ )
+
+ provider_index = getattr(enricher, "_contract_provider_index", {})
+ consumer_index = getattr(enricher, "_contract_consumer_index", {})
+ src = (source_repo, source_file)
+ tgt = (target_repo, target_file)
+
+ def touching(key: tuple[str, str]) -> list[dict]:
+ # .get, not []: the indexes are defaultdicts and a read must not grow them.
+ return [*provider_index.get(key, []), *consumer_index.get(key, [])]
+
+ src_links = touching(src)
+ pair = {src, tgt}
+ pair_links = [
+ lk
+ for lk in src_links
+ if {
+ (lk.get("provider_repo"), lk.get("provider_file")),
+ (lk.get("consumer_repo"), lk.get("consumer_file")),
+ }
+ == pair
+ ]
+
+ repos = {source_repo, target_repo}
+ by_type: dict[str, int] = {}
+ for lk in getattr(enricher, "_contract_links", []):
+ if {lk.get("provider_repo"), lk.get("consumer_repo")} == repos:
+ ct = lk.get("contract_type", "unknown")
+ by_type[ct] = by_type.get(ct, 0) + 1
+
+ return WorkspaceCoChangeStructure(
+ pair_links=[_contract_link(lk) for lk in pair_links],
+ repo_links_total=sum(by_type.values()),
+ repo_links_by_type=by_type,
+ source_file_links=len(src_links),
+ target_file_links=len(touching(tgt)),
)
diff --git a/packages/server/src/repowise/server/schemas/__init__.py b/packages/server/src/repowise/server/schemas/__init__.py
index 89e9168d3..ffd0f4e69 100644
--- a/packages/server/src/repowise/server/schemas/__init__.py
+++ b/packages/server/src/repowise/server/schemas/__init__.py
@@ -260,6 +260,7 @@ from .workspace import (
WorkspaceBreakingChangesResponse,
WorkspaceCoChangeEntry,
WorkspaceCoChangesResponse,
+ WorkspaceCoChangeStructure,
WorkspaceConformanceResponse,
WorkspaceConformanceViolation,
WorkspaceContractDetail,
@@ -503,6 +504,7 @@ __all__ = [
"WorkspaceBreakingChange",
"WorkspaceBreakingChangesResponse",
"WorkspaceCoChangeEntry",
+ "WorkspaceCoChangeStructure",
"WorkspaceCoChangesResponse",
"WorkspaceConformanceResponse",
"WorkspaceConformanceViolation",
diff --git a/packages/server/src/repowise/server/schemas/workspace.py b/packages/server/src/repowise/server/schemas/workspace.py
index cb1ff07bf..dae39ce51 100644
--- a/packages/server/src/repowise/server/schemas/workspace.py
+++ b/packages/server/src/repowise/server/schemas/workspace.py
@@ -2,6 +2,8 @@
from __future__ import annotations
+from typing import Literal
+
from pydantic import BaseModel, Field
@@ -182,6 +184,27 @@ class WorkspaceCoChangesResponse(BaseModel):
#: of every pair in git history — each session's file list is bounded
#: before pairing.
total_mined: int = 0
+ #: The most pairs the miner keeps for any one repository pair, so a page
+ #: can say why every repository pair stops at the same count.
+ per_repo_pair_cap: int | None = None
+ #: The most pairs the miner keeps across the whole workspace.
+ total_cap: int | None = None
+ #: Which cap trimmed the stored overlay: ``"total"``, ``"per_repo_pair"``,
+ #: or None when nothing was dropped.
+ truncated_by: Literal["total", "per_repo_pair"] | None = None
+
+
+class WorkspaceCoChangeStructure(BaseModel):
+ """What declared structure connects one co-changing file pair."""
+
+ #: Contract links where one of the two files provides and the other consumes.
+ pair_links: list[WorkspaceContractLinkEntry]
+ #: Contract links between the two repositories through any files.
+ repo_links_total: int
+ repo_links_by_type: dict[str, int]
+ #: Contract links touching each file, whatever the other end.
+ source_file_links: int
+ target_file_links: int
class WorkspaceGraphNode(BaseModel):
diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.ts
index ebb397611..adb26c637 100644
--- a/packages/types/src/generated/http.ts
+++ b/packages/types/src/generated/http.ts
@@ -2912,10 +2912,22 @@ export interface WorkspaceCoChangeEntry {
last_date: string;
}
+/** What declared structure connects one co-changing file pair. */
+export interface WorkspaceCoChangeStructure {
+ pair_links: WorkspaceContractLinkEntry[];
+ repo_links_total: number;
+ repo_links_by_type: Record<string, number>;
+ source_file_links: number;
+ target_file_links: number;
+}
+
export interface WorkspaceCoChangesResponse {
co_changes: WorkspaceCoChangeEntry[];
total: number;
total_mined?: number;
+ per_repo_pair_cap?: number | null;
+ total_cap?: number | null;
+ truncated_by?: "total" | "per_repo_pair" | null;
}
export interface WorkspaceConformanceResponse {
diff --git a/packages/ui/__tests__/workspace/co-change-ai-prompt.test.ts b/packages/ui/__tests__/workspace/co-change-ai-prompt.test.ts
new file mode 100644
index 000000000..74e0599c1
--- /dev/null
+++ b/packages/ui/__tests__/workspace/co-change-ai-prompt.test.ts
@@ -0,0 +1,169 @@
+import { describe, it, expect } from "vitest";
+import type { WorkspaceCoChangeEntry } from "@repowise-dev/types/workspace";
+import {
+ MAX_PROMPT_PAIRS,
+ buildCoChangePairAiPrompt,
+ buildCoChangeRepoPairAiPrompt,
+} from "../../src/workspace/co-change-ai-prompt.js";
+import { capRule, nearbyCommits } from "../../src/workspace/co-change-facts.js";
+
+function pair(overrides: Partial<WorkspaceCoChangeEntry> = {}): WorkspaceCoChangeEntry {
+ return {
+ source_repo: "backend",
+ source_file: "app/models/schemas/repos.py",
+ target_repo: "frontend",
+ target_file: "src/lib/api/types.ts",
+ strength: 0.694,
+ frequency: 3,
+ last_date: "2026-09-01",
+ ...overrides,
+ };
+}
+
+describe("nearbyCommits", () => {
+ const a = { sha: "aaaaaaaa1", date: "2026-09-01T10:00:00Z", author: "Ana", message: "feat: add field" };
+ const b = { sha: "bbbbbbbb1", date: "2026-09-01T12:30:00Z", author: "ana", message: "feat: mirror field" };
+
+ it("pairs commits by the same author inside the window", () => {
+ const out = nearbyCommits([a], [b]);
+ expect(out).toHaveLength(1);
+ expect(out[0]!.gapHours).toBeCloseTo(2.5);
+ });
+
+ it("ignores other authors and commits outside the window", () => {
+ expect(nearbyCommits([a], [{ ...b, author: "Bo" }])).toEqual([]);
+ expect(nearbyCommits([a], [{ ...b, date: "2026-09-03T12:30:00Z" }])).toEqual([]);
+ });
+
+ it("keeps the closest partner and sorts newest first", () => {
+ const later = { ...a, sha: "aaaaaaaa2", date: "2026-09-05T09:00:00Z" };
+ const far = { ...b, sha: "bbbbbbbb2", date: "2026-09-01T20:00:00Z" };
+ const near = { ...b, sha: "bbbbbbbb3", date: "2026-09-05T09:10:00Z" };
+ const out = nearbyCommits([a, later], [far, b, near]);
+ expect(out.map((p) => [p.source.sha, p.target.sha])).toEqual([
+ ["aaaaaaaa2", "bbbbbbbb3"],
+ ["aaaaaaaa1", "bbbbbbbb1"],
+ ]);
+ });
+});
+
+describe("buildCoChangePairAiPrompt", () => {
+ it("carries both files, the counts with units, and the check-the-partner rule", () => {
+ const p = buildCoChangePairAiPrompt({ pair: pair() });
+ expect(p).toContain("`backend` `app/models/schemas/repos.py`");
+ expect(p).toContain("`frontend` `src/lib/api/types.ts`");
+ expect(p).toContain("Shared work sessions: **3**");
+ expect(p).toContain("**69%**");
+ expect(p).toContain("2026-09-01");
+ expect(p).toContain("When you edit either file, check the other");
+ expect(p).toContain("generated client");
+ expect(p).toContain("not checked");
+ });
+
+ it("names a hidden coupling when no contract joins the files", () => {
+ const p = buildCoChangePairAiPrompt({
+ pair: pair(),
+ structure: { pairLinks: [], repoLinksTotal: 180, repoLinksByType: { http: 178, code: 2 } },
+ });
+ expect(p).toContain("hidden coupling");
+ expect(p).toContain("180 contract links (178 http, 2 code), none through these two files");
+ });
+
+ it("names the contract when one joins the files", () => {
+ const p = buildCoChangePairAiPrompt({
+ pair: pair(),
+ structure: {
+ pairLinks: [
+ {
+ contract_id: "http::GET::/repos/mine",
+ contract_type: "http",
+ provider_repo: "backend",
+ provider_file: "app/models/schemas/repos.py",
+ consumer_repo: "frontend",
+ consumer_file: "src/lib/api/types.ts",
+ },
+ ],
+ repoLinksTotal: 1,
+ repoLinksByType: { http: 1 },
+ },
+ });
+ expect(p).toContain("`http::GET::/repos/mine`");
+ expect(p).not.toContain("hidden coupling");
+ });
+
+ it("lists reconstructed commits and file facts when given", () => {
+ const p = buildCoChangePairAiPrompt({
+ pair: pair(),
+ sourceFacts: { commits90d: 6, churnPercentile: 73.2, priorFixes: 3, isHotspot: true },
+ commits: [
+ {
+ source: { sha: "2b6e6c44ffff", date: "2026-08-30T19:54:46Z", message: "fix: scope\nbody", author: "Ana" },
+ target: { sha: "d71154cdffff", date: "2026-08-30T19:39:33Z", message: "feat: narrow", author: "Ana" },
+ gapHours: 0.25,
+ },
+ ],
+ });
+ expect(p).toContain("6 commits in 90 days, churn percentile 73, 3 prior bug fixes, a hotspot");
+ expect(p).toContain('2b6e6c44 "fix: scope"');
+ expect(p).toContain("under an hour apart");
+ expect(p).toContain("does not record which sessions");
+ });
+
+ it("points the MCP flavor at repowise tools", () => {
+ const p = buildCoChangePairAiPrompt({ pair: pair(), flavor: "claude-code-mcp" });
+ expect(p).toContain("get_context(['app/models/schemas/repos.py'])");
+ expect(p).toContain("get_blast_radius");
+ });
+});
+
+describe("buildCoChangeRepoPairAiPrompt", () => {
+ it("ranks the evidence, caps the list and names recurring files", () => {
+ const pairs = Array.from({ length: MAX_PROMPT_PAIRS + 3 }, (_, i) =>
+ pair({ target_file: `src/f${i}.ts`, strength: 0.3 + i / 100 }),
+ );
+ const p = buildCoChangeRepoPairAiPrompt({
+ repo1: "backend",
+ repo2: "frontend",
+ pairs,
+ caps: { truncatedBy: "per_repo_pair", perRepoPairCap: 18, totalCap: 200 },
+ });
+ expect(p).toContain("File pairs: **18** (the miner keeps the strongest 18 for each repository pair");
+ expect(p).toContain("...and 3 more file pairs not listed.");
+ // Strongest first.
+ expect(p.indexOf("src/f17.ts")).toBeLessThan(p.indexOf("src/f16.ts"));
+ expect(p).toContain("`backend` `app/models/schemas/repos.py` appears in 18 pairs");
+ });
+
+ it("does not claim a cap the list did not hit", () => {
+ const p = buildCoChangeRepoPairAiPrompt({
+ repo1: "a",
+ repo2: "b",
+ pairs: [pair()],
+ caps: { truncatedBy: "per_repo_pair", perRepoPairCap: 50, totalCap: 200 },
+ });
+ expect(p).toContain("File pairs: **1**");
+ expect(p).not.toContain("the miner keeps");
+ });
+});
+
+describe("capRule", () => {
+ it("names the cap the server says applied", () => {
+ expect(capRule({ truncatedBy: null, perRepoPairCap: 50, totalCap: 200 })).toBeNull();
+ expect(capRule({ truncatedBy: "per_repo_pair", perRepoPairCap: 50, totalCap: 200 })).toBe(
+ "the miner keeps the strongest 50 for each repository pair",
+ );
+ expect(capRule({ truncatedBy: "total", perRepoPairCap: 50, totalCap: 200 })).toBe(
+ "the miner keeps the strongest 200 across the workspace, and at most 50 for any one repository pair",
+ );
+ });
+
+ it("says a workspace-wide cut may have trimmed a repository pair below its own cap", () => {
+ const p = buildCoChangeRepoPairAiPrompt({
+ repo1: "a",
+ repo2: "b",
+ pairs: [pair()],
+ caps: { truncatedBy: "total", perRepoPairCap: 50, totalCap: 200 },
+ });
+ expect(p).toContain("File pairs: **1** (the miner keeps the strongest 200 across the workspace");
+ });
+});
diff --git a/packages/ui/__tests__/workspace/co-change-pair-drawer.test.tsx b/packages/ui/__tests__/workspace/co-change-pair-drawer.test.tsx
new file mode 100644
index 000000000..debbe2c99
--- /dev/null
+++ b/packages/ui/__tests__/workspace/co-change-pair-drawer.test.tsx
@@ -0,0 +1,82 @@
+import { describe, it, expect, vi } from "vitest";
+import { render, screen, fireEvent } from "@testing-library/react";
+import type { WorkspaceCoChangeEntry } from "@repowise-dev/types/workspace";
+import {
+ CoChangePairDrawer,
+ type CoChangeFileHistory,
+ type Loadable,
+} from "../../src/workspace/co-change-pair-drawer.js";
+import { nearbyCommits } from "../../src/workspace/co-change-facts.js";
+
+const PAIR: WorkspaceCoChangeEntry = {
+ source_repo: "backend",
+ source_file: "app/schemas/repos.py",
+ target_repo: "frontend",
+ target_file: "src/lib/api/types.ts",
+ strength: 0.69,
+ frequency: 3,
+ last_date: "2026-09-01",
+};
+
+function history(sha: string, date: string): Loadable<CoChangeFileHistory> {
+ return {
+ state: "ready",
+ data: {
+ commits90d: 6,
+ churnPercentile: 73,
+ priorFixes: 0,
+ isHotspot: true,
+ commits: [{ sha, date, author: "Ana", message: `commit ${sha}` }],
+ },
+ };
+}
+
+describe("CoChangePairDrawer", () => {
+ it("names a hidden coupling, links both files and reconstructs nearby commits", () => {
+ const onPrompt = vi.fn();
+ render(
+ <CoChangePairDrawer
+ pair={PAIR}
+ onClose={() => {}}
+ structure={{ state: "ready", data: { pairLinks: [], repoLinksTotal: 12, repoLinksByType: { http: 12 } } }}
+ sourceHistory={history("aaaaaaaa11", "2026-09-01T10:00:00Z")}
+ targetHistory={history("bbbbbbbb22", "2026-09-01T11:00:00Z")}
+ commits={nearbyCommits(
+ [{ sha: "aaaaaaaa11", date: "2026-09-01T10:00:00Z", author: "Ana", message: "commit aaaaaaaa11" }],
+ [{ sha: "bbbbbbbb22", date: "2026-09-01T11:00:00Z", author: "Ana", message: "commit bbbbbbbb22" }],
+ )}
+ fileHref={(repo, path) => (repo === "backend" ? `/repos/b/files/${path}` : null)}
+ onGeneratePrompt={onPrompt}
+ />,
+ );
+ expect(screen.getByText("No declared link")).toBeInTheDocument();
+ expect(screen.getByText(/a hidden coupling/)).toBeInTheDocument();
+ expect(screen.getByText(/12 contract links \(12 http\)/)).toBeInTheDocument();
+ expect(screen.getAllByText("Open file page")).toHaveLength(1);
+ expect(screen.getByText(/frontend is not indexed/)).toBeInTheDocument();
+ expect(screen.getByText("commit aaaaaaaa11")).toBeInTheDocument();
+ // Paths break only after a slash: the directory segments are separate nodes.
+ expect(screen.getByText("app/")).toBeInTheDocument();
+ expect(screen.getByText("schemas/")).toBeInTheDocument();
+ expect(screen.getAllByText("Hotspot")).toHaveLength(2);
+ fireEvent.click(screen.getByRole("button", { name: /AI investigation prompt/ }));
+ expect(onPrompt).toHaveBeenCalled();
+ });
+
+ it("says what is still loading or was not checked", () => {
+ render(
+ <CoChangePairDrawer
+ pair={PAIR}
+ onClose={() => {}}
+ structure={{ state: "unavailable", reason: "Contract links failed to load." }}
+ sourceHistory={{ state: "loading" }}
+ targetHistory={{ state: "loading" }}
+ commits={null}
+ onGeneratePrompt={() => {}}
+ />,
+ );
+ expect(screen.getByText("Declared links not checked")).toBeInTheDocument();
+ expect(screen.getByText("Contract links failed to load.")).toBeInTheDocument();
+ expect(screen.getByText(/Loading each file/)).toBeInTheDocument();
+ });
+});
diff --git a/packages/ui/__tests__/workspace/co-change-table.test.tsx b/packages/ui/__tests__/workspace/co-change-table.test.tsx
index ef21201e1..753d93b80 100644
--- a/packages/ui/__tests__/workspace/co-change-table.test.tsx
+++ b/packages/ui/__tests__/workspace/co-change-table.test.tsx
@@ -1,14 +1,14 @@
-import { describe, it, expect } from "vitest";
-import { render, screen } from "@testing-library/react";
+import { describe, it, expect, vi } from "vitest";
+import { render, screen, fireEvent } from "@testing-library/react";
import type { WorkspaceCoChangeEntry } from "@repowise-dev/types/workspace";
-import { CoChangeTable } from "../../src/workspace/co-change-table.js";
+import { CoChangeTable, coChangeKey } from "../../src/workspace/co-change-table.js";
function cc(
sourceRepo: string,
sourceFile: string,
targetRepo: string,
targetFile: string,
- strength = 5,
+ strength = 0.5,
): WorkspaceCoChangeEntry {
return {
source_repo: sourceRepo,
@@ -21,28 +21,42 @@ function cc(
};
}
-describe("CoChangeTable (virtualized)", () => {
- it("renders a row per co-change with repos and files", () => {
- const rows = [
- cc("api", "api/a.py", "core", "core/b.py", 8),
- cc("ui", "ui/c.tsx", "core", "core/d.py", 2),
- ];
+describe("CoChangeTable", () => {
+ it("renders each file as repo, dim directory and full filename", () => {
+ const rows = [cc("api", "api/a.py", "core", "core/b.py", 0.72), cc("ui", "ui/c.tsx", "core", "core/d.py")];
render(<CoChangeTable coChanges={rows} />);
- expect(screen.getByText("api/a.py")).toBeInTheDocument();
- expect(screen.getByText("core/b.py")).toBeInTheDocument();
- expect(screen.getByText("ui/c.tsx")).toBeInTheDocument();
- expect(screen.getByText("core/d.py")).toBeInTheDocument();
- expect(screen.getAllByText("core").length).toBeGreaterThan(0);
+ expect(screen.getByText("a.py")).toBeInTheDocument();
+ expect(screen.getAllByText("api/").length).toBe(1);
+ expect(screen.getByTitle("core/b.py")).toBeInTheDocument();
+ expect(screen.getAllByText("core").length).toBe(2);
+ expect(screen.getByText("72%")).toBeInTheDocument();
});
- it("shows the frequency cell when not compact", () => {
- render(<CoChangeTable coChanges={[cc("api", "a.py", "core", "b.py")]} />);
- expect(screen.getByText("3x")).toBeInTheDocument();
+ it("shows sessions and date unless compact", () => {
+ const { rerender } = render(<CoChangeTable coChanges={[cc("api", "a.py", "core", "b.py")]} />);
+ expect(screen.getByText("Sessions")).toBeInTheDocument();
+ expect(screen.getByText("3")).toBeInTheDocument();
+ rerender(<CoChangeTable coChanges={[cc("api", "a.py", "core", "b.py")]} compact />);
+ expect(screen.queryByText("Sessions")).not.toBeInTheDocument();
+ expect(screen.queryByText("3")).not.toBeInTheDocument();
});
- it("hides the frequency cell when compact", () => {
- render(<CoChangeTable coChanges={[cc("api", "a.py", "core", "b.py")]} compact />);
- expect(screen.queryByText("3x")).not.toBeInTheDocument();
+ it("opens a pair on click or Enter and marks the selected row", () => {
+ const onSelect = vi.fn();
+ const row = cc("api", "a.py", "core", "b.py");
+ render(<CoChangeTable coChanges={[row]} onSelect={onSelect} selectedKey={coChangeKey(row)} />);
+ const tr = screen.getByText("a.py").closest("tr")!;
+ expect(tr).toHaveAttribute("aria-current", "true");
+ fireEvent.click(tr);
+ fireEvent.keyDown(tr, { key: "Enter" });
+ expect(onSelect).toHaveBeenCalledTimes(2);
+ expect(onSelect).toHaveBeenCalledWith(row);
+ });
+
+ it("keys a pair the same whichever file leads", () => {
+ const row = cc("api", "a.py", "core", "b.py");
+ const flipped = cc("core", "b.py", "api", "a.py");
+ expect(coChangeKey(row)).toBe(coChangeKey(flipped));
});
it("shows the empty state when there are no co-changes", () => {
diff --git a/packages/ui/__tests__/workspace/repo-pair-table.test.tsx b/packages/ui/__tests__/workspace/repo-pair-table.test.tsx
index 682c5d5b5..134778dc0 100644
--- a/packages/ui/__tests__/workspace/repo-pair-table.test.tsx
+++ b/packages/ui/__tests__/workspace/repo-pair-table.test.tsx
@@ -18,7 +18,20 @@ function pair(
};
}
-describe("RepoPairTable (virtualized)", () => {
+describe("RepoPairTable", () => {
+ it("names the narrowing, and opens the repo-pair prompt without narrowing", () => {
+ const onSelect = vi.fn();
+ const onPrompt = vi.fn();
+ const p = pair("api", "core");
+ render(
+ <RepoPairTable repoPairs={[p]} onSelectPair={onSelect} onPrompt={onPrompt} selectedPairId={p.id} />,
+ );
+ expect(screen.getByText("Showing only these")).toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "AI prompt for api and core" }));
+ expect(onPrompt).toHaveBeenCalledWith(p);
+ expect(onSelect).not.toHaveBeenCalled();
+ });
+
it("renders a row per pair with both repo names and the file-pair count", () => {
const rows = [pair("api", "core", 7), pair("ui", "core", 2)];
render(<RepoPairTable repoPairs={rows} />);
diff --git a/packages/ui/package.json b/packages/ui/package.json
index c11adfe79..8fb8b94e5 100644
--- a/packages/ui/package.json
+++ b/packages/ui/package.json
@@ -71,6 +71,8 @@
"./overview": "./src/overview/index.ts",
"./overview/*": "./src/overview/*.tsx",
"./workspace": "./src/workspace/index.ts",
+ "./workspace/co-change-ai-prompt": "./src/workspace/co-change-ai-prompt.ts",
+ "./workspace/co-change-facts": "./src/workspace/co-change-facts.ts",
"./workspace/contract-ai-prompt": "./src/workspace/contract-ai-prompt.ts",
"./workspace/contract-facts": "./src/workspace/contract-facts.ts",
"./workspace/contract-type-label": "./src/workspace/contract-type-label.ts",
diff --git a/packages/ui/src/coupling/coupling-pair-drawer.tsx b/packages/ui/src/coupling/coupling-pair-drawer.tsx
index f64dcd257..49dc6fc55 100644
--- a/packages/ui/src/coupling/coupling-pair-drawer.tsx
+++ b/packages/ui/src/coupling/coupling-pair-drawer.tsx
@@ -4,8 +4,8 @@ import * as React from "react";
import { ExternalLink } from "lucide-react";
import { AdaptivePanel } from "../shared/adaptive-panel";
import { HealthBadge } from "../health/health-badge";
-import { AiPromptButton } from "../health/ai-prompt-button";
import { formatDate, formatDateTime } from "../lib/format";
+import { PAIR_MICRO as MICRO, PairAgentSection, PairFactGrid, type PairFact } from "./pair-drawer-parts";
import {
couplingClaim,
dependencyKindPhrase,
@@ -61,8 +61,6 @@ const VERDICT: Record<CouplingSegment, { word: string; dot: string; body: string
},
};
-const MICRO = "font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]";
-
function pct(v: number | null | undefined): string | null {
return typeof v === "number" ? `${Math.round(v * 100)}%` : null;
}
@@ -102,7 +100,7 @@ export function CouplingPairDrawer({
const moduleA = edge ? (nodeByPath.get(edge.source)?.module ?? null) : null;
const moduleB = edge ? (nodeByPath.get(edge.target)?.module ?? null) : null;
- const facts: { label: string; value: React.ReactNode }[] = edge
+ const facts: PairFact[] = edge
? [
{
label: "Shared commits",
@@ -200,25 +198,7 @@ export function CouplingPairDrawer({
)}
</div>
- {/* A hairline ribbon, not tiles: four different kinds of fact, and
- equal-weight boxes would claim they are one. */}
- <dl className="grid grid-cols-2 border-y border-[var(--color-border-default)]">
- {facts.map((f, i) => (
- <div
- key={f.label}
- className={[
- "min-w-0 px-3 py-2.5 border-[var(--color-border-default)]",
- i % 2 === 1 ? "border-l" : "",
- i >= 2 ? "border-t" : "",
- ]
- .filter(Boolean)
- .join(" ")}
- >
- <dt className={MICRO}>{f.label}</dt>
- <dd className="mt-1">{f.value}</dd>
- </div>
- ))}
- </dl>
+ <PairFactGrid facts={facts} />
{/* The asymmetry is the finding, so each direction gets its own bar
rather than collapsing into a single "up to N%". */}
@@ -309,21 +289,12 @@ export function CouplingPairDrawer({
</ul>
</section>
- {/* The one action, named and explained. */}
{onGeneratePrompt && (
- <section className="flex flex-col gap-2">
- <h3 className={MICRO}>Hand this to an agent</h3>
- <p className="text-xs leading-relaxed text-[var(--color-text-secondary)]">
- Builds a prompt carrying the evidence above, so your agent can judge
- whether the coupling is accidental or legitimate and propose the
- smallest decoupling that holds.
- </p>
- <AiPromptButton
- label="AI decouple prompt"
- onClick={() => onGeneratePrompt(edge)}
- className="w-fit"
- />
- </section>
+ <PairAgentSection
+ body="Builds a prompt carrying the evidence above, so your agent can judge whether the coupling is accidental or legitimate and propose the smallest decoupling that holds."
+ label="AI decouple prompt"
+ onClick={() => onGeneratePrompt(edge)}
+ />
)}
</div>
)}
diff --git a/packages/ui/src/coupling/pair-drawer-parts.tsx b/packages/ui/src/coupling/pair-drawer-parts.tsx
new file mode 100644
index 000000000..8ed79f03e
--- /dev/null
+++ b/packages/ui/src/coupling/pair-drawer-parts.tsx
@@ -0,0 +1,68 @@
+"use client";
+
+import * as React from "react";
+import { AiPromptButton } from "../health/ai-prompt-button";
+
+/**
+ * The anatomy two co-change drawers share: the single-repo coupling pair and
+ * the cross-repo workspace pair. Their evidence differs (directional shares
+ * and a graph verdict on one side, repositories and contract links on the
+ * other), so each drawer owns its sections; these are the parts that must
+ * read the same in both.
+ */
+
+export const PAIR_MICRO =
+ "font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]";
+
+export interface PairFact {
+ label: string;
+ /** Optional explainer beside the label, e.g. an InfoTip. */
+ hint?: React.ReactNode;
+ value: React.ReactNode;
+}
+
+/** A hairline two-column ribbon, not tiles: different kinds of fact, and
+ * equal-weight boxes would claim they are one. */
+export function PairFactGrid({ facts }: { facts: PairFact[] }) {
+ return (
+ <dl className="grid grid-cols-2 border-y border-[var(--color-border-default)]">
+ {facts.map((f, i) => (
+ <div
+ key={f.label}
+ className={[
+ "min-w-0 px-3 py-2.5 border-[var(--color-border-default)]",
+ i % 2 === 1 ? "border-l" : "",
+ i >= 2 ? "border-t" : "",
+ ]
+ .filter(Boolean)
+ .join(" ")}
+ >
+ <dt className={f.hint ? `${PAIR_MICRO} flex items-center gap-1` : PAIR_MICRO}>
+ {f.label}
+ {f.hint}
+ </dt>
+ <dd className="mt-1">{f.value}</dd>
+ </div>
+ ))}
+ </dl>
+ );
+}
+
+/** The drawer's one action, named and explained. */
+export function PairAgentSection({
+ body,
+ label,
+ onClick,
+}: {
+ body: React.ReactNode;
+ label: string;
+ onClick: () => void;
+}) {
+ return (
+ <section className="flex flex-col gap-2">
+ <h3 className={PAIR_MICRO}>Hand this to an agent</h3>
+ <p className="text-xs leading-relaxed text-[var(--color-text-secondary)]">{body}</p>
+ <AiPromptButton label={label} onClick={onClick} className="w-fit" />
+ </section>
+ );
+}
diff --git a/packages/ui/src/workspace/co-change-ai-prompt.ts b/packages/ui/src/workspace/co-change-ai-prompt.ts
new file mode 100644
index 000000000..df2ae1fe4
--- /dev/null
+++ b/packages/ui/src/workspace/co-change-ai-prompt.ts
@@ -0,0 +1,292 @@
+/**
+ * Agent prompts for cross-repo co-changes: one file pair, and one repository
+ * pair with its strongest file pairs as evidence.
+ *
+ * Same shape as the health and contract builders (role, evidence, tasks,
+ * constraints, what to hand back). Co-change is a work pattern read from git
+ * history, not a declared dependency, so every prompt asks the agent to find
+ * the shared concept first and only then decide whether a contract, a shared
+ * type or a generated client should replace the manual lockstep.
+ */
+
+import type { AiPromptFlavor } from "../health/ai-prompt-builder";
+import type { WorkspaceCoChangeEntry } from "@repowise-dev/types/workspace";
+import {
+ gapPhrase,
+ hiddenCouplingSentence,
+ MAX_COMMIT_PAIRS,
+ SESSION_WINDOW_HOURS,
+ capRule,
+ type CoChangeCaps,
+ type CoChangeStructureFacts,
+ type NearbyCommitPair,
+} from "./co-change-facts";
+
+/** File pairs listed in a repository-pair prompt before the rest become a count. */
+export const MAX_PROMPT_PAIRS = 15;
+
+const PREAMBLE: Record<AiPromptFlavor, string> = {
+ generic:
+ "You are a senior engineer working across the repositories of one workspace. The evidence below is a work pattern repowise mined from git history: files in different repositories that the same author changed in the same work sessions. It is a lead, not a verified dependency. Open the files it names and read the commits before you conclude anything.",
+ "claude-code":
+ "You are Claude Code working across the repositories of one workspace. The evidence below is a work pattern repowise mined from git history: files in different repositories that the same author changed in the same work sessions. Treat it as a lead, not a verified dependency. Use Read, Grep and Glob on the files it names, and `git log` in each repository, before planning edits. Use TodoWrite for non-trivial steps.",
+ "claude-code-mcp":
+ "You are Claude Code working across the repositories of one workspace indexed by repowise, with its MCP tools available. The evidence below is a work pattern repowise mined from git history: files in different repositories that the same author changed in the same work sessions. Treat it as a lead, not a verified dependency. Pull what repowise already computed before re-reading by hand: `get_context([...])` for a file's skeleton, `get_risk([...])` for its co-change partners and test gaps, `get_why(...)` for the decision behind its shape, `search_codebase` to find a type or route by name, and `get_blast_radius` for which services a change reaches. Fall back to Read / Grep only for what the index cannot serve.",
+ cursor:
+ "Work across the repositories referenced below. The evidence is a work pattern repowise mined from git history: files in different repositories that the same author changed in the same work sessions. Treat it as a lead, not a verified dependency. Use @file and @codebase to read every file it names before editing.",
+};
+
+function bullets(items: (string | null | undefined | false)[]): string {
+ return items
+ .filter(Boolean)
+ .map((s) => `- ${s}`)
+ .join("\n");
+}
+
+function join(sections: (string | null | undefined | false)[]): string {
+ return sections.filter((s) => s !== null && s !== undefined && s !== false && s !== "").join("\n");
+}
+
+function where(repo: string, file: string): string {
+ return `\`${repo}\` \`${file}\``;
+}
+
+function pct(v: number): string {
+ return `${Math.round(v * 100)}%`;
+}
+
+function sessions(n: number): string {
+ return `${n} shared work ${n === 1 ? "session" : "sessions"}`;
+}
+
+// ---------------------------------------------------------------------------
+// One file pair
+// ---------------------------------------------------------------------------
+
+/** What the per-repo git index says about one side, when it was fetched. */
+export interface CoChangeFileFacts {
+ commits90d?: number | null;
+ churnPercentile?: number | null;
+ priorFixes?: number | null;
+ isHotspot?: boolean | null;
+}
+
+export interface BuildCoChangePairPromptOptions {
+ pair: WorkspaceCoChangeEntry;
+ flavor?: AiPromptFlavor;
+ structure?: CoChangeStructureFacts | null;
+ sourceFacts?: CoChangeFileFacts | null;
+ targetFacts?: CoChangeFileFacts | null;
+ commits?: NearbyCommitPair[];
+}
+
+function factsTail(f: CoChangeFileFacts | null | undefined): string {
+ if (!f) return "";
+ const parts = [
+ f.commits90d != null ? `${f.commits90d} commits in 90 days` : null,
+ f.churnPercentile != null ? `churn percentile ${Math.round(f.churnPercentile)}` : null,
+ f.priorFixes ? `${f.priorFixes} prior bug fixes` : null,
+ f.isHotspot ? "a hotspot" : null,
+ ].filter(Boolean);
+ return parts.length ? ` (${parts.join(", ")})` : "";
+}
+
+function structureLine(pair: WorkspaceCoChangeEntry, s: CoChangeStructureFacts | null | undefined) {
+ if (!s) return "Declared link: not checked. Look for a contract or shared package between them yourself.";
+ if (s.pairLinks.length > 0) {
+ const ids = s.pairLinks
+ .slice(0, 5)
+ .map((l) => `\`${l.contract_id}\` (${l.contract_type}, ${l.provider_repo} provides, ${l.consumer_repo} consumes)`)
+ .join("; ");
+ return `Declared link: these files are joined by ${s.pairLinks.length === 1 ? "a contract" : `${s.pairLinks.length} contracts`}: ${ids}. The co-change is at least partly explained; judge whether the contract is the right shape.`;
+ }
+ return `Declared link: **none**. ${hiddenCouplingSentence(pair, s, (r) => `\`${r}\``)}`;
+}
+
+function commitLine(c: NearbyCommitPair, pair: WorkspaceCoChangeEntry): string {
+ const day = c.source.date.slice(0, 10);
+ const msg = (m?: string | null) => (m ? ` "${m.split("\n")[0]}"` : "");
+ return `${day}: \`${pair.source_repo}\` ${c.source.sha.slice(0, 8)}${msg(c.source.message)} and \`${pair.target_repo}\` ${c.target.sha.slice(0, 8)}${msg(c.target.message)} (${c.source.author ?? "same author"}, ${gapPhrase(c.gapHours)})`;
+}
+
+export function buildCoChangePairAiPrompt({
+ pair,
+ flavor = "generic",
+ structure,
+ sourceFacts,
+ targetFacts,
+ commits = [],
+}: BuildCoChangePairPromptOptions): string {
+ const a = where(pair.source_repo, pair.source_file);
+ const b = where(pair.target_repo, pair.target_file);
+ const shownCommits = commits.slice(0, MAX_COMMIT_PAIRS);
+
+ const closer =
+ flavor === "claude-code-mcp"
+ ? `Call \`get_context(['${pair.source_file}'])\` in \`${pair.source_repo}\` and \`get_context(['${pair.target_file}'])\` in \`${pair.target_repo}\`, \`get_risk([...])\` on each for its other co-change partners and test gaps, \`get_why(...)\` for any decision that governs either file, and \`get_blast_radius\` for what else in the workspace a change to either reaches. Don't restructure until you can name why they move together.`
+ : `Read both files, then run \`git log\` for each in its own repository around the shared dates. The session count is a symptom; find the shared concept driving it before you change anything.`;
+
+ return join([
+ PREAMBLE[flavor],
+ "",
+ "## Two files that change together across repositories",
+ "",
+ bullets([
+ `File A: ${a}${factsTail(sourceFacts)}`,
+ `File B: ${b}${factsTail(targetFacts)}`,
+ `Shared work sessions: **${pair.frequency}** (the same author changed both, with commits in the two repositories no more than ${SESSION_WINDOW_HOURS} hours apart)`,
+ `Strength: **${pct(pair.strength)}**, the recency-weighted share of the less active file's work sessions that also touched the other. A work-pattern signal, not a verified dependency.`,
+ pair.last_date ? `Last changed together: ${pair.last_date.slice(0, 10)}` : null,
+ structureLine(pair, structure),
+ "Source: repowise cross-repo co-change mining over each repository's git history. Treat it as a lead.",
+ ]),
+ "",
+ shownCommits.length > 0
+ ? join([
+ "## Commits close together",
+ "",
+ bullets(shownCommits.map((c) => commitLine(c, pair))),
+ "",
+ "Reconstructed from each file's recent significant commits: the miner does not record which sessions it counted, so some may be missing.",
+ "",
+ ])
+ : "",
+ "## What to find out",
+ "",
+ "1. Why do these two files change together? Read both and the commits that touched them in the same sessions, then name the shared concept: a wire type, an API shape, a config key, documentation of code, generated output, or something else.",
+ "2. Is the lockstep manual? If one file restates what the other defines (a schema retyped by hand, a route described in prose, a client written against a server), decide whether a declared contract, a shared type package, or a generated client or document should own it so the second edit disappears.",
+ "3. If the coupling is legitimate and cheap to keep (documentation that must track code), say so and propose the lightest guard: a test, a CI check, or a note in each file naming its partner.",
+ "",
+ "## Hard constraints",
+ "",
+ bullets([
+ "**Diagnose before changing.** Name the shared concept and cite the lines on both sides before proposing anything.",
+ "**When you edit either file, check the other in the same change.** Until the coupling is removed, a change to one is half a change.",
+ "Keep the contract between the repositories stable. Do not move code across a repository boundary without saying why the boundary is wrong.",
+ "Preserve behavior. Add or update a test or check that fails when the two drift apart.",
+ "If the evidence turns out to be coincidence (unrelated work in one sitting), say so and stop.",
+ ]),
+ "",
+ "## What I expect back",
+ "",
+ "1. A verdict: the shared concept, and whether the coupling is accidental, legitimate but manual, or legitimate and fine.",
+ "2. If manual: what should own the shared concept (contract, shared type, generated client or doc), where it would live, and the smallest safe first step.",
+ "3. The first change, scoped, with the test or check that guards it.",
+ "4. If the coupling stays: the one-line note to add to each file naming its partner.",
+ "",
+ closer,
+ ]);
+}
+
+// ---------------------------------------------------------------------------
+// One repository pair
+// ---------------------------------------------------------------------------
+
+export interface BuildCoChangeRepoPairPromptOptions {
+ repo1: string;
+ repo2: string;
+ /** Every file pair shown for this repository pair; ranked here by strength. */
+ pairs: WorkspaceCoChangeEntry[];
+ flavor?: AiPromptFlavor;
+ /** Which cap trimmed the mined pairs, when the server says. */
+ caps?: CoChangeCaps | null;
+}
+
+/** Files that recur across several pairs: usually where the shared concept lives. */
+function recurringFiles(pairs: WorkspaceCoChangeEntry[]): { repo: string; file: string; n: number }[] {
+ const counts = new Map<string, { repo: string; file: string; n: number }>();
+ for (const p of pairs) {
+ for (const [repo, file] of [
+ [p.source_repo, p.source_file],
+ [p.target_repo, p.target_file],
+ ] as const) {
+ const key = `${repo}\u0000${file}`;
+ const hit = counts.get(key) ?? { repo, file, n: 0 };
+ hit.n += 1;
+ counts.set(key, hit);
+ }
+ }
+ return [...counts.values()]
+ .filter((c) => c.n >= 2)
+ .sort((a, b) => b.n - a.n || a.file.localeCompare(b.file))
+ .slice(0, 8);
+}
+
+export function buildCoChangeRepoPairAiPrompt({
+ repo1,
+ repo2,
+ pairs,
+ flavor = "generic",
+ caps,
+}: BuildCoChangeRepoPairPromptOptions): string {
+ const ranked = pairs.slice().sort((a, b) => b.strength - a.strength || b.frequency - a.frequency);
+ const shown = ranked.slice(0, MAX_PROMPT_PAIRS);
+ const hidden = ranked.length - shown.length;
+ const latest = ranked.reduce((d, p) => (p.last_date > d ? p.last_date : d), "");
+ const hubs = recurringFiles(ranked);
+ // A global cap may have trimmed any pair; the per-pair cap only one that filled it.
+ const rule = caps ? capRule(caps) : null;
+ const capped =
+ rule !== null &&
+ (caps!.truncatedBy === "total" || (caps!.perRepoPairCap != null && ranked.length >= caps!.perRepoPairCap));
+
+ const closer =
+ flavor === "claude-code-mcp"
+ ? `Start with \`get_blast_radius\` on \`${repo1}\` and \`${repo2}\` to see what already connects them, then \`get_context\` and \`get_risk\` on the recurring files above. \`search_codebase\` for the type or route names you find on both sides. repowise already mapped the contracts and history; use it before grepping.`
+ : "Start with the recurring files: they are usually where the shared concept lives. Read them in both repositories and the commits that changed them together before proposing anything.";
+
+ return join([
+ PREAMBLE[flavor],
+ "",
+ "## Two repositories that change together",
+ "",
+ bullets([
+ `Repositories: \`${repo1}\` and \`${repo2}\``,
+ `File pairs: **${ranked.length}**${capped ? ` (${rule}, so there are likely more)` : ""}`,
+ ranked[0] ? `Strongest pair: ${pct(ranked[0].strength)}` : null,
+ latest ? `Latest shared session: ${latest.slice(0, 10)}` : null,
+ "Source: repowise cross-repo co-change mining over git history. Treat it as a lead.",
+ ]),
+ "",
+ "## Strongest file pairs",
+ "",
+ shown
+ .map(
+ (p, i) =>
+ `${i + 1}. ${where(p.source_repo, p.source_file)} with ${where(p.target_repo, p.target_file)}: ${pct(p.strength)}, ${sessions(p.frequency)}, last ${p.last_date.slice(0, 10)}`,
+ )
+ .join("\n"),
+ hidden > 0 ? `...and ${hidden} more file pairs not listed.` : "",
+ "",
+ hubs.length > 0
+ ? join([
+ "## Files that recur across pairs",
+ "",
+ bullets(hubs.map((h) => `${where(h.repo, h.file)} appears in ${h.n} pairs`)),
+ "",
+ ])
+ : "",
+ "## What to find out",
+ "",
+ "1. Group the pairs by the concept they share (an API surface, a schema, a set of docs describing code, release plumbing).",
+ "2. For each group, check whether a declared contract, shared package or generated client already covers it. If not, say whether one should, and what it would replace.",
+ "3. Rank the groups by payoff: how often they force a second edit, and how bad a missed edit would be.",
+ "",
+ "## Hard constraints",
+ "",
+ bullets([
+ "**Diagnose before changing.** Cite the lines on both sides for every group you name.",
+ "Keep the contract between the repositories stable, and do not move code across the boundary without saying why the boundary is wrong.",
+ "One group per change, each independently revertible, each with a test or check that fails when the two sides drift.",
+ "Some groups will be coincidence or legitimate documentation upkeep. Say so and leave them.",
+ ]),
+ "",
+ "## What I expect back",
+ "",
+ "1. The groups, each with its shared concept and the pairs that belong to it.",
+ "2. For each: accidental, legitimate but manual, or legitimate and fine, with the reason.",
+ "3. A ranked plan for the manual ones: what should own the concept, where, and the first step.",
+ "",
+ closer,
+ ]);
+}
diff --git a/packages/ui/src/workspace/co-change-facts.ts b/packages/ui/src/workspace/co-change-facts.ts
new file mode 100644
index 000000000..9d3ea484b
--- /dev/null
+++ b/packages/ui/src/workspace/co-change-facts.ts
@@ -0,0 +1,150 @@
+/**
+ * The facts and wording the co-change page, its drawer and its agent prompts
+ * share, so a definition or a sentence has one source. No "use client": the
+ * server page reads the definitions too.
+ */
+
+import type { WorkspaceCoChangeEntry } from "@repowise-dev/types/workspace";
+
+/** The miner's session window: an author's commits chain into one session while under this gap. */
+export const SESSION_WINDOW_HOURS = 24;
+
+/** Reconstructed commit pairs shown in the drawer and listed in the prompt. */
+export const MAX_COMMIT_PAIRS = 8;
+
+export const STRENGTH_DEFINITION =
+ "Share of the less active file's recent work sessions that also touched its partner, weighted toward recent sessions. 100% would mean they always change together. A work pattern from git history, not a verified dependency.";
+
+export const SESSIONS_DEFINITION = `Work sessions in which both files changed: one author's commits, chained while they stay within ${SESSION_WINDOW_HOURS} hours of each other, touching both repositories.`;
+
+/** Order-independent id of a repository pair, e.g. `backend↔frontend`. */
+export function repoPairId(a: string, b: string): string {
+ const [x, y] = [a, b].sort();
+ return `${x}↔${y}`;
+}
+
+export function coChangeRepoPairId(cc: WorkspaceCoChangeEntry): string {
+ return repoPairId(cc.source_repo, cc.target_repo);
+}
+
+export function gapPhrase(hours: number): string {
+ return hours < 1 ? "under an hour apart" : `${Math.round(hours)}h apart`;
+}
+
+export function byTypePhrase(byType: Record<string, number>): string {
+ return Object.entries(byType)
+ .sort((a, b) => b[1] - a[1])
+ .map(([t, n]) => `${n} ${t}`)
+ .join(", ");
+}
+
+/** One contract link joining the two files, as the structure endpoint returns it. */
+export interface CoChangeLink {
+ contract_id: string;
+ contract_type: string;
+ provider_repo: string;
+ provider_file: string;
+ consumer_repo: string;
+ consumer_file: string;
+}
+
+/** Declared structure behind one file pair. */
+export interface CoChangeStructureFacts {
+ pairLinks: CoChangeLink[];
+ repoLinksTotal: number;
+ repoLinksByType: Record<string, number>;
+}
+
+/**
+ * The hidden-coupling finding in prose, for a pair no contract joins.
+ * `name` formats a repository name (the prompt wraps it in backticks).
+ */
+export function hiddenCouplingSentence(
+ pair: WorkspaceCoChangeEntry,
+ s: CoChangeStructureFacts,
+ name: (repo: string) => string = (r) => r,
+): string {
+ const a = name(pair.source_repo);
+ const b = name(pair.target_repo);
+ const repoPart =
+ s.repoLinksTotal > 0
+ ? `Between ${a} and ${b} there are ${s.repoLinksTotal} contract links (${byTypePhrase(s.repoLinksByType)}), none through these two files.`
+ : `No contract links ${a} and ${b} at all.`;
+ return `No contract repowise extracted connects these two files, so nothing declared explains why they move together: a hidden coupling. ${repoPart}`;
+}
+
+// ---------------------------------------------------------------------------
+// Commit evidence
+// ---------------------------------------------------------------------------
+
+export interface CoChangeCommit {
+ sha: string;
+ /** ISO timestamp. */
+ date: string;
+ message?: string | null;
+ author?: string | null;
+}
+
+export interface NearbyCommitPair {
+ source: CoChangeCommit;
+ target: CoChangeCommit;
+ /** Absolute gap between the two commits, in hours. */
+ gapHours: number;
+}
+
+/**
+ * Pair each source commit with the closest target commit by the same author
+ * inside the session window, newest first.
+ *
+ * A reconstruction, not the miner's record: the miner keeps a session count
+ * and a date, never the commits, and the inputs here are each file's recent
+ * significant commits, so a real shared session can be missing from the result.
+ */
+export function nearbyCommits(
+ source: CoChangeCommit[],
+ target: CoChangeCommit[],
+ windowHours: number = SESSION_WINDOW_HOURS,
+): NearbyCommitPair[] {
+ const same = (a?: string | null, b?: string | null) =>
+ !!a && !!b && a.trim().toLowerCase() === b.trim().toLowerCase();
+ const out: NearbyCommitPair[] = [];
+ for (const s of source) {
+ const st = Date.parse(s.date);
+ if (Number.isNaN(st)) continue;
+ let best: NearbyCommitPair | null = null;
+ for (const t of target) {
+ if (!same(s.author, t.author)) continue;
+ const tt = Date.parse(t.date);
+ if (Number.isNaN(tt)) continue;
+ const gapHours = Math.abs(st - tt) / 3_600_000;
+ if (gapHours > windowHours) continue;
+ if (!best || gapHours < best.gapHours) best = { source: s, target: t, gapHours };
+ }
+ if (best) out.push(best);
+ }
+ return out.sort((a, b) => Date.parse(b.source.date) - Date.parse(a.source.date));
+}
+
+// ---------------------------------------------------------------------------
+// Scope
+// ---------------------------------------------------------------------------
+
+/** Which of the miner's caps trimmed the stored pairs, as the server reports it. */
+export interface CoChangeCaps {
+ truncatedBy: "total" | "per_repo_pair" | null;
+ perRepoPairCap: number | null;
+ totalCap: number | null;
+}
+
+/** The rule that trimmed the list, as a clause; null when nothing was dropped. */
+export function capRule(c: CoChangeCaps): string | null {
+ if (c.truncatedBy === "per_repo_pair" && c.perRepoPairCap) {
+ return `the miner keeps the strongest ${c.perRepoPairCap} for each repository pair`;
+ }
+ if (c.truncatedBy === "total" && c.totalCap) {
+ return `the miner keeps the strongest ${c.totalCap} across the workspace${
+ c.perRepoPairCap ? `, and at most ${c.perRepoPairCap} for any one repository pair` : ""
+ }`;
+ }
+ return c.truncatedBy ? "the miner keeps only the strongest" : null;
+}
diff --git a/packages/ui/src/workspace/co-change-pair-drawer.tsx b/packages/ui/src/workspace/co-change-pair-drawer.tsx
new file mode 100644
index 000000000..63d2df123
--- /dev/null
+++ b/packages/ui/src/workspace/co-change-pair-drawer.tsx
@@ -0,0 +1,383 @@
+"use client";
+
+import * as React from "react";
+import { ExternalLink } from "lucide-react";
+import { AdaptivePanel } from "../shared/adaptive-panel";
+import { InfoTip } from "../shared/info-tip";
+import { formatDate, formatDateTime } from "../lib/format";
+import { PAIR_MICRO as MICRO, PairAgentSection, PairFactGrid, type PairFact } from "../coupling/pair-drawer-parts";
+import { RepoPath } from "./co-change-table";
+import {
+ gapPhrase,
+ hiddenCouplingSentence,
+ MAX_COMMIT_PAIRS,
+ SESSION_WINDOW_HOURS,
+ SESSIONS_DEFINITION,
+ STRENGTH_DEFINITION,
+ type CoChangeCommit,
+ type CoChangeLink,
+ type CoChangeStructureFacts,
+ type NearbyCommitPair,
+} from "./co-change-facts";
+import type { WorkspaceCoChangeEntry } from "@repowise-dev/types/workspace";
+
+/** Injected link component (e.g. Next's Link); defaults to a plain anchor. */
+type LinkLike = React.ElementType<{ href: string; className?: string; children: React.ReactNode }>;
+
+/** Evidence fetched when the drawer opens: pending, missing (with why), or here. */
+export type Loadable<T> =
+ | { state: "loading" }
+ | { state: "unavailable"; reason: string }
+ | { state: "ready"; data: T };
+
+export interface CoChangeFileHistory {
+ commits90d: number;
+ churnPercentile: number;
+ priorFixes: number;
+ isHotspot: boolean;
+ /** The per-repo index's most recent significant commits for this file. */
+ commits: CoChangeCommit[];
+}
+
+export interface CoChangePairDrawerProps {
+ /** The pair to describe; `null` closes the panel. */
+ pair: WorkspaceCoChangeEntry | null;
+ onClose: () => void;
+ structure: Loadable<CoChangeStructureFacts>;
+ sourceHistory: Loadable<CoChangeFileHistory>;
+ targetHistory: Loadable<CoChangeFileHistory>;
+ /** Commits reconstructed from both histories; null until both are ready. The
+ * host computes them once and hands the same list to the agent prompt. */
+ commits: NearbyCommitPair[] | null;
+ /** A file's page in its own repository; null when that repo is not indexed. */
+ fileHref?: ((repo: string, path: string) => string | null) | undefined;
+ /** Where one contract link opens. */
+ contractHref?: ((link: CoChangeLink) => string) | undefined;
+ LinkComponent?: LinkLike | undefined;
+ onGeneratePrompt: () => void;
+}
+
+function basename(path: string): string {
+ return path.split("/").pop() ?? path;
+}
+
+/**
+ * Everything the workspace knows about one cross-repo file pair: the claim,
+ * whether anything declared explains it, both files with their history, the
+ * commits that plausibly formed the shared sessions, and the agent prompt.
+ *
+ * Same anatomy as the single-repo `CouplingPairDrawer` (verdict and claim,
+ * hairline facts, sections under micro-headings, one action) through the
+ * shared pair parts. The verdict here is structural: a contract joining the
+ * two files explains the co-change; its absence is the exception worth a mark.
+ */
+export function CoChangePairDrawer({
+ pair,
+ onClose,
+ structure,
+ sourceHistory,
+ targetHistory,
+ commits,
+ fileHref,
+ contractHref,
+ LinkComponent,
+ onGeneratePrompt,
+}: CoChangePairDrawerProps) {
+ const Anchor: LinkLike = LinkComponent ?? "a";
+
+ const linked = structure.state === "ready" && structure.data.pairLinks.length > 0;
+ const hidden = structure.state === "ready" && structure.data.pairLinks.length === 0;
+
+ const facts: PairFact[] = pair
+ ? [
+ {
+ label: "Strength",
+ hint: <InfoTip content={STRENGTH_DEFINITION} label="What strength means" />,
+ value: (
+ <span className="font-mono text-lg font-semibold tabular-nums text-[var(--color-text-primary)]">
+ {Math.round(pair.strength * 100)}%
+ </span>
+ ),
+ },
+ {
+ label: "Shared sessions",
+ hint: <InfoTip content={SESSIONS_DEFINITION} label="What a shared session is" />,
+ value: (
+ <span className="text-xs text-[var(--color-text-primary)]">
+ <span className="font-mono text-lg font-semibold tabular-nums">{pair.frequency}</span>{" "}
+ <span className="text-[var(--color-text-tertiary)]">work sessions</span>
+ </span>
+ ),
+ },
+ {
+ label: "Last together",
+ value: (
+ <span
+ className="font-mono text-xs tabular-nums text-[var(--color-text-primary)]"
+ title={pair.last_date ? formatDateTime(pair.last_date) : undefined}
+ >
+ {pair.last_date ? formatDate(pair.last_date) : "unknown"}
+ </span>
+ ),
+ },
+ {
+ label: "Contract links",
+ value: (
+ <span className="text-xs text-[var(--color-text-primary)]">
+ {structure.state === "loading" ? (
+ <span className="text-[var(--color-text-tertiary)]">checking</span>
+ ) : structure.state === "unavailable" ? (
+ <span className="text-[var(--color-text-tertiary)]">not checked</span>
+ ) : linked ? (
+ <span className="font-mono tabular-nums">{structure.data.pairLinks.length}</span>
+ ) : (
+ "none between these files"
+ )}
+ </span>
+ ),
+ },
+ ]
+ : [];
+
+ return (
+ <AdaptivePanel
+ open={pair !== null}
+ onOpenChange={(o) => !o && onClose()}
+ modal={false}
+ widthClassName="md:max-w-[640px]"
+ eyebrow="Cross-repo co-change"
+ title={
+ pair ? (
+ <span className="font-mono [overflow-wrap:break-word]">
+ {basename(pair.source_file)} and {basename(pair.target_file)}
+ </span>
+ ) : (
+ ""
+ )
+ }
+ >
+ {pair && (
+ <div className="flex flex-col gap-6 px-4 py-4">
+ <div className="flex flex-col gap-2">
+ <p className="flex items-center gap-1.5">
+ <span
+ className={`h-1.5 w-1.5 shrink-0 rounded-full ${
+ hidden ? "bg-[var(--color-caution)]" : "bg-[var(--color-text-tertiary)]"
+ }`}
+ aria-hidden
+ />
+ <span className={MICRO}>
+ {structure.state === "loading"
+ ? "Checking declared links"
+ : structure.state === "unavailable"
+ ? "Declared links not checked"
+ : linked
+ ? "Linked by contract"
+ : "No declared link"}
+ </span>
+ </p>
+ <p className="text-[15px] leading-relaxed text-[var(--color-text-primary)] [text-wrap:pretty]">
+ <span className="font-mono">{basename(pair.source_file)}</span> in {pair.source_repo} and{" "}
+ <span className="font-mono">{basename(pair.target_file)}</span> in {pair.target_repo} changed in
+ the same work session {pair.frequency === 1 ? "once" : `${pair.frequency} times`}
+ {pair.last_date ? `, most recently on ${formatDate(pair.last_date)}` : ""}.
+ </p>
+ {structure.state === "ready" && (
+ <p className="text-xs leading-relaxed text-[var(--color-text-secondary)] [text-wrap:pretty]">
+ {linked
+ ? "A contract joins these files, so at least part of the co-change is accounted for. Worth a look only if the contract is the wrong shape or one side restates it by hand."
+ : `${hiddenCouplingSentence(pair, structure.data)} Until that changes, check the other file whenever you edit one.`}
+ </p>
+ )}
+ {structure.state === "unavailable" && (
+ <p className="text-xs leading-relaxed text-[var(--color-text-tertiary)]">{structure.reason}</p>
+ )}
+ </div>
+
+ <PairFactGrid facts={facts} />
+
+ <section className="flex flex-col gap-2">
+ <h3 className={MICRO}>The two files</h3>
+ <ul className="border-y border-[var(--color-border-default)]">
+ {(
+ [
+ [pair.source_repo, pair.source_file, sourceHistory],
+ [pair.target_repo, pair.target_file, targetHistory],
+ ] as const
+ ).map(([repo, path, history]) => {
+ const href = fileHref?.(repo, path) ?? null;
+ return (
+ <li
+ key={`${repo}:${path}`}
+ className="min-w-0 border-t border-[var(--color-border-default)] px-3 py-2.5 first:border-t-0"
+ >
+ {/* Wrapped, not truncated: the one place the exact file is legible. */}
+ <RepoPath repo={repo} path={path} wrap />
+ <p className="mt-1 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-[var(--color-text-tertiary)]">
+ <FileHistoryFacts history={history} />
+ {href ? (
+ <Anchor
+ href={href}
+ className="inline-flex items-center gap-1 font-medium text-[var(--color-accent-primary)] hover:underline"
+ >
+ <ExternalLink className="h-3 w-3" aria-hidden />
+ Open file page
+ </Anchor>
+ ) : (
+ <span>{repo} is not indexed, so there is no file page</span>
+ )}
+ </p>
+ </li>
+ );
+ })}
+ </ul>
+ </section>
+
+ <section className="flex flex-col gap-2">
+ <h3 className={MICRO}>Commits close together</h3>
+ <CommitEvidence
+ pair={pair}
+ commits={commits}
+ sourceHistory={sourceHistory}
+ targetHistory={targetHistory}
+ />
+ </section>
+
+ {linked && (
+ <section className="flex flex-col gap-2">
+ <h3 className={MICRO}>Contracts joining them</h3>
+ <ul className="border-y border-[var(--color-border-default)]">
+ {structure.data.pairLinks.map((l) => (
+ <li
+ key={`${l.contract_id}|${l.provider_file}|${l.consumer_file}`}
+ className="min-w-0 border-t border-[var(--color-border-default)] px-3 py-2.5 first:border-t-0"
+ >
+ <p className="break-all font-mono text-xs text-[var(--color-text-primary)]">{l.contract_id}</p>
+ <p className="mt-1 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-[var(--color-text-tertiary)]">
+ <span>
+ {l.contract_type}: {l.provider_repo} provides, {l.consumer_repo} consumes
+ </span>
+ {contractHref && (
+ <Anchor
+ href={contractHref(l)}
+ className="font-medium text-[var(--color-accent-primary)] hover:underline"
+ >
+ Open contract
+ </Anchor>
+ )}
+ </p>
+ </li>
+ ))}
+ </ul>
+ </section>
+ )}
+
+ <PairAgentSection
+ body="Builds a prompt carrying the evidence above, so your agent can find the concept these files share, decide whether a contract, shared type or generated client should replace the manual lockstep, and keep the other file in view when editing one."
+ label="AI investigation prompt"
+ onClick={onGeneratePrompt}
+ />
+ </div>
+ )}
+ </AdaptivePanel>
+ );
+}
+
+function FileHistoryFacts({ history }: { history: Loadable<CoChangeFileHistory> }) {
+ if (history.state === "loading") return <span>Loading history</span>;
+ if (history.state === "unavailable") return <span>{history.reason}</span>;
+ const h = history.data;
+ return (
+ <>
+ <span className="tabular-nums">
+ {h.commits90d} {h.commits90d === 1 ? "commit" : "commits"} in 90 days
+ </span>
+ <span className="tabular-nums">churn percentile {Math.round(h.churnPercentile)}</span>
+ {h.priorFixes > 0 && (
+ <span className="tabular-nums">
+ {h.priorFixes} prior {h.priorFixes === 1 ? "fix" : "fixes"}
+ </span>
+ )}
+ {/* The exception gets the mark; an ordinary file says nothing. */}
+ {h.isHotspot && (
+ <span className="inline-flex items-center gap-1 text-[var(--color-text-secondary)]">
+ <span className="h-1.5 w-1.5 rounded-full bg-[var(--color-warning)]" aria-hidden />
+ Hotspot
+ </span>
+ )}
+ </>
+ );
+}
+
+function CommitEvidence({
+ pair,
+ commits,
+ sourceHistory,
+ targetHistory,
+}: {
+ pair: WorkspaceCoChangeEntry;
+ commits: NearbyCommitPair[] | null;
+ sourceHistory: Loadable<CoChangeFileHistory>;
+ targetHistory: Loadable<CoChangeFileHistory>;
+}) {
+ const caveat = "The miner counts shared sessions but does not record which commits formed them.";
+ if (sourceHistory.state === "loading" || targetHistory.state === "loading") {
+ return <p className="text-xs text-[var(--color-text-tertiary)]">Loading each file&apos;s history.</p>;
+ }
+ if (commits === null) {
+ return (
+ <p className="text-xs leading-relaxed text-[var(--color-text-tertiary)]">
+ {caveat} Commit history for one of the files is not available here, so they cannot be
+ reconstructed.
+ </p>
+ );
+ }
+ const nA = sourceHistory.state === "ready" ? sourceHistory.data.commits.length : 0;
+ const nB = targetHistory.state === "ready" ? targetHistory.data.commits.length : 0;
+ const basis = `Matched by author within ${SESSION_WINDOW_HOURS} hours, from the ${nA} and ${nB} most recent significant commits of each file. ${caveat}`;
+ if (commits.length === 0) {
+ return (
+ <p className="text-xs leading-relaxed text-[var(--color-text-tertiary)]">
+ None of the recent significant commits line up. {basis}
+ </p>
+ );
+ }
+ const shown = commits.slice(0, MAX_COMMIT_PAIRS);
+ return (
+ <>
+ <ul className="border-y border-[var(--color-border-default)]">
+ {shown.map((c) => (
+ <li
+ key={`${c.source.sha}|${c.target.sha}`}
+ className="min-w-0 border-t border-[var(--color-border-default)] px-3 py-2.5 first:border-t-0"
+ >
+ <p className="font-mono text-[10px] tabular-nums text-[var(--color-text-tertiary)]">
+ {formatDate(c.source.date)}
+ {c.source.author ? ` · ${c.source.author}` : ""}
+ {` · ${gapPhrase(c.gapHours)}`}
+ </p>
+ {(
+ [
+ [pair.source_repo, c.source],
+ [pair.target_repo, c.target],
+ ] as const
+ ).map(([repo, commit]) => (
+ <p key={repo} className="mt-1 flex min-w-0 gap-2 text-xs">
+ <span className="shrink-0 font-mono text-[var(--color-text-tertiary)]">
+ {repo} {commit.sha.slice(0, 8)}
+ </span>
+ <span className="min-w-0 truncate text-[var(--color-text-secondary)]" title={commit.message ?? undefined}>
+ {commit.message?.split("\n")[0] ?? ""}
+ </span>
+ </p>
+ ))}
+ </li>
+ ))}
+ </ul>
+ <p className="text-xs leading-relaxed text-[var(--color-text-tertiary)]">
+ {commits.length > shown.length ? `Showing ${shown.length} of ${commits.length}. ` : ""}
+ {basis}
+ </p>
+ </>
+ );
+}
diff --git a/packages/ui/src/workspace/co-change-table.tsx b/packages/ui/src/workspace/co-change-table.tsx
index e81c2c2a2..b5d2bd539 100644
--- a/packages/ui/src/workspace/co-change-table.tsx
+++ b/packages/ui/src/workspace/co-change-table.tsx
@@ -1,116 +1,201 @@
"use client";
-import { Badge } from "../ui/badge";
+import * as React from "react";
import { EmptyState } from "../shared/empty-state";
-import { VirtualizedTable } from "../shared/virtualized-table";
+import { InfoTip } from "../shared/info-tip";
+import { clickableRowProps, CLICKABLE_ROW_CLS } from "../shared/responsive-table";
+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";
interface CoChangeTableProps {
coChanges: WorkspaceCoChangeEntry[];
+ /** Drops the sessions and date columns, for previews. */
compact?: boolean;
+ /** Makes rows open the pair; omitted, rows are plain. */
+ onSelect?: (cc: WorkspaceCoChangeEntry) => void;
+ /** `coChangeKey` of the open pair, marked as selected. */
+ selectedKey?: string | null;
}
-// Column-priority hide classes, mirroring the shared ResponsiveTable scale:
-// priority 2 hides below md (768px), priority 3 hides below lg (1024px). The
-// source/target identity columns (priority 1) are always visible.
+/**
+ * Stable identity for one file pair, used for row keys and the `?cc=` param.
+ * Order-independent, so a row flipped to lead with a searched file keeps it.
+ */
+export function coChangeKey(cc: WorkspaceCoChangeEntry): string {
+ const a = `${cc.source_repo}:${cc.source_file}`;
+ const b = `${cc.target_repo}:${cc.target_file}`;
+ return a < b ? `${a}|${b}` : `${b}|${a}`;
+}
+
+
+// Priority 2 hides below md, matching the shared ResponsiveTable scale. The two
+// files and the strength stay at every width.
const HIDE_BELOW_MD = "max-md:hidden";
-const HIDE_BELOW_LG = "max-lg:hidden";
+
+function splitPath(path: string): [dir: string, base: string] {
+ const i = path.lastIndexOf("/");
+ return i < 0 ? ["", path] : [path.slice(0, i + 1), path.slice(i + 1)];
+}
/**
- * Cross-repo co-change list: one row per file pair that changed together.
- *
- * The body is virtualized (windowed `<tbody>`) so long co-change lists stay
- * cheap to render; below the wrapper's threshold every row renders, so the
- * common short list behaves exactly as a plain table.
+ * A repository as a quiet micro-label over its path: directory dim, filename
+ * full strength and never cut, so the part a reader recognises survives any
+ * width. In a row the directory truncates (full path in the DOM and the
+ * title); with `wrap`, where the exact file must be legible, lines break only
+ * after a "/".
*/
-export function CoChangeTable({ coChanges, compact }: CoChangeTableProps) {
- if (coChanges.length === 0) {
+export function RepoPath({ repo, path, wrap = false }: { repo: string; path: string; wrap?: boolean }) {
+ const [dir, base] = splitPath(path);
+ if (wrap) {
return (
- <EmptyState
- title="No cross-repo co-changes"
- description="No files in sibling repos have changed together yet."
- />
+ <div className="min-w-0">
+ <span className={cn(MICRO, "block")}>{repo}</span>
+ <p className="min-w-0 font-mono text-xs leading-5 [overflow-wrap:break-word]">
+ {dir.split("/").filter(Boolean).map((seg, i) => (
+ <React.Fragment key={i}>
+ <span className="text-[var(--color-text-tertiary)]">{seg}/</span>
+ <wbr />
+ </React.Fragment>
+ ))}
+ <span className="font-medium text-[var(--color-text-primary)]">{base}</span>
+ </p>
+ </div>
);
}
-
- const header = (
- <tr className="bg-[var(--color-bg-elevated)] text-[var(--color-text-tertiary)] text-xs uppercase tracking-wider">
- <th className="px-3 py-2 text-left font-medium">Source</th>
- <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="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
+ return (
+ <div className="min-w-0">
+ <span className={cn(MICRO, "block")}>{repo}</span>
+ <span className="flex min-w-0 font-mono text-xs leading-5" title={path}>
+ {dir && <span className="truncate text-[var(--color-text-tertiary)]">{dir}</span>}
+ <span className="max-w-full shrink-0 font-medium text-[var(--color-text-primary)] [overflow-wrap:anywhere]">
+ {base}
</span>
- </th>
- {compact ? null : (
- <>
- <th className={`px-3 py-2 text-right font-medium ${HIDE_BELOW_LG}`}>Freq</th>
- <th className={`px-3 py-2 text-left font-medium ${HIDE_BELOW_LG}`}>Last</th>
- </>
- )}
- </tr>
+ </span>
+ </div>
);
+}
- const renderRow = (cc: WorkspaceCoChangeEntry) => (
- <tr className="border-t border-[var(--color-border-default)] hover:bg-[var(--color-bg-elevated)]">
- <td className="px-3 py-2 text-left min-w-[160px] max-w-[280px]">
- <div className="flex flex-col gap-0.5">
- <Badge variant="default" className="w-fit text-xs">{cc.source_repo}</Badge>
- <span className="text-xs font-mono text-[var(--color-text-secondary)] truncate block" title={cc.source_file}>
- {cc.source_file}
- </span>
- </div>
+interface RowProps {
+ cc: WorkspaceCoChangeEntry;
+ compact: boolean;
+ selected: boolean;
+ onSelect: ((cc: WorkspaceCoChangeEntry) => void) | undefined;
+}
+
+/** Memoised so opening a pair or narrowing the list re-renders only the rows that changed. */
+const CoChangeRow = React.memo(function CoChangeRow({ cc, compact, selected, onSelect }: RowProps) {
+ const interactive = onSelect !== undefined;
+ return (
+ <tr
+ className={cn(
+ "border-t border-[var(--color-border-default)] align-top",
+ interactive && "hover:bg-[var(--color-bg-elevated)]",
+ selected && "bg-[var(--color-accent-muted)]",
+ interactive && CLICKABLE_ROW_CLS,
+ )}
+ aria-current={selected ? "true" : undefined}
+ {...(interactive ? clickableRowProps(() => onSelect(cc)) : {})}
+ >
+ <td className="px-3 py-2.5 text-left">
+ <RepoPath repo={cc.source_repo} path={cc.source_file} />
</td>
- <td className="px-3 py-2 text-left min-w-[160px] max-w-[280px]">
- <div className="flex flex-col gap-0.5">
- <Badge variant="default" className="w-fit text-xs">{cc.target_repo}</Badge>
- <span className="text-xs font-mono text-[var(--color-text-secondary)] truncate block" title={cc.target_file}>
- {cc.target_file}
- </span>
- </div>
+ <td className="px-3 py-2.5 text-left">
+ <RepoPath repo={cc.target_repo} path={cc.target_file} />
</td>
- <td className={`px-3 py-2 text-left ${HIDE_BELOW_MD}`}>
- <div className="flex items-center gap-2 min-w-[90px]">
- <div className="h-1.5 flex-1 rounded-full bg-[var(--color-bg-inset)] overflow-hidden">
- <div
- className="h-full rounded-full bg-[var(--color-accent-primary)] transition-all"
- 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 * 100)}%`}
- </span>
- </div>
+ <td className="px-3 py-2.5 text-right align-middle font-mono text-xs tabular-nums text-[var(--color-text-primary)]">
+ {Math.round(cc.strength * 100)}%
</td>
{compact ? null : (
<>
- <td className={`px-3 py-2 text-right text-xs text-[var(--color-text-secondary)] tabular-nums ${HIDE_BELOW_LG}`}>
- {`${cc.frequency}x`}
+ <td
+ className={`px-3 py-2.5 text-right align-middle font-mono text-xs tabular-nums text-[var(--color-text-secondary)] ${HIDE_BELOW_MD}`}
+ >
+ {cc.frequency}
</td>
- <td className={`px-3 py-2 text-left text-xs text-[var(--color-text-tertiary)] ${HIDE_BELOW_LG}`}>
+ <td
+ className={`whitespace-nowrap px-3 py-2.5 text-right align-middle font-mono text-xs tabular-nums text-[var(--color-text-tertiary)] ${HIDE_BELOW_MD}`}
+ >
{/* formatDate, not toLocaleDateString(): the bare call resolves
the ambient locale, so Node and the browser can render the same
date differently and hydration fails. */}
<span title={cc.last_date ? formatDateTime(cc.last_date) : undefined}>
- {cc.last_date ? formatDate(cc.last_date) : "—"}
+ {cc.last_date ? formatDate(cc.last_date) : "unknown"}
</span>
</td>
</>
)}
</tr>
);
+});
+
+/**
+ * Cross-repo co-change list: one row per file pair that changed together.
+ *
+ * A plain table in the page flow rather than a windowed inner scroller: the
+ * miner stores at most 200 pairs and the endpoint serves at most 500, and a
+ * fixed-height scroller left the page empty below it. Rows are memoised
+ * instead. If the endpoint ever serves thousands, window it again.
+ *
+ * No strength bar: in a list sorted by strength, neighbouring rows differ by a
+ * point or two, so a bar per row repeats one shape. The figure is exact and
+ * aligns.
+ */
+export function CoChangeTable({ coChanges, compact = false, onSelect, selectedKey }: CoChangeTableProps) {
+ if (coChanges.length === 0) {
+ return (
+ <EmptyState
+ title="No cross-repo co-changes"
+ description="No files in sibling repos have changed together yet."
+ />
+ );
+ }
return (
- <VirtualizedTable<WorkspaceCoChangeEntry>
- rows={coChanges}
- rowKey={(cc) => `${cc.source_repo}|${cc.source_file}|${cc.target_repo}|${cc.target_file}`}
- header={header}
- renderRow={renderRow}
- aria-label="Cross-repo co-changed files"
- />
+ <div className="overflow-x-auto">
+ <table className="w-full border-collapse" aria-label="Cross-repo co-changed files">
+ <thead>
+ <tr className="border-b border-[var(--color-border-default)]">
+ <th className={cn(MICRO, "px-3 py-2 text-left font-normal")}>File</th>
+ <th className={cn(MICRO, "px-3 py-2 text-left font-normal")}>Changes with</th>
+ <th className={cn(MICRO, "px-3 py-2 text-right font-normal")}>
+ <span className="inline-flex items-center gap-1">
+ Strength
+ <InfoTip content={STRENGTH_DEFINITION} label="What strength means" />
+ </span>
+ </th>
+ {compact ? null : (
+ <>
+ <th className={cn(MICRO, "px-3 py-2 text-right font-normal", HIDE_BELOW_MD)}>
+ <span className="inline-flex items-center gap-1">
+ Sessions
+ <InfoTip content={SESSIONS_DEFINITION} label="What a shared session is" />
+ </span>
+ </th>
+ <th className={cn(MICRO, "px-3 py-2 text-right font-normal", HIDE_BELOW_MD)}>
+ Last together
+ </th>
+ </>
+ )}
+ </tr>
+ </thead>
+ <tbody>
+ {coChanges.map((cc) => {
+ const key = coChangeKey(cc);
+ return (
+ <CoChangeRow
+ key={key}
+ cc={cc}
+ compact={compact}
+ selected={selectedKey === key}
+ onSelect={onSelect}
+ />
+ );
+ })}
+ </tbody>
+ </table>
+ </div>
);
}
diff --git a/packages/ui/src/workspace/index.ts b/packages/ui/src/workspace/index.ts
index a543cec9f..e40495732 100644
--- a/packages/ui/src/workspace/index.ts
+++ b/packages/ui/src/workspace/index.ts
@@ -1,5 +1,8 @@
export * from "./breaking-change-row";
export * from "./breaking-changes-view";
+export * from "./co-change-ai-prompt";
+export * from "./co-change-facts";
+export * from "./co-change-pair-drawer";
export * from "./co-change-table";
export * from "./contract-ai-prompt";
export * from "./contract-attention";
diff --git a/packages/ui/src/workspace/repo-pair-table.tsx b/packages/ui/src/workspace/repo-pair-table.tsx
index 66529a8fe..d8c02dc76 100644
--- a/packages/ui/src/workspace/repo-pair-table.tsx
+++ b/packages/ui/src/workspace/repo-pair-table.tsx
@@ -1,12 +1,11 @@
"use client";
-import { Badge } from "../ui/badge";
import { EmptyState } from "../shared/empty-state";
-import { VirtualizedTable } from "../shared/virtualized-table";
import { clickableRowProps, CLICKABLE_ROW_CLS } from "../shared/responsive-table";
+import { AiPromptButton } from "../health/ai-prompt-button";
+import { PAIR_MICRO as MICRO } from "../coupling/pair-drawer-parts";
import { cn } from "../lib/cn";
import { formatDate, formatDateTime } from "../lib/format";
-import { ChevronRight } from "lucide-react";
export interface RepoPairSummary {
id: string; // "repo1↔repo2"
@@ -21,22 +20,22 @@ interface RepoPairTableProps {
repoPairs: RepoPairSummary[];
onSelectPair?: (id: string) => void;
selectedPairId?: string | null;
+ /** Opens the AI prompt for one repository pair. */
+ onPrompt?: (pair: RepoPairSummary) => void;
}
-// Column-priority hide classes, mirroring the shared ResponsiveTable scale:
-// priority 2 hides below md (768px), priority 3 hides below lg (1024px). The
-// pair identity, max-strength and action columns (priority 1) stay visible.
+// Priority 2 hides below md, priority 3 below lg, matching ResponsiveTable.
const HIDE_BELOW_MD = "max-md:hidden";
const HIDE_BELOW_LG = "max-lg:hidden";
/**
- * Cross-repo pair summary: one row per repository pair, click to drill in.
+ * Cross-repo pair summary: one row per repository pair. Choosing a row narrows
+ * the file list; the row says so, since a narrowing is not a navigation.
*
- * The body is virtualized (windowed `<tbody>`) so long pair lists stay cheap to
- * render; below the wrapper's threshold every row renders, so the common short
- * list behaves exactly as a plain table.
+ * Repository names are plain mono text rather than chips: they are neutral
+ * categories, and a bordered chip reads as a control the row already is.
*/
-export function RepoPairTable({ repoPairs, onSelectPair, selectedPairId }: RepoPairTableProps) {
+export function RepoPairTable({ repoPairs, onSelectPair, selectedPairId, onPrompt }: RepoPairTableProps) {
if (repoPairs.length === 0) {
return (
<EmptyState
@@ -46,75 +45,91 @@ export function RepoPairTable({ repoPairs, onSelectPair, selectedPairId }: RepoP
);
}
- const header = (
- <tr className="bg-[var(--color-bg-elevated)] text-[var(--color-text-tertiary)] text-xs uppercase tracking-wider">
- <th className="px-3 py-2 text-left font-medium">Repository Pair</th>
- <th className={`px-3 py-2 text-right font-medium ${HIDE_BELOW_MD}`}>File Pairs</th>
- <th className="px-3 py-2 text-left font-medium w-32">Max Strength</th>
- <th className={`px-3 py-2 text-right font-medium ${HIDE_BELOW_LG}`}>Latest Activity</th>
- {onSelectPair ? <th className="px-3 py-2 text-right font-medium" /> : null}
- </tr>
- );
-
- const renderRow = (p: RepoPairSummary) => {
- const onClick = onSelectPair ? () => onSelectPair(p.id) : undefined;
- const isSelected = selectedPairId != null && selectedPairId === p.id;
- return (
- <tr
- className={cn(
- "border-t border-[var(--color-border-default)] hover:bg-[var(--color-bg-elevated)]",
- isSelected && "bg-[var(--color-accent-muted)]/30",
- onClick && CLICKABLE_ROW_CLS,
- )}
- {...(onClick ? clickableRowProps(onClick) : {})}
- >
- <td className="px-3 py-2 text-left">
- <div className="flex items-center gap-2">
- <Badge variant="default" className="text-xs">{p.repo1}</Badge>
- <span className="text-[var(--color-text-tertiary)] text-xs">↔</span>
- <Badge variant="default" className="text-xs">{p.repo2}</Badge>
- </div>
- </td>
- <td className={`px-3 py-2 text-right text-xs text-[var(--color-text-secondary)] tabular-nums ${HIDE_BELOW_MD}`}>
- {p.filePairCount}
- </td>
- <td className="px-3 py-2 text-left">
- <div className="flex items-center gap-2 min-w-[90px]">
- <div className="h-1.5 flex-1 rounded-full bg-[var(--color-bg-inset)] overflow-hidden">
- <div
- className="h-full rounded-full bg-[var(--color-accent-primary)] transition-all"
- 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 * 100)}%`}
- </span>
- </div>
- </td>
- <td className={`px-3 py-2 text-right text-xs text-[var(--color-text-tertiary)] ${HIDE_BELOW_LG}`}>
- {/* formatDate, not toLocaleDateString(): the bare call resolves the
- ambient locale, so Node and the browser can render the same date
- differently and hydration fails. */}
- <span title={p.lastDate ? formatDateTime(p.lastDate) : undefined}>
- {p.lastDate ? formatDate(p.lastDate) : "—"}
- </span>
- </td>
- {onSelectPair ? (
- <td className="px-3 py-2 text-right">
- <ChevronRight className="h-4 w-4 text-[var(--color-text-tertiary)] inline-block" />
- </td>
- ) : null}
- </tr>
- );
- };
-
return (
- <VirtualizedTable<RepoPairSummary>
- rows={repoPairs}
- rowKey={(p) => p.id}
- header={header}
- renderRow={renderRow}
- aria-label="Cross-repo pairs"
- />
+ <div className="overflow-x-auto">
+ <table className="w-full border-collapse" aria-label="Cross-repo pairs">
+ <thead>
+ <tr className="border-b border-[var(--color-border-default)]">
+ <th className={cn(MICRO, "px-3 py-2 text-left font-normal")}>Repositories</th>
+ <th className={cn(MICRO, "px-3 py-2 text-right font-normal", HIDE_BELOW_MD)}>File pairs</th>
+ <th className={cn(MICRO, "px-3 py-2 text-right font-normal")}>Strongest</th>
+ <th className={cn(MICRO, "px-3 py-2 text-right font-normal", HIDE_BELOW_LG)}>Latest</th>
+ {onSelectPair || onPrompt ? (
+ <th className="px-3 py-2">
+ <span className="sr-only">Actions</span>
+ </th>
+ ) : null}
+ </tr>
+ </thead>
+ <tbody>
+ {repoPairs.map((p) => {
+ const onClick = onSelectPair ? () => onSelectPair(p.id) : undefined;
+ const isSelected = selectedPairId != null && selectedPairId === p.id;
+ return (
+ <tr
+ key={p.id}
+ className={cn(
+ "border-t border-[var(--color-border-default)] first:border-t-0",
+ onClick && "hover:bg-[var(--color-bg-elevated)]",
+ isSelected && "bg-[var(--color-accent-muted)]",
+ onClick && CLICKABLE_ROW_CLS,
+ )}
+ aria-current={isSelected ? "true" : undefined}
+ {...(onClick ? clickableRowProps(onClick) : {})}
+ >
+ <td className="px-3 py-2.5 text-left font-mono text-xs font-medium text-[var(--color-text-primary)]">
+ <span>{p.repo1}</span>
+ <span className="px-1.5 font-sans font-normal text-[var(--color-text-tertiary)]">and</span>
+ <span>{p.repo2}</span>
+ </td>
+ <td
+ className={`px-3 py-2.5 text-right font-mono text-xs tabular-nums text-[var(--color-text-secondary)] ${HIDE_BELOW_MD}`}
+ >
+ {p.filePairCount}
+ </td>
+ <td className="px-3 py-2.5 text-right font-mono text-xs tabular-nums text-[var(--color-text-primary)]">
+ {Math.round(p.maxStrength * 100)}%
+ </td>
+ <td
+ className={`whitespace-nowrap px-3 py-2.5 text-right font-mono text-xs tabular-nums text-[var(--color-text-tertiary)] ${HIDE_BELOW_LG}`}
+ >
+ {/* formatDate, not toLocaleDateString(): the bare call resolves the
+ ambient locale, so Node and the browser can render the same date
+ differently and hydration fails. */}
+ <span title={p.lastDate ? formatDateTime(p.lastDate) : undefined}>
+ {p.lastDate ? formatDate(p.lastDate) : "unknown"}
+ </span>
+ </td>
+ {onSelectPair || onPrompt ? (
+ <td className="px-3 py-2 text-right">
+ <span className="inline-flex items-center justify-end gap-3">
+ {onSelectPair && (
+ <span
+ className={cn(
+ "whitespace-nowrap text-xs max-sm:sr-only",
+ isSelected
+ ? "font-medium text-[var(--color-accent-primary)]"
+ : "text-[var(--color-text-tertiary)]",
+ )}
+ >
+ {isSelected ? "Showing only these" : "Show only these"}
+ </span>
+ )}
+ {onPrompt && (
+ <AiPromptButton
+ variant="icon"
+ label={`AI prompt for ${p.repo1} and ${p.repo2}`}
+ onClick={() => onPrompt(p)}
+ />
+ )}
+ </span>
+ </td>
+ ) : null}
+ </tr>
+ );
+ })}
+ </tbody>
+ </table>
+ </div>
);
}
diff --git a/packages/web/src/app/workspace/co-changes/co-changes-explorer.tsx b/packages/web/src/app/workspace/co-changes/co-changes-explorer.tsx
new file mode 100644
index 000000000..30a01ffde
--- /dev/null
+++ b/packages/web/src/app/workspace/co-changes/co-changes-explorer.tsx
@@ -0,0 +1,376 @@
+"use client";
+
+import { useCallback, useEffect, useMemo, useState } from "react";
+import Link from "next/link";
+import useSWR from "swr";
+import { Search, X } from "lucide-react";
+import type { GitMetadataResponse, WorkspaceCoChangeEntry } from "@repowise-dev/api-client/types";
+import { OverviewSection } from "@repowise-dev/ui/overview";
+import { EmptyState } from "@repowise-dev/ui/shared/empty-state";
+import { fileEntityPath } from "@repowise-dev/ui/shared/entity";
+import { AiPromptModal } from "@repowise-dev/ui/health/ai-prompt-modal";
+import type { AiPromptFlavor } from "@repowise-dev/ui/health/ai-prompt-builder";
+import { CoChangeTable, coChangeKey } from "@repowise-dev/ui/workspace/co-change-table";
+import { RepoPairTable, type RepoPairSummary } from "@repowise-dev/ui/workspace/repo-pair-table";
+import {
+ CoChangePairDrawer,
+ type CoChangeFileHistory,
+ type Loadable,
+} from "@repowise-dev/ui/workspace/co-change-pair-drawer";
+import {
+ buildCoChangePairAiPrompt,
+ buildCoChangeRepoPairAiPrompt,
+} from "@repowise-dev/ui/workspace/co-change-ai-prompt";
+import {
+ capRule,
+ coChangeRepoPairId,
+ nearbyCommits,
+ type CoChangeCaps,
+} from "@repowise-dev/ui/workspace/co-change-facts";
+import { formatNumber } from "@repowise-dev/ui/lib/format";
+import { getWorkspaceCoChangeStructure } from "@/lib/api/workspace";
+import { getGitMetadata } from "@/lib/api/git";
+
+interface Props {
+ coChanges: WorkspaceCoChangeEntry[];
+ repoPairs: RepoPairSummary[];
+ totalMined: number;
+ /** Which of the miner's caps trimmed the list, as the server reports it. */
+ caps: CoChangeCaps;
+ /** Alias to indexed repo id; repos without one have no file pages. */
+ repoIds: Record<string, string>;
+ initialPair: string | null;
+ initialQuery: string;
+ initialOpen: string | null;
+}
+
+type PromptTarget = { kind: "file" } | { kind: "repo"; pair: RepoPairSummary } | null;
+
+const SEARCH_DEBOUNCE_MS = 150;
+
+function flip(cc: WorkspaceCoChangeEntry): WorkspaceCoChangeEntry {
+ return {
+ ...cc,
+ source_repo: cc.target_repo,
+ source_file: cc.target_file,
+ target_repo: cc.source_repo,
+ target_file: cc.source_file,
+ };
+}
+
+/** `repo/path`, so a query can name the repository too. */
+function haystack(repo: string, file: string): string {
+ return `${repo}/${file}`.toLowerCase();
+}
+
+/**
+ * Write the reader's state to the URL without a navigation. The rows are all
+ * on the client already, so a router push would only re-run the server page
+ * to hand back the same data.
+ */
+function syncUrl(pair: string | null, q: string, cc: string | null) {
+ const url = new URL(window.location.href);
+ const set = (k: string, v: string | null) => (v ? url.searchParams.set(k, v) : url.searchParams.delete(k));
+ set("pair", pair);
+ set("q", q.trim() || null);
+ set("cc", cc);
+ window.history.replaceState(null, "", `${url.pathname}${url.search}`);
+}
+
+/** One side's per-repo git facts, or why there are none. Keyed like the docs
+ * viewer's fetch, so a file already seen there costs nothing here. */
+function useFileHistory(repoId: string | undefined, path: string | undefined): Loadable<CoChangeFileHistory> {
+ const { data, error } = useSWR<GitMetadataResponse | null>(
+ repoId && path ? `git-meta:${repoId}:${path}` : null,
+ () =>
+ getGitMetadata(repoId!, path!).catch((err) => {
+ if (err?.status === 404) return null;
+ throw err;
+ }),
+ { revalidateOnFocus: false, shouldRetryOnError: false },
+ );
+ // Memoised so the history keeps its identity between renders, which is what
+ // lets the reconstructed commits be computed once per pair.
+ return useMemo((): Loadable<CoChangeFileHistory> => {
+ if (!path) return { state: "loading" };
+ if (!repoId) return { state: "unavailable", reason: "Repository not indexed, so no history" };
+ if (error) return { state: "unavailable", reason: "History failed to load" };
+ if (data === undefined) return { state: "loading" };
+ if (data === null) return { state: "unavailable", reason: "No git history indexed for this file" };
+ return {
+ state: "ready",
+ data: {
+ commits90d: data.commit_count_90d,
+ churnPercentile: data.churn_percentile,
+ priorFixes: data.prior_defect_count ?? 0,
+ isHotspot: data.is_hotspot,
+ commits: (data.significant_commits ?? []).map((c) => ({
+ sha: String(c.sha ?? ""),
+ date: String(c.date ?? ""),
+ message: typeof c.message === "string" ? c.message : null,
+ author: typeof c.author === "string" ? c.author : null,
+ })),
+ },
+ };
+ }, [repoId, path, data, error]);
+}
+
+export function CoChangesExplorer({
+ coChanges,
+ repoPairs,
+ totalMined,
+ caps,
+ repoIds,
+ initialPair,
+ initialQuery,
+ initialOpen,
+}: Props) {
+ const [selectedPair, setSelectedPair] = useState<string | null>(initialPair);
+ const [query, setQuery] = useState(initialQuery);
+ const [debouncedQuery, setDebouncedQuery] = useState(initialQuery);
+ const [openKey, setOpenKey] = useState<string | null>(initialOpen);
+ const [prompt, setPrompt] = useState<PromptTarget>(null);
+
+ useEffect(() => {
+ const t = setTimeout(() => setDebouncedQuery(query), SEARCH_DEBOUNCE_MS);
+ return () => clearTimeout(t);
+ }, [query]);
+
+ useEffect(() => {
+ syncUrl(selectedPair, debouncedQuery, openKey);
+ }, [selectedPair, debouncedQuery, openKey]);
+
+ const byKey = useMemo(() => new Map(coChanges.map((c) => [coChangeKey(c), c])), [coChanges]);
+
+ // Narrow by repository pair, then by path. A row whose match is only on its
+ // second file is flipped so the searched file leads: the list then reads as
+ // "what changes with this file".
+ const rows = useMemo(() => {
+ const terms = debouncedQuery.trim().toLowerCase().split(/\s+/).filter(Boolean);
+ const out: WorkspaceCoChangeEntry[] = [];
+ for (const c of coChanges) {
+ if (selectedPair && coChangeRepoPairId(c) !== selectedPair) continue;
+ if (terms.length === 0) {
+ out.push(c);
+ continue;
+ }
+ const a = haystack(c.source_repo, c.source_file);
+ const b = haystack(c.target_repo, c.target_file);
+ const onA = terms.every((t) => a.includes(t));
+ const onB = terms.every((t) => b.includes(t));
+ if (onA) out.push(c);
+ else if (onB) out.push(flip(c));
+ }
+ return out;
+ }, [coChanges, selectedPair, debouncedQuery]);
+
+ const openPair = useMemo(() => {
+ if (!openKey) return null;
+ return rows.find((r) => coChangeKey(r) === openKey) ?? byKey.get(openKey) ?? null;
+ }, [openKey, rows, byKey]);
+
+ const onSelectRow = useCallback((cc: WorkspaceCoChangeEntry) => setOpenKey(coChangeKey(cc)), []);
+ const onSelectPair = useCallback(
+ (id: string) => setSelectedPair((cur) => (cur === id ? null : id)),
+ [],
+ );
+ const onRepoPrompt = useCallback((pair: RepoPairSummary) => setPrompt({ kind: "repo", pair }), []);
+
+ // Drawer evidence, fetched only while a pair is open and cached per pair.
+ const { data: structureData, error: structureError } = useSWR(
+ openPair ? `workspace:co-changes:structure:${coChangeKey(openPair)}` : null,
+ () =>
+ getWorkspaceCoChangeStructure({
+ source_repo: openPair!.source_repo,
+ source_file: openPair!.source_file,
+ target_repo: openPair!.target_repo,
+ target_file: openPair!.target_file,
+ }),
+ { revalidateOnFocus: false, shouldRetryOnError: false },
+ );
+ const structure = useMemo(
+ () =>
+ structureError
+ ? ({ state: "unavailable", reason: "Contract links failed to load, so this pair was not checked." } as const)
+ : structureData
+ ? ({
+ state: "ready",
+ data: {
+ pairLinks: structureData.pair_links,
+ repoLinksTotal: structureData.repo_links_total,
+ repoLinksByType: structureData.repo_links_by_type,
+ },
+ } as const)
+ : ({ state: "loading" } as const),
+ [structureData, structureError],
+ );
+ const sourceHistory = useFileHistory(
+ openPair ? repoIds[openPair.source_repo] : undefined,
+ openPair?.source_file,
+ );
+ const targetHistory = useFileHistory(
+ openPair ? repoIds[openPair.target_repo] : undefined,
+ openPair?.target_file,
+ );
+ // Once per pair, for both the drawer and the prompt.
+ const commits = useMemo(
+ () =>
+ sourceHistory.state === "ready" && targetHistory.state === "ready"
+ ? nearbyCommits(sourceHistory.data.commits, targetHistory.data.commits)
+ : null,
+ [sourceHistory, targetHistory],
+ );
+
+ const getPrompt = useMemo(() => {
+ if (prompt?.kind === "repo") {
+ const pairs = coChanges.filter((c) => coChangeRepoPairId(c) === prompt.pair.id);
+ return (flavor: AiPromptFlavor) =>
+ buildCoChangeRepoPairAiPrompt({
+ repo1: prompt.pair.repo1,
+ repo2: prompt.pair.repo2,
+ pairs,
+ flavor,
+ caps,
+ });
+ }
+ if (prompt?.kind === "file" && openPair) {
+ const facts = (h: Loadable<CoChangeFileHistory>) =>
+ h.state === "ready"
+ ? {
+ commits90d: h.data.commits90d,
+ churnPercentile: h.data.churnPercentile,
+ priorFixes: h.data.priorFixes,
+ isHotspot: h.data.isHotspot,
+ }
+ : null;
+ return (flavor: AiPromptFlavor) =>
+ buildCoChangePairAiPrompt({
+ pair: openPair,
+ flavor,
+ structure: structure.state === "ready" ? structure.data : null,
+ sourceFacts: facts(sourceHistory),
+ targetFacts: facts(targetHistory),
+ commits: commits ?? [],
+ });
+ }
+ return null;
+ }, [prompt, coChanges, caps, openPair, structure, sourceHistory, targetHistory, commits]);
+
+ const selected = selectedPair ? repoPairs.find((p) => p.id === selectedPair) ?? null : null;
+ const trimmed = debouncedQuery.trim();
+ const inScope = selected ? selected.filePairCount : coChanges.length;
+ const rule = capRule(caps);
+ const dropped = totalMined - coChanges.length;
+
+ const scope = [
+ trimmed
+ ? `${formatNumber(rows.length)} of ${formatNumber(inScope)} pairs ${selected ? `in ${selected.repo1} and ${selected.repo2} ` : ""}touch a path matching "${trimmed}", strongest first.`
+ : selected
+ ? `${formatNumber(rows.length)} file pairs in ${selected.repo1} and ${selected.repo2}, strongest first.`
+ : `${formatNumber(coChanges.length)} of ${formatNumber(totalMined)} pairs, strongest first.`,
+ rule && dropped > 0
+ ? ` ${rule[0]!.toUpperCase()}${rule.slice(1)}, so ${formatNumber(dropped)} weaker pairs across the workspace are not listed.`
+ : "",
+ ].join("");
+
+ return (
+ <>
+ <OverviewSection
+ title="Repository pairs"
+ description={
+ caps.truncatedBy === "per_repo_pair" && caps.perRepoPairCap
+ ? `Ranked by their strongest file pair. File pairs stop at ${caps.perRepoPairCap} per repository pair because the miner keeps no more.`
+ : "Ranked by their strongest file pair."
+ }
+ >
+ <RepoPairTable
+ repoPairs={repoPairs}
+ selectedPairId={selectedPair}
+ onSelectPair={onSelectPair}
+ onPrompt={onRepoPrompt}
+ />
+ </OverviewSection>
+
+ <OverviewSection
+ title={selected ? `Files in ${selected.repo1} and ${selected.repo2}` : "Files that change together"}
+ description={scope}
+ >
+ <div className="flex flex-wrap items-center gap-3">
+ <label className="relative flex min-w-0 max-w-[420px] flex-1 items-center">
+ <span className="sr-only">Filter by file path</span>
+ <Search
+ className="pointer-events-none absolute left-2.5 h-3.5 w-3.5 text-[var(--color-text-tertiary)]"
+ aria-hidden
+ />
+ <input
+ type="search"
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ placeholder="What changes with this file? Type a path"
+ className="h-8 w-full rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] pl-8 pr-3 font-mono text-xs text-[var(--color-text-primary)] placeholder:font-sans placeholder:text-[var(--color-text-tertiary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ />
+ </label>
+ {selected && (
+ <button
+ type="button"
+ onClick={() => setSelectedPair(null)}
+ className="inline-flex items-center gap-1 rounded-md px-2 py-1 text-xs text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ >
+ <X className="h-3 w-3" aria-hidden />
+ Show all repository pairs
+ </button>
+ )}
+ </div>
+ {rows.length === 0 ? (
+ <EmptyState
+ title="No file pairs match"
+ description={`No listed pair touches a path containing "${trimmed}". Only the ${formatNumber(coChanges.length)} strongest pairs are listed, so a weaker partner may exist that is not shown.`}
+ />
+ ) : (
+ <CoChangeTable coChanges={rows} onSelect={onSelectRow} selectedKey={openKey} />
+ )}
+ </OverviewSection>
+
+ <CoChangePairDrawer
+ pair={openPair}
+ onClose={() => setOpenKey(null)}
+ structure={structure}
+ sourceHistory={sourceHistory}
+ targetHistory={targetHistory}
+ commits={commits}
+ fileHref={(repo, path) => {
+ const id = repoIds[repo];
+ return id ? fileEntityPath(`/repos/${id}`, path) : null;
+ }}
+ contractHref={(l) =>
+ `/workspace/contracts?${new URLSearchParams({
+ contract: l.contract_id,
+ repo: l.provider_repo,
+ file: l.provider_file,
+ }).toString()}`
+ }
+ LinkComponent={Link}
+ onGeneratePrompt={() => setPrompt({ kind: "file" })}
+ />
+
+ <AiPromptModal
+ open={prompt !== null}
+ onOpenChange={(o) => !o && setPrompt(null)}
+ getPrompt={getPrompt}
+ filePath={
+ prompt?.kind === "repo"
+ ? `${prompt.pair.repo1} and ${prompt.pair.repo2}`
+ : openPair
+ ? `${openPair.source_file} and ${openPair.target_file}`
+ : null
+ }
+ title="AI co-change prompt"
+ description={
+ prompt?.kind === "repo"
+ ? "A ready-to-paste prompt that has your agent group this repository pair's co-changing files by the concept they share and decide which lockstep a contract, shared type or generated client should replace."
+ : "A ready-to-paste prompt that has your agent find why these two files change together and whether a contract, shared type or generated client should replace the manual lockstep."
+ }
+ />
+ </>
+ );
+}
diff --git a/packages/web/src/app/workspace/co-changes/page.tsx b/packages/web/src/app/workspace/co-changes/page.tsx
index 5c20eb19d..0612c8b62 100644
--- a/packages/web/src/app/workspace/co-changes/page.tsx
+++ b/packages/web/src/app/workspace/co-changes/page.tsx
@@ -4,13 +4,12 @@ import type { WorkspaceCoChangeEntry } from "@repowise-dev/api-client/types";
import { PageShell } from "@repowise-dev/ui/shared";
import { PageLede } from "@repowise-dev/ui/shared/page-lede";
import { EmptyState } from "@repowise-dev/ui/shared/empty-state";
-import { OverviewSection } from "@repowise-dev/ui/overview";
import { StatRibbon, type RibbonStat } from "@repowise-dev/ui/stats/stat-ribbon";
-import { CoChangeTable } from "@repowise-dev/ui/workspace/co-change-table";
import type { RepoPairSummary } from "@repowise-dev/ui/workspace/repo-pair-table";
import { formatNumber } from "@repowise-dev/ui/lib/format";
-import { getWorkspaceCoChanges } from "@/lib/api/workspace";
-import { RepoPairLinks } from "./repo-pair-links";
+import { repoPairId, STRENGTH_DEFINITION } from "@repowise-dev/ui/workspace/co-change-facts";
+import { getWorkspace, getWorkspaceCoChanges } from "@/lib/api/workspace";
+import { CoChangesExplorer } from "./co-changes-explorer";
export const metadata: Metadata = { title: "Co-changes" };
@@ -21,172 +20,132 @@ export const revalidate = 30;
const ROW_LIMIT = 500;
type Props = {
- searchParams: Promise<{ pair?: string }>;
+ searchParams: Promise<{ pair?: string; q?: string; cc?: string }>;
};
/**
* Cross-repo co-changes.
*
- * The three `MetricCard`s here were the clearest case in the workspace set of
- * figures that should not exist rather than figures that needed restyling:
- *
- * - "Avg Strength" averaged a heuristic across unrelated repository pairs,
- * over a list already sorted by that same heuristic and cut at 100 rows.
- * It could only ever report a high number. Peak strength replaces it,
- * because a maximum survives truncation that keeps the strongest rows.
- * - "Total Co-Change Pairs" reported the miner's own per-pair cap as though
- * it were a count of what exists.
- * - "Repo Pairs" was derived from the loaded page rather than the total.
- *
- * The view toggle and its drill-down went too: the rollup and the file pairs
- * are two altitudes of one subject, so they are two sections now, and choosing
- * a pair narrows the lower one instead of replacing the page.
+ * The server renders the figures; everything that responds to the reader (the
+ * repository-pair narrowing, the path search and the pair drawer) lives in one
+ * client leaf, which filters the rows it was handed instead of asking the
+ * server again. The URL still carries all three, so a narrowed list or an open
+ * pair is a linkable address.
*/
export default async function CoChangesPage({ searchParams }: Props) {
- const { pair } = await searchParams;
-
- const res = await Promise.allSettled([getWorkspaceCoChanges({ limit: ROW_LIMIT })]);
- const data = res[0].status === "fulfilled" ? res[0].value : null;
+ const { pair, q, cc } = await searchParams;
+
+ // One wave. The workspace call is what the layout already makes, and it
+ // gives the alias-to-repo-id map the drawer's file links need.
+ const [res, ws] = await Promise.allSettled([
+ getWorkspaceCoChanges({ limit: ROW_LIMIT }),
+ getWorkspace(),
+ ]);
+ const data = res.status === "fulfilled" ? res.value : null;
const coChanges = data?.co_changes ?? [];
// What the miner found before its own caps trimmed the artifact. Above
// coChanges.length means this page is the top of a longer list.
const totalMined = data?.total_mined ?? coChanges.length;
+ const repoIds: Record<string, string> = {};
+ if (ws.status === "fulfilled") {
+ for (const r of ws.value.repos) if (r.repo_id) repoIds[r.alias] = r.repo_id;
+ }
- const repoPairs = summarisePairs(coChanges);
- const selected = pair && repoPairs.some((p) => p.id === pair) ? pair : null;
- const filePairs = selected
- ? coChanges.filter((cc) => pairId(cc) === selected)
- : coChanges;
+ const icon = <GitMerge className="h-5 w-5 text-[var(--color-text-tertiary)]" />;
+ const description = "Files in different repositories that recent commits touched together.";
+
+ if (coChanges.length === 0) {
+ return (
+ <PageShell title="Co-changes" icon={icon} description={description}>
+ <EmptyState
+ title="No cross-repo co-changes found"
+ description="Co-changes are mined from each repository's git history during a workspace sync. Pairs appear once commits close together in time touch files in two repositories."
+ icon={<GitMerge className="h-8 w-8" />}
+ />
+ </PageShell>
+ );
+ }
+ const repoPairs = summarisePairs(coChanges);
const strongest = repoPairs[0] ?? null;
const mostRecent = coChanges.reduce<string>(
- (latest, cc) => (cc.last_date > latest ? cc.last_date : latest),
+ (latest, c) => (c.last_date > latest ? c.last_date : latest),
"",
);
+ const freqs = coChanges.map((c) => c.frequency);
+ const minFreq = Math.min(...freqs);
+ const maxFreq = Math.max(...freqs);
+ // The lede owns the file-pair count, so the ribbon does not repeat it.
const ribbon: RibbonStat[] = [
{
label: "Repository pairs",
- value: coChanges.length > 0 ? String(repoPairs.length) : "—",
- sub: "with at least one shared work session",
- },
- {
- label: "File pairs",
- value: coChanges.length > 0 ? formatNumber(coChanges.length) : "—",
- sub:
- totalMined > coChanges.length
- ? `of ${formatNumber(totalMined)} found; capped by the miner`
- : "every pair the miner found",
+ value: String(repoPairs.length),
+ sub: "with shared work sessions",
},
{
label: "Strongest pair",
- value: strongest ? `${strongest.repo1} ↔ ${strongest.repo2}` : "—",
- sub: "most tightly coupled by work pattern",
+ value: strongest ? `${strongest.repo1} and ${strongest.repo2}` : "",
+ sub: "by its strongest file pair",
},
{
label: "Peak strength",
- value: strongest ? `${Math.round(strongest.maxStrength * 100)}%` : "—",
+ value: strongest ? `${Math.round(strongest.maxStrength * 100)}%` : "",
+ hint: STRENGTH_DEFINITION,
sub: "the single strongest file pair",
},
+ {
+ label: "Sessions per pair",
+ value: minFreq === maxFreq ? String(minFreq) : `${minFreq} to ${maxFreq}`,
+ sub: "shared work sessions per file pair",
+ },
{
label: "Most recent",
- value: mostRecent ? mostRecent.slice(0, 10) : "—",
- sub: "last commit touching a linked pair",
+ value: mostRecent ? mostRecent.slice(0, 10) : "",
+ sub: "last shared session",
},
];
- if (coChanges.length === 0) {
- return (
- <PageShell
- title="Co-changes"
- icon={<GitMerge className="h-5 w-5 text-[var(--color-text-tertiary)]" />}
- description="Files in different repositories that recent commits touched together."
- >
- <EmptyState
- title="No cross-repo co-changes found"
- description="Co-changes are mined from each repository's git history during a workspace sync. Pairs appear once commits close together in time touch files in two repositories."
- icon={<GitMerge className="h-8 w-8" />}
- />
- </PageShell>
- );
- }
-
return (
- <PageShell
- title="Co-changes"
- icon={<GitMerge className="h-5 w-5 text-[var(--color-text-tertiary)]" />}
- description="Files in different repositories that recent commits touched together."
- >
+ <PageShell title="Co-changes" icon={icon} description={description}>
<PageLede
- label="Repository pairs"
- value={String(repoPairs.length)}
- unit="change together"
+ label="File pairs"
+ value={formatNumber(coChanges.length)}
+ unit={totalMined > coChanges.length ? `of ${formatNumber(totalMined)} found` : "found"}
layout="beside"
>
<p>
- {formatNumber(coChanges.length)} file pairs across{" "}
- {repoPairs.length === 1 ? "one repository pair" : `${repoPairs.length} repository pairs`}{" "}
- were touched in the same work sessions.
- {strongest && (
- <>
- {" "}
- {strongest.repo1} and {strongest.repo2} are the most tightly coupled, peaking at{" "}
- {Math.round(strongest.maxStrength * 100)}%.
- </>
- )}
- </p>
- <p>
- Strength is the share of the less-active file&rsquo;s recent sessions that also touched
- its partner. This is a work-pattern signal from git history, not a declared or verified
- dependency, so it is a place to start looking rather than proof of coupling.
- {totalMined > coChanges.length ? (
- <>
- {" "}
- The miner found {formatNumber(totalMined)} qualifying file pairs and kept the
- strongest {formatNumber(coChanges.length)}, so this is the top of the list rather
- than all of it.
- </>
- ) : (
- " Every pair the miner found is shown."
- )}
+ Files in two repositories that the same author keeps changing in the same work
+ sessions: a pattern read from git history, not a declared dependency.
</p>
</PageLede>
<StatRibbon stats={ribbon} />
- <OverviewSection
- title="Repository pairs"
- description="Ranked by their strongest file pair. Choose one to narrow the files below; choose it again to clear."
- >
- <RepoPairLinks repoPairs={repoPairs} />
- </OverviewSection>
-
- <OverviewSection
- title={selected ? `Files in ${selected.replace("↔", " and ")}` : "Files that change together"}
- description={
- selected
- ? `${formatNumber(filePairs.length)} file ${filePairs.length === 1 ? "pair" : "pairs"} in this repository pair, strongest first.`
- : `All ${formatNumber(filePairs.length)} file pairs, strongest first.`
- }
- >
- <CoChangeTable coChanges={filePairs} />
- </OverviewSection>
+ <CoChangesExplorer
+ coChanges={coChanges}
+ repoPairs={repoPairs}
+ totalMined={totalMined}
+ caps={{
+ truncatedBy: data?.truncated_by ?? null,
+ perRepoPairCap: data?.per_repo_pair_cap ?? null,
+ totalCap: data?.total_cap ?? null,
+ }}
+ repoIds={repoIds}
+ initialPair={pair && repoPairs.some((p) => p.id === pair) ? pair : null}
+ initialQuery={q ?? ""}
+ initialOpen={cc ?? null}
+ />
</PageShell>
);
}
-/** Stable id for a repo pair, order-independent so A→B and B→A are one pair. */
-function pairId(cc: WorkspaceCoChangeEntry): string {
- const [a, b] = [cc.source_repo, cc.target_repo].sort();
- return `${a}↔${b}`;
-}
-
/** Roll file pairs up to the repository pairs they connect. */
function summarisePairs(coChanges: WorkspaceCoChangeEntry[]): RepoPairSummary[] {
const map = new Map<string, RepoPairSummary>();
- for (const cc of coChanges) {
- const [repo1, repo2] = [cc.source_repo, cc.target_repo].sort();
- const id = `${repo1}↔${repo2}`;
+ for (const c of coChanges) {
+ const [repo1, repo2] = [c.source_repo, c.target_repo].sort() as [string, string];
+ const id = repoPairId(repo1, repo2);
const summary = map.get(id) ?? {
id,
repo1,
@@ -196,8 +155,8 @@ function summarisePairs(coChanges: WorkspaceCoChangeEntry[]): RepoPairSummary[]
lastDate: "",
};
summary.filePairCount += 1;
- if (cc.strength > summary.maxStrength) summary.maxStrength = cc.strength;
- if (cc.last_date > summary.lastDate) summary.lastDate = cc.last_date;
+ if (c.strength > summary.maxStrength) summary.maxStrength = c.strength;
+ if (c.last_date > summary.lastDate) summary.lastDate = c.last_date;
map.set(id, summary);
}
return [...map.values()].sort((a, b) => b.maxStrength - a.maxStrength);
diff --git a/packages/web/src/app/workspace/co-changes/repo-pair-links.tsx b/packages/web/src/app/workspace/co-changes/repo-pair-links.tsx
deleted file mode 100644
index e34657215..000000000
--- a/packages/web/src/app/workspace/co-changes/repo-pair-links.tsx
+++ /dev/null
@@ -1,42 +0,0 @@
-"use client";
-
-import { useRouter, useSearchParams } from "next/navigation";
-import { useTransition } from "react";
-import {
- RepoPairTable,
- type RepoPairSummary,
-} from "@repowise-dev/ui/workspace/repo-pair-table";
-
-/**
- * The repo-pair rollup, with selection kept in the URL.
- *
- * This replaces a `useState` drill-down that hid the file pairs behind a view
- * toggle and a Back button. Selecting a pair now narrows the section below
- * instead of navigating away from it, so both altitudes stay on screen and a
- * selected pair is a linkable address.
- */
-export function RepoPairLinks({ repoPairs }: { repoPairs: RepoPairSummary[] }) {
- const router = useRouter();
- const params = useSearchParams();
- const [, startTransition] = useTransition();
- const selected = params.get("pair");
-
- return (
- <RepoPairTable
- repoPairs={repoPairs}
- selectedPairId={selected}
- onSelectPair={(id) => {
- const next = new URLSearchParams(params.toString());
- // Clicking the selected pair clears it, so the control can undo itself.
- if (id === selected) next.delete("pair");
- else next.set("pair", id);
- startTransition(() => {
- router.push(
- next.size > 0 ? `?${next.toString()}` : "/workspace/co-changes",
- { scroll: false },
- );
- });
- }}
- />
- );
-}
diff --git a/tests/unit/server/test_workspace_router.py b/tests/unit/server/test_workspace_router.py
index 3e96d0684..c42879852 100644
--- a/tests/unit/server/test_workspace_router.py
+++ b/tests/unit/server/test_workspace_router.py
@@ -15,6 +15,7 @@ from fastapi import FastAPI
from fastapi.responses import JSONResponse
from httpx import ASGITransport, AsyncClient
+from repowise.core.workspace.cross_repo import MAX_EDGES, MAX_EDGES_PER_REPO_PAIR
from repowise.core.workspace.test_impact import (
UnresolvedLink,
WorkspaceTestImpactResult,
@@ -754,6 +755,82 @@ class TestGetCoChanges:
data = resp.json()
assert data["total"] == 0
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ ("stored", "total_mined", "expected"),
+ [
+ (1, 1, None), # nothing dropped
+ (1, 9, "per_repo_pair"), # trimmed below the global budget
+ (MAX_EDGES, MAX_EDGES + 5, "total"), # the workspace-wide cap stopped it
+ ],
+ )
+ async def test_reports_which_cap_trimmed(
+ self, tmp_path: Path, stored: int, total_mined: int, expected: str | None
+ ) -> None:
+ """The page words its scope from the cap that applied, not a guess."""
+ enricher = _make_enricher(tmp_path)
+ row = enricher._co_changes[0]
+ enricher._co_changes = [dict(row, source_file=f"f{i}.py") for i in range(stored)]
+ enricher._total_co_changes = total_mined
+ app = _make_workspace_app(ws_config=_make_ws_config(), enricher=enricher)
+ async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as c:
+ # A filter narrower than the overlay must not change the verdict.
+ resp = await c.get("/api/workspace/co-changes", params={"limit": 1})
+ data = resp.json()
+ assert data["truncated_by"] == expected
+ assert data["per_repo_pair_cap"] == MAX_EDGES_PER_REPO_PAIR
+ assert data["total_cap"] == MAX_EDGES
+
+
+class TestGetCoChangeStructure:
+ @staticmethod
+ async def _get(tmp_path: Path, **params: str) -> dict:
+ app = _make_workspace_app(ws_config=_make_ws_config(), enricher=_make_enricher(tmp_path))
+ async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as c:
+ resp = await c.get("/api/workspace/co-changes/structure", params=params)
+ assert resp.status_code == 200
+ return resp.json()
+
+ @pytest.mark.asyncio
+ async def test_pair_linked_by_contract(self, tmp_path: Path) -> None:
+ """Either orientation of the pair finds the link between the two files."""
+ data = await self._get(
+ tmp_path,
+ source_repo="frontend",
+ source_file="client.ts",
+ target_repo="backend",
+ target_file="routes.py",
+ )
+ assert [lk["contract_id"] for lk in data["pair_links"]] == ["http::GET::/api/users"]
+ assert data["repo_links_total"] == 1
+ assert data["repo_links_by_type"] == {"http": 1}
+ assert data["source_file_links"] == 1
+ assert data["target_file_links"] == 1
+
+ @pytest.mark.asyncio
+ async def test_pair_with_no_declared_link(self, tmp_path: Path) -> None:
+ """A pair the contracts do not connect still reports the repo-level links."""
+ data = await self._get(
+ tmp_path,
+ source_repo="backend",
+ source_file="api/routes.py",
+ target_repo="frontend",
+ target_file="src/client.ts",
+ )
+ assert data["pair_links"] == []
+ assert data["repo_links_total"] == 1
+ assert data["source_file_links"] == 0
+ assert data["target_file_links"] == 0
+
+ @pytest.mark.asyncio
+ async def test_all_four_params_required(self, tmp_path: Path) -> None:
+ app = _make_workspace_app(ws_config=_make_ws_config(), enricher=_make_enricher(tmp_path))
+ async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as c:
+ resp = await c.get(
+ "/api/workspace/co-changes/structure", params={"source_repo": "backend"}
+ )
+ assert resp.status_code == 422
+
# ---------------------------------------------------------------------------
# Tests — GET /api/workspace/graph
diff --git a/tests/unit/workspace/test_cross_repo.py b/tests/unit/workspace/test_cross_repo.py
index f4accdfb2..fc1fdc686 100644
--- a/tests/unit/workspace/test_cross_repo.py
+++ b/tests/unit/workspace/test_cross_repo.py
@@ -395,7 +395,7 @@ class TestCrossRepoCoChanges:
# 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):
+ with patch.object(cr, "MAX_EDGES_PER_REPO_PAIR", 5):
results = self._detect_with_mocked_logs(
{
"a": _make_commits("a", ab_a + ac_a),
@@ -439,7 +439,7 @@ class TestCoChangeTruncationTotals:
]
import repowise.core.workspace.cross_repo as cr
- with patch.object(cr, "_MAX_EDGES_PER_REPO_PAIR", 3):
+ with patch.object(cr, "MAX_EDGES_PER_REPO_PAIR", 3):
results, total = self._detect(
{"a": _make_commits("a", commits_a), "b": _make_commits("b", commits_b)},
min_score=0.0,