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(web): put the workspace pages on the design language (#1582)

Raghav Chamadiya254b6448a380
diff --git a/packages/api-client/src/types/workspace.ts b/packages/api-client/src/types/workspace.ts
index efe138815..dded80dd2 100644
--- a/packages/api-client/src/types/workspace.ts
+++ b/packages/api-client/src/types/workspace.ts
@@ -15,6 +15,10 @@ export interface WorkspaceRepoEntry {
page_count: number;
doc_coverage_pct: number;
hotspot_count: number;
+ // Canonical 0-100 health score. Optional so a frontend ahead of its server
+ // degrades rather than rendering NaN; null means "not measured", which is
+ // not the same as a measured zero.
+ health_score?: number | null;
// Phase B server augmentation
status?: "indexed" | "needs_index" | "missing_dir" | null;
docs_enabled?: boolean | null;
diff --git a/packages/api-client/src/workspace.ts b/packages/api-client/src/workspace.ts
index 80e9e3780..8454dd2b2 100644
--- a/packages/api-client/src/workspace.ts
+++ b/packages/api-client/src/workspace.ts
@@ -10,6 +10,7 @@ import type {
WorkspaceBreakingChangesResponse,
WorkspaceConformanceResponse,
WorkspaceArchitectureResponse,
+ ExtractionDiagnostics,
} from "./types";
export async function getWorkspace(
@@ -50,6 +51,24 @@ export async function getWorkspaceGraph(): Promise<WorkspaceGraphResponse> {
return apiGet<WorkspaceGraphResponse>("/api/workspace/graph");
}
+/**
+ * Why the cross-repo link count is what it is: providers and consumers found,
+ * consumers that matched nothing and why, and providers nobody calls.
+ *
+ * These are the denominators the Contracts page needs. Without them the only
+ * available totals are the filtered, paginated contract rows, which cannot say
+ * how much of the workspace they represent.
+ */
+export async function getWorkspaceDiagnostics(
+ fetchOptions?: RequestInit,
+): Promise<ExtractionDiagnostics> {
+ return apiGet<ExtractionDiagnostics>(
+ "/api/workspace/diagnostics",
+ undefined,
+ fetchOptions,
+ );
+}
+
/**
* The service-granular system graph (nodes = services, typed directed edges)
* that the Live System Map renders. Thin pass-through over the persisted
diff --git a/packages/server/src/repowise/server/routers/workspace.py b/packages/server/src/repowise/server/routers/workspace.py
index de8e02f91..9d99c044f 100644
--- a/packages/server/src/repowise/server/routers/workspace.py
+++ b/packages/server/src/repowise/server/routers/workspace.py
@@ -84,8 +84,8 @@ def _compute_health_score(file_count: int, doc_coverage_pct: float, hotspot_coun
return max(0, min(100, round(coverage_component + hotspot_component)))
-def _resolve_graph_health_score(db_path: Path, stats: dict) -> tuple[float, str]:
- canonical = read_repo_health_score(db_path)
+def _resolve_graph_health_score(stats: dict) -> tuple[float, str]:
+ canonical = stats.get("health_score")
if canonical is not None:
return canonical, "canonical"
return (
@@ -104,8 +104,11 @@ def _query_repo_stats(db_path: Path) -> dict:
"""Query basic stats from a repo's wiki.db using raw sqlite3.
Returns a dict with repo_id, file_count, symbol_count, page_count,
- doc_coverage_pct, hotspot_count, status, docs_enabled, and
+ doc_coverage_pct, hotspot_count, health_score, status, docs_enabled, and
docs_skip_reason. All values default to sensible neutrals on error.
+
+ ``health_score`` is None when the repo carries no health metrics; callers
+ decide whether to fall back to a derived score or to render nothing.
"""
result: dict = {
"repo_id": None,
@@ -114,6 +117,7 @@ def _query_repo_stats(db_path: Path) -> dict:
"page_count": 0,
"doc_coverage_pct": 0.0,
"hotspot_count": 0,
+ "health_score": None,
"status": "needs_index",
"docs_enabled": False,
"docs_skip_reason": None,
@@ -173,6 +177,10 @@ def _query_repo_stats(db_path: Path) -> dict:
conn.close()
except Exception:
_log.debug("Failed to query stats from %s", db_path, exc_info=True)
+
+ # Read once here rather than per-endpoint: both the workspace listing and
+ # the graph need the canonical score, and this used to be a second sweep.
+ result["health_score"] = read_repo_health_score(db_path)
return result
@@ -406,7 +414,7 @@ async def get_workspace_graph(
db_path = repo_path / ".repowise" / "wiki.db"
stats = _query_repo_stats(db_path)
top_language = _query_top_language(db_path)
- health_score, health_score_source = _resolve_graph_health_score(db_path, stats)
+ health_score, health_score_source = _resolve_graph_health_score(stats)
else:
health_score = 0.0
health_score_source = "derived"
diff --git a/packages/server/src/repowise/server/schemas/workspace.py b/packages/server/src/repowise/server/schemas/workspace.py
index 753e22b56..39ae6af3a 100644
--- a/packages/server/src/repowise/server/schemas/workspace.py
+++ b/packages/server/src/repowise/server/schemas/workspace.py
@@ -18,6 +18,10 @@ class WorkspaceRepoEntry(BaseModel):
page_count: int = 0
doc_coverage_pct: float = 0.0
hotspot_count: int = 0
+ # Canonical 0-100 health score, or None when the repo carries no health
+ # metrics. Nullable rather than 0.0 so the UI can tell "not measured"
+ # apart from "measured as zero".
+ health_score: float | None = None
# Lifecycle status — surfaced so the web UI can render "needs index"
# or "missing directory" affordances instead of silently dropping the
# repo from the sidebar.
diff --git a/packages/server/src/repowise/server/services/module_health.py b/packages/server/src/repowise/server/services/module_health.py
index e5f6f3d49..8e194a886 100644
--- a/packages/server/src/repowise/server/services/module_health.py
+++ b/packages/server/src/repowise/server/services/module_health.py
@@ -257,31 +257,30 @@ def read_repo_health_score(db_path: Path) -> float | None:
"""Return the canonical repo health score from a repo-local wiki.db."""
if not db_path.exists():
return None
+ # Aggregate in SQL rather than reading every row. A workspace calls this once
+ # per repo, and the fetchall() this replaces read ~6,000 rows per repo to
+ # produce one number: 61.6ms against 33.2ms across six large repos, and the
+ # row count grows with the repo. MAX(CAST(..), 1) reproduces the previous
+ # `max(int(nloc or 0), 1)` weight, truncation included; verified identical on
+ # 109 real databases.
try:
with sqlite3.connect(str(db_path)) as conn:
row = conn.execute(
- "SELECT score, COALESCE(nloc, 1) FROM health_file_metrics"
- ).fetchall()
+ "SELECT SUM(score * w), SUM(w) FROM ("
+ " SELECT score, MAX(CAST(COALESCE(nloc, 0) AS INTEGER), 1) AS w"
+ " FROM health_file_metrics WHERE score IS NOT NULL"
+ ")"
+ ).fetchone()
except sqlite3.OperationalError:
return None
except Exception:
return None
- if not row:
+ if not row or not row[1]:
return None
- weights = [max(int(nloc or 0), 1) for _, nloc in row]
- total_weight = sum(weights)
- if total_weight:
- average = (
- sum(
- float(score) * weight
- for (score, _), weight in zip(row, weights, strict=True)
- )
- / total_weight
- )
- else:
- average = sum(float(score) for score, _ in row) / len(row)
+ weighted_sum, total_weight = row
+ average = float(weighted_sum) / float(total_weight)
return max(0.0, min(100.0, round(average * 10.0, 1)))
diff --git a/packages/ui/src/workspace/co-change-table.tsx b/packages/ui/src/workspace/co-change-table.tsx
index fbef91b10..e81c2c2a2 100644
--- a/packages/ui/src/workspace/co-change-table.tsx
+++ b/packages/ui/src/workspace/co-change-table.tsx
@@ -3,6 +3,7 @@
import { Badge } from "../ui/badge";
import { EmptyState } from "../shared/empty-state";
import { VirtualizedTable } from "../shared/virtualized-table";
+import { formatDate, formatDateTime } from "../lib/format";
import type { WorkspaceCoChangeEntry } from "@repowise-dev/types/workspace";
interface CoChangeTableProps {
@@ -91,8 +92,11 @@ export function CoChangeTable({ coChanges, compact }: CoChangeTableProps) {
{`${cc.frequency}x`}
</td>
<td className={`px-3 py-2 text-left text-xs text-[var(--color-text-tertiary)] ${HIDE_BELOW_LG}`}>
- <span title={cc.last_date ? new Date(cc.last_date).toLocaleString() : undefined}>
- {cc.last_date ? new Date(cc.last_date).toLocaleDateString() : "—"}
+ {/* 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) : "—"}
</span>
</td>
</>
diff --git a/packages/ui/src/workspace/repo-pair-table.tsx b/packages/ui/src/workspace/repo-pair-table.tsx
index e8f41b5e2..66529a8fe 100644
--- a/packages/ui/src/workspace/repo-pair-table.tsx
+++ b/packages/ui/src/workspace/repo-pair-table.tsx
@@ -5,6 +5,7 @@ import { EmptyState } from "../shared/empty-state";
import { VirtualizedTable } from "../shared/virtualized-table";
import { clickableRowProps, CLICKABLE_ROW_CLS } from "../shared/responsive-table";
import { cn } from "../lib/cn";
+import { formatDate, formatDateTime } from "../lib/format";
import { ChevronRight } from "lucide-react";
export interface RepoPairSummary {
@@ -91,8 +92,11 @@ export function RepoPairTable({ repoPairs, onSelectPair, selectedPairId }: RepoP
</div>
</td>
<td className={`px-3 py-2 text-right text-xs text-[var(--color-text-tertiary)] ${HIDE_BELOW_LG}`}>
- <span title={p.lastDate ? new Date(p.lastDate).toLocaleString() : undefined}>
- {p.lastDate ? new Date(p.lastDate).toLocaleDateString() : "—"}
+ {/* 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 ? (
diff --git a/packages/web/src/app/workspace/co-changes/page.tsx b/packages/web/src/app/workspace/co-changes/page.tsx
index 068a4f99e..559cf4bf8 100644
--- a/packages/web/src/app/workspace/co-changes/page.tsx
+++ b/packages/web/src/app/workspace/co-changes/page.tsx
@@ -1,204 +1,190 @@
-"use client";
-
-import { useState, useMemo } from "react";
-import { GitMerge, Filter, ArrowLeft, LayoutList, Columns } from "lucide-react";
-import { useWorkspaceCoChanges, useWorkspace } from "@/lib/hooks/use-workspace";
+import type { Metadata } from "next";
+import { GitMerge } from "lucide-react";
+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 { RepoPairTable, type RepoPairSummary } from "@repowise-dev/ui/workspace/repo-pair-table";
-import { Card, CardContent, CardHeader, CardTitle } from "@repowise-dev/ui/ui/card";
-import { MetricCard } from "@repowise-dev/ui/shared/metric-card";
-import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
-import { Button } from "@repowise-dev/ui/ui/button";
-
-export default function CoChangesPage() {
- const { workspace } = useWorkspace();
- const [repo, setRepo] = useState("");
- const [viewMode, setViewMode] = useState<"pairs" | "flat">("pairs");
- const [selectedPairId, setSelectedPairId] = useState<string | null>(null);
-
- const { data, isLoading } = useWorkspaceCoChanges({
- repo: repo || undefined,
- limit: 100,
- });
-
- const repos = workspace?.repos ?? [];
-
- const selectClass =
- "rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-3 py-1.5 text-sm text-[var(--color-text-primary)] outline-none focus:border-[var(--color-accent-primary)]";
-
- const repoPairs = useMemo(() => {
- if (!data?.co_changes) return [];
- const map = new Map<string, RepoPairSummary>();
- for (const cc of data.co_changes) {
- const sorted = [cc.source_repo, cc.target_repo].sort();
- const id = `${sorted[0]}↔${sorted[1]}`;
-
- if (!map.has(id)) {
- map.set(id, {
- id,
- repo1: sorted[0],
- repo2: sorted[1],
- filePairCount: 0,
- maxStrength: 0,
- lastDate: "",
- });
- }
- const summary = map.get(id)!;
- summary.filePairCount += 1;
- if (cc.strength > summary.maxStrength) {
- summary.maxStrength = cc.strength;
- }
- if (!summary.lastDate || cc.last_date > summary.lastDate) {
- summary.lastDate = cc.last_date;
- }
- }
- return Array.from(map.values()).sort((a, b) => b.maxStrength - a.maxStrength);
- }, [data?.co_changes]);
-
- const displayedCoChanges = useMemo(() => {
- if (!data?.co_changes) return [];
- if (viewMode === "pairs" && selectedPairId) {
- return data.co_changes.filter((cc) => {
- const sorted = [cc.source_repo, cc.target_repo].sort();
- return `${sorted[0]}↔${sorted[1]}` === selectedPairId;
- });
- }
- return data.co_changes;
- }, [data?.co_changes, viewMode, selectedPairId]);
+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";
- return (
- <div className="p-5 sm:p-8 space-y-6 max-w-[1200px]">
- {/* Header */}
- <div>
- <div className="flex items-center justify-between mb-1">
- <div className="flex items-center gap-2.5">
- <GitMerge className="h-6 w-6 text-[var(--color-accent-primary)]" />
- <h1 className="text-2xl font-semibold text-[var(--color-text-primary)]">
- Co-Changes
- </h1>
- </div>
- <div className="flex items-center rounded-md border border-[var(--color-border-default)] p-1 bg-[var(--color-bg-surface)]">
- <button
- onClick={() => { setViewMode("pairs"); setSelectedPairId(null); }}
- className={`flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium rounded transition-colors ${
- viewMode === "pairs"
- ? "bg-[var(--color-bg-elevated)] text-[var(--color-text-primary)] shadow-sm"
- : "text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]"
- }`}
- >
- <Columns className="h-4 w-4" />
- Repo Pairs
- </button>
- <button
- onClick={() => { setViewMode("flat"); setSelectedPairId(null); }}
- className={`flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium rounded transition-colors ${
- viewMode === "flat"
- ? "bg-[var(--color-bg-elevated)] text-[var(--color-text-primary)] shadow-sm"
- : "text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]"
- }`}
- >
- <LayoutList className="h-4 w-4" />
- Flat List
- </button>
- </div>
- </div>
- <p className="text-sm text-[var(--color-text-secondary)] mt-2">
- Files the same author tends to change in the same work sessions across
- repositories. Strength is the share of the less-active file&apos;s recent
- sessions that also touched the partner. This is a temporal work-pattern
- hint from git history, not a verified technical dependency, so treat it
- as a starting point for inspection rather than proof of coupling.
- </p>
- </div>
-
- {/* Summary */}
- <div className="grid grid-cols-2 gap-3 lg:grid-cols-3">
- <MetricCard
- label="Total Co-Change Pairs"
- value={data?.total ?? "—"}
- icon={<GitMerge className="h-4 w-4 text-[var(--color-accent-primary)]" />}
- />
- <MetricCard
- label="Repo Pairs"
- value={data?.co_changes ? repoPairs.length : "—"}
- icon={<GitMerge className="h-4 w-4 text-[var(--color-accent-secondary)]" />}
- />
- <MetricCard
- label="Avg Strength"
- value={
- data?.co_changes && data.co_changes.length > 0
- ? `${Math.round(
- (data.co_changes.reduce((sum, cc) => sum + cc.strength, 0) /
- data.co_changes.length) *
- 100,
- )}%`
- : "—"
- }
- icon={<GitMerge className="h-4 w-4 text-[var(--color-accent-primary)]" />}
+export const metadata: Metadata = { title: "Co-changes" };
+
+export const revalidate = 30;
+
+/** The endpoint's ceiling. Asked for in full so the table is not a second,
+ * narrower cap on top of the one the miner already applied. */
+const ROW_LIMIT = 500;
+
+type Props = {
+ searchParams: Promise<{ pair?: 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.
+ */
+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 coChanges = data?.co_changes ?? [];
+
+ 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 strongest = repoPairs[0] ?? null;
+ const mostRecent = coChanges.reduce<string>(
+ (latest, cc) => (cc.last_date > latest ? cc.last_date : latest),
+ "",
+ );
+
+ 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: "capped per repository pair by the miner",
+ },
+ {
+ label: "Strongest pair",
+ value: strongest ? `${strongest.repo1} ↔ ${strongest.repo2}` : "—",
+ sub: "most tightly coupled by work pattern",
+ },
+ {
+ label: "Peak strength",
+ value: strongest ? `${Math.round(strongest.maxStrength * 100)}%` : "—",
+ sub: "the single strongest file pair",
+ },
+ {
+ label: "Most recent",
+ value: mostRecent ? mostRecent.slice(0, 10) : "—",
+ sub: "last commit touching a linked pair",
+ },
+ ];
+
+ 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" />}
/>
- </div>
-
- {/* Filters */}
- <div className="flex items-center justify-between">
- {viewMode === "pairs" && selectedPairId ? (
- <Button
- variant="outline"
- size="sm"
- onClick={() => setSelectedPairId(null)}
- className="flex items-center gap-1.5"
- >
- <ArrowLeft className="h-4 w-4" />
- Back to Repo Pairs
- </Button>
- ) : (
- <div className="flex items-center gap-3">
- <Filter className="h-4 w-4 text-[var(--color-text-tertiary)]" />
- <span className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider">
- Filter
- </span>
- <select
- value={repo}
- onChange={(e) => setRepo(e.target.value)}
- className={selectClass}
- >
- <option value="">All Repos</option>
- {repos.map((r) => (
- <option key={r.alias} value={r.alias}>
- {r.alias}
- </option>
- ))}
- </select>
- </div>
- )}
- </div>
-
- {/* Table */}
- <Card>
- <CardHeader className="pb-2">
- <CardTitle className="text-sm font-medium">
- {viewMode === "pairs" && !selectedPairId
- ? `Repo Pairs (${repoPairs.length})`
- : `Co-Change Pairs (${displayedCoChanges.length})`}
- </CardTitle>
- </CardHeader>
- <CardContent className="pt-0">
- {isLoading ? (
- <div className="space-y-3 py-4">
- {Array.from({ length: 8 }).map((_, i) => (
- <Skeleton key={i} className="h-10 w-full" />
- ))}
- </div>
- ) : viewMode === "pairs" && !selectedPairId ? (
- <RepoPairTable
- repoPairs={repoPairs}
- onSelectPair={setSelectedPairId}
- selectedPairId={selectedPairId}
- />
- ) : (
- <CoChangeTable coChanges={displayedCoChanges} />
+ </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."
+ >
+ <PageLede
+ label="Repository pairs"
+ value={String(repoPairs.length)}
+ unit="change together"
+ 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)}%.
+ </>
)}
- </CardContent>
- </Card>
- </div>
+ </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. The miner
+ keeps only the strongest file pairs for each repository pair, so this is the top of the
+ list rather than all of it.
+ </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>
+ </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}`;
+ const summary = map.get(id) ?? {
+ id,
+ repo1,
+ repo2,
+ filePairCount: 0,
+ maxStrength: 0,
+ lastDate: "",
+ };
+ summary.filePairCount += 1;
+ if (cc.strength > summary.maxStrength) summary.maxStrength = cc.strength;
+ if (cc.last_date > summary.lastDate) summary.lastDate = cc.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
new file mode 100644
index 000000000..e34657215
--- /dev/null
+++ b/packages/web/src/app/workspace/co-changes/repo-pair-links.tsx
@@ -0,0 +1,42 @@
+"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/packages/web/src/app/workspace/conformance/conformance-ai-prompt.tsx b/packages/web/src/app/workspace/conformance/conformance-ai-prompt.tsx
new file mode 100644
index 000000000..036b47232
--- /dev/null
+++ b/packages/web/src/app/workspace/conformance/conformance-ai-prompt.tsx
@@ -0,0 +1,51 @@
+"use client";
+
+import { useState } from "react";
+import {
+ AiPromptButton,
+ AiPromptModal,
+ buildConformanceAiPrompt,
+} from "@repowise-dev/ui/health";
+import type { ConformanceViolation } from "@repowise-dev/api-client/types";
+
+/**
+ * The one piece of state on this page: whether the prompt dialog is open.
+ *
+ * Kept in its own boundary so the report itself stays server-rendered — the
+ * page used to be a client component in full, which put a hydration boundary
+ * above every figure on it for the sake of one modal.
+ */
+export function ConformanceAiPrompt({
+ violations,
+}: {
+ violations: ConformanceViolation[];
+}) {
+ const [open, setOpen] = useState(false);
+
+ return (
+ <>
+ <AiPromptButton label="Fix violations with AI" onClick={() => setOpen(true)} />
+ <AiPromptModal
+ open={open}
+ onOpenChange={setOpen}
+ getPrompt={(flavor) =>
+ buildConformanceAiPrompt({
+ violations: violations.map((v) => ({
+ source: v.source,
+ target: v.target,
+ source_name: v.source_name,
+ target_name: v.target_name,
+ edge_kind: v.edge_kind,
+ rule_source: v.rule_source,
+ rule_target: v.rule_target,
+ rule_description: v.rule_description,
+ })),
+ flavor,
+ })
+ }
+ title="AI conformance fix"
+ description="A ready-to-paste prompt that has your AI agent resolve these architecture rule violations by removing the disallowed dependencies."
+ />
+ </>
+ );
+}
diff --git a/packages/web/src/app/workspace/conformance/page.tsx b/packages/web/src/app/workspace/conformance/page.tsx
index 87cb2ed31..bf1877278 100644
--- a/packages/web/src/app/workspace/conformance/page.tsx
+++ b/packages/web/src/app/workspace/conformance/page.tsx
@@ -1,222 +1,324 @@
-"use client";
-
-import { useMemo, useState } from "react";
-import { useRouter } from "next/navigation";
-import { ShieldCheck, ShieldAlert, RefreshCw, Waypoints, ListChecks, Gauge } from "lucide-react";
+import type { Metadata } from "next";
+import Link from "next/link";
+import { ShieldCheck } from "lucide-react";
+import type {
+ ConformanceReport,
+ ArchitectureMetrics,
+} from "@repowise-dev/api-client/types";
+import { PageShell } from "@repowise-dev/ui/shared";
+import { PageLede, LedeLink } from "@repowise-dev/ui/shared/page-lede";
+import { EmptyState } from "@repowise-dev/ui/shared/empty-state";
+import { OverviewSection, SectionLink } from "@repowise-dev/ui/overview";
+import { StatRibbon, type RibbonStat } from "@repowise-dev/ui/stats/stat-ribbon";
import { buildDsm, DsmMatrixView } from "@repowise-dev/ui/workspace/dsm";
-import { AiPromptButton, AiPromptModal, buildConformanceAiPrompt } from "@repowise-dev/ui/health";
-import { Card, CardContent, CardHeader, CardTitle } from "@repowise-dev/ui/ui/card";
-import { MetricCard } from "@repowise-dev/ui/shared/metric-card";
-import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
+import { formatNumber } from "@repowise-dev/ui/lib/format";
import {
- useWorkspaceSystemGraph,
- useWorkspaceConformance,
- useWorkspaceArchitecture,
-} from "@/lib/hooks/use-workspace";
-
-export default function ConformancePage() {
- const router = useRouter();
- const [promptOpen, setPromptOpen] = useState(false);
- const { data: graph, isLoading: graphLoading } = useWorkspaceSystemGraph();
- const { data: report, isLoading: reportLoading } = useWorkspaceConformance();
- const { data: metrics } = useWorkspaceArchitecture();
-
- const isLoading = graphLoading || reportLoading;
- const matrix = useMemo(() => buildDsm(graph, report), [graph, report]);
-
- const violations = report?.violations ?? [];
+ getWorkspaceSystemGraph,
+ getWorkspaceConformance,
+ getWorkspaceArchitecture,
+} from "@/lib/api/workspace";
+import { ConformanceAiPrompt } from "./conformance-ai-prompt";
+
+export const metadata: Metadata = { title: "Conformance" };
+
+export const revalidate = 30;
+
+/**
+ * The matrix counts a co-change relationship as a filled cell and the ribbon's
+ * structural-link figure does not, so the two numbers differ by design and sit
+ * a few hundred pixels apart. Reconciled in the copy rather than left for the
+ * reader to work out, and stated here rather than changing the shared matrix's
+ * own caption, which is accurate for what it counts.
+ */
+const DSM_DESCRIPTION =
+ "Each filled cell means the row service depends on the column service, tinted by transport. Red cells break a declared rule; amber cells sit on a cycle. The matrix counts co-change relationships too, so its total runs above the structural-link figure above.";
+
+/**
+ * Whether the conformance analyser has ever produced this report.
+ *
+ * The artifact is written with `generated_at: ""` and every count at zero
+ * before anything runs, which is indistinguishable from a clean pass unless
+ * this is checked — and a clean pass is what the page used to show. Three
+ * states have to stay separate: never ran, ran with no rules to check, and ran
+ * against real rules.
+ *
+ * Reads only fields already on the wire. Phase 4 of the workspace overhaul
+ * replaces the empty string with a proper null and adds the same distinction
+ * to the CLI and the artifact; this is the frontend half, and it should follow
+ * that contract when it lands rather than keeping the empty-string check
+ * forever.
+ */
+function reportState(
+ report: ConformanceReport | null,
+): "unavailable" | "never_ran" | "no_rules" | "checked" {
+ if (!report) return "unavailable";
+ if (!report.generated_at) return "never_ran";
+ if ((report.rules_evaluated ?? 0) === 0) return "no_rules";
+ return "checked";
+}
+
+export default async function ConformancePage() {
+ const [sg, cf, arch] = await Promise.allSettled([
+ getWorkspaceSystemGraph(),
+ getWorkspaceConformance(),
+ getWorkspaceArchitecture(),
+ ]);
+
+ const graph = sg.status === "fulfilled" ? sg.value : null;
+ const report = cf.status === "fulfilled" ? cf.value : null;
+ const metrics = arch.status === "fulfilled" ? arch.value : null;
+
+ const state = reportState(report);
+ const violations = state === "checked" ? (report?.violations ?? []) : [];
+ // Cycle *membership* comes from the report, but the count is recomputed from
+ // the graph on every request, so it stays true even when nothing has run.
const cycles = report?.cycles ?? [];
+ const cycleCount = metrics?.cycle_count ?? cycles.length;
+
+ const matrix = buildDsm(graph, report);
+
+ const ribbon: RibbonStat[] = [
+ {
+ label: "Services",
+ value: metrics ? formatNumber(metrics.node_count) : "—",
+ sub: "repositories and their sub-packages",
+ },
+ {
+ label: "Structural links",
+ value: metrics ? formatNumber(metrics.structural_edge_count) : "—",
+ sub: "contracts and imports, not co-changes",
+ },
+ {
+ label: "Propagation cost",
+ value: metrics ? `${metrics.propagation_cost_pct.toFixed(1)}%` : "—",
+ sub: "of the system a change can reach",
+ },
+ {
+ label: "Core size",
+ value: metrics ? formatNumber(metrics.core_size) : "—",
+ sub: metrics
+ ? `${Math.round(metrics.core_ratio * 100)}% of all services`
+ : "mutually dependent centre",
+ },
+ {
+ label: "Cycles",
+ value: metrics ? formatNumber(cycleCount) : "—",
+ sub: "circular service dependencies",
+ },
+ ];
return (
- <div className="p-5 sm:p-8 space-y-6 max-w-[1400px]">
- <div>
- <div className="flex items-center gap-2.5 mb-1">
- <ShieldCheck className="h-6 w-6 text-[var(--color-accent-primary)]" />
- <h1 className="text-2xl font-semibold text-[var(--color-text-primary)]">
- Architecture Conformance
- </h1>
- </div>
- <p className="text-sm text-[var(--color-text-secondary)]">
- Declared dependency rules checked against the live system graph, plus any
- circular service dependencies. Declare rules under{" "}
- <code className="text-[var(--color-text-primary)]">conformance:</code> in
- your <code className="text-[var(--color-text-primary)]">.repowise-workspace.yaml</code>;
- run <code className="text-[var(--color-text-primary)]">repowise workspace check</code> to
- gate CI.
- </p>
- </div>
-
- <div className="grid grid-cols-2 gap-3 lg:grid-cols-4">
- <MetricCard
- label="Architecture score"
- value={metrics ? `${metrics.score.toFixed(1)} / 10` : "—"}
- description={
- metrics
- ? `${metrics.architecture_type} · ${metrics.propagation_cost_pct.toFixed(1)}% propagation cost`
- : "Coupling + core roll-up"
- }
- icon={<Gauge className="h-4 w-4 text-[var(--color-accent-primary)]" />}
- />
- <MetricCard
- label="Rules evaluated"
- value={isLoading ? "—" : (report?.rules_evaluated ?? 0)}
- icon={<ListChecks className="h-4 w-4 text-[var(--color-accent-secondary)]" />}
- />
- <MetricCard
- label="Violations"
- value={isLoading ? "—" : violations.length}
- description="Dependencies that break a declared rule"
- icon={<ShieldAlert className="h-4 w-4 text-[var(--color-risk-high)]" />}
- />
- <MetricCard
- label="Dependency cycles"
- value={isLoading ? "—" : cycles.length}
- description="Circular service dependencies"
- icon={<RefreshCw className="h-4 w-4 text-[var(--color-warning)]" />}
- />
- </div>
-
- {/* DSM */}
- <Card>
- <CardHeader className="pb-2 flex-row items-center justify-between">
- <CardTitle className="text-sm font-medium">
- Dependency-structure matrix
- </CardTitle>
- <button
- type="button"
- onClick={() => router.push("/workspace/system-map")}
- className="inline-flex items-center gap-1.5 text-xs text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)]"
- >
- <Waypoints className="h-3.5 w-3.5" />
- Open System Map
- </button>
- </CardHeader>
- <CardContent className="pt-0">
- <p className="text-xs text-[var(--color-text-tertiary)] mb-3">
- Each filled cell means the row service depends on the column service,
- tinted by transport. Red cells break a rule; amber cells sit on a cycle.
+ <PageShell
+ title="Conformance"
+ icon={<ShieldCheck className="h-5 w-5 text-[var(--color-text-tertiary)]" />}
+ description="How the workspace is shaped, and whether it obeys the dependency rules you declared."
+ >
+ <PageLede
+ label="Architecture score"
+ value={metrics ? metrics.score.toFixed(1) : "—"}
+ unit="out of 10"
+ {...(metrics?.architecture_type
+ ? { band: { label: metrics.architecture_type } }
+ : {})}
+ layout="beside"
+ action={
+ <LedeLink href="/workspace/system-map" LinkComponent={Link}>
+ See the system map
+ </LedeLink>
+ }
+ >
+ {metrics ? (
+ <p>
+ A change here can reach {metrics.propagation_cost_pct.toFixed(1)}% of the system
+ through {formatNumber(metrics.structural_edge_count)} structural links between{" "}
+ {formatNumber(metrics.node_count)} services. The score weighs that reach against
+ the size of the mutually dependent core and any cycles; it is computed from the
+ system graph on every request, so it does not depend on the check below having run.
</p>
- {isLoading ? (
- <Skeleton className="h-72 w-full" />
- ) : (
- <DsmMatrixView matrix={matrix} {...(metrics ? { metrics } : {})} />
- )}
- </CardContent>
- </Card>
-
- {/* Governance findings */}
- <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
- <Card>
- <CardHeader className="pb-2 flex-row items-center justify-between gap-2">
- <CardTitle className="text-sm font-medium inline-flex items-center gap-2">
- <ShieldAlert className="h-4 w-4 text-[var(--color-risk-high)]" />
- Rule violations ({violations.length})
- </CardTitle>
- {violations.length > 0 && (
- <AiPromptButton
- label="Fix violations with AI"
- onClick={() => setPromptOpen(true)}
- />
- )}
- </CardHeader>
- <CardContent className="pt-0 space-y-3">
- {isLoading ? (
- <Skeleton className="h-20 w-full" />
- ) : violations.length === 0 ? (
- <p className="text-sm text-[var(--color-text-tertiary)]">
- {report && report.rules_evaluated > 0
- ? "No dependencies violate the declared rules."
- : "No rules declared yet. Add a conformance block to start enforcing allowed dependencies."}
- </p>
- ) : (
- violations.map((v) => (
- <div
- key={`${v.edge_id}:${v.rule_source}:${v.rule_target}`}
- className="rounded-md border border-[var(--color-border-subtle)] p-3 text-sm"
- >
- <div className="flex items-center gap-2 flex-wrap">
- <span className="font-semibold text-[var(--color-text-primary)]">
- {v.source_name || v.source}
- </span>
- <span className="text-[var(--color-text-tertiary)]">→</span>
- <span className="font-semibold text-[var(--color-text-primary)]">
- {v.target_name || v.target}
- </span>
- <span className="text-xs text-[var(--color-text-tertiary)]">
- ({v.edge_kind})
- </span>
- </div>
- <div className="text-[var(--color-text-secondary)] mt-1">
- breaks{" "}
- <code className="text-[var(--color-warning)]">
- {v.rule_source} !-&gt; {v.rule_target}
- </code>
- </div>
- {v.rule_description && (
- <div className="text-xs text-[var(--color-text-tertiary)] mt-1">
- {v.rule_description}
- </div>
- )}
- </div>
- ))
- )}
- </CardContent>
- </Card>
-
- <Card>
- <CardHeader className="pb-2">
- <CardTitle className="text-sm font-medium inline-flex items-center gap-2">
- <RefreshCw className="h-4 w-4 text-[var(--color-warning)]" />
- Dependency cycles ({cycles.length})
- </CardTitle>
- </CardHeader>
- <CardContent className="pt-0 space-y-3">
- {isLoading ? (
- <Skeleton className="h-20 w-full" />
- ) : cycles.length === 0 ? (
- <p className="text-sm text-[var(--color-text-tertiary)]">
- No circular service dependencies detected.
- </p>
- ) : (
- cycles.map((c) => (
- <div
- key={c.nodes.join("->")}
- className="rounded-md border border-[var(--color-border-subtle)] p-3 text-sm"
- >
- <div className="text-xs uppercase tracking-wide text-[var(--color-text-tertiary)] mb-1">
- {c.length} services
- </div>
- <div className="text-[var(--color-text-primary)] break-words">
- {c.nodes.join(" → ")} → {c.nodes[0]}
- </div>
- </div>
- ))
- )}
- </CardContent>
- </Card>
- </div>
-
- <AiPromptModal
- open={promptOpen}
- onOpenChange={setPromptOpen}
- getPrompt={(flavor) =>
- buildConformanceAiPrompt({
- violations: violations.map((v) => ({
- source: v.source,
- target: v.target,
- source_name: v.source_name,
- target_name: v.target_name,
- edge_kind: v.edge_kind,
- rule_source: v.rule_source,
- rule_target: v.rule_target,
- rule_description: v.rule_description,
- })),
- flavor,
- })
+ ) : (
+ <p>
+ No system graph has been built yet, so there is nothing to measure. Run a workspace
+ sync to build one.
+ </p>
+ )}
+ {ruleSentence(state, report)}
+ </PageLede>
+
+ <StatRibbon stats={ribbon} />
+
+ <OverviewSection
+ title="Dependency-structure matrix"
+ description={DSM_DESCRIPTION}
+ action={
+ <SectionLink href="/workspace/system-map" LinkComponent={Link}>
+ System map
+ </SectionLink>
+ }
+ >
+ <DsmMatrixView matrix={matrix} {...(metrics ? { metrics } : {})} />
+ </OverviewSection>
+
+ <OverviewSection
+ title={
+ state === "checked" ? `Rule violations (${violations.length})` : "Rule violations"
}
- title="AI conformance fix"
- description="A ready-to-paste prompt that has your AI agent resolve these architecture rule violations by removing the disallowed dependencies."
+ description="Dependencies that exist in the graph but are forbidden by a rule you declared."
+ {...(violations.length > 0
+ ? { action: <ConformanceAiPrompt violations={violations} /> }
+ : {})}
+ >
+ {violations.length === 0 ? (
+ <ViolationsEmptyState state={state} />
+ ) : (
+ <ul className="m-0 list-none divide-y divide-[var(--color-border-default)] border-t border-[var(--color-border-default)] p-0">
+ {violations.map((v) => (
+ <li
+ key={`${v.edge_id}:${v.rule_source}:${v.rule_target}`}
+ className="py-3.5"
+ >
+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1 text-sm">
+ <span className="font-medium text-[var(--color-text-primary)]">
+ {v.source_name || v.source}
+ </span>
+ <span aria-hidden className="text-[var(--color-text-tertiary)]">
+ →
+ </span>
+ <span className="font-medium text-[var(--color-text-primary)]">
+ {v.target_name || v.target}
+ </span>
+ <span className="font-mono text-[11px] text-[var(--color-text-tertiary)]">
+ {v.edge_kind}
+ </span>
+ </div>
+ <p className="mt-1 text-xs text-[var(--color-text-secondary)]">
+ Breaks{" "}
+ <span className="font-mono text-[var(--color-warning)]">
+ {v.rule_source} !&gt; {v.rule_target}
+ </span>
+ {v.rule_description ? ` — ${v.rule_description}` : ""}
+ </p>
+ </li>
+ ))}
+ </ul>
+ )}
+ </OverviewSection>
+
+ <OverviewSection
+ title={`Dependency cycles (${cycleCount})`}
+ description="Groups of services that depend on each other in a loop, so none of them can be changed or deployed independently."
+ >
+ {cycles.length === 0 ? (
+ <EmptyState
+ className="p-6"
+ title={
+ cycleCount > 0
+ ? `${cycleCount} ${cycleCount === 1 ? "cycle" : "cycles"} detected, but not listed`
+ : "No circular dependencies"
+ }
+ description={
+ cycleCount > 0
+ ? "The count is recomputed from the system graph, but the services in each cycle are recorded by the conformance check. Run it to see which services are involved."
+ : "Every dependency in the graph runs one way. Nothing has to be changed in lockstep."
+ }
+ />
+ ) : (
+ <ul className="m-0 list-none divide-y divide-[var(--color-border-default)] border-t border-[var(--color-border-default)] p-0">
+ {cycles.map((c) => (
+ <li key={c.nodes.join("->")} className="py-3.5">
+ <p className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ {c.length} services
+ </p>
+ <p className="mt-1 text-sm text-[var(--color-text-primary)] [overflow-wrap:anywhere]">
+ {c.nodes.join(" → ")} → {c.nodes[0]}
+ </p>
+ </li>
+ ))}
+ </ul>
+ )}
+ </OverviewSection>
+ </PageShell>
+ );
+}
+
+/** The sentence in the lede that says whether the check has anything to say. */
+function ruleSentence(
+ state: ReturnType<typeof reportState>,
+ report: ConformanceReport | null,
+) {
+ if (state === "checked") {
+ const n = report?.rules_evaluated ?? 0;
+ const v = report?.violations?.length ?? 0;
+ return (
+ <p>
+ {formatNumber(n)} declared {n === 1 ? "rule was" : "rules were"} checked against that
+ graph, and {v === 0 ? "nothing breaks them" : `${formatNumber(v)} ${v === 1 ? "dependency breaks" : "dependencies break"} them`}.
+ </p>
+ );
+ }
+ if (state === "no_rules") {
+ return (
+ <p>
+ The check has run, but no dependency rules are declared, so it had nothing to enforce.
+ Add a <code className="font-mono text-[var(--color-text-primary)]">conformance:</code>{" "}
+ block to{" "}
+ <code className="font-mono text-[var(--color-text-primary)]">
+ .repowise-workspace.yaml
+ </code>{" "}
+ to describe which services may depend on which.
+ </p>
+ );
+ }
+ return (
+ <p>
+ The conformance check has not run on this workspace yet, so nothing below is a verdict —
+ an empty violations list here means unmeasured, not clean. Run{" "}
+ <code className="font-mono text-[var(--color-text-primary)]">
+ repowise workspace check
+ </code>{" "}
+ to evaluate it.
+ </p>
+ );
+}
+
+/**
+ * Three empty states, because they mean three different things.
+ *
+ * Collapsing them into one "no violations" message is the failure this page
+ * shipped with: the artifact's zeros are written before anything runs.
+ */
+function ViolationsEmptyState({ state }: { state: ReturnType<typeof reportState> }) {
+ if (state === "checked") {
+ return (
+ <EmptyState
+ className="p-6"
+ title="No rules are broken"
+ description="Every dependency in the graph is allowed by the rules you declared."
/>
- </div>
+ );
+ }
+ if (state === "no_rules") {
+ return (
+ <EmptyState
+ className="p-6"
+ title="No rules declared"
+ description="Nothing has been forbidden yet, so nothing can be violated. Declare which services may depend on which under `conformance:` in .repowise-workspace.yaml, then run `repowise workspace check` to gate CI on it."
+ />
+ );
+ }
+ if (state === "never_ran") {
+ return (
+ <EmptyState
+ className="p-6"
+ title="Not checked yet"
+ description="The conformance analyser has not run on this workspace, so no rules have been evaluated. This is not a clean bill of health — run `repowise workspace check` to produce one."
+ />
+ );
+ }
+ return (
+ <EmptyState
+ className="p-6"
+ title="Conformance report unavailable"
+ description="The report could not be read. Run a workspace sync to rebuild it."
+ />
);
}
diff --git a/packages/web/src/app/workspace/contracts/contract-filters.tsx b/packages/web/src/app/workspace/contracts/contract-filters.tsx
new file mode 100644
index 000000000..6eb61eae2
--- /dev/null
+++ b/packages/web/src/app/workspace/contracts/contract-filters.tsx
@@ -0,0 +1,110 @@
+"use client";
+
+import { useRouter, useSearchParams } from "next/navigation";
+import { useCallback, useTransition } from "react";
+import { Filter } from "lucide-react";
+
+const TYPE_OPTIONS = [
+ { value: "", label: "All types" },
+ { value: "http", label: "HTTP" },
+ { value: "grpc", label: "gRPC" },
+ { value: "socket", label: "Socket" },
+ { value: "topic", label: "Topic" },
+ { value: "data", label: "Table" },
+];
+
+const ROLE_OPTIONS = [
+ { value: "", label: "All roles" },
+ { value: "provider", label: "Providers" },
+ { value: "consumer", label: "Consumers" },
+];
+
+const SELECT_CLASS =
+ "rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-3 py-1.5 text-sm text-[var(--color-text-primary)] outline-none focus:border-[var(--color-border-active)] disabled:opacity-60";
+
+/**
+ * The contracts table's filters.
+ *
+ * The only stateful thing on an otherwise server-rendered page, and it keeps
+ * its state in the URL rather than in React: the page re-renders on the server
+ * with the new filter, so a filtered view is linkable and the table's counts
+ * come from the same request that drew the rows.
+ */
+export function ContractFilters({ repos }: { repos: string[] }) {
+ const router = useRouter();
+ const params = useSearchParams();
+ const [pending, startTransition] = useTransition();
+
+ const set = useCallback(
+ (key: string, value: string) => {
+ const next = new URLSearchParams(params.toString());
+ if (value) next.set(key, value);
+ else next.delete(key);
+ startTransition(() => {
+ router.push(next.size > 0 ? `?${next.toString()}` : "/workspace/contracts");
+ });
+ },
+ [params, router],
+ );
+
+ return (
+ <div className="flex flex-wrap items-center gap-3">
+ <span className="flex items-center gap-2 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ <Filter className="h-3.5 w-3.5" aria-hidden />
+ Filter
+ </span>
+
+ <label className="sr-only" htmlFor="contract-type">
+ Contract type
+ </label>
+ <select
+ id="contract-type"
+ className={SELECT_CLASS}
+ disabled={pending}
+ value={params.get("type") ?? ""}
+ onChange={(e) => set("type", e.target.value)}
+ >
+ {TYPE_OPTIONS.map((o) => (
+ <option key={o.value} value={o.value}>
+ {o.label}
+ </option>
+ ))}
+ </select>
+
+ <label className="sr-only" htmlFor="contract-repo">
+ Repository
+ </label>
+ <select
+ id="contract-repo"
+ className={SELECT_CLASS}
+ disabled={pending}
+ value={params.get("repo") ?? ""}
+ onChange={(e) => set("repo", e.target.value)}
+ >
+ <option value="">All repositories</option>
+ {repos.map((r) => (
+ <option key={r} value={r}>
+ {r}
+ </option>
+ ))}
+ </select>
+
+ <label className="sr-only" htmlFor="contract-role">
+ Role
+ </label>
+ <select
+ id="contract-role"
+ className={SELECT_CLASS}
+ disabled={pending}
+ value={params.get("role") ?? ""}
+ onChange={(e) => set("role", e.target.value)}
+ >
+ {ROLE_OPTIONS.map((o) => (
+ <option key={o.value} value={o.value}>
+ {o.label}
+ </option>
+ ))}
+ </select>
+ </div>
+ );
+}
diff --git a/packages/web/src/app/workspace/contracts/contracts-table.tsx b/packages/web/src/app/workspace/contracts/contracts-table.tsx
new file mode 100644
index 000000000..1b79c01e0
--- /dev/null
+++ b/packages/web/src/app/workspace/contracts/contracts-table.tsx
@@ -0,0 +1,81 @@
+"use client";
+
+import {
+ ResponsiveTable,
+ type ResponsiveColumn,
+} from "@repowise-dev/ui/shared";
+import {
+ ContractTypeBadge,
+ RoleBadge,
+} from "@repowise-dev/ui/workspace/contract-type-badge";
+import type { WorkspaceContractEntry } from "@/lib/api/types";
+
+type ContractRow = WorkspaceContractEntry & { _key: string };
+
+/**
+ * The contracts table.
+ *
+ * This is a client boundary for a mechanical reason rather than a stateful
+ * one: `ResponsiveTable` takes its columns as `render` functions, and a
+ * function cannot cross the server-to-client boundary. Keeping the column
+ * definitions on this side lets the page itself stay a server component that
+ * passes nothing but rows.
+ */
+const CONTRACT_COLUMNS: ResponsiveColumn<ContractRow>[] = [
+ {
+ key: "contract_id",
+ header: "Contract",
+ render: (c) => (
+ <span className="font-mono text-xs text-[var(--color-text-secondary)] [overflow-wrap:anywhere]">
+ {c.contract_id}
+ </span>
+ ),
+ },
+ {
+ key: "contract_type",
+ header: "Type",
+ render: (c) => <ContractTypeBadge type={c.contract_type} />,
+ },
+ { key: "role", header: "Role", render: (c) => <RoleBadge role={c.role} /> },
+ {
+ key: "repo",
+ header: "Repository",
+ render: (c) => (
+ <span className="text-xs font-medium text-[var(--color-text-primary)]">{c.repo}</span>
+ ),
+ },
+ {
+ key: "file_path",
+ header: "File",
+ priority: 2,
+ render: (c) => (
+ // No truncation: a path is exactly the string somebody is scanning for.
+ <span className="font-mono text-xs text-[var(--color-text-tertiary)] [overflow-wrap:anywhere]">
+ {c.file_path}
+ </span>
+ ),
+ },
+ {
+ key: "confidence",
+ header: "Confidence",
+ align: "right",
+ render: (c) => (
+ <span className="text-xs tabular-nums text-[var(--color-text-tertiary)]">
+ {Math.round(c.confidence * 100)}%
+ </span>
+ ),
+ },
+];
+
+export function ContractsTable({ contracts }: { contracts: WorkspaceContractEntry[] }) {
+ return (
+ <ResponsiveTable
+ columns={CONTRACT_COLUMNS}
+ rows={contracts.map((c, i) => ({ ...c, _key: `${c.contract_id}|${i}` }))}
+ rowKey={(c) => c._key}
+ caption="All detected contracts"
+ stacked="md"
+ bare
+ />
+ );
+}
diff --git a/packages/web/src/app/workspace/contracts/page.tsx b/packages/web/src/app/workspace/contracts/page.tsx
index c85d48bec..de44f58bd 100644
--- a/packages/web/src/app/workspace/contracts/page.tsx
+++ b/packages/web/src/app/workspace/contracts/page.tsx
@@ -1,251 +1,211 @@
-"use client";
-
-import { useState } from "react";
-import { Link2, Filter } from "lucide-react";
-import { useWorkspaceContracts } from "@/lib/hooks/use-workspace";
-import { useWorkspace } from "@/lib/hooks/use-workspace";
+import type { Metadata } from "next";
+import Link from "next/link";
+import { Link2 } from "lucide-react";
+import type { ExtractionDiagnostics } from "@repowise-dev/api-client/types";
+import { PageShell, EmptyState } from "@repowise-dev/ui/shared";
+import { PageLede } from "@repowise-dev/ui/shared/page-lede";
+import { OverviewSection } from "@repowise-dev/ui/overview";
+import { StatRibbon, type RibbonStat } from "@repowise-dev/ui/stats/stat-ribbon";
import { ContractLinksTable } from "@repowise-dev/ui/workspace/contract-links-table";
-import { ContractTypeBadge, RoleBadge } from "@repowise-dev/ui/workspace/contract-type-badge";
-import { Card, CardContent, CardHeader, CardTitle } from "@repowise-dev/ui/ui/card";
-import { MetricCard } from "@repowise-dev/ui/shared/metric-card";
+import { formatNumber } from "@repowise-dev/ui/lib/format";
import {
- EmptyState,
- ResponsiveTable,
- TableSkeleton,
- type ResponsiveColumn,
-} from "@repowise-dev/ui/shared";
-import type { WorkspaceContractEntry } from "@/lib/api/types";
-
-const TYPE_OPTIONS = [
- { value: "", label: "All Types" },
- { value: "http", label: "HTTP" },
- { value: "grpc", label: "gRPC" },
- { value: "socket", label: "Socket" },
- { value: "topic", label: "Topic" },
- { value: "data", label: "Table" },
-];
-
-const ROLE_OPTIONS = [
- { value: "", label: "All Roles" },
- { value: "provider", label: "Providers" },
- { value: "consumer", label: "Consumers" },
-];
-
-type ContractRow = WorkspaceContractEntry & { _key: string };
-
-const CONTRACT_COLUMNS: ResponsiveColumn<ContractRow>[] = [
- {
- key: "contract_id",
- header: "Contract ID",
- render: (c) => (
- <span className="text-xs font-mono text-[var(--color-text-secondary)] break-all">
- {c.contract_id}
- </span>
- ),
- },
- {
- key: "contract_type",
- header: "Type",
- render: (c) => <ContractTypeBadge type={c.contract_type} />,
- },
- {
- key: "role",
- header: "Role",
- render: (c) => <RoleBadge role={c.role} />,
- },
- {
- key: "repo",
- header: "Repo",
- render: (c) => (
- <span className="text-xs font-medium text-[var(--color-text-primary)]">{c.repo}</span>
- ),
- },
- {
- key: "file_path",
- header: "File",
- priority: 2,
- render: (c) => (
- <span className="text-xs font-mono text-[var(--color-text-tertiary)] truncate block max-w-[200px]">
- {c.file_path}
- </span>
- ),
- },
- {
- key: "confidence",
- header: "Confidence",
- align: "right",
- render: (c) => (
- <span className="text-xs text-[var(--color-text-tertiary)] tabular-nums">
- {Math.round(c.confidence * 100)}%
- </span>
- ),
- },
-];
-
-export default function ContractsPage() {
- const { workspace } = useWorkspace();
- const [contractType, setContractType] = useState("");
- const [repo, setRepo] = useState("");
- const [role, setRole] = useState("");
-
- const { data, isLoading } = useWorkspaceContracts({
- contract_type: contractType || undefined,
- repo: repo || undefined,
- role: role || undefined,
- });
-
- const repos = workspace?.repos ?? [];
-
- // Count unmatched contracts (providers with no link, consumers with no link)
- const linkedContractIds = new Set(
- (data?.links ?? []).map((l) => l.contract_id),
- );
- const unmatchedCount = (data?.contracts ?? []).filter(
- (c) => !linkedContractIds.has(c.contract_id),
- ).length;
+ getWorkspace,
+ getWorkspaceContracts,
+ getWorkspaceDiagnostics,
+} from "@/lib/api/workspace";
+import { ContractFilters } from "./contract-filters";
+import { ContractsTable } from "./contracts-table";
+
+export const metadata: Metadata = { title: "Contracts" };
+
+export const revalidate = 30;
+
+/** Rows the table draws. The server caps at 1,000; this is the page's own
+ * window and it is always reported against the filtered total below. */
+const ROW_WINDOW = 200;
+
+type Props = {
+ searchParams: Promise<{ type?: string; repo?: string; role?: string }>;
+};
- const selectClass =
- "rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-3 py-1.5 text-sm text-[var(--color-text-primary)] outline-none focus:border-[var(--color-accent-primary)]";
+/**
+ * Contracts detected across the workspace, and which of them matched.
+ *
+ * The four `MetricCard`s this replaces could not be restyled into a ribbon,
+ * because three of them were counting the wrong things. "Total Contracts" and
+ * "Unmatched" were both derived from the contract rows, which arrive filtered
+ * *and* paginated — so "Unmatched" was computed over one page of 200 and
+ * reported as a workspace figure, and it moved whenever a filter changed. "By
+ * Type" was arithmetically identical to "Total Contracts", since the sum of a
+ * breakdown is the thing it breaks down.
+ *
+ * The figures come from `/api/workspace/diagnostics` now, which is the
+ * endpoint that already knows the denominators: how many providers and
+ * consumers extraction found, how many linked, and why the rest did not. Those
+ * are workspace-wide and deliberately do not move when the table is filtered.
+ */
+export default async function ContractsPage({ searchParams }: Props) {
+ const { type, repo, role } = await searchParams;
+
+ const [ct, diag, ws] = await Promise.allSettled([
+ getWorkspaceContracts({
+ contract_type: type || undefined,
+ repo: repo || undefined,
+ role: role || undefined,
+ limit: ROW_WINDOW,
+ }),
+ getWorkspaceDiagnostics(),
+ getWorkspace(),
+ ]);
+
+ const data = ct.status === "fulfilled" ? ct.value : null;
+ const diagnostics = diag.status === "fulfilled" ? diag.value : null;
+ const repos = ws.status === "fulfilled" ? ws.value.repos.map((r) => r.alias) : [];
+
+ const rows = data?.contracts ?? [];
+ const links = data?.links ?? [];
+ const filtered = Boolean(type || repo || role);
+
+ const ribbon: RibbonStat[] = [
+ {
+ label: "Providers",
+ value: diagnostics ? formatNumber(diagnostics.total_providers) : "—",
+ sub: "routes, topics and tables published",
+ },
+ {
+ label: "Consumers",
+ value: diagnostics ? formatNumber(diagnostics.total_consumers) : "—",
+ sub: "call sites resolved to a contract",
+ },
+ {
+ label: "Matched links",
+ value: diagnostics ? formatNumber(diagnostics.total_links) : "—",
+ sub: "provider joined to consumer",
+ },
+ {
+ label: "Unmatched consumers",
+ value: diagnostics ? formatNumber(diagnostics.unmatched_consumers.length) : "—",
+ sub: unmatchedReasonSub(diagnostics),
+ },
+ {
+ label: "Unused providers",
+ value: diagnostics ? formatNumber(diagnostics.orphan_providers.length) : "—",
+ sub: "nothing in the workspace calls them",
+ },
+ ];
return (
- <div className="p-5 sm:p-8 space-y-6 max-w-[1200px]">
- {/* Header */}
- <div>
- <div className="flex items-center gap-2.5 mb-1">
- <Link2 className="h-6 w-6 text-[var(--color-accent-primary)]" />
- <h1 className="text-2xl font-semibold text-[var(--color-text-primary)]">
- Contracts
- </h1>
- </div>
- <p className="text-sm text-[var(--color-text-secondary)]">
- HTTP routes, gRPC services, socket endpoints, and message topics detected across repositories.
- </p>
- </div>
-
- {/* Summary Stats */}
- <div className="grid grid-cols-2 gap-3 lg:grid-cols-4">
- <MetricCard
- label="Total Contracts"
- value={data?.total_contracts ?? "—"}
- icon={<Link2 className="h-4 w-4" />}
- />
- <MetricCard
- label="Matched Links"
- value={data?.total_links ?? "—"}
- icon={<Link2 className="h-4 w-4 text-[var(--color-success)]" />}
- />
- <MetricCard
- label="Unmatched"
- value={isLoading ? "—" : unmatchedCount}
- description="No matching provider or consumer"
- icon={<Link2 className="h-4 w-4 text-[var(--color-warning)]" />}
- />
- <MetricCard
- label="By Type"
- value={
- data?.by_type
- ? Object.values(data.by_type).reduce((a, b) => a + b, 0)
- : "—"
- }
+ <PageShell
+ title="Contracts"
+ icon={<Link2 className="h-5 w-5 text-[var(--color-text-tertiary)]" />}
+ description="Routes, topics and tables one repository publishes and another consumes."
+ >
+ <PageLede
+ label="Matched links"
+ value={diagnostics ? formatNumber(diagnostics.total_links) : "—"}
+ unit="provider to consumer"
+ layout="beside"
+ >
+ {diagnostics ? (
+ <>
+ <p>
+ Extraction found {formatNumber(diagnostics.total_providers)} providers and{" "}
+ {formatNumber(diagnostics.total_consumers)} consumers across the workspace, and
+ joined {formatNumber(diagnostics.total_links)} of them into cross-repo links. A
+ link means a call site was resolved to the code that serves it, not that the two
+ were declared against a shared schema.
+ </p>
+ <p>
+ {formatNumber(diagnostics.orphan_providers.length)} providers have no caller in
+ this workspace. Read that against the consumer count rather than on its own: an
+ endpoint looks unused both when nothing calls it and when the call was written in
+ a form this analysis could not follow, and those two are not separated yet.
+ </p>
+ </>
+ ) : (
+ <p>
+ Extraction diagnostics are not available, so the totals below cannot be shown.
+ Run a workspace sync to rebuild them.
+ </p>
+ )}
+ </PageLede>
+
+ <StatRibbon stats={ribbon} />
+
+ {links.length > 0 && (
+ <OverviewSection
+ title="Matched links"
description={
- data?.by_type
- ? Object.entries(data.by_type)
- .map(([k, v]) => `${v} ${k}`)
- .join(", ")
- : undefined
+ filtered
+ ? "Links matching the current filter, provider on the left and consumer on the right."
+ : "Every provider joined to the consumer that calls it, with the confidence of the match."
}
- icon={<Filter className="h-4 w-4 text-[var(--color-accent-secondary)]" />}
- />
- </div>
-
- {/* Filters */}
- <div className="flex flex-wrap items-center gap-3">
- <div className="flex items-center gap-2">
- <Filter className="h-4 w-4 text-[var(--color-text-tertiary)]" />
- <span className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider">
- Filters
- </span>
- </div>
- <select
- value={contractType}
- onChange={(e) => setContractType(e.target.value)}
- className={selectClass}
- >
- {TYPE_OPTIONS.map((o) => (
- <option key={o.value} value={o.value}>
- {o.label}
- </option>
- ))}
- </select>
- <select
- value={repo}
- onChange={(e) => setRepo(e.target.value)}
- className={selectClass}
>
- <option value="">All Repos</option>
- {repos.map((r) => (
- <option key={r.alias} value={r.alias}>
- {r.alias}
- </option>
- ))}
- </select>
- <select
- value={role}
- onChange={(e) => setRole(e.target.value)}
- className={selectClass}
+ <ContractLinksTable links={links} />
+ </OverviewSection>
+ )}
+
+ <OverviewSection
+ title="All detected contracts"
+ description={tableDescription(rows.length, data?.total_contracts ?? 0, filtered)}
+ action={<ContractFilters repos={repos} />}
+ >
+ {rows.length === 0 ? (
+ <EmptyState
+ className="p-6"
+ title={filtered ? "No contracts match this filter" : "No contracts detected"}
+ description={
+ filtered
+ ? "Clear a filter to widen the search."
+ : "Contracts are detected during a workspace sync, by reading the routes each repository serves and the calls the others make."
+ }
+ />
+ ) : (
+ <ContractsTable contracts={rows} />
+ )}
+ </OverviewSection>
+
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ Contracts are matched on path. Two routes that share a path are one contract here, so a
+ repository can appear against a contract it declares for its own use.{" "}
+ <Link
+ href="/workspace/system-map"
+ className="text-[var(--color-accent-primary)] hover:underline"
>
- {ROLE_OPTIONS.map((o) => (
- <option key={o.value} value={o.value}>
- {o.label}
- </option>
- ))}
- </select>
- </div>
-
- {/* Contract Links */}
- <Card>
- <CardHeader className="pb-2">
- <CardTitle className="text-sm font-medium">
- Matched Contract Links ({data?.total_links ?? 0})
- </CardTitle>
- </CardHeader>
- <CardContent className="pt-0">
- {isLoading ? (
- <TableSkeleton rows={5} className="py-4" />
- ) : (
- <ContractLinksTable links={data?.links ?? []} />
- )}
- </CardContent>
- </Card>
-
- {/* All Contracts */}
- <Card>
- <CardHeader className="pb-2">
- <CardTitle className="text-sm font-medium">
- All Detected Contracts ({data?.total_contracts ?? 0})
- </CardTitle>
- </CardHeader>
- <CardContent className="pt-0">
- {isLoading ? (
- <TableSkeleton rows={5} className="py-4" />
- ) : (data?.contracts ?? []).length === 0 ? (
- <EmptyState
- className="p-6"
- title="No contracts detected"
- description="API contracts are detected during workspace indexing when providers and consumers share schemas."
- />
- ) : (
- <ResponsiveTable
- columns={CONTRACT_COLUMNS}
- rows={(data?.contracts ?? []).map((c, i) => ({ ...c, _key: `${c.contract_id}|${i}` }))}
- rowKey={(c) => c._key}
- caption="All detected contracts"
- stacked="md"
- bare
- />
- )}
- </CardContent>
- </Card>
- </div>
+ See how they connect
+ </Link>
+ .
+ </p>
+ </PageShell>
);
}
+
+/**
+ * Say the bound. The endpoint pages the rows but reports the unpaged total, so
+ * without this the heading claims a number the table does not draw.
+ */
+function tableDescription(shown: number, total: number, filtered: boolean): string {
+ const scope = filtered ? "matching the current filter" : "detected across the workspace";
+ if (total === 0) return `Every contract ${scope}.`;
+ if (shown >= total) {
+ return `All ${formatNumber(total)} ${total === 1 ? "contract" : "contracts"} ${scope}. One contract can be declared in several places, so a name may repeat.`;
+ }
+ return `Showing ${formatNumber(shown)} of ${formatNumber(total)} contracts ${scope}. One contract can be declared in several places, so a name may repeat.`;
+}
+
+/** Name why consumers went unmatched, since the count alone invites the wrong read. */
+function unmatchedReasonSub(diagnostics: ExtractionDiagnostics | null): string {
+ if (!diagnostics) return "";
+ const reasons = Object.entries(diagnostics.unmatched_by_reason ?? {})
+ .filter(([, n]) => n > 0)
+ .sort((a, b) => b[1] - a[1]);
+ if (reasons.length === 0) return "every consumer matched a provider";
+ return reasons.map(([reason, n]) => `${n} ${REASON_LABEL[reason] ?? reason}`).join(", ");
+}
+
+const REASON_LABEL: Record<string, string> = {
+ no_provider: "no provider found",
+ internal_only: "internal to one repo",
+ external_host: "external host",
+ unlinked: "unlinked",
+};
diff --git a/packages/web/src/app/workspace/page.tsx b/packages/web/src/app/workspace/page.tsx
index b062b8916..d0980ce63 100644
--- a/packages/web/src/app/workspace/page.tsx
+++ b/packages/web/src/app/workspace/page.tsx
@@ -1,279 +1,351 @@
+import type { ReactNode } from "react";
import type { Metadata } from "next";
import Link from "next/link";
-import {
- Layers,
- FileText,
- Code2,
- BarChart3,
- Flame,
- Link2,
- GitMerge,
- ArrowRight,
-} from "lucide-react";
-import { getWorkspace, getWorkspaceCoChanges } from "@/lib/api/workspace";
-import { MetricCard } from "@repowise-dev/ui/shared/metric-card";
+import { Layers } from "lucide-react";
+import type { WorkspaceRepoEntry } from "@repowise-dev/api-client/types";
+import { PageShell } from "@repowise-dev/ui/shared";
+import { PageLede, LedeLink } from "@repowise-dev/ui/shared/page-lede";
import { EmptyState } from "@repowise-dev/ui/shared/empty-state";
-import { Card, CardContent, CardHeader, CardTitle } from "@repowise-dev/ui/ui/card";
-import { RepoCard } from "@repowise-dev/ui/workspace/repo-card";
-import { CrossRepoSummary } from "@repowise-dev/ui/workspace/cross-repo-summary";
+import {
+ OverviewSection,
+ SectionLink,
+ RepoRows,
+ type RepoRow,
+} from "@repowise-dev/ui/overview";
+// Direct path, not the `ui/stats` barrel: that barrel re-exports two
+// "use client" modules, which would drag a hydration boundary into this
+// server page for a component that has no state.
+import { StatRibbon, type RibbonStat } from "@repowise-dev/ui/stats/stat-ribbon";
import { CoChangeTable } from "@repowise-dev/ui/workspace/co-change-table";
import { ContractTypeBadge } from "@repowise-dev/ui/workspace/contract-type-badge";
import { formatNumber } from "@repowise-dev/ui/lib/format";
-import { WorkspaceGraphSection } from "./workspace-graph-section";
+import { getWorkspace, getWorkspaceCoChanges } from "@/lib/api/workspace";
import { SyncButton } from "./sync-buttons";
export const metadata: Metadata = { title: "Workspace" };
export const revalidate = 30;
-async function safeFetch<T>(fn: () => Promise<T>): Promise<T | null> {
- try {
- return await fn();
- } catch {
- return null;
- }
-}
+/** Co-change rows shown inline. The full list has its own page, and this
+ * figure is never reported as a total, so the cap cannot be read as one. */
+const COCHANGE_PREVIEW = 8;
+/**
+ * The workspace overview.
+ *
+ * It used to open with five cross-repo `MetricCard`s and put the repositories
+ * themselves in a grid of cards underneath, which is the same shape the
+ * multi-repo dashboard carried before #1578. Three of those figures were
+ * rebuilt rather than restyled:
+ *
+ * - "Avg Coverage" averaged per-repo percentages unweighted, so a 50-file
+ * repo at 100% and a 5,000-file repo at 10% reported 55%. It is weighted by
+ * page count now, and named for what the rest of the app calls it.
+ * - The cross-repo force-directed graph drew seven nodes and thirteen edges
+ * on a real workspace — a list wearing a canvas — and cost a third request
+ * that swept every repo's sqlite a second time. The system map owns that
+ * view; this page links to it.
+ * - The repo grid became `RepoRows`, so a repository's health leads the row
+ * that decides whether you open it.
+ */
export default async function WorkspaceDashboardPage() {
- const [workspace, coChanges] = await Promise.all([
- safeFetch(() => getWorkspace()),
- safeFetch(() => getWorkspaceCoChanges({ limit: 10 })),
+ // One wave, both on the server. The graph section that used to sit here was
+ // a client component fetching after mount, which waterfalled a second
+ // per-repo sqlite sweep in behind the paint.
+ const [ws, cc] = await Promise.allSettled([
+ getWorkspace(),
+ getWorkspaceCoChanges({ limit: COCHANGE_PREVIEW }),
]);
- const wsRepos = workspace?.repos ?? [];
-
- // Aggregate stats from per-repo data embedded in the workspace response
- let totalFiles = 0;
- let totalSymbols = 0;
- let totalCoveragePctSum = 0;
- let totalHotspots = 0;
- let reposWithStats = 0;
+ const workspace = ws.status === "fulfilled" ? ws.value : null;
+ const coChanges = cc.status === "fulfilled" ? cc.value : null;
+ const repos = workspace?.repos ?? [];
+ const crossRepo = workspace?.cross_repo_summary ?? null;
+ const contracts = workspace?.contract_summary ?? null;
- for (const r of wsRepos) {
- totalFiles += r.file_count;
- totalSymbols += r.symbol_count;
- totalCoveragePctSum += r.doc_coverage_pct;
- totalHotspots += r.hotspot_count;
- if (r.file_count > 0) reposWithStats++;
+ if (repos.length === 0) {
+ return (
+ <PageShell
+ title={workspace?.workspace_name ?? "Workspace"}
+ icon={<Layers className="h-5 w-5 text-[var(--color-text-tertiary)]" />}
+ description="Every repository registered in this workspace, and what connects them."
+ >
+ <EmptyState
+ title="No repositories discovered yet"
+ description="Run `repowise init .` in the workspace root to scan for git repositories and index them. They show up here as soon as the scan lands."
+ icon={<Layers className="h-8 w-8" />}
+ />
+ </PageShell>
+ );
}
- const avgCoverage = reposWithStats > 0 ? Math.round(totalCoveragePctSum / reposWithStats) : 0;
- // "Needs attention" rollup across the whole workspace (not a page slice).
- const needsIndex = wsRepos.filter(
- (r) => (r.status ?? (r.repo_id ? "indexed" : "needs_index")) === "needs_index",
+ const totals = repos.reduce(
+ (acc, r) => ({
+ files: acc.files + r.file_count,
+ symbols: acc.symbols + r.symbol_count,
+ pages: acc.pages + r.page_count,
+ // Page-weighted, so a small repo cannot pull the workspace average.
+ confidenceWeighted: acc.confidenceWeighted + r.doc_coverage_pct * r.page_count,
+ hotspots: acc.hotspots + r.hotspot_count,
+ }),
+ { files: 0, symbols: 0, pages: 0, confidenceWeighted: 0, hotspots: 0 },
);
- const missingDirs = wsRepos.filter((r) => r.status === "missing_dir");
- const docsSkipped = wsRepos.filter((r) => r.docs_skip_reason);
- const attentionItems: string[] = [];
- if (needsIndex.length > 0)
- attentionItems.push(
- `${needsIndex.length} repo${needsIndex.length === 1 ? "" : "s"} not indexed yet (${needsIndex
- .slice(0, 3)
- .map((r) => r.alias)
- .join(", ")}${needsIndex.length > 3 ? ", …" : ""})`,
- );
- if (missingDirs.length > 0)
- attentionItems.push(
- `${missingDirs.length} repo director${missingDirs.length === 1 ? "y is" : "ies are"} missing on disk (${missingDirs
- .slice(0, 3)
- .map((r) => r.alias)
- .join(", ")}${missingDirs.length > 3 ? ", …" : ""})`,
- );
- if (docsSkipped.length > 0)
- attentionItems.push(
- `docs skipped for ${docsSkipped.length} repo${docsSkipped.length === 1 ? "" : "s"}`,
- );
+ // Floored, not rounded: 99.7% rounds to a perfect 100% and tells the reader
+ // every page is current when some are not. Erring low never overclaims.
+ const docFreshness =
+ totals.pages > 0 ? Math.floor(totals.confidenceWeighted / totals.pages) : null;
+
+ const ribbon: RibbonStat[] = [
+ {
+ label: "Files",
+ value: formatNumber(totals.files),
+ sub: `across ${repos.length} ${repos.length === 1 ? "repository" : "repositories"}`,
+ },
+ {
+ label: "Symbols",
+ value: formatNumber(totals.symbols),
+ sub: "functions, classes and methods",
+ },
+ {
+ label: "Doc freshness",
+ value: docFreshness === null ? "—" : `${docFreshness}%`,
+ sub:
+ docFreshness === null
+ ? "no documentation generated yet"
+ : `weighted across ${formatNumber(totals.pages)} pages`,
+ },
+ {
+ label: "Hotspots",
+ value: formatNumber(totals.hotspots),
+ sub: "files by churn and prior fixes",
+ },
+ {
+ label: "Contract links",
+ value: contracts ? formatNumber(contracts.total_links) : "—",
+ // No href: a linked ribbon cell drops its `sub`, and the sentence under
+ // the figure is worth more than a second route to the section below,
+ // which already carries its own link.
+ sub: contracts ? "matched provider to consumer" : "no contract data yet",
+ },
+ ];
+
+ const contractTypes = Object.entries(contracts?.by_type ?? {}).sort((a, b) => b[1] - a[1]);
return (
- <div className="p-5 sm:p-8 space-y-8 max-w-[1200px]">
- {/* Header */}
- <div className="flex items-start justify-between gap-4 flex-wrap">
- <div>
- <div className="flex items-center gap-2.5 mb-1">
- <Layers className="h-6 w-6 text-[var(--color-accent-primary)]" />
- <h1 className="text-2xl font-semibold text-[var(--color-text-primary)]">
- {workspace?.workspace_name ?? "Workspace"}
- </h1>
- </div>
- <p className="text-sm text-[var(--color-text-secondary)]">
- {workspace?.repos.length ?? 0} repositories
- {workspace?.workspace_root && (
- <span
- className="text-[var(--color-text-tertiary)] font-mono break-all"
- title={workspace.workspace_root}
- >
- {" "}&middot; {workspace.workspace_root}
+ <PageShell
+ title={workspace?.workspace_name ?? "Workspace"}
+ icon={<Layers className="h-5 w-5 text-[var(--color-text-tertiary)]" />}
+ description="Every repository registered in this workspace, and what connects them."
+ actions={<SyncButton variant="primary" label="Sync workspace" />}
+ >
+ <PageLede
+ label="Repositories"
+ value={String(repos.length)}
+ unit="in this workspace"
+ layout="beside"
+ action={<LedeLink href="/workspace/system-map" LinkComponent={Link}>See the system map</LedeLink>}
+ >
+ <p>
+ {formatNumber(totals.files)} files and {formatNumber(totals.symbols)} symbols are under
+ intelligence here
+ {totals.pages > 0
+ ? `, with ${formatNumber(totals.pages)} documentation pages written from them`
+ : ""}
+ .{" "}
+ {workspace?.workspace_root && (
+ <>
+ Everything is rooted at{" "}
+ <span className="font-mono text-[var(--color-text-tertiary)] [overflow-wrap:anywhere]">
+ {workspace.workspace_root}
</span>
- )}
- </p>
- </div>
- {(workspace?.repos.length ?? 0) > 0 && (
- <SyncButton variant="primary" label="Sync workspace" />
- )}
- </div>
+ .
+ </>
+ )}
+ </p>
+ <p>{attentionSentence(repos)}</p>
+ {unregisteredNote(repos, crossRepo)}
+ </PageLede>
- {/* Needs attention */}
- {attentionItems.length > 0 && (
- <div className="rounded-lg border border-[var(--color-warning)]/40 bg-[var(--color-warning)]/5 px-4 py-3">
- <p className="text-xs font-medium uppercase tracking-wider text-[var(--color-warning)]">
- Needs attention
- </p>
- <ul className="mt-1.5 list-disc space-y-0.5 pl-4 text-xs text-[var(--color-text-secondary)]">
- {attentionItems.map((item) => (
- <li key={item}>{item}</li>
+ <StatRibbon stats={ribbon} LinkComponent={Link} />
+
+ <OverviewSection
+ title="Repositories"
+ description="Ordered by what needs attention first — never indexed, then missing on disk, then by health score — rather than by name."
+ >
+ <RepoRows
+ repos={repos.slice().sort(byAttention).map(toRow)}
+ LinkComponent={Link}
+ actionsFor={(repo) =>
+ repo.status === "missing_dir" ? null : (
+ <SyncButton
+ alias={repo.id}
+ label={repo.status === "indexed" ? "Sync" : "Index now"}
+ />
+ )
+ }
+ />
+ </OverviewSection>
+
+ {contracts && contracts.total_contracts > 0 && (
+ <OverviewSection
+ title="Contracts"
+ description="Routes, topics and tables one repository publishes and another consumes, matched across the workspace."
+ action={
+ <SectionLink href="/workspace/contracts" LinkComponent={Link}>
+ All contracts
+ </SectionLink>
+ }
+ >
+ {/* Badge and figure sit together rather than spanning the cell:
+ justify-between across a quarter of 1280px pushed them so far
+ apart they stopped reading as one pair. */}
+ <dl className="m-0 flex flex-wrap gap-x-10 gap-y-3">
+ {contractTypes.map(([type, count]) => (
+ <div key={type} className="flex items-center gap-2.5">
+ <dt>
+ <ContractTypeBadge type={type} />
+ </dt>
+ <dd className="text-sm font-medium tabular-nums text-[var(--color-text-primary)]">
+ {formatNumber(count)}
+ </dd>
+ </div>
))}
- </ul>
- </div>
+ </dl>
+ </OverviewSection>
)}
- {/* Aggregate Stats */}
- <div className="grid grid-cols-2 gap-4 lg:grid-cols-5">
- <MetricCard
- label="Total Files"
- value={formatNumber(totalFiles)}
- icon={<FileText className="h-4 w-4" />}
- />
- <MetricCard
- label="Total Symbols"
- value={formatNumber(totalSymbols)}
- icon={<Code2 className="h-4 w-4" />}
- />
- <MetricCard
- label="Avg Coverage"
- value={`${avgCoverage}%`}
- icon={<BarChart3 className="h-4 w-4" />}
- />
- <MetricCard
- label="Hotspots"
- value={totalHotspots}
- icon={<Flame className="h-4 w-4 text-[var(--color-warning)]" />}
- />
- <MetricCard
- label="Pages"
- value={formatNumber(wsRepos.reduce((a, r) => a + r.page_count, 0))}
- icon={<Code2 className="h-4 w-4 text-[var(--color-text-tertiary)]" />}
- />
- </div>
+ {coChanges && coChanges.co_changes.length > 0 && (
+ <OverviewSection
+ title="Files that change together"
+ description="Cross-repo file pairs that recent commits touched in the same session. A work-pattern signal mined from git history, not a declared dependency."
+ action={
+ <SectionLink href="/workspace/co-changes" LinkComponent={Link}>
+ All co-changes
+ </SectionLink>
+ }
+ >
+ <CoChangeTable coChanges={coChanges.co_changes} compact />
+ </OverviewSection>
+ )}
+ </PageShell>
+ );
+}
- {/* Repo Cards */}
- <section>
- <h2 className="text-sm font-medium text-[var(--color-text-primary)] mb-3">
- Repositories
- </h2>
- {wsRepos.length === 0 && (
- <EmptyState
- title="No repositories discovered yet"
- description="Run `repowise init .` in the workspace root to scan for git repositories and index them. They show up here as soon as the scan lands."
- icon={<Layers className="h-8 w-8" />}
- />
- )}
- <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
- {wsRepos.map((wsRepo) => {
- const status = wsRepo.status ?? (wsRepo.repo_id ? "indexed" : "needs_index");
- const isUnindexed = status !== "indexed";
- return (
- <RepoCard
- key={wsRepo.alias}
- repoId={wsRepo.repo_id ?? ""}
- alias={wsRepo.alias}
- name={wsRepo.alias}
- path={wsRepo.path}
- isPrimary={wsRepo.is_primary}
- status={status}
- docsSkipReason={wsRepo.docs_skip_reason ?? null}
- stats={wsRepo.file_count > 0 ? {
- file_count: wsRepo.file_count,
- doc_coverage_pct: wsRepo.doc_coverage_pct,
- } : null}
- gitSummary={wsRepo.file_count > 0 ? {
- hotspot_count: wsRepo.hotspot_count,
- } : null}
- actions={
- status !== "missing_dir" ? (
- <SyncButton
- alias={wsRepo.alias}
- label={isUnindexed ? "Index now" : "Sync"}
- />
- ) : null
- }
- />
- );
- })}
- </div>
- </section>
+/** Status the server may not have stamped yet, derived the same way everywhere. */
+function statusOf(repo: WorkspaceRepoEntry): "indexed" | "needs_index" | "missing_dir" {
+ return repo.status ?? (repo.repo_id ? "indexed" : "needs_index");
+}
- {/* Cross-Repo Graph */}
- <WorkspaceGraphSection repoCount={wsRepos.length} />
+/**
+ * Worst first: never indexed, then missing on disk, then lowest health.
+ * Mirrors the dashboard's ordering so the two lists read the same way.
+ */
+function byAttention(a: WorkspaceRepoEntry, b: WorkspaceRepoEntry): number {
+ const rank = (r: WorkspaceRepoEntry) => {
+ const s = statusOf(r);
+ if (s === "needs_index") return 0;
+ if (s === "missing_dir") return 1;
+ return 2;
+ };
+ const byRank = rank(a) - rank(b);
+ if (byRank !== 0) return byRank;
+ // A repo with no score sorts after scored ones rather than as a zero.
+ const ha = a.health_score ?? Number.POSITIVE_INFINITY;
+ const hb = b.health_score ?? Number.POSITIVE_INFINITY;
+ return ha - hb;
+}
- {/* Cross-Repo Intelligence */}
- {(workspace?.cross_repo_summary || workspace?.contract_summary) && (
- <section>
- <h2 className="text-sm font-medium text-[var(--color-text-primary)] mb-3">
- Cross-Repo Intelligence
- </h2>
- <CrossRepoSummary
- crossRepo={workspace?.cross_repo_summary ?? null}
- contracts={workspace?.contract_summary ?? null}
- />
+function toRow(repo: WorkspaceRepoEntry): RepoRow {
+ return {
+ id: repo.alias,
+ name: repo.alias,
+ localPath: repo.path,
+ href: repo.repo_id ? `/repos/${repo.repo_id}/overview` : "/workspace",
+ status: statusOf(repo),
+ // The wire carries 0-100; RepoRows and `bandForScore` are both 0-10.
+ // Optional on the type, so a web build ahead of its server shows "—"
+ // rather than NaN.
+ health: repo.health_score == null ? null : repo.health_score / 10,
+ fileCount: repo.file_count,
+ hotspotCount: repo.hotspot_count,
+ // The workspace payload has no per-repo fresh-page or dead-export counts.
+ // Zero here means the row omits those clauses; it never prints "0% fresh",
+ // which would report a missing measurement as a bad one.
+ docPageCount: 0,
+ docFreshPageCount: 0,
+ deadExportCount: 0,
+ updatedAt: repo.indexed_at,
+ indexBehind: null,
+ };
+}
- {/* Contract type breakdown */}
- {workspace?.contract_summary && workspace.contract_summary.total_links > 0 && (
- <Card className="mt-3">
- <CardHeader className="pb-2">
- <div className="flex items-center justify-between">
- <CardTitle className="text-sm font-medium flex items-center gap-2">
- <Link2 className="h-4 w-4 text-[var(--color-accent-primary)]" />
- API Contracts
- </CardTitle>
- <Link
- href="/workspace/contracts"
- className="text-xs text-[var(--color-accent-primary)] hover:underline flex items-center gap-1"
- >
- View all <ArrowRight className="h-3 w-3" />
- </Link>
- </div>
- </CardHeader>
- <CardContent className="pt-0">
- <div className="flex items-center gap-3">
- {Object.entries(workspace.contract_summary.by_type).map(([type, count]) => (
- <div key={type} className="flex items-center gap-1.5">
- <ContractTypeBadge type={type} />
- <span className="text-xs text-[var(--color-text-secondary)] tabular-nums">
- {count}
- </span>
- </div>
- ))}
- </div>
- </CardContent>
- </Card>
- )}
- </section>
- )}
+/** One sentence naming what needs doing, or confirming nothing does. */
+function attentionSentence(repos: WorkspaceRepoEntry[]): string {
+ const names = (list: WorkspaceRepoEntry[]) =>
+ list.length <= 3
+ ? list.map((r) => r.alias).join(", ")
+ : `${list
+ .slice(0, 3)
+ .map((r) => r.alias)
+ .join(", ")} and ${list.length - 3} more`;
- {/* Top Co-Changes */}
- {coChanges && coChanges.co_changes.length > 0 && (
- <section>
- <Card>
- <CardHeader className="pb-2">
- <div className="flex items-center justify-between">
- <CardTitle className="text-sm font-medium flex items-center gap-2">
- <GitMerge className="h-4 w-4 text-[var(--color-accent-primary)]" />
- Top Cross-Repo Co-Changes
- </CardTitle>
- <Link
- href="/workspace/co-changes"
- className="text-xs text-[var(--color-accent-primary)] hover:underline flex items-center gap-1"
- >
- View all <ArrowRight className="h-3 w-3" />
- </Link>
- </div>
- </CardHeader>
- <CardContent className="pt-0">
- <CoChangeTable coChanges={coChanges.co_changes} compact />
- </CardContent>
- </Card>
- </section>
- )}
- </div>
+ const parts: string[] = [];
+ const needsIndex = repos.filter((r) => statusOf(r) === "needs_index");
+ const missing = repos.filter((r) => statusOf(r) === "missing_dir");
+ const docsSkipped = repos.filter((r) => r.docs_skip_reason);
+
+ if (needsIndex.length > 0) {
+ parts.push(
+ `${needsIndex.length} ${needsIndex.length === 1 ? "repository has" : "repositories have"} not been indexed yet (${names(needsIndex)})`,
+ );
+ }
+ if (missing.length > 0) {
+ parts.push(
+ `${missing.length} ${missing.length === 1 ? "directory is" : "directories are"} missing on disk (${names(missing)})`,
+ );
+ }
+ if (docsSkipped.length > 0) {
+ parts.push(
+ `documentation was skipped for ${docsSkipped.length} (${names(docsSkipped)})`,
+ );
+ }
+
+ if (parts.length === 0) {
+ return "Every registered repository is indexed and present on disk.";
+ }
+ return `${parts.join("; ")}. Each is marked in the list below.`;
+}
+
+/**
+ * Name repositories the cross-repo artifacts cover but the config no longer
+ * registers.
+ *
+ * The two halves of this page come from different sources: the repo list is
+ * read from `.repowise-workspace.yaml` while every cross-repo figure is folded
+ * out of the persisted artifacts. When the config loses a repo, the page shows
+ * a small repo count directly above figures spanning more of them, and nothing
+ * says why. Saying it is cheap; the disagreement is itself the signal.
+ */
+function unregisteredNote(
+ repos: WorkspaceRepoEntry[],
+ crossRepo: { top_connections: Array<{ repos: string[] }> } | null,
+): ReactNode {
+ if (!crossRepo) return null;
+ const registered = new Set(repos.map((r) => r.alias));
+ const seen = new Set<string>();
+ for (const c of crossRepo.top_connections) {
+ for (const alias of c.repos) {
+ if (!registered.has(alias)) seen.add(alias);
+ }
+ }
+ if (seen.size === 0) return null;
+ const names = [...seen].sort();
+ return (
+ <p>
+ Cross-repo figures below also cover {names.length}{" "}
+ {names.length === 1 ? "repository" : "repositories"} the workspace config no longer
+ registers ({names.join(", ")}). Re-run a workspace sync to bring the two back into
+ agreement.
+ </p>
);
}
diff --git a/packages/web/src/app/workspace/workspace-graph-section.tsx b/packages/web/src/app/workspace/workspace-graph-section.tsx
deleted file mode 100644
index 7fc207276..000000000
--- a/packages/web/src/app/workspace/workspace-graph-section.tsx
+++ /dev/null
@@ -1,83 +0,0 @@
-"use client";
-
-import { useEffect, useState } from "react";
-import { useRouter } from "next/navigation";
-import { Network, Loader2 } from "lucide-react";
-import { Card, CardContent, CardHeader, CardTitle } from "@repowise-dev/ui/ui/card";
-import { WorkspaceGraph, type WorkspaceGraphData } from "@repowise-dev/ui/workspace/workspace-graph";
-import { EmptyState } from "@repowise-dev/ui/shared/empty-state";
-import { getWorkspaceGraph } from "@/lib/api/workspace";
-
-interface WorkspaceGraphSectionProps {
- repoCount: number;
-}
-
-export function WorkspaceGraphSection({ repoCount }: WorkspaceGraphSectionProps) {
- const router = useRouter();
- const [data, setData] = useState<WorkspaceGraphData | null>(null);
- const [loading, setLoading] = useState(true);
-
- useEffect(() => {
- if (repoCount < 2) {
- setLoading(false);
- return;
- }
- getWorkspaceGraph()
- .then(setData)
- .catch(() => setData(null))
- .finally(() => setLoading(false));
- }, [repoCount]);
-
- if (repoCount < 2) {
- return (
- <section>
- <h2 className="text-sm font-medium text-[var(--color-text-primary)] mb-3">
- Cross-Repo Graph
- </h2>
- <EmptyState
- icon={<Network className="h-8 w-8" />}
- title="Not enough repositories"
- description="Add at least 2 repositories to see cross-repo relationships."
- />
- </section>
- );
- }
-
- return (
- <section>
- <h2 className="text-sm font-medium text-[var(--color-text-primary)] mb-3">
- Cross-Repo Graph
- </h2>
- <Card>
- <CardHeader className="pb-2">
- <CardTitle className="text-sm font-medium flex items-center gap-2">
- <Network className="h-4 w-4 text-[var(--color-accent-primary)]" />
- Workspace Overview
- </CardTitle>
- </CardHeader>
- <CardContent className="pt-0">
- <div className="h-[450px] rounded-lg overflow-hidden border border-[var(--color-border-default)]">
- {loading ? (
- <div className="flex items-center justify-center h-full">
- <Loader2 className="w-5 h-5 animate-spin text-[var(--color-text-tertiary)]" />
- </div>
- ) : data && data.nodes.length >= 2 ? (
- <WorkspaceGraph
- data={data}
- onRepoClick={(repoId) => router.push(`/repos/${repoId}/architecture?view=graph`)}
- />
- ) : (
- <div className="flex items-center justify-center h-full">
- <EmptyState
- icon={<Network className="h-8 w-8" />}
- title="No graph data"
- description="Repository data is still being indexed."
- />
- </div>
- )}
- </div>
- </CardContent>
- </Card>
- </section>
- );
-}
diff --git a/tests/unit/server/test_workspace_router.py b/tests/unit/server/test_workspace_router.py
index 5782dad72..f04f0bb5a 100644
--- a/tests/unit/server/test_workspace_router.py
+++ b/tests/unit/server/test_workspace_router.py
@@ -6,7 +6,7 @@ import json
import sqlite3
from contextlib import asynccontextmanager
from pathlib import Path
-from unittest.mock import MagicMock
+from unittest.mock import MagicMock, patch
import pytest
from fastapi import FastAPI
@@ -509,6 +509,32 @@ class TestGetWorkspaceGraph:
assert backend["health_score"] == 62.0
assert backend["health_score_source"] == "derived"
+ @pytest.mark.asyncio
+ async def test_weights_a_zero_nloc_file_as_one_line(self, tmp_path: Path) -> None:
+ """A zero-nloc row still counts once, rather than dropping out of the average.
+
+ The score is a weighted mean over nloc, so a naive weight would let an
+ empty file contribute nothing. Both scores here would otherwise average
+ to 80.0; the clamped weight is what makes it 60.0.
+ """
+ ws_config = _make_ws_config()
+ _create_workspace_repo_db(
+ tmp_path,
+ "backend",
+ health_rows=[(4.0, 0), (8.0, 1)],
+ )
+ app = _make_workspace_app(
+ ws_config=ws_config,
+ workspace_root=str(tmp_path),
+ )
+ transport = ASGITransport(app=app)
+ async with AsyncClient(transport=transport, base_url="http://test") as c:
+ resp = await c.get("/api/workspace/graph")
+
+ assert resp.status_code == 200
+ backend = next(n for n in resp.json()["nodes"] if n["name"] == "backend")
+ assert backend["health_score"] == 60.0
+
# ---------------------------------------------------------------------------
# Tests — _query_repo_stats
@@ -1034,3 +1060,98 @@ class TestGetConformance:
data = resp.json()
assert data["violation_count"] == 0
assert data["cycle_count"] == 0
+
+
+# ---------------------------------------------------------------------------
+# Tests — per-repo query budget
+# ---------------------------------------------------------------------------
+
+
+class TestRepoQueryBudget:
+ """Pin the per-repo sqlite cost of the workspace listing.
+
+ Workspace repos each live in their own wiki.db, so unlike the dashboard's
+ /api/repos/summary there is no shared table to GROUP BY and the total query
+ count is necessarily O(repos). What must stay flat is the cost *per* repo:
+ this fails if someone adds a query to the loop or reintroduces a second
+ sweep over the same databases.
+ """
+
+ QUERIES_PER_REPO = 7
+ CONNECTIONS_PER_REPO = 2
+
+ def _config_for(self, aliases: list[str]):
+ ws_config = MagicMock()
+ repos = []
+ for i, alias in enumerate(aliases):
+ r = MagicMock()
+ r.alias = alias
+ r.path = f"./{alias}"
+ r.is_primary = i == 0
+ r.indexed_at = None
+ r.last_commit_at_index = None
+ repos.append(r)
+ ws_config.repos = repos
+ ws_config.default_repo = aliases[0]
+ return ws_config
+
+ async def _measure(self, tmp_path: Path, count: int) -> tuple[int, int]:
+ """Return (statements, connections) for one GET /api/workspace."""
+ root = tmp_path / f"ws{count}"
+ aliases = [f"repo{i}" for i in range(count)]
+ for alias in aliases:
+ _create_workspace_repo_db(root, alias, health_rows=[(7.0, 100)])
+
+ statements = 0
+ connections = 0
+ real_connect = sqlite3.connect
+
+ def counting_connect(*args, **kwargs):
+ nonlocal connections
+ connections += 1
+ conn = real_connect(*args, **kwargs)
+
+ def trace(_stmt):
+ nonlocal statements
+ statements += 1
+
+ conn.set_trace_callback(trace)
+ return conn
+
+ app = _make_workspace_app(
+ ws_config=self._config_for(aliases),
+ workspace_root=str(root),
+ )
+ transport = ASGITransport(app=app)
+ with patch.object(sqlite3, "connect", counting_connect):
+ async with AsyncClient(transport=transport, base_url="http://test") as c:
+ resp = await c.get("/api/workspace")
+ assert resp.status_code == 200
+ assert len(resp.json()["repos"]) == count
+ return statements, connections
+
+ @pytest.mark.asyncio
+ async def test_per_repo_cost_does_not_grow_with_repo_count(
+ self, tmp_path: Path
+ ) -> None:
+ two_stmts, two_conns = await self._measure(tmp_path, 2)
+ six_stmts, six_conns = await self._measure(tmp_path, 6)
+
+ assert two_stmts / 2 == six_stmts / 6, (
+ f"per-repo statements moved from {two_stmts / 2} (2 repos) to "
+ f"{six_stmts / 6} (6 repos) — the loop is doing more work per repo"
+ )
+ assert two_conns / 2 == six_conns / 6, (
+ f"per-repo connections moved from {two_conns / 2} to {six_conns / 6}"
+ )
+
+ @pytest.mark.asyncio
+ async def test_per_repo_cost_is_pinned(self, tmp_path: Path) -> None:
+ """Pinned so "flat" has a value, and so a second sweep cannot slip back in.
+
+ Six stats queries plus one weighted health average, over one connection
+ for the stats block and one for the health read.
+ """
+ statements, connections = await self._measure(tmp_path, 3)
+ assert statements == self.QUERIES_PER_REPO * 3
+ assert connections == self.CONNECTIONS_PER_REPO * 3