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): group the repo sidebar, give Tests and Security their own pages (#4142)

Raghav Chamadiyaa2b04e6360a3
diff --git a/packages/core/src/repowise/core/analysis/test_reachability.py b/packages/core/src/repowise/core/analysis/test_reachability.py
index f769ad8f7..5fb1e560e 100644
--- a/packages/core/src/repowise/core/analysis/test_reachability.py
+++ b/packages/core/src/repowise/core/analysis/test_reachability.py
@@ -199,6 +199,7 @@ __all__ = [
"ReachDistance",
"ReachedBy",
"any_tests_reaching",
+ "cached_files_reached_by_tests",
"cached_test_files",
"call_graph_from_db",
"call_graph_from_graph",
@@ -280,30 +281,30 @@ async def call_graph_from_db(session: AsyncSession, repo_id: str) -> CallGraphVi
walk is seeded with a change's files; this question is seeded with the
repository, and a per-level ``IN`` list over every file is the shape it was
explicitly not built for.
+
+ The view carries no call-site lines: reachability reads only ``declares``
+ and the forward/reverse adjacency, and ``call_lines_json`` was most of the
+ read's cost (measured on this repository, 189k edges: 8.4 s cold with the
+ column, under 2 s without it).
"""
wanted = ["defines", *sorted(EXECUTION_EDGE_TYPES)]
params: dict[str, Any] = {"repo_id": repo_id}
ets = _in_clause("e", wanted, params)
rows = await session.execute(
text(
- "SELECT source_node_id, target_node_id, edge_type, resolution_origin, "
- "call_lines_json "
+ "SELECT source_node_id, target_node_id, edge_type, resolution_origin "
"FROM graph_edges WHERE repository_id = :repo_id "
f"AND edge_type IN ({ets}) "
"ORDER BY source_node_id, target_node_id, edge_type"
),
params,
)
- edge_rows = []
- for src, dst, edge_type, origin, call_lines_json in rows:
- try:
- call_lines = json.loads(call_lines_json or "[]")
- except (TypeError, ValueError):
- call_lines = []
- edge_rows.append((src, dst, edge_type, origin, call_lines))
- # No spawn lines here: test reachability reads only forward/reverse, never
- # first-hop sites, ``spawn_only`` or roles, and a spawned callee is still reached.
- return ExecutionGraphIndex(edge_rows=edge_rows)
+ # No call or spawn lines here: test reachability reads only forward/reverse,
+ # never first-hop sites, ``spawn_only`` or roles, and a spawned callee is
+ # still reached.
+ return ExecutionGraphIndex(
+ edge_rows=((src, dst, edge_type, origin, None) for src, dst, edge_type, origin in rows)
+ )
def files_reached_by_tests(
@@ -449,6 +450,21 @@ async def cached_test_files(session: AsyncSession, repo_id: str) -> frozenset[st
return _cache.remember(key, frozenset(await load_test_files(session, repo_id)))
+async def cached_files_reached_by_tests(session: AsyncSession, repo_id: str) -> frozenset[str]:
+ """:func:`files_reached_by_tests` over the stored graph, walked once per index state.
+
+ The Tests page asks this on every load and the answer moves only when an
+ index run rewrites the graph, so the bulk edge read is paid once per index.
+ """
+ key = await _cache_key(session, repo_id, "files_reached")
+ if key in _cache:
+ _cache.move_to_end(key)
+ return _cache[key]
+ test_files = set(await cached_test_files(session, repo_id))
+ view = await call_graph_from_db(session, repo_id)
+ return _remember(key, frozenset(files_reached_by_tests(view, test_files)))
+
+
async def any_tests_reaching(
session: AsyncSession, repo_id: str, targets: Collection[str]
) -> dict[str, ReachedBy]:
diff --git a/packages/server/src/repowise/server/routers/code_health/coverage_routes.py b/packages/server/src/repowise/server/routers/code_health/coverage_routes.py
index a9d663b81..27717d246 100644
--- a/packages/server/src/repowise/server/routers/code_health/coverage_routes.py
+++ b/packages/server/src/repowise/server/routers/code_health/coverage_routes.py
@@ -21,9 +21,8 @@ from fastapi import Depends, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.analysis.test_reachability import (
- call_graph_from_db,
- files_reached_by_tests,
- load_test_files,
+ cached_files_reached_by_tests,
+ cached_test_files,
tests_reaching_by_tier,
)
from repowise.core.persistence import crud
@@ -217,7 +216,7 @@ async def _inferred_coverage(
wrong trade.
"""
try:
- test_files = await load_test_files(session, repo_id)
+ test_files = await cached_test_files(session, repo_id)
if not test_files:
return {
"basis": "none",
@@ -257,8 +256,8 @@ async def _inferred_coverage(
"test_file_count": len(test_files),
},
}
- view = await call_graph_from_db(session, repo_id)
- reached = files_reached_by_tests(view, test_files)
+ # Walked once per index state: the edge read is the cost of this tab.
+ reached = await cached_files_reached_by_tests(session, repo_id)
except Exception:
return {
"basis": "none",
diff --git a/packages/ui/__tests__/dead-code/findings-table.test.tsx b/packages/ui/__tests__/dead-code/findings-table.test.tsx
index 92617cfb5..4ffd17946 100644
--- a/packages/ui/__tests__/dead-code/findings-table.test.tsx
+++ b/packages/ui/__tests__/dead-code/findings-table.test.tsx
@@ -284,18 +284,21 @@ describe("FindingsTable row affordances", () => {
expect(inTable().getByText("No importers in the dependency graph")).toBeInTheDocument();
});
- it("offers an AI prompt per row and for the current selection", () => {
+ it("leads each row with the agent prompt and offers one for the filtered rows or the selection", () => {
const onGeneratePrompt = vi.fn();
renderTable([finding({ id: "a" }), finding({ id: "b" })], { onGeneratePrompt });
- // Per-row: behind the overflow, with Resolve as the row's one visible verb.
- fireEvent.click(inTable().getByRole("button", { name: "More actions for src/a.ts" }));
- fireEvent.click(screen.getByRole("button", { name: "Draft AI cleanup prompt" }));
+ // Per-row: the prompt leads the row, named for the file it is about.
+ fireEvent.click(inTable().getByRole("button", { name: "Copy prompt for your agent: src/a.ts" }));
expect(onGeneratePrompt).toHaveBeenCalledWith(["a"]);
- fireEvent.click(screen.getByLabelText("Select all findings"));
- fireEvent.click(screen.getByRole("button", { name: "AI prompt for 2 selected" }));
+ // Header: every row the filters show, until there is a selection.
+ fireEvent.click(screen.getByRole("button", { name: "Copy prompt for these 2" }));
expect(onGeneratePrompt).toHaveBeenLastCalledWith(["a", "b"]);
+
+ fireEvent.click(inTable().getByLabelText("Select finding src/a.ts"));
+ fireEvent.click(screen.getByRole("button", { name: "Copy prompt for 1 selected" }));
+ expect(onGeneratePrompt).toHaveBeenLastCalledWith(["a"]);
});
it("renders the graph action from the host's route, and hides it without one", () => {
diff --git a/packages/ui/__tests__/health/batch-prompts.test.ts b/packages/ui/__tests__/health/batch-prompts.test.ts
new file mode 100644
index 000000000..cc9027c11
--- /dev/null
+++ b/packages/ui/__tests__/health/batch-prompts.test.ts
@@ -0,0 +1,45 @@
+import { describe, it, expect } from "vitest";
+
+import {
+ buildCoverageAiPrompt,
+ buildCoverageBatchAiPrompt,
+ buildSecurityAiPrompt,
+ buildSecurityBatchAiPrompt,
+} from "../../src/health/ai-prompt-builder";
+
+const finding = (i: number, kind = "weak_hash") => ({
+ file_path: `src/f${i}.py`,
+ kind,
+ severity: "low",
+ line_number: i,
+});
+const row = (i: number) => ({ file_path: `src/f${i}.py`, line_coverage_pct: i, health_score: 5 });
+
+describe("batch prompts", () => {
+ it("fall back to the single prompt for one row", () => {
+ expect(buildSecurityBatchAiPrompt({ findings: [finding(1)] })).toBe(
+ buildSecurityAiPrompt({ finding: finding(1) }),
+ );
+ expect(buildCoverageBatchAiPrompt({ rows: [row(1)] })).toBe(buildCoverageAiPrompt({ row: row(1) }));
+ });
+
+ it("list every row up to the cap and count the rest", () => {
+ const security = buildSecurityBatchAiPrompt({
+ findings: Array.from({ length: 45 }, (_, i) => finding(i)),
+ });
+ expect(security).toContain("Findings: **45**");
+ expect(security).toContain("`src/f3.py:3` — **weak_hash** (LOW)");
+ expect(security).toContain("…and 5 more");
+
+ const coverage = buildCoverageBatchAiPrompt({ rows: Array.from({ length: 3 }, (_, i) => row(i)) });
+ expect(coverage).toContain("`src/f2.py` — line coverage 2.0%, health 5.0/10");
+ expect(coverage).not.toContain("more in the same list");
+ });
+
+ it("keeps the rotation note when any finding in the batch is a secret", () => {
+ const prompt = buildSecurityBatchAiPrompt({
+ findings: [finding(1), finding(2, "public_env_secret")],
+ });
+ expect(prompt).toContain("**rotated**");
+ });
+});
diff --git a/packages/ui/__tests__/health/bulk-agent-prompt-label.test.ts b/packages/ui/__tests__/health/bulk-agent-prompt-label.test.ts
new file mode 100644
index 000000000..327161294
--- /dev/null
+++ b/packages/ui/__tests__/health/bulk-agent-prompt-label.test.ts
@@ -0,0 +1,13 @@
+import { describe, expect, it } from "vitest";
+
+import { bulkAgentPromptLabel } from "../../src/health/ai-prompt-action";
+
+describe("bulkAgentPromptLabel", () => {
+ it("names one item as this one, not these 1", () => {
+ expect(bulkAgentPromptLabel(1)).toBe("Copy prompt for this one");
+ });
+
+ it("counts a group", () => {
+ expect(bulkAgentPromptLabel(4)).toBe("Copy prompt for these 4");
+ });
+});
diff --git a/packages/ui/__tests__/health/row-prompt-action.test.tsx b/packages/ui/__tests__/health/row-prompt-action.test.tsx
new file mode 100644
index 000000000..b062aae9d
--- /dev/null
+++ b/packages/ui/__tests__/health/row-prompt-action.test.tsx
@@ -0,0 +1,39 @@
+import { describe, it, expect, vi } from "vitest";
+import { fireEvent, render, screen } from "@testing-library/react";
+
+import { PromptForRowsButton, RowPromptAction } from "../../src/health/row-prompt-action";
+
+describe("RowPromptAction", () => {
+ it("is a ghost action, hidden until row hover, focus or selection, and named for its row", () => {
+ const onClick = vi.fn();
+ const onRow = vi.fn();
+ render(
+ <div className="group/row" onClick={onRow}>
+ <RowPromptAction subject="src/a.ts" onClick={onClick} />
+ </div>,
+ );
+ const button = screen.getByRole("button", { name: "Copy prompt for your agent: src/a.ts" });
+ expect(button).toHaveTextContent("Copy prompt for your agent");
+ expect(button.className).toMatch(/opacity-0/);
+ expect(button.className).toMatch(/group-hover\/row:opacity-100/);
+ expect(button.className).toMatch(/group-focus-within\/row:opacity-100/);
+ expect(button.className).toMatch(/focus-visible:opacity-100/);
+ // No resting fill: the model tint appears on hover only.
+ expect(button.className.split(" ")).not.toContain("bg-[var(--color-model-muted)]");
+ fireEvent.click(button);
+ expect(onClick).toHaveBeenCalledOnce();
+ // The row's own click (open the file) does not fire as well.
+ expect(onRow).not.toHaveBeenCalled();
+ });
+});
+
+describe("PromptForRowsButton", () => {
+ it("counts the rows it covers and renders nothing for none", () => {
+ const onClick = vi.fn();
+ const { rerender, container } = render(<PromptForRowsButton count={12} onClick={onClick} />);
+ fireEvent.click(screen.getByRole("button", { name: "Copy prompt for these 12" }));
+ expect(onClick).toHaveBeenCalledOnce();
+ rerender(<PromptForRowsButton count={0} onClick={onClick} />);
+ expect(container).toBeEmptyDOMElement();
+ });
+});
diff --git a/packages/ui/__tests__/shared/clean-state.test.tsx b/packages/ui/__tests__/shared/clean-state.test.tsx
new file mode 100644
index 000000000..5b34e12ad
--- /dev/null
+++ b/packages/ui/__tests__/shared/clean-state.test.tsx
@@ -0,0 +1,22 @@
+import { describe, it, expect } from "vitest";
+import { render, screen } from "@testing-library/react";
+
+import { CleanState } from "../../src/shared/clean-state";
+
+describe("CleanState", () => {
+ it("is the positive tone, named with its scope, and unboxed", () => {
+ const { container } = render(
+ <CleanState title="No dead code across 5,612 files" description="No unreachable files." />,
+ );
+ const root = container.firstElementChild as HTMLElement;
+ expect(root).toHaveAttribute("data-tone", "positive");
+ expect(root.className).not.toMatch(/border-\[var/);
+ expect(screen.getByRole("heading", { name: "No dead code across 5,612 files" })).toBeInTheDocument();
+ expect(screen.getByText("No unreachable files.")).toBeInTheDocument();
+ });
+
+ it("aligns to the start when it sits under a lede", () => {
+ const { container } = render(<CleanState title="All clear" align="start" />);
+ expect((container.firstElementChild as HTMLElement).className).toMatch(/items-start/);
+ });
+});
diff --git a/packages/ui/src/commits/commits-lede.tsx b/packages/ui/src/commits/commits-lede.tsx
index 8181994a7..423383e4b 100644
--- a/packages/ui/src/commits/commits-lede.tsx
+++ b/packages/ui/src/commits/commits-lede.tsx
@@ -45,7 +45,7 @@ export function CommitsLede({ stats, base, LinkComponent }: CommitsLedeProps) {
value: stats.fix_commit_count.toLocaleString(),
unit: `${fixPct}%`,
why: "Commits whose subject reads as a bug fix rather than new work.",
- href: `${base}/code-health?tab=triage`,
+ href: `${base}/code-health`,
},
];
if (stats.agent_commit_count != null && stats.agent_commit_count > 0) {
@@ -83,7 +83,7 @@ export function CommitsLede({ stats, base, LinkComponent }: CommitsLedeProps) {
value: stats.high_cut.toFixed(1),
unit: "out of 10",
why: "Score a commit has to clear to land in this repo's top tercile.",
- href: `${base}/code-health?tab=triage`,
+ href: `${base}/code-health`,
});
}
diff --git a/packages/ui/src/dashboard/attention-href.ts b/packages/ui/src/dashboard/attention-href.ts
index 4664c3c7e..19e121ba1 100644
--- a/packages/ui/src/dashboard/attention-href.ts
+++ b/packages/ui/src/dashboard/attention-href.ts
@@ -89,7 +89,7 @@ export function attentionSourceHref(source: string, prefix: string): string {
// `doc_drift` and `dead_code` name an area and an item type at once and
// route to the same page either way, so they need no separate case.
case "security":
- return `${prefix}/code-health?tab=security`;
+ return `${prefix}/security`;
case "health":
return `${prefix}/code-health?tab=findings`;
case "ownership":
@@ -101,13 +101,13 @@ export function attentionSourceHref(source: string, prefix: string): string {
case "knowledge_silo":
return `${prefix}/owners`;
case "ungoverned_hotspot":
- return `${prefix}/code-health?tab=triage`;
+ return `${prefix}/code-health`;
case "health_finding":
return `${prefix}/code-health?tab=findings`;
case "refactoring":
return `${prefix}/refactoring`;
case "security_finding":
- return `${prefix}/code-health?tab=security`;
+ return `${prefix}/security`;
case "doc_drift":
return `${prefix}/code-health?tab=doc-drift`;
case "dead_code":
diff --git a/packages/ui/src/dashboard/health-overview-card.tsx b/packages/ui/src/dashboard/health-overview-card.tsx
index 88c711a99..b162cf4d6 100644
--- a/packages/ui/src/dashboard/health-overview-card.tsx
+++ b/packages/ui/src/dashboard/health-overview-card.tsx
@@ -322,20 +322,20 @@ export function HealthOverviewCard({
{/* The scores above, checked against this repo's own git history. */}
{defectAccuracy && (
- <AccuracyStrip data={defectAccuracy} href={`${reportHref}?tab=triage`} />
+ <AccuracyStrip data={defectAccuracy} href={`${reportHref}`} />
)}
{/* Findings + worst performer */}
<div className="px-4 py-3.5 space-y-3">
{severityTotal > 0 ? (
<FindingsLine
- href={`${reportHref}?tab=triage`}
+ href={`${reportHref}`}
segments={severities}
count={data.open_findings}
/>
) : (
<a
- href={`${reportHref}?tab=triage`}
+ href={`${reportHref}`}
className="flex items-center gap-1.5 text-xs text-[var(--color-success)] hover:underline"
>
<ShieldAlert className="h-3 w-3" />
diff --git a/packages/ui/src/dashboard/hotspots-mini.tsx b/packages/ui/src/dashboard/hotspots-mini.tsx
index 05abd738f..616543647 100644
--- a/packages/ui/src/dashboard/hotspots-mini.tsx
+++ b/packages/ui/src/dashboard/hotspots-mini.tsx
@@ -66,7 +66,7 @@ export function HotspotsMini({
</span>
</span>
<a
- href={`${prefix}/code-health?tab=triage`}
+ href={`${prefix}/code-health`}
className="text-[10px] text-[var(--color-accent-primary)] hover:underline font-normal"
>
View all
diff --git a/packages/ui/src/dead-code/dead-code-view.tsx b/packages/ui/src/dead-code/dead-code-view.tsx
index 89b75c142..19883d8d0 100644
--- a/packages/ui/src/dead-code/dead-code-view.tsx
+++ b/packages/ui/src/dead-code/dead-code-view.tsx
@@ -32,6 +32,7 @@ import { Button } from "../ui/button";
import { Skeleton } from "../ui/skeleton";
import { ApiError } from "../shared/api-error";
import { EmptyState } from "../shared/empty-state";
+import { CleanState, type CleanStateCopy } from "../shared/clean-state";
import { Segmented } from "../shared/segmented";
import { OverviewSection } from "../overview/section";
import { AiPromptModal } from "../health/ai-prompt-modal";
@@ -75,10 +76,13 @@ function RetryCard({
export function DeadCodeView({
adapter,
ledeLabels,
+ clean: cleanCopy,
}: {
adapter: DeadCodeAdapter;
/** The lede's copy, for a host that translates it. */
ledeLabels?: Partial<DeadCodeLedeLabels>;
+ /** The clean state's copy, for a host that translates it or knows the file count. */
+ clean?: CleanStateCopy;
}) {
const [analyzing, setAnalyzing] = useState(false);
const [promptIds, setPromptIds] = useState<string[] | null>(null);
@@ -364,14 +368,13 @@ export function DeadCodeView({
{...(ledeLabels ? { labels: ledeLabels } : {})}
>
{clean ? (
- <EmptyState
- tone="positive"
- className="items-start px-0 py-0 text-left"
- title="No dead code found"
+ <CleanState
+ align="start"
+ title={cleanCopy?.title ?? "No dead code found"}
description={
<>
- No unreachable files, unused exports or zombie packages across this
- repository.
+ {cleanCopy?.description ??
+ "No unreachable files, unused exports or zombie packages across this repository."}
<AnalysedAt at={summary.analyzed_at} />
</>
}
diff --git a/packages/ui/src/dead-code/finding-cells.tsx b/packages/ui/src/dead-code/finding-cells.tsx
index c11454d05..df968978c 100644
--- a/packages/ui/src/dead-code/finding-cells.tsx
+++ b/packages/ui/src/dead-code/finding-cells.tsx
@@ -2,7 +2,7 @@
import { useState, type MouseEvent } from "react";
import type * as React from "react";
-import { CircleSlash, Eye, GitBranch, MoreHorizontal, Sparkles } from "lucide-react";
+import { CircleSlash, Eye, GitBranch, MoreHorizontal } from "lucide-react";
import { toast } from "sonner";
import { Button } from "../ui/button";
import { ConfirmDialog } from "../ui/confirm-dialog";
@@ -11,6 +11,7 @@ import { formatConfidence } from "../lib/format";
import { toFriendlyMessage } from "../lib/errors";
import { cn } from "../lib/cn";
import { PreviewBadge } from "../health/preview-badge";
+import { RowPromptAction } from "../health/row-prompt-action";
import {
deadCodeRiskFactorLabel,
type DeadCodeFinding,
@@ -278,6 +279,12 @@ export function FindingRowActions({
return (
<span onClick={(e) => e.stopPropagation()}>
<span className="flex items-center justify-end gap-1">
+ {onGeneratePrompt && (
+ <RowPromptAction
+ subject={finding.file_path}
+ onClick={() => onGeneratePrompt(finding.id)}
+ />
+ )}
{finding.status === "open" ? (
<Button
size="sm"
@@ -322,10 +329,6 @@ export function FindingRowActions({
)}
</>
)}
- {onGeneratePrompt &&
- menuItem("Draft AI cleanup prompt", Sparkles, () =>
- onGeneratePrompt(finding.id),
- )}
{graphHref && (
<a
href={graphHref(finding.file_path)}
diff --git a/packages/ui/src/dead-code/findings-table.tsx b/packages/ui/src/dead-code/findings-table.tsx
index 00b2ff5f3..32834647c 100644
--- a/packages/ui/src/dead-code/findings-table.tsx
+++ b/packages/ui/src/dead-code/findings-table.tsx
@@ -13,6 +13,7 @@ import { EmptyState } from "../shared/empty-state";
import { ResponsiveTable, type ResponsiveColumn } from "../shared/responsive-table";
import { toFriendlyMessage } from "../lib/errors";
import { AiPromptButton } from "../health/ai-prompt-button";
+import { PromptForRowsButton } from "../health/row-prompt-action";
import { formatDateTime, formatNumber, formatRelativeTimeOrNull } from "../lib/format";
import { FindingIdentity, FindingConfidence, FindingRowActions } from "./finding-cells";
import {
@@ -304,7 +305,7 @@ export function FindingsTable({
key: "path",
header: "File / Symbol",
sortable: true,
- cellClassName: "min-w-[200px] max-w-[480px]",
+ cellClassName: "min-w-[200px] max-w-[360px]",
render: (f) => (
<FindingIdentity
finding={f}
@@ -388,9 +389,8 @@ export function FindingsTable({
key: "actions",
header: <span className="sr-only">Actions</span>,
mobileLabel: "Actions",
- // Two controls, not five: the cell no longer has to reserve room for a
- // cluster that wrapped onto a second line at this width.
- headerClassName: "w-24",
+ // The agent prompt leads, Resolve follows, the rest sit in the menu.
+ headerClassName: "w-64",
align: "right",
render: (f) => (
<FindingRowActions
@@ -469,12 +469,20 @@ export function FindingsTable({
</Button>
)}
- {onGeneratePrompt && selectedCount > 0 && (
- <AiPromptButton
- label={`AI prompt for ${selectedCount} selected`}
- onClick={() => onGeneratePrompt(visibleSelected)}
- />
- )}
+ {/* The selection when there is one, else every row the filters show. */}
+ {onGeneratePrompt &&
+ (selectedCount > 0 ? (
+ <AiPromptButton
+ label={`Copy prompt for ${selectedCount} selected`}
+ onClick={() => onGeneratePrompt(visibleSelected)}
+ className="whitespace-nowrap"
+ />
+ ) : (
+ <PromptForRowsButton
+ count={current.length}
+ onClick={() => onGeneratePrompt(current.map((f) => f.id))}
+ />
+ ))}
</div>
<ConfirmDialog
open={bulkConfirmOpen}
diff --git a/packages/ui/src/doc-drift/doc-drift-view.tsx b/packages/ui/src/doc-drift/doc-drift-view.tsx
index a756a4047..fe3f9b533 100644
--- a/packages/ui/src/doc-drift/doc-drift-view.tsx
+++ b/packages/ui/src/doc-drift/doc-drift-view.tsx
@@ -34,7 +34,7 @@ import {
import { Skeleton } from "../ui/skeleton";
import { ApiError } from "../shared/api-error";
-import { EmptyState } from "../shared/empty-state";
+import { CleanState, type CleanStateCopy } from "../shared/clean-state";
import { CiHint } from "../shared/ci-hint";
import { OverviewSection } from "../overview/section";
import { toFriendlyMessage } from "../lib/errors";
@@ -92,8 +92,11 @@ export function DocDriftView({
renderError,
renderLoading,
initialDocument,
+ clean: cleanCopy,
}: {
adapter: DocDriftAdapter;
+ /** The clean state's copy, for a host that translates it. */
+ clean?: CleanStateCopy | undefined;
/** Open narrowed to one document, e.g. from a `?document=` deep link. */
initialDocument?: string | undefined;
/** Host-specific failure card — an auth toast, a permissions notice. */
@@ -209,10 +212,12 @@ export function DocDriftView({
{summary.findings_total === 0 && !filtered ? (
<div className="flex flex-col items-center gap-2">
- <EmptyState
- tone="positive"
- title="No documentation drift found"
- description="Every reference this detector could resolve still resolves. It re-checks on each update, so this is worth a second look after a rename or a move."
+ <CleanState
+ title={cleanCopy?.title ?? "No documentation drift found"}
+ description={
+ cleanCopy?.description ??
+ "Every reference this detector could resolve still resolves. It re-checks on each update, so this is worth a second look after a rename or a move."
+ }
/>
<CiHint command="repowise doc-drift --check" checks="that every reference in the docs still resolves" />
</div>
diff --git a/packages/ui/src/docs/docs-header.tsx b/packages/ui/src/docs/docs-header.tsx
index 1f22022c5..c0c3f2a14 100644
--- a/packages/ui/src/docs/docs-header.tsx
+++ b/packages/ui/src/docs/docs-header.tsx
@@ -1,6 +1,6 @@
"use client";
-import { BookOpen, BarChart3 } from "lucide-react";
+import { BookOpen, BarChart3, FileWarning } from "lucide-react";
import { cn } from "../lib/cn";
import type { ReaderLinkComponent } from "./docs-reader";
@@ -8,17 +8,20 @@ export interface DocsHeaderTab {
label: string;
href: string;
isActive: boolean;
- icon: "explorer" | "freshness";
+ icon: "explorer" | "freshness" | "drift";
+ /** A cheap count shown beside the label, e.g. open drift findings. */
+ badge?: number | undefined;
}
const ICONS = {
explorer: BookOpen,
freshness: BarChart3,
+ drift: FileWarning,
} as const;
/**
* Single compact chrome row for the documentation surface: the Explorer /
- * Doc-freshness view switch as a segmented control, and a right-aligned slot
+ * Doc freshness / Doc drift view switch as a segmented control, and a right-aligned slot
* for page-specific actions. Pure presentation — the host resolves tab
* hrefs/active state and injects a router-aware ``LinkComponent``.
*
@@ -67,6 +70,11 @@ export function DocsHeader({
in the row and the least load-bearing, since the active tab is
already marked by its filled ground. */}
<span className="hidden sm:inline">{tab.label}</span>
+ {tab.badge !== undefined && (
+ <span className="font-mono text-[10px] tabular-nums text-[var(--color-text-tertiary)]">
+ {tab.badge}
+ </span>
+ )}
</Link>
);
})}
diff --git a/packages/ui/src/git/ownership-table.tsx b/packages/ui/src/git/ownership-table.tsx
index be84abca1..a9cf63e5e 100644
--- a/packages/ui/src/git/ownership-table.tsx
+++ b/packages/ui/src/git/ownership-table.tsx
@@ -132,7 +132,7 @@ export function OwnershipTable({ entries, repoId, linkPrefix }: OwnershipTablePr
<RowActions
actions={[
{ icon: GitBranch, label: "Graph", href: `${prefix}/architecture?view=files&node=${encodeURIComponent(entry.module_path)}` },
- { icon: Flame, label: "Hotspots", href: `${prefix}/code-health?tab=triage` },
+ { icon: Flame, label: "Hotspots", href: `${prefix}/code-health` },
]}
/>
)}
diff --git a/packages/ui/src/health/ai-prompt-action.tsx b/packages/ui/src/health/ai-prompt-action.tsx
new file mode 100644
index 000000000..ce8c4210c
--- /dev/null
+++ b/packages/ui/src/health/ai-prompt-action.tsx
@@ -0,0 +1,67 @@
+"use client";
+
+import { lazy, Suspense, useCallback, useMemo, useState, type ReactNode } from "react";
+import type { ChatContext } from "@repowise-dev/types/chat";
+
+import type { AiPromptFlavor } from "./ai-prompt-builder";
+import type { PromptSource } from "./ai-prompt-modal";
+
+/**
+ * The one "prompt for your agent" action: a surface describes the prompt it
+ * wants, and this opens the shared modal on it. People fix issues through
+ * their agents, so this is the primary verb on every actionable item; the
+ * modal is loaded only the first time somebody asks for a prompt.
+ */
+
+const AiPromptModal = lazy(() =>
+ import("./ai-prompt-modal").then((module) => ({ default: module.AiPromptModal })),
+);
+
+/** The label every actionable row's primary button carries. */
+export const AGENT_PROMPT_LABEL = "Copy prompt for your agent";
+
+/** The same verb for a group: "Copy prompt for these 4", or "this one" for one. */
+export function bulkAgentPromptLabel(count: number): string {
+ return count === 1 ? "Copy prompt for this one" : `Copy prompt for these ${count.toLocaleString()}`;
+}
+
+export interface AiPromptRequest {
+ title: string;
+ description?: string;
+ /** One-line identifier beside the title, usually a path. */
+ filePath?: string | null;
+ /** A pure builder; ignored when `promptSource` is given. */
+ getPrompt?: ((flavor: AiPromptFlavor) => string) | null;
+ /** A fetched prompt. Held for the life of the request, so it fetches once per flavor. */
+ promptSource?: PromptSource;
+ chatContext?: ChatContext;
+}
+
+export function useAiPromptAction(): {
+ openPrompt: (request: AiPromptRequest) => void;
+ promptModal: ReactNode;
+} {
+ const [request, setRequest] = useState<AiPromptRequest | null>(null);
+ const openPrompt = useCallback((next: AiPromptRequest) => setRequest(next), []);
+ const promptModal = useMemo(
+ () =>
+ request ? (
+ <Suspense fallback={null}>
+ <AiPromptModal
+ open
+ onOpenChange={(open) => {
+ if (!open) setRequest(null);
+ }}
+ title={request.title}
+ {...(request.description ? { description: request.description } : {})}
+ filePath={request.filePath ?? null}
+ getPrompt={request.getPrompt ?? null}
+ promptSource={request.promptSource}
+ chatContext={request.chatContext}
+ />
+ </Suspense>
+ ) : null,
+ [request],
+ );
+ return { openPrompt, promptModal };
+}
diff --git a/packages/ui/src/health/ai-prompt-builder.ts b/packages/ui/src/health/ai-prompt-builder.ts
index a2b11c463..37026e76c 100644
--- a/packages/ui/src/health/ai-prompt-builder.ts
+++ b/packages/ui/src/health/ai-prompt-builder.ts
@@ -10,6 +10,8 @@ export type { AiPromptFlavor } from "./ai-prompts/shared";
export { buildAiPrompt, type BuildPromptOptions } from "./ai-prompts/refactor-prompt";
export {
buildCoverageAiPrompt,
+ buildCoverageBatchAiPrompt,
+ type BuildCoverageBatchPromptOptions,
type BuildCoveragePromptOptions,
type CoverageFilePromptInput,
} from "./ai-prompts/coverage-prompt";
@@ -41,6 +43,8 @@ export {
} from "./ai-prompts/conformance-prompt";
export {
buildSecurityAiPrompt,
+ buildSecurityBatchAiPrompt,
+ type BuildSecurityBatchPromptOptions,
type BuildSecurityPromptOptions,
type SecurityPromptFinding,
} from "./ai-prompts/security-prompt";
diff --git a/packages/ui/src/health/ai-prompt-button.tsx b/packages/ui/src/health/ai-prompt-button.tsx
index 4f7c87e37..b48fa8371 100644
--- a/packages/ui/src/health/ai-prompt-button.tsx
+++ b/packages/ui/src/health/ai-prompt-button.tsx
@@ -11,8 +11,12 @@ export interface AiPromptButtonProps {
* `default` shows the green sparkles pill with a label (cards, headers).
* `icon` is a compact icon-only button for dense table rows; the label
* still rides along as the tooltip / accessible name.
+ * `ghost` is icon + label with no fill, for a per-row action that should
+ * not repeat a filled pill down every row (see `RowPromptAction`).
*/
- variant?: "default" | "icon";
+ variant?: "default" | "icon" | "ghost";
+ /** Accessible name when the visible label repeats down a list, e.g. naming the row. */
+ ariaLabel?: string;
className?: string;
}
@@ -26,6 +30,7 @@ export function AiPromptButton({
onClick,
label = "AI fix prompt",
variant = "default",
+ ariaLabel,
className,
}: AiPromptButtonProps) {
const base =
@@ -39,13 +44,33 @@ export function AiPromptButton({
onClick();
}}
title={label}
- aria-label={label}
+ aria-label={ariaLabel ?? label}
className={cn(base, "h-6 w-6 justify-center p-0", className)}
>
<Sparkles className="h-3.5 w-3.5 transition-transform group-hover/ai:rotate-12" />
</button>
);
}
+ if (variant === "ghost") {
+ return (
+ <button
+ type="button"
+ onClick={(e) => {
+ e.stopPropagation();
+ onClick();
+ }}
+ title={label}
+ aria-label={ariaLabel}
+ className={cn(
+ "group/ai inline-flex items-center gap-1.5 rounded-md px-2 py-1 text-xs font-medium text-[var(--color-text-secondary)] transition-colors hover:bg-[var(--color-model-muted)] hover:text-[var(--color-model)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]",
+ className,
+ )}
+ >
+ <Sparkles className="h-3.5 w-3.5 text-[var(--color-model)] transition-transform group-hover/ai:rotate-12" />
+ {label}
+ </button>
+ );
+ }
return (
<button
type="button"
@@ -54,6 +79,7 @@ export function AiPromptButton({
onClick();
}}
title={label}
+ aria-label={ariaLabel}
className={cn(base, "px-2.5 py-1 text-xs", className)}
>
<Sparkles className="h-3.5 w-3.5 transition-transform group-hover/ai:rotate-12" />
diff --git a/packages/ui/src/health/ai-prompts/coverage-prompt.ts b/packages/ui/src/health/ai-prompts/coverage-prompt.ts
index 1989b8672..4e2d180cd 100644
--- a/packages/ui/src/health/ai-prompts/coverage-prompt.ts
+++ b/packages/ui/src/health/ai-prompts/coverage-prompt.ts
@@ -131,3 +131,51 @@ export function buildCoverageAiPrompt({
explorationCloser(flavor, row.file_path, "coverage"),
]);
}
+
+/** Files listed in a batch prompt; the rest are counted, not dropped silently. */
+const MAX_BATCH_FILES = 25;
+
+export interface BuildCoverageBatchPromptOptions {
+ rows: CoverageFilePromptInput[];
+ flavor?: AiPromptFlavor;
+ repoName?: string;
+}
+
+/** One prompt over several files, e.g. every row the current filter shows. */
+export function buildCoverageBatchAiPrompt({
+ rows,
+ flavor = "generic",
+ repoName,
+}: BuildCoverageBatchPromptOptions): string {
+ const only = rows.length === 1 ? rows[0] : undefined;
+ if (only) return buildCoverageAiPrompt({ row: only, flavor, ...(repoName ? { repoName } : {}) });
+ const shown = rows.slice(0, MAX_BATCH_FILES);
+ const hidden = rows.length - shown.length;
+ const pct = (v: number | null) => (v == null ? "no data" : `${v.toFixed(1)}%`);
+
+ return joinSections([
+ FLAVOR_PREAMBLE[flavor],
+ "",
+ `## Target files${repoSuffix(repoName)}`,
+ "",
+ bulletList(
+ shown.map(
+ (r) =>
+ `\`${r.file_path}\` — line coverage ${pct(r.line_coverage_pct)}${
+ r.health_score != null ? `, health ${r.health_score.toFixed(1)}/10` : ""
+ }`,
+ ),
+ ),
+ hidden > 0 ? `…and ${hidden} more in the same list (open the Tests page in repowise for all of them).` : "",
+ "",
+ "## Your task",
+ "",
+ bulletList([
+ "Add tests for these files, weakest coverage and lowest health first, covering their riskiest paths rather than padding the number.",
+ "Work one file at a time and finish each before starting the next.",
+ ]),
+ "",
+ ...closingSections(CONSTRAINTS, EXPECTED),
+ explorationCloser(flavor, shown[0]?.file_path ?? "", "coverage"),
+ ]);
+}
diff --git a/packages/ui/src/health/ai-prompts/security-prompt.ts b/packages/ui/src/health/ai-prompts/security-prompt.ts
index 67dc51dc5..e5f565152 100644
--- a/packages/ui/src/health/ai-prompts/security-prompt.ts
+++ b/packages/ui/src/health/ai-prompts/security-prompt.ts
@@ -17,6 +17,7 @@ export interface SecurityPromptFinding {
kind: string;
severity: string;
snippet?: string | null;
+ line_number?: number | null;
}
export interface BuildSecurityPromptOptions {
@@ -30,9 +31,38 @@ export function buildSecurityAiPrompt({
flavor = "generic",
repoName,
}: BuildSecurityPromptOptions): string {
- const isSecret = /secret|key|token|credential|password/i.test(finding.kind);
+ const isSecret = isSecretKind(finding.kind);
- const constraintList = [
+ return joinSections([
+ FLAVOR_PREAMBLE[flavor],
+ "",
+ `## Security finding${repoSuffix(repoName)}`,
+ "",
+ bulletList([
+ `File: \`${finding.file_path}\``,
+ `Type: **${finding.kind}**`,
+ `Severity: **${finding.severity.toUpperCase()}**`,
+ "Source: repowise local security scan (pattern-based — treat as a lead).",
+ ]),
+ "",
+ finding.snippet
+ ? ["## Flagged code", "", "```", finding.snippet, "```", ""].join("\n")
+ : "",
+ "## Your task",
+ "",
+ `Investigate and remediate this ${finding.kind} finding in \`${finding.file_path}\`.`,
+ "",
+ ...closingSections(constraints(isSecret), contract(isSecret)),
+ explorationCloser(flavor, finding.file_path, "security"),
+ ]);
+}
+
+function isSecretKind(kind: string): boolean {
+ return /secret|key|token|credential|password/i.test(kind);
+}
+
+function constraints(isSecret: boolean): string[] {
+ return [
"**Confirm it's real first.** Reproduce the issue or trace the data flow before editing. Pattern scanners over-flag — test fixtures, sample data, and already-sanitized paths are common false positives. If this is one, say so and stop.",
isSecret
? "If this is a live secret, the fix is two-part: (1) remove it from the code and load it from a secret manager / env var, and (2) call out that the secret must be **rotated** — it is compromised the moment it lands in git history."
@@ -41,34 +71,62 @@ export function buildSecurityAiPrompt({
"Add or update a test that fails on the vulnerable behavior and passes after the fix, where the project's setup allows it.",
"Don't introduce a new dependency for this unless there's no safe stdlib/first-party option; if you do, justify it.",
];
+}
- const completionContract = [
+function contract(isSecret: boolean): string[] {
+ return [
"1. A one-line verdict: is this exploitable, and how (or why it's a false positive)?",
"2. The fix, scoped to the smallest change that closes the issue.",
"3. The test that now covers it, if one was feasible.",
isSecret ? "4. An explicit rotation/remediation note for the exposed secret." : "4. Any related spots in the codebase with the same pattern that should get the same fix.",
];
+}
+
+/** Findings listed in a batch prompt; the rest are counted, not dropped silently. */
+const MAX_BATCH_FINDINGS = 40;
+
+export interface BuildSecurityBatchPromptOptions {
+ findings: SecurityPromptFinding[];
+ flavor?: AiPromptFlavor;
+ repoName?: string;
+}
+
+/** One prompt over several findings, e.g. every row the current filters show. */
+export function buildSecurityBatchAiPrompt({
+ findings,
+ flavor = "generic",
+ repoName,
+}: BuildSecurityBatchPromptOptions): string {
+ const only = findings.length === 1 ? findings[0] : undefined;
+ if (only) return buildSecurityAiPrompt({ finding: only, flavor, ...(repoName ? { repoName } : {}) });
+ const isSecret = findings.some((f) => isSecretKind(f.kind));
+ const shown = findings.slice(0, MAX_BATCH_FINDINGS);
+ const hidden = findings.length - shown.length;
+ const location = (f: SecurityPromptFinding) =>
+ f.line_number != null ? `${f.file_path}:${f.line_number}` : f.file_path;
return joinSections([
FLAVOR_PREAMBLE[flavor],
"",
- `## Security finding${repoSuffix(repoName)}`,
+ `## Security findings${repoSuffix(repoName)}`,
"",
bulletList([
- `File: \`${finding.file_path}\``,
- `Type: **${finding.kind}**`,
- `Severity: **${finding.severity.toUpperCase()}**`,
- "Source: repowise local security scan (pattern-based — treat as a lead).",
+ `Findings: **${findings.length}**`,
+ "Source: repowise local security scan (pattern-based — treat each as a lead).",
]),
"",
- finding.snippet
- ? ["## Flagged code", "", "```", finding.snippet, "```", ""].join("\n")
- : "",
+ "## Findings, in the order to work them",
+ "",
+ bulletList(
+ shown.map((f) => `\`${location(f)}\` — **${f.kind}** (${f.severity.toUpperCase()})`),
+ ),
+ hidden > 0 ? `…and ${hidden} more in the same list (open the security page in repowise for all of them).` : "",
+ "",
"## Your task",
"",
- `Investigate and remediate this ${finding.kind} finding in \`${finding.file_path}\`.`,
+ "Work through these findings one at a time, shipped code before tests and docs. Confirm each before changing anything, and group fixes that share a root cause.",
"",
- ...closingSections(constraintList, completionContract),
- explorationCloser(flavor, finding.file_path, "security"),
+ ...closingSections(constraints(isSecret), contract(isSecret)),
+ explorationCloser(flavor, shown[0]?.file_path ?? "", "security"),
]);
}
diff --git a/packages/ui/src/health/coverage-lede.tsx b/packages/ui/src/health/coverage-lede.tsx
index 001708c55..6af68a5d3 100644
--- a/packages/ui/src/health/coverage-lede.tsx
+++ b/packages/ui/src/health/coverage-lede.tsx
@@ -91,7 +91,7 @@ export function CoverageLede({
across {formatNumber(summary.file_count)} instrumented files
{moduleCount > 0 ? ` in ${formatNumber(moduleCount)} directories` : ""}.
{band ? ` We rate that ${band.label.toLowerCase()}.` : ""} These are the
- lines your own test run executed, so every figure on this tab is
+ lines your own test run executed, so every figure on this page is
line-level and exact. Without a report we can still name which tests
reach which files, but not how much of a file they run.
</p>
diff --git a/packages/ui/src/health/coverage-view.tsx b/packages/ui/src/health/coverage-view.tsx
index 0899891dd..9df90bfc7 100644
--- a/packages/ui/src/health/coverage-view.tsx
+++ b/packages/ui/src/health/coverage-view.tsx
@@ -19,7 +19,7 @@
*/
import { useMemo, useState } from "react";
-import { ArrowUpRight, Sparkles } from "lucide-react";
+import { ArrowUpRight } from "lucide-react";
import useSWR from "swr";
import { GOOD_MIN } from "@repowise-dev/types/health";
import type {
@@ -32,13 +32,17 @@ import type {
import { Skeleton } from "../ui/skeleton";
import { EmptyState } from "../shared/empty-state";
+import { CleanState } from "../shared/clean-state";
+import { formatNumber } from "../lib/format";
import { ApiError } from "../shared/api-error";
import { toFriendlyMessage } from "../lib/errors";
import { ResponsiveTable, type ResponsiveColumn } from "../shared/responsive-table";
import { ResultsFooter } from "../shared/results-footer";
import { OverviewSection } from "../overview/section";
-import { AiPromptModal, fileChatContext } from "./ai-prompt-modal";
+import { fileChatContext } from "./ai-prompt-modal";
+import { AGENT_PROMPT_LABEL, useAiPromptAction } from "./ai-prompt-action";
+import { PromptForRowsButton, RowPromptAction } from "./row-prompt-action";
import { CoverageLede } from "./coverage-lede";
import { CoverageBar } from "./coverage-bar";
import { ModuleCoverageList } from "./module-coverage-list";
@@ -49,7 +53,7 @@ import {
import { RiskCoverageScatter } from "./risk-coverage-scatter";
import { InferredTestsView } from "./inferred-tests-view";
import {
- buildCoverageAiPrompt,
+ buildCoverageBatchAiPrompt,
type CoverageFilePromptInput,
} from "./ai-prompt-builder";
import { bandForScore } from "@repowise-dev/types/health";
@@ -66,8 +70,51 @@ import { COVERAGE_REPORT_FORMATS_LABEL } from "./coverage-formats";
import { CiHint } from "../shared/ci-hint";
import type { CodeHealthAdapter } from "./code-health-adapter";
-export function CoverageView({ adapter }: { adapter: CodeHealthAdapter }) {
- const [promptRow, setPromptRow] = useState<CoverageFilePromptInput | null>(null);
+/** Copy a host can override: the agent-prompt action and the clean state. */
+export interface CoverageViewCopy {
+ /** The primary row action, handing the file's gaps to an agent. */
+ promptLabel?: string;
+ /** The header action over every row a list shows, for `n` files. */
+ batchPromptLabel?: (count: number) => string;
+ /** "No untested hotspots across N measured files". */
+ cleanTitle?: (measuredFiles: number) => string;
+ cleanDescription?: string;
+}
+
+/** The prompt input for one file row. */
+function promptInputFor(f: CoverageFileRow): CoverageFilePromptInput {
+ return {
+ file_path: f.file_path,
+ line_coverage_pct: f.line_coverage_pct,
+ branch_coverage_pct: f.branch_coverage_pct,
+ total_coverable_lines: f.total_coverable_lines,
+ ...(f.covered_lines && { covered_lines: f.covered_lines }),
+ source_format: f.source_format,
+ health_score: f.health_score ?? null,
+ nloc: f.nloc ?? null,
+ };
+}
+
+export function CoverageView({
+ adapter,
+ copy,
+}: {
+ adapter: CodeHealthAdapter;
+ copy?: CoverageViewCopy | undefined;
+}) {
+ const { openPrompt, promptModal } = useAiPromptAction();
+ // One file from a row, or every file a list shows, through the shared modal.
+ const promptFor = (rows: CoverageFilePromptInput[]) => {
+ const one = rows.length === 1 ? rows[0]!.file_path : undefined;
+ openPrompt({
+ title: "AI test prompt",
+ description:
+ "A ready-to-paste prompt that asks your AI coding agent to add tests for the uncovered lines and branches.",
+ filePath: one ?? null,
+ ...(one ? { chatContext: fileChatContext(one)! } : {}),
+ getPrompt: (flavor) => buildCoverageBatchAiPrompt({ rows, flavor }),
+ });
+ };
const { data, isLoading, error, mutate } = useSWR<HealthCoverageResponse>(
`code-health-coverage:${adapter.cacheKey}`,
@@ -121,25 +168,12 @@ export function CoverageView({ adapter }: { adapter: CodeHealthAdapter }) {
data={data}
untestedFindings={untestedFindings ?? []}
onOpenFile={openFilePage}
- onGeneratePrompt={(r) => setPromptRow(r)}
+ onGeneratePrompt={promptFor}
+ copy={copy}
/>
)}
- <AiPromptModal
- open={promptRow !== null}
- onOpenChange={(open) => {
- if (!open) setPromptRow(null);
- }}
- filePath={promptRow?.file_path ?? null}
- chatContext={fileChatContext(promptRow?.file_path)}
- title="AI test prompt"
- description="A ready-to-paste prompt that asks your AI coding agent to add tests for this file's uncovered lines and branches."
- getPrompt={
- promptRow
- ? (flavor) => buildCoverageAiPrompt({ row: promptRow, flavor })
- : null
- }
- />
+ {promptModal}
</div>
);
}
@@ -149,12 +183,16 @@ function CoverageBody({
untestedFindings,
onOpenFile,
onGeneratePrompt,
+ copy,
}: {
data: HealthCoverageResponse;
untestedFindings: HealthFinding[];
onOpenFile: (path: string) => void;
- onGeneratePrompt: (row: CoverageFilePromptInput) => void;
+ /** One file or several; the modal builds a single or a batch prompt. */
+ onGeneratePrompt: (rows: CoverageFilePromptInput[]) => void;
+ copy?: CoverageViewCopy | undefined;
}) {
+ const promptLabel = copy?.promptLabel ?? AGENT_PROMPT_LABEL;
const { summary, files, modules } = data;
// The true count, not the length of what came back. They differ only if the
// rollup was capped, but the lede claims to describe the repo.
@@ -182,8 +220,9 @@ function CoverageBody({
// Untested hotspots: prefer the real biomarker findings (which carry
// dependents/commit context); fall back to the low-coverage × low-score
// heuristic when the biomarker never fired (e.g. coverage just ingested).
+ const filesByPath = useMemo(() => new Map(files.map((f) => [f.file_path, f])), [files]);
const untested = useMemo<UntestedHotspotEntry[]>(() => {
- const covByPath = new Map(files.map((f) => [f.file_path, f]));
+ const covByPath = filesByPath;
if (untestedFindings.length > 0) {
return untestedFindings.slice(0, 10).map((f) => {
const cov = covByPath.get(f.file_path);
@@ -217,7 +256,12 @@ function CoverageBody({
if (f.health_score != null) entry.health_score = f.health_score;
return entry;
});
- }, [files, untestedFindings]);
+ }, [files, filesByPath, untestedFindings]);
+ // The untested entries that have a measured row, which is what a prompt needs.
+ const untestedRows = useMemo(
+ () => untested.flatMap((e) => filesByPath.get(e.file_path) ?? []),
+ [untested, filesByPath],
+ );
const scatterPoints = useMemo(
() =>
@@ -363,26 +407,11 @@ function CoverageBody({
priority: 1,
align: "right",
render: (f) => (
- <button
- type="button"
- onClick={(e) => {
- e.stopPropagation();
- onGeneratePrompt({
- file_path: f.file_path,
- line_coverage_pct: f.line_coverage_pct,
- branch_coverage_pct: f.branch_coverage_pct,
- total_coverable_lines: f.total_coverable_lines,
- ...(f.covered_lines && { covered_lines: f.covered_lines }),
- source_format: f.source_format,
- health_score: f.health_score ?? null,
- nloc: f.nloc ?? null,
- });
- }}
- title="Generate AI test prompt for this file"
- className="inline-flex items-center justify-center rounded-md p-1 text-[var(--color-text-tertiary)] hover:text-[var(--color-model)] hover:bg-[var(--color-model-muted)] transition-colors"
- >
- <Sparkles className="h-3.5 w-3.5" />
- </button>
+ <RowPromptAction
+ label={promptLabel}
+ subject={f.file_path}
+ onClick={() => onGeneratePrompt([promptInputFor(f)])}
+ />
),
},
];
@@ -411,14 +440,41 @@ function CoverageBody({
/>
</OverviewSection>
- {untested.length > 0 ? (
- <OverviewSection
- title="Untested hotspots"
- description="Files that change often or that much of the codebase depends on, with little or no coverage. A gap here is worth more than the same gap in code nobody touches."
- >
- <UntestedHotspotWarning entries={untested} onSelect={onOpenFile} />
- </OverviewSection>
- ) : null}
+ <OverviewSection
+ title="Untested hotspots"
+ description="Files that change often or that much of the codebase depends on, with little or no coverage. A gap here is worth more than the same gap in code nobody touches."
+ action={
+ <PromptForRowsButton
+ count={untestedRows.length}
+ onClick={() => onGeneratePrompt(untestedRows.map(promptInputFor))}
+ {...(copy?.batchPromptLabel ? { label: copy.batchPromptLabel } : {})}
+ />
+ }
+ >
+ {untested.length > 0 ? (
+ <UntestedHotspotWarning
+ entries={untested}
+ onSelect={onOpenFile}
+ onGeneratePrompt={(path) => {
+ const row = filesByPath.get(path);
+ if (row) onGeneratePrompt([promptInputFor(row)]);
+ }}
+ promptLabel={promptLabel}
+ />
+ ) : (
+ <CleanState
+ align="start"
+ title={
+ copy?.cleanTitle?.(summary.file_count) ??
+ `No untested hotspots across ${formatNumber(summary.file_count)} measured files`
+ }
+ description={
+ copy?.cleanDescription ??
+ "Every file that changes often or that much of the code depends on has tests watching it."
+ }
+ />
+ )}
+ </OverviewSection>
<OverviewSection
title="Module coverage"
@@ -429,8 +485,14 @@ function CoverageBody({
<OverviewSection
title="Every file"
- description="Sorted worst first. Click a row for the line-level heatmap, or the prompt icon to draft a brief that has your AI agent write the missing tests."
+ description="Sorted worst first. Click a row for the line-level heatmap, or copy a prompt that has your agent write the missing tests."
action={
+ <div className="flex flex-wrap items-center gap-2">
+ <PromptForRowsButton
+ count={sortedFiles.length}
+ onClick={() => onGeneratePrompt(sortedFiles.map(promptInputFor))}
+ {...(copy?.batchPromptLabel ? { label: copy.batchPromptLabel } : {})}
+ />
<input
value={search}
onChange={(e) => {
@@ -441,6 +503,7 @@ function CoverageBody({
aria-label="Filter files by path"
className="w-48 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-2 py-1.5 text-xs focus:border-[var(--color-border-hover)] focus:outline-none sm:w-56"
/>
+ </div>
}
>
<div className="border-t border-[var(--color-border-default)]">
@@ -653,7 +716,7 @@ function NoCoverageState() {
</h2>
<p className="text-[15px] leading-relaxed text-[var(--color-text-secondary)] [text-wrap:pretty]">
No coverage report has been ingested, and the dependency graph found no
- test files to trace either. Either would fill this tab: a report gives the
+ test files to trace either. Either would fill this page: a report gives the
lines your tests executed, and the graph alone can name which tests reach
which files with no setup at all. Run your suite with coverage on and hand
us the report.
diff --git a/packages/ui/src/health/index.ts b/packages/ui/src/health/index.ts
index 902fb007d..6b962460b 100644
--- a/packages/ui/src/health/index.ts
+++ b/packages/ui/src/health/index.ts
@@ -29,6 +29,8 @@ export * from "./health-file-drawer";
export * from "./ai-prompt-builder";
export * from "./ai-prompt-modal";
export * from "./ai-prompt-button";
+export * from "./ai-prompt-action";
+export * from "./row-prompt-action";
export * from "./hot-functions-panel";
export * from "./hidden-coupling-list";
export * from "./defect-accuracy-card";
diff --git a/packages/ui/src/health/row-prompt-action.tsx b/packages/ui/src/health/row-prompt-action.tsx
new file mode 100644
index 000000000..fbe0fcd51
--- /dev/null
+++ b/packages/ui/src/health/row-prompt-action.tsx
@@ -0,0 +1,67 @@
+"use client";
+
+import { cn } from "../lib/cn";
+import { AiPromptButton } from "./ai-prompt-button";
+import { AGENT_PROMPT_LABEL, bulkAgentPromptLabel } from "./ai-prompt-action";
+
+/**
+ * The per-row "hand this to your agent" action. Ghost (icon + label, no fill)
+ * so a column of them does not shout, and revealed on row hover, keyboard
+ * focus within the row, and the selected row. It stays in the tab order and
+ * shows on focus, and it is always visible where there is no hover (touch).
+ *
+ * The row must carry `group/row` (and `data-selected` when selected), as
+ * `ResponsiveTable` rows do. The click usually calls `openPrompt` from
+ * {@link useAiPromptAction}, the one modal host.
+ */
+export function RowPromptAction({
+ onClick,
+ label = AGENT_PROMPT_LABEL,
+ subject,
+ className,
+}: {
+ onClick: () => void;
+ label?: string;
+ /** What the row is about, e.g. its path; names the action for screen readers. */
+ subject?: string;
+ className?: string;
+}) {
+ return (
+ <AiPromptButton
+ variant="ghost"
+ label={label}
+ {...(subject ? { ariaLabel: `${label}: ${subject}` } : {})}
+ onClick={onClick}
+ className={cn(
+ "whitespace-nowrap opacity-0 focus-visible:opacity-100 group-hover/row:opacity-100 group-focus-within/row:opacity-100 group-data-[selected=true]/row:opacity-100 [@media(hover:none)]:opacity-100",
+ className,
+ )}
+ />
+ );
+}
+
+/**
+ * The filled header action: one prompt over every row the current filters
+ * show. Renders nothing for an empty list, since a prompt about nothing is
+ * not an action.
+ */
+export function PromptForRowsButton({
+ count,
+ onClick,
+ label = bulkAgentPromptLabel,
+ className,
+}: {
+ count: number;
+ onClick: () => void;
+ label?: (count: number) => string;
+ className?: string;
+}) {
+ if (count === 0) return null;
+ return (
+ <AiPromptButton
+ label={label(count)}
+ onClick={onClick}
+ className={cn("whitespace-nowrap", className)}
+ />
+ );
+}
diff --git a/packages/ui/src/health/untested-hotspot-warning.tsx b/packages/ui/src/health/untested-hotspot-warning.tsx
index 82fbee3c5..cd65b8b63 100644
--- a/packages/ui/src/health/untested-hotspot-warning.tsx
+++ b/packages/ui/src/health/untested-hotspot-warning.tsx
@@ -1,6 +1,8 @@
import { ArrowUpRight } from "lucide-react";
import { coverageBand } from "./tokens";
+import { RowPromptAction } from "./row-prompt-action";
+import { AGENT_PROMPT_LABEL } from "./ai-prompt-action";
export interface UntestedHotspotEntry {
file_path: string;
@@ -15,6 +17,10 @@ export interface UntestedHotspotWarningProps {
limit?: number;
/** Open a file's coverage page. When set, rows become clickable. */
onSelect?: ((filePath: string) => void) | undefined;
+ /** Hand one file's gap to an agent. When set, each row leads with it. */
+ onGeneratePrompt?: ((filePath: string) => void) | undefined;
+ /** The prompt action's label. */
+ promptLabel?: string;
}
/**
@@ -30,6 +36,8 @@ export function UntestedHotspotWarning({
entries,
limit = 6,
onSelect,
+ onGeneratePrompt,
+ promptLabel = AGENT_PROMPT_LABEL,
}: UntestedHotspotWarningProps) {
if (entries.length === 0) return null;
const shown = entries.slice(0, limit);
@@ -72,19 +80,27 @@ export function UntestedHotspotWarning({
return (
<li
key={e.file_path}
- className="border-b border-[var(--color-border-default)]"
+ className="group/row flex items-center gap-3 border-b border-[var(--color-border-default)]"
>
{onSelect ? (
<button
type="button"
onClick={() => onSelect(e.file_path)}
- className="group/row flex w-full items-baseline gap-x-4 py-2.5 text-left hover:bg-[var(--color-bg-elevated)]"
+ className="group/row flex min-w-0 flex-1 items-baseline gap-x-4 py-2.5 text-left hover:bg-[var(--color-bg-elevated)]"
>
{body}
<ArrowUpRight className="h-3 w-3 shrink-0 self-center text-[var(--color-text-tertiary)] group-hover/row:text-[var(--color-accent-primary)]" />
</button>
) : (
- <div className="flex w-full items-baseline gap-x-4 py-2.5">{body}</div>
+ <div className="flex min-w-0 flex-1 items-baseline gap-x-4 py-2.5">{body}</div>
+ )}
+ {onGeneratePrompt && (
+ <RowPromptAction
+ label={promptLabel}
+ subject={e.file_path}
+ onClick={() => onGeneratePrompt(e.file_path)}
+ className="shrink-0"
+ />
)}
</li>
);
diff --git a/packages/ui/src/overview/overview-body.tsx b/packages/ui/src/overview/overview-body.tsx
index d8482d76c..c463dfd55 100644
--- a/packages/ui/src/overview/overview-body.tsx
+++ b/packages/ui/src/overview/overview-body.tsx
@@ -217,7 +217,7 @@ export function OverviewBody({
title="Where the risk concentrates"
description="Ranked by prior bug fixes and change frequency, mined from full git history rather than from the code alone."
action={
- <SectionLink href={`${base}/code-health?tab=triage`} LinkComponent={LinkComponent}>
+ <SectionLink href={`${base}/code-health`} LinkComponent={LinkComponent}>
{`All ${formatNumber(stats.hotspot_count)} hotspots`}
</SectionLink>
}
diff --git a/packages/ui/src/overview/overview-model.ts b/packages/ui/src/overview/overview-model.ts
index 2a7d2bea5..fa58f80b3 100644
--- a/packages/ui/src/overview/overview-model.ts
+++ b/packages/ui/src/overview/overview-model.ts
@@ -195,7 +195,7 @@ export function buildReads(summary: OverviewSummaryResponse, routes: OverviewRou
label: "Score validation",
value: `${formatNumber(accuracy.hits)}/${formatNumber(accuracy.k)}`,
...(accuracy.lift ? { unit: `${accuracy.lift.toFixed(1)}× baseline` } : {}),
- href: `${r.base}/code-health?tab=triage`,
+ href: `${r.base}/code-health`,
why: "Top-ranked files that did go on to need a bug fix",
});
}
diff --git a/packages/ui/src/security/findings-table.tsx b/packages/ui/src/security/findings-table.tsx
index ebd4b0c9c..5693fed48 100644
--- a/packages/ui/src/security/findings-table.tsx
+++ b/packages/ui/src/security/findings-table.tsx
@@ -8,7 +8,8 @@ import { EmptyState } from "../shared/empty-state";
import { CiHint } from "../shared/ci-hint";
import { Segmented } from "../shared/segmented";
import { ResponsiveTable, type ResponsiveColumn } from "../shared/responsive-table";
-import { AiPromptButton } from "../health/ai-prompt-button";
+import { PromptForRowsButton, RowPromptAction } from "../health/row-prompt-action";
+import { AGENT_PROMPT_LABEL } from "../health/ai-prompt-action";
import { SeverityMark } from "../health/severity-mark";
import type { Severity } from "../health/tokens";
import { formatDate, formatDateTime, formatRelativeTimeOrNull } from "../lib/format";
@@ -121,11 +122,27 @@ function FindingLocation({ finding }: { finding: SecurityFinding }) {
export interface SecurityFindingsTableProps {
findings: SecurityFinding[];
onSelect?: (finding: SecurityFinding) => void;
- /** When set, each row shows an "AI fix prompt" action that calls this. */
+ /**
+ * When set, each row leads with an agent-prompt action that calls this:
+ * the row's primary verb, since fixes happen through the reader's agent.
+ */
onGeneratePrompt?: (finding: SecurityFinding) => void;
+ /** The prompt action's label. */
+ promptLabel?: string;
+ /** One prompt over every finding the current filters show. */
+ onGenerateBatchPrompt?: (findings: SecurityFinding[]) => void;
+ /** The batch action's label for `n` findings. */
+ batchPromptLabel?: (count: number) => string;
}
-export function SecurityFindingsTable({ findings, onSelect, onGeneratePrompt }: SecurityFindingsTableProps) {
+export function SecurityFindingsTable({
+ findings,
+ onSelect,
+ onGeneratePrompt,
+ promptLabel = AGENT_PROMPT_LABEL,
+ onGenerateBatchPrompt,
+ batchPromptLabel,
+}: SecurityFindingsTableProps) {
const [q, setQ] = useState("");
const [sev, setSev] = useState<SeverityFilter>("all");
@@ -182,7 +199,7 @@ export function SecurityFindingsTable({ findings, onSelect, onGeneratePrompt }:
priority: 2,
render: (f) => (
<span
- className="block max-w-[320px] truncate font-mono text-xs text-[var(--color-text-tertiary)]"
+ className="block max-w-[240px] truncate font-mono text-xs text-[var(--color-text-tertiary)]"
title={f.snippet ?? ""}
>
{f.snippet || "—"}
@@ -221,21 +238,13 @@ export function SecurityFindingsTable({ findings, onSelect, onGeneratePrompt }:
cols.push({
key: "actions",
header: "",
- headerClassName: "w-10",
- hideInCard: true,
render: (f) => (
- <span onClick={(e) => e.stopPropagation()}>
- <AiPromptButton
- variant="icon"
- label="AI fix prompt"
- onClick={() => onGeneratePrompt(f)}
- />
- </span>
+ <RowPromptAction label={promptLabel} subject={f.file_path} onClick={() => onGeneratePrompt(f)} />
),
});
}
return cols;
- }, [onGeneratePrompt]);
+ }, [onGeneratePrompt, promptLabel]);
if (findings.length === 0) {
return (
@@ -271,6 +280,14 @@ export function SecurityFindingsTable({ findings, onSelect, onGeneratePrompt }:
/>
</div>
<Segmented label="Severity" value={sev} onChange={setSev} options={options} />
+ {onGenerateBatchPrompt && (
+ <PromptForRowsButton
+ count={filtered.length}
+ onClick={() => onGenerateBatchPrompt(filtered)}
+ {...(batchPromptLabel ? { label: batchPromptLabel } : {})}
+ className="sm:ml-auto"
+ />
+ )}
</div>
{/* Scrolls sideways inside its own frame on a phone rather than
diff --git a/packages/ui/src/shared/clean-state.tsx b/packages/ui/src/shared/clean-state.tsx
new file mode 100644
index 000000000..5a2ec0e9f
--- /dev/null
+++ b/packages/ui/src/shared/clean-state.tsx
@@ -0,0 +1,56 @@
+import * as React from "react";
+import { cn } from "../lib/cn";
+import { EmptyState, type EmptyStateAction } from "./empty-state";
+
+/** Copy a host can override on a view's clean state; omitted keys keep the view's English. */
+export interface CleanStateCopy {
+ title?: string;
+ description?: string;
+}
+
+export interface CleanStateProps {
+ /** Names the result with its scope: "No dead code across 5,612 files". */
+ title: string;
+ /** One plain sentence on what was checked, or what keeps it this way. */
+ description?: React.ReactNode;
+ action?: EmptyStateAction;
+ secondaryAction?: EmptyStateAction;
+ /** `start` when it sits under a lede rather than standing alone. Default `center`. */
+ align?: "center" | "start";
+ /** Default `h3`. */
+ titleAs?: "h2" | "h3";
+ className?: string;
+ children?: React.ReactNode;
+}
+
+/**
+ * The good result of a check: it ran, and found nothing to fix.
+ *
+ * Calm on purpose: the success check and plain words that name the scope the
+ * claim covers, with no animation or fill. Render it only when the check is
+ * known to have run; "never ran" is a neutral empty state, not good news.
+ */
+export function CleanState({
+ title,
+ description,
+ action,
+ secondaryAction,
+ align = "center",
+ titleAs,
+ className,
+ children,
+}: CleanStateProps) {
+ return (
+ <EmptyState
+ tone="positive"
+ title={title}
+ description={description}
+ {...(action ? { action } : {})}
+ {...(secondaryAction ? { secondaryAction } : {})}
+ {...(titleAs ? { titleAs } : {})}
+ className={cn(align === "start" && "items-start px-0 py-0 text-left", className)}
+ >
+ {children}
+ </EmptyState>
+ );
+}
diff --git a/packages/ui/src/shared/index.ts b/packages/ui/src/shared/index.ts
index c82e5f846..aca719d59 100644
--- a/packages/ui/src/shared/index.ts
+++ b/packages/ui/src/shared/index.ts
@@ -25,6 +25,7 @@ export {
export { Toaster, toast, type ToasterProps } from "./toast";
export * from "./breadcrumb";
export * from "./empty-state";
+export * from "./clean-state";
export { Callout, type CalloutProps, type CalloutTone } from "./callout";
export {
RouteError,
diff --git a/packages/ui/src/shared/responsive-table/responsive-table.tsx b/packages/ui/src/shared/responsive-table/responsive-table.tsx
index 19aa0441c..c4e95c5bb 100644
--- a/packages/ui/src/shared/responsive-table/responsive-table.tsx
+++ b/packages/ui/src/shared/responsive-table/responsive-table.tsx
@@ -276,8 +276,9 @@ export function ResponsiveTable<T>({
key={key}
ref={tableWindow.measure}
data-index={index}
+ data-selected={isSelected || undefined}
className={cn(
- "border-t border-[var(--color-table-divider)] hover:bg-[var(--color-bg-elevated)]",
+ "group/row border-t border-[var(--color-table-divider)] hover:bg-[var(--color-bg-elevated)]",
isSelected && "bg-[var(--color-accent-muted)]/30",
onRowClick && CLICKABLE_ROW_CLS,
rowClassName?.(row),
@@ -329,8 +330,9 @@ export function ResponsiveTable<T>({
key={key}
ref={cardsWindow.measure}
data-index={index}
+ data-selected={isSelected || undefined}
className={cn(
- "px-3 py-2.5",
+ "group/row px-3 py-2.5",
isSelected && "bg-[var(--color-accent-muted)]/30",
onRowClick && cn("hover:bg-[var(--color-bg-elevated)]", CLICKABLE_ROW_CLS),
rowClassName?.(row),
diff --git a/packages/web/messages/en.json b/packages/web/messages/en.json
index 22a6af98d..9a3ed39bf 100644
--- a/packages/web/messages/en.json
+++ b/packages/web/messages/en.json
@@ -151,7 +151,11 @@
"contracts": "Contracts",
"coChanges": "Co-Changes",
"groupPeopleAndHistory": "People & History",
- "groupSettings": "Settings"
+ "groupSettings": "Settings",
+ "groupUnderstand": "Understand",
+ "groupCodeQuality": "Code quality",
+ "tests": "Tests",
+ "security": "Security"
},
"breadcrumb": {
"overview": "Overview",
@@ -182,7 +186,9 @@
"settings": "Settings",
"knowledgeGraph": "Knowledge Graph",
"zoom": "Zoom Map",
- "files": "Files"
+ "files": "Files",
+ "tests": "Tests",
+ "docDrift": "Doc drift"
},
"errors": {
"workspaceErrorTitle": "Failed to load the workspace",
@@ -282,7 +288,9 @@
"viewLabel": "History view",
"viewByChange": "By change",
"viewByCommit": "By commit",
- "viewEvents": "Events"
+ "viewEvents": "Events",
+ "viewReview": "Review a change",
+ "reviewDescription": "Pick the files a change touches to see what depends on them, what tends to change with them, and who should review."
},
"changes": {
"description": "Every merged change on the main line, read back from git: pull and merge requests, Gerrit changes and lone commits, with the files each one landed.",
@@ -422,14 +430,10 @@
"coChangeNoticeLess": "Hide",
"coChangeNoticeBody": "Several false findings are gone: classes whose methods share no state no longer read as low cohesion, chained ternaries and conditional expressions no longer count as deep nesting, import cycles count only imports that run, and expected-exception tests and noqa lines no longer flag swallowed exceptions, so many files score higher. Functions defined inside other functions are now measured, and a test-named Python module that pytest does not collect is scored as production code, so some files score lower. PHP files now get complexity, cohesion and test-assertion checks, so PHP scores move as well.",
"tabs": {
- "triage": "Overview",
"performance": "Performance",
"findings": "Findings",
- "coverage": "Tests",
"deadCode": "Dead code",
- "docDrift": "Doc drift",
- "security": "Security",
- "impact": "Blast radius"
+ "map": "Map"
}
},
"knowledgeGraph": {
@@ -639,6 +643,27 @@
"low": "low",
"info": "info"
}
+ },
+ "security": {
+ "title": "Security",
+ "description": "Secrets and dangerous calls the pattern scan matched, shipped code first."
+ },
+ "tests": {
+ "title": "Tests",
+ "description": "Which code your tests reach: measured from a coverage report when one is ingested, inferred from the dependency graph otherwise.",
+ "promptAction": "Copy prompt for your agent",
+ "cleanTitle": "No untested hotspots across {files} measured files",
+ "cleanBody": "Every file that changes often or that much of the code depends on has tests watching it.",
+ "batchPromptAction": "Copy prompt for these {count}"
+ },
+ "docDrift": {
+ "cleanTitle": "No documentation drift found",
+ "cleanBody": "Every file path the documentation names still resolves. It re-checks on each update, so look again after a rename or a move."
+ },
+ "docsTabs": {
+ "explorer": "Explorer",
+ "freshness": "Doc freshness",
+ "drift": "Doc drift"
}
},
"settings": {
@@ -1090,7 +1115,8 @@
"notScannedBody": "The pattern scan for secrets and dangerous calls runs when the repository syncs. Start one with Re-scan, or run repowise update in the repository.",
"capped": "Showing the first {count} findings. The counts on this page cover those {count}.",
"byDirectory": "By directory",
- "byDirectoryBody": "Where the matches concentrate, busiest directories first."
+ "byDirectoryBody": "Where the matches concentrate, busiest directories first.",
+ "clearTitleScoped": "No security findings across {files} files"
},
"deadCodeLede": {
"label": "Deletion-ready",
@@ -1115,7 +1141,16 @@
"allFindings": "All findings",
"findingsCount": "{count} findings",
"promptTitle": "AI fix prompt",
- "promptDescription": "A ready-to-paste prompt that walks your AI agent through confirming and remediating this security finding."
+ "promptDescription": "A ready-to-paste prompt that walks your AI agent through confirming and remediating this security finding.",
+ "rescan": "Re-scan",
+ "rescanning": "Re-scanning…",
+ "promptAction": "Copy prompt for your agent",
+ "deadCodeClean": {
+ "title": "No dead code found",
+ "titleScoped": "No dead code across {files} files",
+ "body": "No unreachable files, unused exports or zombie packages."
+ },
+ "batchPromptAction": "Copy prompt for these {count}"
},
"symbols": {
"clearFileFilter": "Clear file filter",
diff --git a/packages/web/messages/zh-CN.json b/packages/web/messages/zh-CN.json
index b51620354..683f3a771 100644
--- a/packages/web/messages/zh-CN.json
+++ b/packages/web/messages/zh-CN.json
@@ -151,7 +151,11 @@
"contracts": "契约",
"coChanges": "共变分析",
"groupPeopleAndHistory": "人员与历史",
- "groupSettings": "设置"
+ "groupSettings": "设置",
+ "groupUnderstand": "理解",
+ "groupCodeQuality": "代码质量",
+ "tests": "测试",
+ "security": "安全"
},
"breadcrumb": {
"overview": "概览",
@@ -182,7 +186,9 @@
"settings": "设置",
"knowledgeGraph": "知识图谱",
"zoom": "缩放地图",
- "files": "文件"
+ "files": "文件",
+ "tests": "测试",
+ "docDrift": "文档漂移"
},
"errors": {
"workspaceErrorTitle": "无法加载工作区",
@@ -282,7 +288,9 @@
"viewLabel": "历史视图",
"viewByChange": "按变更",
"viewByCommit": "按提交",
- "viewEvents": "事件"
+ "viewEvents": "事件",
+ "viewReview": "审查变更",
+ "reviewDescription": "选择一次变更涉及的文件,查看依赖它们的代码、常与它们一起变更的文件,以及合适的审查者。"
},
"changes": {
"description": "主线上每个已合并的变更,均从 git 历史读取:拉取请求、合并请求、Gerrit 变更和单独提交,以及每个变更带入的文件。",
@@ -422,14 +430,10 @@
"coChangeNoticeLess": "收起",
"coChangeNoticeBody": "一些误报已被移除:方法之间不共享状态的类不再被判为低内聚,链式三元表达式和条件表达式不再计为深层嵌套,导入循环只统计实际运行的导入,预期异常的测试和带 noqa 的行不再被标记为吞掉异常,因此许多文件的分数会升高。定义在其他函数内部的函数现在也会被度量,pytest 不会收集的、以测试命名的 Python 模块会按生产代码评分,因此部分文件的分数会降低。PHP 文件现在会进行复杂度、内聚性和测试断言检查,因此 PHP 的分数也会变化。",
"tabs": {
- "triage": "总览",
"performance": "性能",
"findings": "发现",
- "coverage": "测试",
"deadCode": "死代码",
- "docDrift": "文档漂移",
- "security": "安全",
- "impact": "影响范围"
+ "map": "地图"
}
},
"knowledgeGraph": {
@@ -639,6 +643,27 @@
"low": "低",
"info": "信息"
}
+ },
+ "security": {
+ "title": "安全",
+ "description": "模式扫描匹配到的密钥与危险调用,已发布代码优先列出。"
+ },
+ "tests": {
+ "title": "测试",
+ "description": "你的测试覆盖了哪些代码:已导入覆盖率报告时为实测结果,否则根据依赖图推断。",
+ "promptAction": "为你的智能体复制提示词",
+ "cleanTitle": "{files} 个已测量文件中没有未测试的热点",
+ "cleanBody": "所有频繁变更或被大量代码依赖的文件都有测试覆盖。",
+ "batchPromptAction": "为这 {count} 项复制提示词"
+ },
+ "docDrift": {
+ "cleanTitle": "未发现文档漂移",
+ "cleanBody": "文档中提到的每个文件路径仍然有效。每次更新都会重新检查,重命名或移动文件后值得再看一次。"
+ },
+ "docsTabs": {
+ "explorer": "浏览",
+ "freshness": "文档新鲜度",
+ "drift": "文档漂移"
}
},
"settings": {
@@ -1090,7 +1115,8 @@
"notScannedBody": "密钥与危险调用的模式扫描会在仓库同步时运行。点击「重新扫描」启动一次,或在仓库中运行 repowise update。",
"capped": "仅显示前 {count} 条发现项。本页的计数只涵盖这 {count} 条。",
"byDirectory": "按目录",
- "byDirectoryBody": "匹配集中的位置,按数量从多到少排列。"
+ "byDirectoryBody": "匹配集中的位置,按数量从多到少排列。",
+ "clearTitleScoped": "{files} 个文件中没有安全发现项"
},
"deadCodeLede": {
"label": "可删除",
@@ -1115,7 +1141,16 @@
"allFindings": "全部发现项",
"findingsCount": "{count} 条发现项",
"promptTitle": "AI 修复提示词",
- "promptDescription": "一段可直接粘贴的提示词,引导 AI 智能体确认并修复这条安全发现项。"
+ "promptDescription": "一段可直接粘贴的提示词,引导 AI 智能体确认并修复这条安全发现项。",
+ "rescan": "重新扫描",
+ "rescanning": "正在重新扫描…",
+ "promptAction": "为你的智能体复制提示词",
+ "deadCodeClean": {
+ "title": "未发现死代码",
+ "titleScoped": "{files} 个文件中没有死代码",
+ "body": "没有不可达文件、未使用的导出或僵尸依赖包。"
+ },
+ "batchPromptAction": "为这 {count} 项复制提示词"
},
"symbols": {
"clearFileFilter": "清除文件筛选",
@@ -1467,4 +1502,4 @@
"coverage": "正在加载覆盖率",
"knowledgeGraph": "正在加载知识图谱"
}
-}
\ No newline at end of file
+}
diff --git a/packages/web/src/app/repos/[id]/blast-radius/page.tsx b/packages/web/src/app/repos/[id]/blast-radius/page.tsx
index 5bb7bf800..60d22597c 100644
--- a/packages/web/src/app/repos/[id]/blast-radius/page.tsx
+++ b/packages/web/src/app/repos/[id]/blast-radius/page.tsx
@@ -1,11 +1,12 @@
import { redirect } from "next/navigation";
+import { commitsViewHref } from "@/lib/changes";
-/** Legacy route — redirects into the consolidated IA. */
+/** Legacy route: blast radius is the Commits page's "Review a change" view. */
export default async function LegacyRedirect({
params,
}: {
params: Promise<{ id: string }>;
}) {
const { id } = await params;
- redirect(`/repos/${id}/code-health?tab=impact`);
+ redirect(commitsViewHref(id, "review"));
}
diff --git a/packages/web/src/app/repos/[id]/code-health/code-health-view.tsx b/packages/web/src/app/repos/[id]/code-health/code-health-view.tsx
new file mode 100644
index 000000000..156fc361e
--- /dev/null
+++ b/packages/web/src/app/repos/[id]/code-health/code-health-view.tsx
@@ -0,0 +1,569 @@
+"use client";
+
+/**
+ * Code Health — `/repos/[id]/code-health`, the client view behind the route's
+ * server shell (which redirects tabs that moved out).
+ *
+ * One living map, a lede that says what the score means, and a thin drill-down.
+ * The galaxy map is the page spine; a lens switcher recolors the same field
+ * (health / maintainability / performance / churn) so the cross-tab redundancy
+ * collapses.
+ *
+ * Performance has its own causal-opportunity tab; raw observations remain its
+ * evidence rather than competing with the ranked finding queue. Hotspots is
+ * gone: it rendered a *second* galaxy map
+ * on the churn lens directly under this page's, so churn became a lens here and
+ * what the lens cannot say — bus factor, the ranked table — became a section
+ * under the map. Blast radius keeps its `impact` tab id (existing file-card and
+ * symbol-drawer deep links point at it) but is labelled for what it is.
+ *
+ * Four tabs, defined in `./tabs`: Map, Findings, Performance, Dead code.
+ * Tests and Security are pages of their own now, Doc drift a Docs view and
+ * blast radius the Commits page's "Review a change".
+ *
+ * Tabs carry their count where one is cheap to get, so a clean repo says so
+ * before you spend a click. Dead code dedupes onto the key its own tab uses.
+ * Findings is not numbered: the overview's queue inventory is not the list the
+ * tab opens on, and that list's own total is a multi-second query.
+ */
+
+import dynamic from "next/dynamic";
+import { useParams, useRouter, useSearchParams } from "next/navigation";
+import { useCallback, useEffect, useMemo, useState } from "react";
+import useSWR, { useSWRConfig } from "swr";
+import { HeartPulse, RotateCw } from "lucide-react";
+import { PageShell } from "@repowise-dev/ui/shared/page-shell";
+import { ReleaseNotice } from "@repowise-dev/ui/shared/release-notice";
+import { ViewTabs } from "@repowise-dev/ui/shared/view-tabs";
+import { OverviewSection } from "@repowise-dev/ui/overview";
+import { Button } from "@repowise-dev/ui/ui/button";
+import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@repowise-dev/ui/ui/select";
+import { formatDateTime } from "@repowise-dev/ui/lib/format";
+import type { CodeHealthOverlay } from "@repowise-dev/ui/health";
+import type { DeadCodeSummary } from "@repowise-dev/types/dead-code";
+import {
+ HEALTH_COUNTS,
+ HEALTH_SCOPES,
+ type HealthCounts,
+ type HealthScope,
+} from "@repowise-dev/types/health";
+import { TriageTab } from "@/components/code-health/triage-tab";
+import { HotspotsSection } from "@/components/code-health/hotspots-section";
+import { TrendSection } from "@/components/code-health/trend-tab";
+import { getDeadCodeSummary } from "@/lib/api/dead-code";
+import {
+ getChurnComplexity,
+ getHealthMap,
+ getHealthOverview,
+ getHealthTrend,
+ getPerformanceOpportunity,
+ type ChurnComplexityResponse,
+ type HealthMapFeed,
+ type HealthOverviewResponse,
+ type HealthTrendResponse,
+} from "@/lib/api/code-health";
+import { useTranslations } from "next-intl";
+import {
+ CODE_HEALTH_TABS,
+ DEFAULT_TAB,
+ TAB_DEFS,
+ resolveCodeHealthTab,
+ type CodeHealthTabId,
+} from "./tabs";
+
+// The tabs render one at a time behind `?tab=` and the Map is the default, so
+// the others are split out: landing here downloads the Map chunk only.
+// ssr:false because they are interactive, data-fetching client views.
+const TabFallback = () => <Skeleton className="h-[60vh] w-full rounded-lg" />;
+const FindingsTab = dynamic(
+ () => import("@/components/code-health/findings-tab").then((m) => m.FindingsTab),
+ { ssr: false, loading: TabFallback },
+);
+const PerformanceTab = dynamic(
+ () => import("@/components/code-health/performance-tab").then((m) => m.PerformanceTab),
+ { ssr: false, loading: TabFallback },
+);
+const DeadCodeTab = dynamic(
+ () => import("@/components/risk/dead-code-tab").then((m) => m.DeadCodeTab),
+ { ssr: false, loading: TabFallback },
+);
+
+/**
+ * Lenses on the map. The three co-equal health signals ride on the map payload
+ * itself; churn arrives on its own request and is joined in below, which is why
+ * it is listed here rather than in the map component's default.
+ */
+const OVERLAYS: CodeHealthOverlay[] = ["health", "maintainability", "performance", "churn"];
+
+/**
+ * Tabs whose data honours `scope`. Dead code has no production/test split,
+ * and performance carries its own execution-context control, so the toggle is
+ * offered where it does something rather than sitting inert on the others.
+ */
+const SCOPED_TABS: CodeHealthTabId[] = ["map", "findings"];
+
+const SCOPE_LABEL_KEYS: Record<HealthScope, string> = {
+ all: "scopeAll",
+ production: "scopeProduction",
+};
+
+/**
+ * Tabs whose data honours `counts`. The trend is deliberately absent even
+ * though it sits on the Overview: snapshots recorded the full score, so there
+ * is no code-shape series to draw and inventing one from mean deductions would
+ * disagree with the headline wherever a file sits at the score floor.
+ */
+const COUNTED_TABS: CodeHealthTabId[] = ["map", "findings"];
+
+/**
+ * A named dropdown for a view control in the page header.
+ *
+ * These are filters over everything on the page, not navigation, so they read
+ * as a question and its current answer rather than as a second row of tabs
+ * competing with the real one.
+ */
+function ViewSelect({
+ label,
+ value,
+ onValueChange,
+ options,
+}: {
+ label: string;
+ value: string;
+ onValueChange: (next: string) => void;
+ options: { id: string; label: string }[];
+}) {
+ return (
+ <div className="flex min-w-0 items-center gap-2">
+ <span className="shrink-0 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ {label}
+ </span>
+ <Select value={value} onValueChange={onValueChange}>
+ <SelectTrigger aria-label={label} className="h-8 w-auto gap-1.5 px-2.5 text-xs">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {options.map((o) => (
+ <SelectItem key={o.id} value={o.id}>
+ {o.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ );
+}
+
+const COUNTS_LABEL_KEYS: Record<HealthCounts, string> = {
+ everything: "countsEverything",
+ code_shape: "countsCodeShape",
+};
+
+/**
+ * Nodes the map draws at first. The server chooses which ones: pinned paths
+ * first, a floor per module, then production before tooling, tests and
+ * examples, with open performance causes and then the unhealthiest files
+ * leading each tier. "Draw more" steps the cap up to the server's ceiling.
+ */
+const MAP_CAP = 2000;
+const MAP_CAP_STEP = 2000;
+const MAP_CAP_MAX = 8000;
+/** Paths pinned for selections made outside the drawn field, at most. */
+const MAX_EXTRA_PINS = 20;
+/**
+ * Churn points pulled for the churn lens. Deliberately larger than
+ * `MAP_FILE_LIMIT`: the map ranks by NLOC and churn-complexity ranks by
+ * `commit_count × max_ccn`, so the two windows do not contain the same files.
+ * At the old default of 300 this repo joined churn onto 296 of the 1,935 mapped
+ * files that have it, and the other ~1,700 nodes rendered as the legend's
+ * "no data" swatch for data that exists. Matching the map's 2,000 would still
+ * miss 445. 5,000 covers every churned file here with headroom; a repo that
+ * exceeds it degrades back to the same partial join rather than breaking.
+ *
+ * Costs ~469 KB uncompressed on this repo (3,011 points), on a request that
+ * only fires once the churn lens is selected. The hosted route still caps at
+ * 1,000, so porting this page there needs that ceiling raised first or the
+ * request 422s.
+ */
+const CHURN_POINT_LIMIT = 5000;
+
+export function CodeHealthView() {
+ const t = useTranslations("views.codeHealth");
+ const tc = useTranslations("common");
+ const params = useParams<{ id: string }>();
+ const router = useRouter();
+ const searchParams = useSearchParams();
+ const repoId = params.id;
+
+ // `?pillar=` predates the lens and the performance tab: the Overview health
+ // card still links with it. Performance now has a tab of its own and the
+ // other two are lenses, so the parameter resolves onto whichever surface
+ // actually answers it rather than onto a control that no longer exists.
+ const rawPillar = searchParams.get("pillar");
+
+ const activeTab = resolveCodeHealthTab(searchParams.get("tab"), rawPillar);
+
+ const rawScope = searchParams.get("scope");
+ const scope: HealthScope = (HEALTH_SCOPES as readonly string[]).includes(rawScope ?? "")
+ ? (rawScope as HealthScope)
+ : "all";
+ // Only the default population needs no key suffix, so an existing cache entry
+ // stays valid and the narrowed one gets its own.
+ const scopeKey = scope === "all" ? "" : `:${scope}`;
+
+ const rawCounts = searchParams.get("counts");
+ const counts: HealthCounts = (HEALTH_COUNTS as readonly string[]).includes(rawCounts ?? "")
+ ? (rawCounts as HealthCounts)
+ : "everything";
+ // Same convention as scope, and appended after it: the two suffixes have to
+ // compose in one fixed order or the page-level key and the view-level key
+ // stop matching and the overview is fetched twice.
+ const countsKey = counts === "everything" ? "" : `:${counts}`;
+ const viewKey = `${scopeKey}${countsKey}`;
+
+ const rawLens = searchParams.get("lens");
+ const overlay: CodeHealthOverlay = (OVERLAYS as readonly string[]).includes(rawLens ?? "")
+ ? (rawLens as CodeHealthOverlay)
+ : rawPillar === "maintainability"
+ ? "maintainability"
+ : "health";
+
+ // The map's selection and its opportunity highlight live in the URL, so a
+ // link from the performance queue opens this field on the file it is about.
+ const selectedPath = searchParams.get("file");
+ const opportunityId = searchParams.get("opportunity");
+
+ // Shares the SWR key with TriageView, so the meta line costs no extra request.
+ const { data: overview } = useSWR<HealthOverviewResponse>(
+ `code-health-overview:${repoId}${viewKey}`,
+ () => getHealthOverview(repoId, 25, scope, counts),
+ { revalidateOnFocus: false },
+ );
+ const meta = overview?.meta;
+
+ // Refresh revalidates every SWR key for this repo (overview + each tab's own
+ // keys), so the button works on whichever tab is active.
+ const { mutate: mutateAll } = useSWRConfig();
+ const [refreshing, setRefreshing] = useState(false);
+ const refresh = useCallback(async () => {
+ setRefreshing(true);
+ try {
+ await mutateAll((key) => typeof key === "string" && key.includes(repoId), undefined, {
+ revalidate: true,
+ });
+ } finally {
+ setRefreshing(false);
+ }
+ }, [mutateAll, repoId]);
+
+ // Trend fetched ONCE here, fed to the folded Trend section — no second fetch.
+ const {
+ data: trend,
+ isLoading: trendLoading,
+ error: trendError,
+ mutate: mutateTrend,
+ } = useSWR<HealthTrendResponse>(
+ `code-health-trend:${repoId}${scopeKey}`,
+ () => getHealthTrend(repoId, 20, scope),
+ { revalidateOnFocus: false },
+ );
+
+ // The opportunity a link arrived with, so its files can be guaranteed a node
+ // and marked. One bounded request, and only when the link carries an id.
+ const { data: opportunity } = useSWR(
+ opportunityId ? `code-health-map-opportunity:${repoId}:${opportunityId}` : null,
+ () => getPerformanceOpportunity(repoId, opportunityId as string, { evidenceLimit: 25 }),
+ { revalidateOnFocus: false },
+ );
+
+ // The intervention file plus the files its evidence sits in. An id from a
+ // retired model resolves to a state rather than to a row, and that shape
+ // carries no paths, so it simply marks nothing.
+ const highlightPaths = useMemo(() => {
+ if (!opportunity || !("file_path" in opportunity)) return undefined;
+ const paths = [opportunity.file_path, ...opportunity.evidence.map((e) => e.file_path)];
+ return [...new Set(paths.filter(Boolean))];
+ }, [opportunity]);
+
+ // The bounded field: one pull, shared across lenses so switching never
+ // refetches. The paths the page needs on screen ride along as `active`, which
+ // is what makes the guarantee a server-side one rather than a hope that the
+ // ranking happened to include them.
+ //
+ // A selection is pinned only when it is not already drawn, and a pin, once
+ // made, stays: a click on a node the reader can see costs no request, and a
+ // file pinned in does not drop out again on the refetch its own pin caused.
+ // The deep-linked file is pinned from the first request.
+ const [extraPins, setExtraPins] = useState<string[]>(() =>
+ selectedPath ? [selectedPath] : [],
+ );
+ const [mapCap, setMapCap] = useState(MAP_CAP);
+ const [includeHeld, setIncludeHeld] = useState(false);
+ const [pinQuery, setPinQuery] = useState("");
+ const activePaths = useMemo(
+ () => [...new Set([...extraPins, ...(highlightPaths ?? [])])],
+ [extraPins, highlightPaths],
+ );
+ const {
+ data: mapFeed,
+ error: mapError,
+ isValidating: mapValidating,
+ mutate: mutateMap,
+ } = useSWR<HealthMapFeed>(
+ `code-health-map:${repoId}${viewKey}:${mapCap}:${includeHeld ? "held" : ""}:${pinQuery}:${activePaths.join(",")}`,
+ () =>
+ getHealthMap(repoId, {
+ cap: mapCap,
+ ...(activePaths.length ? { active: activePaths } : {}),
+ scope,
+ counts,
+ ...(includeHeld ? { include_held: true } : {}),
+ ...(pinQuery ? { q: pinQuery } : {}),
+ }),
+ { revalidateOnFocus: false, keepPreviousData: true },
+ );
+ const drawnPaths = useMemo(
+ () => new Set(mapFeed?.files.map((f) => f.file_path) ?? []),
+ [mapFeed],
+ );
+ useEffect(() => {
+ if (!selectedPath || !mapFeed || drawnPaths.has(selectedPath)) return;
+ setExtraPins((pins) =>
+ pins.includes(selectedPath) ? pins : [...pins, selectedPath].slice(-MAX_EXTRA_PINS),
+ );
+ }, [selectedPath, mapFeed, drawnPaths]);
+ const canDrawMore = mapCap < MAP_CAP_MAX;
+ const drawMore = useCallback(
+ () => setMapCap((c) => Math.min(MAP_CAP_MAX, c + MAP_CAP_STEP)),
+ [],
+ );
+ const retryMap = useCallback(() => void mutateMap(), [mutateMap]);
+
+ // Churn percentiles for the churn lens. Fetched only once that lens is
+ // selected: it is a second request, and the other three lenses color from
+ // fields already on the map payload.
+ const churnWanted = overlay === "churn";
+ const { data: churn, isLoading: churnLoading } = useSWR<ChurnComplexityResponse>(
+ churnWanted ? `health-churn-complexity:${repoId}` : null,
+ () => getChurnComplexity(repoId, { limit: CHURN_POINT_LIMIT }),
+ { revalidateOnFocus: false, keepPreviousData: true },
+ );
+
+ // Join churn onto the map rows by path. Until it lands every node would be
+ // neutral, so the legend is told it is loading rather than letting an
+ // all-grey field read as "no churn anywhere".
+ const mapFeedWithChurn: HealthMapFeed | undefined = useMemo(() => {
+ if (!mapFeed || !churn) return mapFeed;
+ const byPath = new Map(churn.points.map((p) => [p.file_path, p.churn_percentile]));
+ return {
+ ...mapFeed,
+ files: mapFeed.files.map((file) => ({
+ ...file,
+ churn_percentile: byPath.get(file.file_path) ?? null,
+ })),
+ };
+ }, [mapFeed, churn]);
+
+ // ---- Tab counts ----
+ // Dead code uses the same key + fetcher as its own tab, so this is a prefetch
+ // rather than a duplicate request.
+ const { data: deadCode } = useSWR<DeadCodeSummary>(
+ `dead-code-summary:${repoId}`,
+ () => getDeadCodeSummary(repoId),
+ { revalidateOnFocus: false },
+ );
+ const badges: Partial<Record<CodeHealthTabId, number>> = {};
+ if (deadCode) badges["dead-code"] = deadCode.total_findings;
+
+ const setTab = useCallback(
+ (next: string) => {
+ const sp = new URLSearchParams(searchParams.toString());
+ if (next === DEFAULT_TAB) sp.delete("tab");
+ else sp.set("tab", next);
+ const qs = sp.toString();
+ router.replace(qs ? `?${qs}` : "?", { scroll: false });
+ },
+ [router, searchParams],
+ );
+
+ const setSelectedPath = useCallback(
+ (next: string | null) => {
+ const sp = new URLSearchParams(searchParams.toString());
+ if (next) sp.set("file", next);
+ else sp.delete("file");
+ const qs = sp.toString();
+ router.replace(qs ? `?${qs}` : "?", { scroll: false });
+ },
+ [router, searchParams],
+ );
+
+ const setScope = useCallback(
+ (next: string) => {
+ const sp = new URLSearchParams(searchParams.toString());
+ if (next === "all") sp.delete("scope");
+ else sp.set("scope", next);
+ const qs = sp.toString();
+ router.replace(qs ? `?${qs}` : "?", { scroll: false });
+ },
+ [router, searchParams],
+ );
+
+ const setCounts = useCallback(
+ (next: string) => {
+ const sp = new URLSearchParams(searchParams.toString());
+ if (next === "everything") sp.delete("counts");
+ else sp.set("counts", next);
+ const qs = sp.toString();
+ router.replace(qs ? `?${qs}` : "?", { scroll: false });
+ },
+ [router, searchParams],
+ );
+
+ const setOverlay = useCallback(
+ (next: CodeHealthOverlay) => {
+ const sp = new URLSearchParams(searchParams.toString());
+ if (next === "health") sp.delete("lens");
+ else sp.set("lens", next);
+ const qs = sp.toString();
+ router.replace(qs ? `?${qs}` : "?", { scroll: false });
+ },
+ [router, searchParams],
+ );
+
+ return (
+ <PageShell
+ title={t("title")}
+ icon={<HeartPulse />}
+ // No description: the lede below opens with what the score is built from,
+ // and a header that says it first only says it twice.
+ //
+ // "wide" rather than the style's usual 1280 — a deliberate divergence. At
+ // 1280 the map keeps ~900px beside its 320px inspector; the extra width
+ // goes entirely to the field, which is this page's whole subject.
+ maxWidth="wide"
+ actions={
+ // Two named dropdowns rather than two tab rows. Four choices spelled
+ // out in full overflowed the header on a phone and set the whole page
+ // scrolling sideways; a trigger shows the current answer and spends no
+ // width on the alternative.
+ <div className="flex min-w-0 flex-wrap items-center gap-x-4 gap-y-2">
+ {SCOPED_TABS.includes(activeTab) && (
+ <ViewSelect
+ label={t("scopeFiles")}
+ value={scope}
+ onValueChange={setScope}
+ options={HEALTH_SCOPES.map((id) => ({
+ id,
+ label: t(SCOPE_LABEL_KEYS[id]),
+ }))}
+ />
+ )}
+ {COUNTED_TABS.includes(activeTab) && (
+ <ViewSelect
+ label={t("scopeCounts")}
+ value={counts}
+ onValueChange={setCounts}
+ options={HEALTH_COUNTS.map((id) => ({
+ id,
+ label: t(COUNTS_LABEL_KEYS[id]),
+ }))}
+ />
+ )}
+ <Button size="sm" variant="outline" onClick={refresh} disabled={refreshing}>
+ <RotateCw
+ className={`mr-1.5 h-3.5 w-3.5 ${refreshing ? "motion-safe:animate-spin" : ""}`}
+ />{" "}
+ {refreshing ? t("refreshing") : t("refresh")}
+ </Button>
+ </div>
+ }
+ >
+ {/* Replaced each release that moves health scores, and keyed with that
+ release's version so a reader who dismissed an earlier one sees it. */}
+ <ReleaseNotice
+ id="health-scoring"
+ version="0.56.0"
+ detail={t("coChangeNoticeBody")}
+ detailLabel={t("coChangeNoticeMore")}
+ hideLabel={t("coChangeNoticeLess")}
+ dismissLabel={tc("dismiss")}
+ >
+ {t("coChangeNoticeTitle")}
+ </ReleaseNotice>
+
+ {meta ? (
+ <p className="-mt-3 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ {meta.last_indexed_at
+ ? t("indexed", { date: formatDateTime(meta.last_indexed_at) })
+ : t("notIndexed")}
+ {meta.head_commit ? ` · ${meta.head_commit.slice(0, 8)}` : ""}
+ {` · ${t("snapshots", { count: meta.snapshot_count })}`}
+ </p>
+ ) : null}
+
+ <ViewTabs
+ tabs={CODE_HEALTH_TABS.map((id) => {
+ const Icon = TAB_DEFS[id].icon;
+ return {
+ id,
+ label: t(TAB_DEFS[id].labelKey),
+ icon: <Icon className="h-3.5 w-3.5" />,
+ ...(badges[id] !== undefined ? { badge: badges[id] } : {}),
+ };
+ })}
+ value={activeTab}
+ onValueChange={setTab}
+ >
+ {activeTab === "map" && (
+ <TriageTab
+ counts={counts}
+ repoId={repoId}
+ trend={trend}
+ overlay={overlay}
+ onOverlayChange={setOverlay}
+ lenses={OVERLAYS}
+ mapFeed={mapFeedWithChurn}
+ overlayLoading={churnWanted && churnLoading && !churn}
+ selectedPath={selectedPath}
+ onSelectPath={setSelectedPath}
+ highlightPaths={highlightPaths}
+ scope={scope}
+ onDrawMore={canDrawMore ? drawMore : undefined}
+ drawMoreStep={MAP_CAP_STEP}
+ onIncludeHeldChange={setIncludeHeld}
+ onFindUndrawn={setPinQuery}
+ mapPending={mapValidating}
+ mapError={mapError}
+ onRetryMap={retryMap}
+ hotspotsSlot={<HotspotsSection repoId={repoId} />}
+ trendSlot={
+ <OverviewSection
+ title={t("trendTitle")}
+ description={t("trendDescription")}
+ >
+ <TrendSection
+ data={trend}
+ isLoading={trendLoading}
+ error={trendError}
+ onRetry={() => void mutateTrend()}
+ counts={counts}
+ onSelectFile={setSelectedPath}
+ />
+ </OverviewSection>
+ }
+ />
+ )}
+ {activeTab === "findings" && <FindingsTab repoId={repoId} scope={scope} counts={counts} />}
+ {activeTab === "performance" && <PerformanceTab repoId={repoId} />}
+ {activeTab === "dead-code" && <DeadCodeTab repoId={repoId} />}
+ </ViewTabs>
+ </PageShell>
+ );
+}
diff --git a/packages/web/src/app/repos/[id]/code-health/coverage/page.tsx b/packages/web/src/app/repos/[id]/code-health/coverage/page.tsx
index c78aeef90..cb8fa8718 100644
--- a/packages/web/src/app/repos/[id]/code-health/coverage/page.tsx
+++ b/packages/web/src/app/repos/[id]/code-health/coverage/page.tsx
@@ -1,11 +1,11 @@
import { redirect } from "next/navigation";
-/** Coverage is a tab of the consolidated Code Health section now. */
+/** Legacy route; test coverage has its own page. */
export default async function LegacyRedirect({
params,
}: {
params: Promise<{ id: string }>;
}) {
const { id } = await params;
- redirect(`/repos/${id}/code-health?tab=coverage`);
+ redirect(`/repos/${id}/tests`);
}
diff --git a/packages/web/src/app/repos/[id]/code-health/page.tsx b/packages/web/src/app/repos/[id]/code-health/page.tsx
index bcd2b45bf..de7fbb44b 100644
--- a/packages/web/src/app/repos/[id]/code-health/page.tsx
+++ b/packages/web/src/app/repos/[id]/code-health/page.tsx
@@ -1,697 +1,27 @@
-"use client";
+import { redirect } from "next/navigation";
+import { CodeHealthView } from "./code-health-view";
+import { movedTabHref } from "./tabs";
/**
- * Code Health — `/repos/[id]/code-health`.
- *
- * One living map, a lede that says what the score means, and a thin drill-down.
- * The galaxy map is the page spine; a lens switcher recolors the same field
- * (health / maintainability / performance / churn) so the cross-tab redundancy
- * collapses.
- *
- * Performance has its own causal-opportunity tab; raw observations remain its
- * evidence rather than competing with the ranked finding queue. Hotspots is
- * gone: it rendered a *second* galaxy map
- * on the churn lens directly under this page's, so churn became a lens here and
- * what the lens cannot say — bus factor, the ranked table — became a section
- * under the map. Blast radius keeps its `impact` tab id (existing file-card and
- * symbol-drawer deep links point at it) but is labelled for what it is.
- *
- * Tabs carry their count where one is cheap to get, so a clean repo says so
- * before you spend a click. Dead code dedupes onto the key its own tab uses.
- * Findings is not numbered: the overview's queue inventory is not the list the
- * tab opens on, and that list's own total is a multi-second query. Security
- * has no count endpoint (only a findings list), and blast radius is a tool you
- * operate rather than a pile you read, so neither is numbered.
+ * `/repos/[id]/code-health`. A server shell so a link to a tab that moved out
+ * (Tests, Security, Doc drift, blast radius) redirects before anything
+ * paints, instead of flashing the Map first.
*/
-
-import dynamic from "next/dynamic";
-import { useParams, useRouter, useSearchParams } from "next/navigation";
-import { useCallback, useEffect, useMemo, useState } from "react";
-import useSWR, { useSWRConfig } from "swr";
-import {
- Bug,
- FlaskConical,
- Gauge,
- HeartPulse,
- LayoutDashboard,
- RotateCw,
- Scissors,
- BookText,
- Shield,
- Waypoints,
- type LucideIcon,
-} from "lucide-react";
-import { PageShell } from "@repowise-dev/ui/shared/page-shell";
-import { ReleaseNotice } from "@repowise-dev/ui/shared/release-notice";
-import { ViewTabs } from "@repowise-dev/ui/shared/view-tabs";
-import { OverviewSection } from "@repowise-dev/ui/overview";
-import { Button } from "@repowise-dev/ui/ui/button";
-import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@repowise-dev/ui/ui/select";
-import { formatDateTime } from "@repowise-dev/ui/lib/format";
-import type { CodeHealthOverlay } from "@repowise-dev/ui/health";
-import type { DeadCodeSummary } from "@repowise-dev/types/dead-code";
-import {
- HEALTH_COUNTS,
- HEALTH_SCOPES,
- type HealthCounts,
- type HealthScope,
-} from "@repowise-dev/types/health";
-import type { DocDriftResponse } from "@repowise-dev/types/doc-drift";
-import { TriageTab } from "@/components/code-health/triage-tab";
-import { HotspotsSection } from "@/components/code-health/hotspots-section";
-import { TrendSection } from "@/components/code-health/trend-tab";
-import { getDeadCodeSummary } from "@/lib/api/dead-code";
-import { getDocDrift } from "@/lib/api/doc-drift";
-import {
- getChurnComplexity,
- getHealthCoverage,
- getHealthMap,
- getHealthOverview,
- getHealthTrend,
- getPerformanceOpportunity,
- type ChurnComplexityResponse,
- type HealthCoverageResponse,
- type HealthMapFeed,
- type HealthOverviewResponse,
- type HealthTrendResponse,
-} from "@/lib/api/code-health";
-import { useTranslations } from "next-intl";
-
-// The tabs render one at a time behind `?tab=` and triage is the default, so
-// the others are split out: landing here downloads the triage chunk only.
-// ssr:false because they are interactive, data-fetching client views.
-const TabFallback = () => <Skeleton className="h-[60vh] w-full rounded-lg" />;
-const FindingsTab = dynamic(
- () => import("@/components/code-health/findings-tab").then((m) => m.FindingsTab),
- { ssr: false, loading: TabFallback },
-);
-const PerformanceTab = dynamic(
- () => import("@/components/code-health/performance-tab").then((m) => m.PerformanceTab),
- { ssr: false, loading: TabFallback },
-);
-const CoverageTab = dynamic(
- () => import("@/components/code-health/coverage-tab").then((m) => m.CoverageTab),
- { ssr: false, loading: TabFallback },
-);
-const DeadCodeTab = dynamic(
- () => import("@/components/risk/dead-code-tab").then((m) => m.DeadCodeTab),
- { ssr: false, loading: TabFallback },
-);
-const DocDriftTab = dynamic(
- () => import("@/components/risk/doc-drift-tab").then((m) => m.DocDriftTab),
- { ssr: false, loading: TabFallback },
-);
-const SecurityTab = dynamic(
- () => import("@/components/risk/security-tab").then((m) => m.SecurityTab),
- { ssr: false, loading: TabFallback },
-);
-const ImpactTab = dynamic(
- () => import("@/components/risk/impact-tab").then((m) => m.ImpactTab),
- { ssr: false, loading: TabFallback },
-);
-
-const TABS = [
- "triage",
- "performance",
- "findings",
- "coverage",
- "dead-code",
- "doc-drift",
- "security",
- "impact",
-] as const;
-type TabId = (typeof TABS)[number];
-
-const TAB_LABEL_KEYS: Record<TabId, string> = {
- triage: "tabs.triage",
- performance: "tabs.performance",
- findings: "tabs.findings",
- coverage: "tabs.coverage",
- "dead-code": "tabs.deadCode",
- "doc-drift": "tabs.docDrift",
- security: "tabs.security",
- impact: "tabs.impact",
-};
-
-/**
- * One mark per tab, to make the row scannable without reading every word.
- * They are identity, not status: monochrome, inheriting the tab's own color, so
- * no icon can imply a health band. The label still carries the accessible name,
- * which is why `ViewTabs` renders them `aria-hidden`.
- */
-const TAB_ICONS: Record<TabId, LucideIcon> = {
- triage: LayoutDashboard,
- performance: Gauge,
- findings: Bug,
- coverage: FlaskConical,
- "dead-code": Scissors,
- "doc-drift": BookText,
- security: Shield,
- impact: Waypoints,
-};
-
-/**
- * Legacy tab ids → their new home. `heatmap` was the old churn tab and
- * `hotspots` its successor; both now land on the map, whose churn lens replaced
- * them. `modules` folded into the map's hub layer, `trend` into the section
- * under it.
- */
-const TAB_ALIASES: Record<string, TabId> = {
- heatmap: "triage",
- hotspots: "triage",
- modules: "triage",
- trend: "triage",
-};
-
-/**
- * Lenses on the map. The three co-equal health signals ride on the map payload
- * itself; churn arrives on its own request and is joined in below, which is why
- * it is listed here rather than in the map component's default.
- */
-const OVERLAYS: CodeHealthOverlay[] = ["health", "maintainability", "performance", "churn"];
-
-/**
- * Tabs whose data honours `scope`. The routes behind the others — coverage,
- * dead code, security, blast radius — have no production/test split, and
- * performance carries its own execution-context control, so the toggle is
- * offered where it does something rather than sitting inert on five tabs.
- */
-const SCOPED_TABS: TabId[] = ["triage", "findings"];
-
-const SCOPE_LABEL_KEYS: Record<HealthScope, string> = {
- all: "scopeAll",
- production: "scopeProduction",
-};
-
-/**
- * Tabs whose data honours `counts`. The trend is deliberately absent even
- * though it sits on the Overview: snapshots recorded the full score, so there
- * is no code-shape series to draw and inventing one from mean deductions would
- * disagree with the headline wherever a file sits at the score floor.
- */
-const COUNTED_TABS: TabId[] = ["triage", "findings"];
-
-/**
- * A named dropdown for a view control in the page header.
- *
- * These are filters over everything on the page, not navigation, so they read
- * as a question and its current answer rather than as a second row of tabs
- * competing with the real one.
- */
-function ViewSelect({
- label,
- value,
- onValueChange,
- options,
+export default async function CodeHealthPage({
+ params,
+ searchParams,
}: {
- label: string;
- value: string;
- onValueChange: (next: string) => void;
- options: { id: string; label: string }[];
+ params: Promise<{ id: string }>;
+ searchParams: Promise<Record<string, string | string[] | undefined>>;
}) {
- return (
- <div className="flex min-w-0 items-center gap-2">
- <span className="shrink-0 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
- {label}
- </span>
- <Select value={value} onValueChange={onValueChange}>
- <SelectTrigger aria-label={label} className="h-8 w-auto gap-1.5 px-2.5 text-xs">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {options.map((o) => (
- <SelectItem key={o.id} value={o.id}>
- {o.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </div>
- );
-}
-
-const COUNTS_LABEL_KEYS: Record<HealthCounts, string> = {
- everything: "countsEverything",
- code_shape: "countsCodeShape",
-};
-
-/**
- * Nodes the map draws at first. The server chooses which ones: pinned paths
- * first, a floor per module, then production before tooling, tests and
- * examples, with open performance causes and then the unhealthiest files
- * leading each tier. "Draw more" steps the cap up to the server's ceiling.
- */
-const MAP_CAP = 2000;
-const MAP_CAP_STEP = 2000;
-const MAP_CAP_MAX = 8000;
-/** Paths pinned for selections made outside the drawn field, at most. */
-const MAX_EXTRA_PINS = 20;
-/**
- * Churn points pulled for the churn lens. Deliberately larger than
- * `MAP_FILE_LIMIT`: the map ranks by NLOC and churn-complexity ranks by
- * `commit_count × max_ccn`, so the two windows do not contain the same files.
- * At the old default of 300 this repo joined churn onto 296 of the 1,935 mapped
- * files that have it, and the other ~1,700 nodes rendered as the legend's
- * "no data" swatch for data that exists. Matching the map's 2,000 would still
- * miss 445. 5,000 covers every churned file here with headroom; a repo that
- * exceeds it degrades back to the same partial join rather than breaking.
- *
- * Costs ~469 KB uncompressed on this repo (3,011 points), on a request that
- * only fires once the churn lens is selected. The hosted route still caps at
- * 1,000, so porting this page there needs that ceiling raised first or the
- * request 422s.
- */
-const CHURN_POINT_LIMIT = 5000;
-
-export default function CodeHealthPage() {
- const t = useTranslations("views.codeHealth");
- const tc = useTranslations("common");
- const params = useParams<{ id: string }>();
- const router = useRouter();
- const searchParams = useSearchParams();
- const repoId = params.id;
-
- // `?pillar=` predates the lens and the performance tab: the Overview health
- // card still links with it. Performance now has a tab of its own and the
- // other two are lenses, so the parameter resolves onto whichever surface
- // actually answers it rather than onto a control that no longer exists.
- const rawPillar = searchParams.get("pillar");
-
- const rawTab = searchParams.get("tab");
- const aliased = rawTab ? TAB_ALIASES[rawTab] : undefined;
- const activeTab: TabId =
- aliased ??
- (rawTab && (TABS as readonly string[]).includes(rawTab)
- ? (rawTab as TabId)
- : rawPillar === "performance"
- ? "performance"
- : "triage");
-
- const rawScope = searchParams.get("scope");
- const scope: HealthScope = (HEALTH_SCOPES as readonly string[]).includes(rawScope ?? "")
- ? (rawScope as HealthScope)
- : "all";
- // Only the default population needs no key suffix, so an existing cache entry
- // stays valid and the narrowed one gets its own.
- const scopeKey = scope === "all" ? "" : `:${scope}`;
-
- const rawCounts = searchParams.get("counts");
- const counts: HealthCounts = (HEALTH_COUNTS as readonly string[]).includes(rawCounts ?? "")
- ? (rawCounts as HealthCounts)
- : "everything";
- // Same convention as scope, and appended after it: the two suffixes have to
- // compose in one fixed order or the page-level key and the view-level key
- // stop matching and the overview is fetched twice.
- const countsKey = counts === "everything" ? "" : `:${counts}`;
- const viewKey = `${scopeKey}${countsKey}`;
-
- const rawLens = searchParams.get("lens");
- const overlay: CodeHealthOverlay = (OVERLAYS as readonly string[]).includes(rawLens ?? "")
- ? (rawLens as CodeHealthOverlay)
- : rawPillar === "maintainability"
- ? "maintainability"
- : "health";
-
- // The map's selection and its opportunity highlight live in the URL, so a
- // link from the performance queue opens this field on the file it is about.
- const selectedPath = searchParams.get("file");
- const opportunityId = searchParams.get("opportunity");
-
- // Shares the SWR key with TriageView, so the meta line costs no extra request.
- const { data: overview } = useSWR<HealthOverviewResponse>(
- `code-health-overview:${repoId}${viewKey}`,
- () => getHealthOverview(repoId, 25, scope, counts),
- { revalidateOnFocus: false },
- );
- const meta = overview?.meta;
-
- // Refresh revalidates every SWR key for this repo (overview + each tab's own
- // keys), so the button works on whichever tab is active.
- const { mutate: mutateAll } = useSWRConfig();
- const [refreshing, setRefreshing] = useState(false);
- const refresh = useCallback(async () => {
- setRefreshing(true);
- try {
- await mutateAll((key) => typeof key === "string" && key.includes(repoId), undefined, {
- revalidate: true,
- });
- } finally {
- setRefreshing(false);
+ const { id } = await params;
+ const sp = new URLSearchParams();
+ for (const [key, value] of Object.entries(await searchParams)) {
+ for (const v of Array.isArray(value) ? value : value === undefined ? [] : [value]) {
+ sp.append(key, v);
}
- }, [mutateAll, repoId]);
-
- // Trend fetched ONCE here, fed to the folded Trend section — no second fetch.
- const {
- data: trend,
- isLoading: trendLoading,
- error: trendError,
- mutate: mutateTrend,
- } = useSWR<HealthTrendResponse>(
- `code-health-trend:${repoId}${scopeKey}`,
- () => getHealthTrend(repoId, 20, scope),
- { revalidateOnFocus: false },
- );
-
- // The opportunity a link arrived with, so its files can be guaranteed a node
- // and marked. One bounded request, and only when the link carries an id.
- const { data: opportunity } = useSWR(
- opportunityId ? `code-health-map-opportunity:${repoId}:${opportunityId}` : null,
- () => getPerformanceOpportunity(repoId, opportunityId as string, { evidenceLimit: 25 }),
- { revalidateOnFocus: false },
- );
-
- // The intervention file plus the files its evidence sits in. An id from a
- // retired model resolves to a state rather than to a row, and that shape
- // carries no paths, so it simply marks nothing.
- const highlightPaths = useMemo(() => {
- if (!opportunity || !("file_path" in opportunity)) return undefined;
- const paths = [opportunity.file_path, ...opportunity.evidence.map((e) => e.file_path)];
- return [...new Set(paths.filter(Boolean))];
- }, [opportunity]);
-
- // The bounded field: one pull, shared across lenses so switching never
- // refetches. The paths the page needs on screen ride along as `active`, which
- // is what makes the guarantee a server-side one rather than a hope that the
- // ranking happened to include them.
- //
- // A selection is pinned only when it is not already drawn, and a pin, once
- // made, stays: a click on a node the reader can see costs no request, and a
- // file pinned in does not drop out again on the refetch its own pin caused.
- // The deep-linked file is pinned from the first request.
- const [extraPins, setExtraPins] = useState<string[]>(() =>
- selectedPath ? [selectedPath] : [],
- );
- const [mapCap, setMapCap] = useState(MAP_CAP);
- const [includeHeld, setIncludeHeld] = useState(false);
- const [pinQuery, setPinQuery] = useState("");
- const activePaths = useMemo(
- () => [...new Set([...extraPins, ...(highlightPaths ?? [])])],
- [extraPins, highlightPaths],
- );
- const {
- data: mapFeed,
- error: mapError,
- isValidating: mapValidating,
- mutate: mutateMap,
- } = useSWR<HealthMapFeed>(
- `code-health-map:${repoId}${viewKey}:${mapCap}:${includeHeld ? "held" : ""}:${pinQuery}:${activePaths.join(",")}`,
- () =>
- getHealthMap(repoId, {
- cap: mapCap,
- ...(activePaths.length ? { active: activePaths } : {}),
- scope,
- counts,
- ...(includeHeld ? { include_held: true } : {}),
- ...(pinQuery ? { q: pinQuery } : {}),
- }),
- { revalidateOnFocus: false, keepPreviousData: true },
- );
- const drawnPaths = useMemo(
- () => new Set(mapFeed?.files.map((f) => f.file_path) ?? []),
- [mapFeed],
- );
- useEffect(() => {
- if (!selectedPath || !mapFeed || drawnPaths.has(selectedPath)) return;
- setExtraPins((pins) =>
- pins.includes(selectedPath) ? pins : [...pins, selectedPath].slice(-MAX_EXTRA_PINS),
- );
- }, [selectedPath, mapFeed, drawnPaths]);
- const canDrawMore = mapCap < MAP_CAP_MAX;
- const drawMore = useCallback(
- () => setMapCap((c) => Math.min(MAP_CAP_MAX, c + MAP_CAP_STEP)),
- [],
- );
- const retryMap = useCallback(() => void mutateMap(), [mutateMap]);
-
- // Churn percentiles for the churn lens. Fetched only once that lens is
- // selected: it is a second request, and the other three lenses color from
- // fields already on the map payload.
- const churnWanted = overlay === "churn";
- const { data: churn, isLoading: churnLoading } = useSWR<ChurnComplexityResponse>(
- churnWanted ? `health-churn-complexity:${repoId}` : null,
- () => getChurnComplexity(repoId, { limit: CHURN_POINT_LIMIT }),
- { revalidateOnFocus: false, keepPreviousData: true },
- );
-
- // Join churn onto the map rows by path. Until it lands every node would be
- // neutral, so the legend is told it is loading rather than letting an
- // all-grey field read as "no churn anywhere".
- const mapFeedWithChurn: HealthMapFeed | undefined = useMemo(() => {
- if (!mapFeed || !churn) return mapFeed;
- const byPath = new Map(churn.points.map((p) => [p.file_path, p.churn_percentile]));
- return {
- ...mapFeed,
- files: mapFeed.files.map((file) => ({
- ...file,
- churn_percentile: byPath.get(file.file_path) ?? null,
- })),
- };
- }, [mapFeed, churn]);
-
- // ---- Tab counts ----
- // Dead code uses the same key + fetcher as its own tab, so this is a prefetch
- // rather than a duplicate request.
- const { data: deadCode } = useSWR<DeadCodeSummary>(
- `dead-code-summary:${repoId}`,
- () => getDeadCodeSummary(repoId),
- { revalidateOnFocus: false },
- );
- // Coverage's own tab pulls 5,000 file rows and the module rollup; this badge
- // reads one number off `summary`, so it declines both. `limit` and
- // `module_limit` cap different blocks — one file row and no modules is 0.7 KB
- // against the tab's 442 KB, and `modules_total` still reports the real count
- // to anyone who asks for it.
- const { data: coverage } = useSWR<HealthCoverageResponse>(
- `code-health-coverage-summary:${repoId}`,
- () =>
- getHealthCoverage(repoId, {
- limit: 1,
- module_limit: 0,
- // And declines the graph fallback, which would read every call edge in
- // the repo to answer a question this badge cannot render anyway: the
- // inferred basis has no percentage to show.
- include_inferred: false,
- }),
- { revalidateOnFocus: false },
- );
- const coveragePct = coverage?.summary.line_coverage_pct;
- // `limit: 1` rather than the tab's own key: the summary is computed over the
- // whole query and `findings_total` counts before any cap, so one row of
- // payload carries the badge. Sharing the tab's key would dedupe but pull
- // every finding on page load for a number.
- const { data: docDrift } = useSWR<DocDriftResponse>(
- `doc-drift-badge:${repoId}`,
- () => getDocDrift(repoId, { limit: 1 }),
- { revalidateOnFocus: false },
- );
-
- const badges: Partial<Record<TabId, number | string>> = {};
- if (deadCode) badges["dead-code"] = deadCode.total_findings;
- // No badge when the drift pass has not run: the response carries a cause
- // rather than a summary, and a 0 there would read as clean documentation.
- if (docDrift?.summary) badges["doc-drift"] = docDrift.summary.findings_total;
- if (coveragePct != null) badges.coverage = `${Math.round(coveragePct)}%`;
-
- const setTab = useCallback(
- (next: string) => {
- const sp = new URLSearchParams(searchParams.toString());
- if (next === "triage") sp.delete("tab");
- else sp.set("tab", next);
- // The document filter belongs to the drift tab; it must not ride along.
- if (next !== "doc-drift") sp.delete("document");
- const qs = sp.toString();
- router.replace(qs ? `?${qs}` : "?", { scroll: false });
- },
- [router, searchParams],
- );
-
- const setSelectedPath = useCallback(
- (next: string | null) => {
- const sp = new URLSearchParams(searchParams.toString());
- if (next) sp.set("file", next);
- else sp.delete("file");
- const qs = sp.toString();
- router.replace(qs ? `?${qs}` : "?", { scroll: false });
- },
- [router, searchParams],
- );
-
- const setScope = useCallback(
- (next: string) => {
- const sp = new URLSearchParams(searchParams.toString());
- if (next === "all") sp.delete("scope");
- else sp.set("scope", next);
- const qs = sp.toString();
- router.replace(qs ? `?${qs}` : "?", { scroll: false });
- },
- [router, searchParams],
- );
-
- const setCounts = useCallback(
- (next: string) => {
- const sp = new URLSearchParams(searchParams.toString());
- if (next === "everything") sp.delete("counts");
- else sp.set("counts", next);
- const qs = sp.toString();
- router.replace(qs ? `?${qs}` : "?", { scroll: false });
- },
- [router, searchParams],
- );
-
- const setOverlay = useCallback(
- (next: CodeHealthOverlay) => {
- const sp = new URLSearchParams(searchParams.toString());
- if (next === "health") sp.delete("lens");
- else sp.set("lens", next);
- const qs = sp.toString();
- router.replace(qs ? `?${qs}` : "?", { scroll: false });
- },
- [router, searchParams],
- );
-
- return (
- <PageShell
- title={t("title")}
- icon={<HeartPulse />}
- // No description: the lede below opens with what the score is built from,
- // and a header that says it first only says it twice.
- //
- // "wide" rather than the style's usual 1280 — a deliberate divergence. At
- // 1280 the map keeps ~900px beside its 320px inspector; the extra width
- // goes entirely to the field, which is this page's whole subject.
- maxWidth="wide"
- actions={
- // Two named dropdowns rather than two tab rows. Four choices spelled
- // out in full overflowed the header on a phone and set the whole page
- // scrolling sideways; a trigger shows the current answer and spends no
- // width on the alternative.
- <div className="flex min-w-0 flex-wrap items-center gap-x-4 gap-y-2">
- {SCOPED_TABS.includes(activeTab) && (
- <ViewSelect
- label={t("scopeFiles")}
- value={scope}
- onValueChange={setScope}
- options={HEALTH_SCOPES.map((id) => ({
- id,
- label: t(SCOPE_LABEL_KEYS[id]),
- }))}
- />
- )}
- {COUNTED_TABS.includes(activeTab) && (
- <ViewSelect
- label={t("scopeCounts")}
- value={counts}
- onValueChange={setCounts}
- options={HEALTH_COUNTS.map((id) => ({
- id,
- label: t(COUNTS_LABEL_KEYS[id]),
- }))}
- />
- )}
- <Button size="sm" variant="outline" onClick={refresh} disabled={refreshing}>
- <RotateCw
- className={`mr-1.5 h-3.5 w-3.5 ${refreshing ? "motion-safe:animate-spin" : ""}`}
- />{" "}
- {refreshing ? t("refreshing") : t("refresh")}
- </Button>
- </div>
- }
- >
- {/* Replaced each release that moves health scores, and keyed with that
- release's version so a reader who dismissed an earlier one sees it. */}
- <ReleaseNotice
- id="health-scoring"
- version="0.56.0"
- detail={t("coChangeNoticeBody")}
- detailLabel={t("coChangeNoticeMore")}
- hideLabel={t("coChangeNoticeLess")}
- dismissLabel={tc("dismiss")}
- >
- {t("coChangeNoticeTitle")}
- </ReleaseNotice>
-
- {meta ? (
- <p className="-mt-3 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
- {meta.last_indexed_at
- ? t("indexed", { date: formatDateTime(meta.last_indexed_at) })
- : t("notIndexed")}
- {meta.head_commit ? ` · ${meta.head_commit.slice(0, 8)}` : ""}
- {` · ${t("snapshots", { count: meta.snapshot_count })}`}
- </p>
- ) : null}
-
- <ViewTabs
- tabs={TABS.map((id) => {
- const Icon = TAB_ICONS[id];
- return {
- id,
- label: t(TAB_LABEL_KEYS[id]),
- icon: <Icon className="h-3.5 w-3.5" />,
- ...(badges[id] !== undefined ? { badge: badges[id] } : {}),
- };
- })}
- value={activeTab}
- onValueChange={setTab}
- >
- {activeTab === "triage" && (
- <TriageTab
- counts={counts}
- repoId={repoId}
- trend={trend}
- overlay={overlay}
- onOverlayChange={setOverlay}
- lenses={OVERLAYS}
- mapFeed={mapFeedWithChurn}
- overlayLoading={churnWanted && churnLoading && !churn}
- selectedPath={selectedPath}
- onSelectPath={setSelectedPath}
- highlightPaths={highlightPaths}
- scope={scope}
- onDrawMore={canDrawMore ? drawMore : undefined}
- drawMoreStep={MAP_CAP_STEP}
- onIncludeHeldChange={setIncludeHeld}
- onFindUndrawn={setPinQuery}
- mapPending={mapValidating}
- mapError={mapError}
- onRetryMap={retryMap}
- hotspotsSlot={<HotspotsSection repoId={repoId} />}
- trendSlot={
- <OverviewSection
- title={t("trendTitle")}
- description={t("trendDescription")}
- >
- <TrendSection
- data={trend}
- isLoading={trendLoading}
- error={trendError}
- onRetry={() => void mutateTrend()}
- counts={counts}
- onSelectFile={setSelectedPath}
- />
- </OverviewSection>
- }
- />
- )}
- {activeTab === "findings" && <FindingsTab repoId={repoId} scope={scope} counts={counts} />}
- {activeTab === "performance" && <PerformanceTab repoId={repoId} />}
- {activeTab === "coverage" && <CoverageTab repoId={repoId} />}
- {activeTab === "dead-code" && <DeadCodeTab repoId={repoId} />}
- {activeTab === "doc-drift" && (
- <DocDriftTab
- repoId={repoId}
- initialDocument={searchParams.get("document") ?? undefined}
- />
- )}
- {activeTab === "security" && <SecurityTab repoId={repoId} />}
- {activeTab === "impact" && <ImpactTab repoId={repoId} />}
- </ViewTabs>
- </PageShell>
- );
+ }
+ const moved = movedTabHref(id, sp);
+ if (moved) redirect(moved);
+ return <CodeHealthView />;
}
diff --git a/packages/web/src/app/repos/[id]/code-health/tabs.test.ts b/packages/web/src/app/repos/[id]/code-health/tabs.test.ts
new file mode 100644
index 000000000..c17920241
--- /dev/null
+++ b/packages/web/src/app/repos/[id]/code-health/tabs.test.ts
@@ -0,0 +1,52 @@
+import { describe, expect, it } from "vitest";
+import { CODE_HEALTH_TABS, MOVED_TABS, movedTabHref, resolveCodeHealthTab } from "./tabs";
+
+const sp = (q: string) => new URLSearchParams(q);
+
+describe("resolveCodeHealthTab", () => {
+ it("opens the four tabs by id and the Map by default", () => {
+ for (const id of CODE_HEALTH_TABS) expect(resolveCodeHealthTab(id, null)).toBe(id);
+ expect(resolveCodeHealthTab(null, null)).toBe("map");
+ expect(resolveCodeHealthTab("nonsense", null)).toBe("map");
+ });
+
+ it("keeps the Map's old names working", () => {
+ for (const old of ["triage", "heatmap", "hotspots", "modules", "trend"]) {
+ expect(resolveCodeHealthTab(old, null)).toBe("map");
+ }
+ });
+
+ it("honours the overview card's pillar link", () => {
+ expect(resolveCodeHealthTab(null, "performance")).toBe("performance");
+ expect(resolveCodeHealthTab("findings", "performance")).toBe("findings");
+ });
+});
+
+describe("movedTabHref", () => {
+ it("sends each moved tab to its new home", () => {
+ expect(movedTabHref("r1", sp("tab=coverage"))).toBe("/repos/r1/tests");
+ expect(movedTabHref("r1", sp("tab=security"))).toBe("/repos/r1/security");
+ expect(movedTabHref("r1", sp("tab=doc-drift"))).toBe("/repos/r1/docs/drift");
+ expect(movedTabHref("r1", sp("tab=impact"))).toBe("/repos/r1/commits?view=review");
+ });
+
+ it("carries the parameters the new home reads", () => {
+ expect(movedTabHref("r1", sp("tab=doc-drift&document=docs/a b.md"))).toBe(
+ "/repos/r1/docs/drift?document=docs%2Fa%20b.md",
+ );
+ expect(movedTabHref("r1", sp("tab=impact&file=a.py&file=b/c.py&lens=churn"))).toBe(
+ "/repos/r1/commits?view=review&file=a.py&file=b%2Fc.py",
+ );
+ });
+
+ it("leaves tabs that stayed alone", () => {
+ for (const id of [...CODE_HEALTH_TABS, "triage"]) {
+ expect(movedTabHref("r1", sp(`tab=${id}`))).toBeNull();
+ }
+ expect(movedTabHref("r1", sp(""))).toBeNull();
+ });
+
+ it("answers for every moved id", () => {
+ for (const id of MOVED_TABS) expect(movedTabHref("r1", sp(`tab=${id}`))).not.toBeNull();
+ });
+});
diff --git a/packages/web/src/app/repos/[id]/code-health/tabs.ts b/packages/web/src/app/repos/[id]/code-health/tabs.ts
new file mode 100644
index 000000000..1c4d9c012
--- /dev/null
+++ b/packages/web/src/app/repos/[id]/code-health/tabs.ts
@@ -0,0 +1,85 @@
+/**
+ * Code Health's tab list, and where its retired tabs went. The one source the
+ * page, its legacy redirect, and the route-link guard all read.
+ *
+ * Four tabs: the Map (once "triage"), Findings, Performance and Dead code.
+ * Tests and Security became pages of their own, Doc drift a Docs view, and
+ * blast radius the Commits page's "Review a change" view.
+ */
+
+import { Bug, Gauge, LayoutDashboard, Scissors, type LucideIcon } from "lucide-react";
+import { commitsViewHref } from "@/lib/changes";
+
+export const CODE_HEALTH_TABS = ["map", "findings", "performance", "dead-code"] as const;
+export type CodeHealthTabId = (typeof CODE_HEALTH_TABS)[number];
+
+/** The tab with no `?tab=`. */
+export const DEFAULT_TAB: CodeHealthTabId = "map";
+
+/**
+ * Label key under `views.codeHealth` and the tab's mark. The icons are
+ * identity, not status: monochrome and inheriting the tab's color.
+ */
+export const TAB_DEFS: Record<CodeHealthTabId, { labelKey: string; icon: LucideIcon }> = {
+ map: { labelKey: "tabs.map", icon: LayoutDashboard },
+ findings: { labelKey: "tabs.findings", icon: Bug },
+ performance: { labelKey: "tabs.performance", icon: Gauge },
+ "dead-code": { labelKey: "tabs.deadCode", icon: Scissors },
+};
+
+/**
+ * Retired ids that still open a tab here. `triage` is the Map's old name;
+ * `heatmap` and `hotspots` were churn tabs the Map's churn lens replaced;
+ * `modules` folded into its hub layer and `trend` into the section under it.
+ */
+export const TAB_ALIASES: Record<string, CodeHealthTabId> = {
+ triage: "map",
+ heatmap: "map",
+ hotspots: "map",
+ modules: "map",
+ trend: "map",
+};
+
+/** Tabs that left Code Health, by the id their old links carry. */
+export const MOVED_TABS = ["coverage", "security", "doc-drift", "impact"] as const;
+
+/** The tab a `?tab=` value opens; `?pillar=performance` predates the tab. */
+export function resolveCodeHealthTab(
+ rawTab: string | null,
+ rawPillar: string | null,
+): CodeHealthTabId {
+ if (rawTab) {
+ const aliased = TAB_ALIASES[rawTab];
+ if (aliased) return aliased;
+ if ((CODE_HEALTH_TABS as readonly string[]).includes(rawTab)) return rawTab as CodeHealthTabId;
+ }
+ return rawPillar === "performance" ? "performance" : DEFAULT_TAB;
+}
+
+/**
+ * Where a link to a tab that moved out should land now, carrying the
+ * parameters its new home reads; null when the tab is still here.
+ */
+export function movedTabHref(repoId: string, params: URLSearchParams): string | null {
+ const base = `/repos/${repoId}`;
+ switch (params.get("tab")) {
+ case "coverage":
+ return `${base}/tests`;
+ case "security":
+ return `${base}/security`;
+ case "doc-drift": {
+ const document = params.get("document");
+ return document
+ ? `${base}/docs/drift?document=${encodeURIComponent(document)}`
+ : `${base}/docs/drift`;
+ }
+ case "impact": {
+ const q = new URLSearchParams();
+ for (const file of params.getAll("file")) q.append("file", file);
+ const files = q.toString();
+ return `${commitsViewHref(repoId, "review")}${files ? `&${files}` : ""}`;
+ }
+ default:
+ return null;
+ }
+}
diff --git a/packages/web/src/app/repos/[id]/code-health/trend/page.tsx b/packages/web/src/app/repos/[id]/code-health/trend/page.tsx
index 9f04d250e..c7df20e6c 100644
--- a/packages/web/src/app/repos/[id]/code-health/trend/page.tsx
+++ b/packages/web/src/app/repos/[id]/code-health/trend/page.tsx
@@ -7,5 +7,5 @@ export default async function LegacyRedirect({
params: Promise<{ id: string }>;
}) {
const { id } = await params;
- redirect(`/repos/${id}/code-health?tab=triage`);
+ redirect(`/repos/${id}/code-health`);
}
diff --git a/packages/web/src/app/repos/[id]/commits/page.tsx b/packages/web/src/app/repos/[id]/commits/page.tsx
index f18c9e0ce..8c474653f 100644
--- a/packages/web/src/app/repos/[id]/commits/page.tsx
+++ b/packages/web/src/app/repos/[id]/commits/page.tsx
@@ -14,6 +14,7 @@ import { CommitDistribution } from "@/components/commits/commit-distribution";
import { CommitsViewToggle } from "@/components/commits/commits-view-toggle";
import { ByChangeView, type ByChangeParams } from "@/components/commits/by-change-view";
import { EventsView } from "@/components/commits/events-view";
+import { ImpactTab } from "@/components/risk/impact-tab";
import { parseCommitsView } from "@/lib/changes";
import {
getAgentTrend,
@@ -53,7 +54,9 @@ async function safeFetch<T>(fn: () => Promise<T>): Promise<T | null> {
*
* `?view=changes` swaps all of that for the history grouped by merged change
* (`ByChangeView`), `?view=events` for what moved between index runs
- * (`EventsView`); the commit view stays the default.
+ * (`EventsView`), `?view=review` for a change's blast radius before it lands
+ * (`ImpactTab`, once Code Health's blast-radius tab); the commit view stays
+ * the default.
*/
export default async function CommitsPage({
params,
@@ -97,6 +100,19 @@ export default async function CommitsPage({
);
}
+ if (view === "review") {
+ return (
+ <PageShell
+ icon={<GitCommitHorizontal />}
+ title={t("title")}
+ description={t("reviewDescription")}
+ actions={toggle}
+ >
+ <ImpactTab repoId={id} />
+ </PageShell>
+ );
+ }
+
// One wave. The scatter plots its own recency sample rather than reusing the
// queue's first page: the feed is risk-sorted, so reusing it would draw only
// the top tercile and the "here is the whole spread" reading would be a lie.
@@ -175,7 +191,7 @@ export default async function CommitsPage({
title={t("scoreBehaviourTitle")}
description={t("scoreBehaviourDescription")}
action={
- <SectionLink href={`${base}/code-health?tab=triage`} LinkComponent={Link}>
+ <SectionLink href={`${base}/code-health`} LinkComponent={Link}>
{t("changeRisk")}
</SectionLink>
}
diff --git a/packages/web/src/app/repos/[id]/docs/drift/page.tsx b/packages/web/src/app/repos/[id]/docs/drift/page.tsx
new file mode 100644
index 000000000..1647b4aa0
--- /dev/null
+++ b/packages/web/src/app/repos/[id]/docs/drift/page.tsx
@@ -0,0 +1,34 @@
+import type { Metadata } from "next";
+import { PageFrame } from "@repowise-dev/ui/shared/page-shell";
+import { DocsHeader } from "@/components/docs/docs-header";
+import { DocDriftTab } from "@/components/risk/doc-drift-tab";
+
+export const metadata: Metadata = { title: "Doc drift" };
+
+/**
+ * `/repos/[id]/docs/drift`: documentation lines that name files the
+ * repository no longer has. `?document=` opens narrowed to one document.
+ */
+export default async function DocDriftPage({
+ params,
+ searchParams,
+}: {
+ params: Promise<{ id: string }>;
+ searchParams: Promise<{ document?: string | string[] }>;
+}) {
+ const { id } = await params;
+ const { document } = await searchParams;
+ return (
+ <div className="flex h-full flex-col">
+ <DocsHeader />
+ <div className="min-h-0 flex-1 overflow-y-auto">
+ <PageFrame maxWidth="wide">
+ <DocDriftTab
+ repoId={id}
+ initialDocument={typeof document === "string" ? document : undefined}
+ />
+ </PageFrame>
+ </div>
+ </div>
+ );
+}
diff --git a/packages/web/src/app/repos/[id]/health/coverage/page.tsx b/packages/web/src/app/repos/[id]/health/coverage/page.tsx
index 2fb53aa5f..690370812 100644
--- a/packages/web/src/app/repos/[id]/health/coverage/page.tsx
+++ b/packages/web/src/app/repos/[id]/health/coverage/page.tsx
@@ -7,5 +7,5 @@ export default async function LegacyRedirect({
params: Promise<{ id: string }>;
}) {
const { id } = await params;
- redirect(`/repos/${id}/code-health?tab=coverage`);
+ redirect(`/repos/${id}/tests`);
}
diff --git a/packages/web/src/app/repos/[id]/health/trend/page.tsx b/packages/web/src/app/repos/[id]/health/trend/page.tsx
index f0d6dbaaa..b7e9e81b4 100644
--- a/packages/web/src/app/repos/[id]/health/trend/page.tsx
+++ b/packages/web/src/app/repos/[id]/health/trend/page.tsx
@@ -7,5 +7,5 @@ export default async function LegacyRedirect({
params: Promise<{ id: string }>;
}) {
const { id } = await params;
- redirect(`/repos/${id}/code-health?tab=triage`);
+ redirect(`/repos/${id}/code-health`);
}
diff --git a/packages/web/src/app/repos/[id]/hotspots/page.tsx b/packages/web/src/app/repos/[id]/hotspots/page.tsx
index f0d6dbaaa..b7e9e81b4 100644
--- a/packages/web/src/app/repos/[id]/hotspots/page.tsx
+++ b/packages/web/src/app/repos/[id]/hotspots/page.tsx
@@ -7,5 +7,5 @@ export default async function LegacyRedirect({
params: Promise<{ id: string }>;
}) {
const { id } = await params;
- redirect(`/repos/${id}/code-health?tab=triage`);
+ redirect(`/repos/${id}/code-health`);
}
diff --git a/packages/web/src/app/repos/[id]/modules/[path]/page.tsx b/packages/web/src/app/repos/[id]/modules/[path]/page.tsx
index 1d2b6173f..67ef9c188 100644
--- a/packages/web/src/app/repos/[id]/modules/[path]/page.tsx
+++ b/packages/web/src/app/repos/[id]/modules/[path]/page.tsx
@@ -29,7 +29,7 @@ export default function ModuleHealthPage() {
return (
<ModuleDetailShell
- backHref={`/repos/${id}/code-health?tab=triage`}
+ backHref={`/repos/${id}/code-health`}
LinkComponent={Link}
>
{isLoading && (
@@ -56,7 +56,7 @@ export default function ModuleHealthPage() {
breadcrumb={[
// There is no Modules tab any more — it folded into the map's hub
// layer on the overview. Name where the link actually goes.
- { label: t("breadcrumb"), href: `/repos/${id}/code-health?tab=triage` },
+ { label: t("breadcrumb"), href: `/repos/${id}/code-health` },
{ label: modulePath.split("/").pop() || modulePath },
]}
LinkComponent={Link}
diff --git a/packages/web/src/app/repos/[id]/security/page.tsx b/packages/web/src/app/repos/[id]/security/page.tsx
index 2780ca119..792190aac 100644
--- a/packages/web/src/app/repos/[id]/security/page.tsx
+++ b/packages/web/src/app/repos/[id]/security/page.tsx
@@ -1,11 +1,23 @@
-import { redirect } from "next/navigation";
+import type { Metadata } from "next";
+import { Shield } from "lucide-react";
+import { getTranslations } from "next-intl/server";
+import { PageShell } from "@repowise-dev/ui/shared/page-shell";
+import { SecurityRescanButton, SecurityView } from "@/components/security/security-view";
-/** Legacy route — security now lives as a Code Health tab. */
-export default async function LegacyRedirect({
- params,
-}: {
- params: Promise<{ id: string }>;
-}) {
+export const metadata: Metadata = { title: "Security" };
+
+/** `/repos/[id]/security`: the posture first, then every finding. */
+export default async function SecurityPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
- redirect(`/repos/${id}/code-health?tab=security`);
+ const t = await getTranslations("views.security");
+ return (
+ <PageShell
+ icon={<Shield />}
+ title={t("title")}
+ description={t("description")}
+ actions={<SecurityRescanButton repoId={id} />}
+ >
+ <SecurityView repoId={id} />
+ </PageShell>
+ );
}
diff --git a/packages/web/src/app/repos/[id]/tests/page.tsx b/packages/web/src/app/repos/[id]/tests/page.tsx
new file mode 100644
index 000000000..6d03faef8
--- /dev/null
+++ b/packages/web/src/app/repos/[id]/tests/page.tsx
@@ -0,0 +1,22 @@
+import type { Metadata } from "next";
+import { FlaskConical } from "lucide-react";
+import { getTranslations } from "next-intl/server";
+import { PageShell } from "@repowise-dev/ui/shared/page-shell";
+import { TestsView } from "@/components/tests/tests-view";
+
+export const metadata: Metadata = { title: "Tests" };
+
+/**
+ * `/repos/[id]/tests`: test coverage, measured from an ingested report or
+ * inferred from the graph. Named for tests rather than coverage because
+ * `/docs/coverage` already means documentation freshness.
+ */
+export default async function TestsPage({ params }: { params: Promise<{ id: string }> }) {
+ const { id } = await params;
+ const t = await getTranslations("views.tests");
+ return (
+ <PageShell icon={<FlaskConical />} title={t("title")} description={t("description")}>
+ <TestsView repoId={id} />
+ </PageShell>
+ );
+}
diff --git a/packages/web/src/components/code-health/coverage-tab.tsx b/packages/web/src/components/code-health/coverage-tab.tsx
deleted file mode 100644
index 703785a75..000000000
--- a/packages/web/src/components/code-health/coverage-tab.tsx
+++ /dev/null
@@ -1,40 +0,0 @@
-"use client";
-
-/**
- * Coverage host — binds the shared {@link CoverageView} to web's `/api` client
- * and `/repos/:id` routing. The composition lives in `@repowise-dev/ui/health`;
- * this file only injects the app-specific data fetchers and navigation.
- */
-
-import { useRouter } from "next/navigation";
-import { CoverageView, type CodeHealthAdapter } from "@repowise-dev/ui/health";
-import { fileEntityPath } from "@repowise-dev/ui/shared/entity";
-import {
- getHealthCoverage,
- getTestsReaching,
- getHealthOverview,
- getHealthWorkQueue,
- listHealthFindings,
- updateFindingStatus,
-} from "@/lib/api/code-health";
-
-export function CoverageTab({ repoId: id }: { repoId: string }) {
- const router = useRouter();
- const prefix = `/repos/${id}`;
-
- const adapter: CodeHealthAdapter = {
- cacheKey: id,
- getOverview: (limit) => getHealthOverview(id, limit),
- listFindings: (opts) => listHealthFindings(id, opts),
- getHealthWorkQueue: (opts) => getHealthWorkQueue(id, opts),
- updateFindingStatus: (findingId, status) =>
- updateFindingStatus(id, findingId, status),
- getCoverage: (opts) => getHealthCoverage(id, opts),
- getTestsReaching: (path) => getTestsReaching(id, path),
- fileHref: (path) => fileEntityPath(prefix, path),
- navigate: (href) => router.push(href),
- renderFileDrawer: () => null,
- };
-
- return <CoverageView adapter={adapter} />;
-}
diff --git a/packages/web/src/components/commits/commits-view-toggle.tsx b/packages/web/src/components/commits/commits-view-toggle.tsx
index 6fbc3b454..b8f44f2a2 100644
--- a/packages/web/src/components/commits/commits-view-toggle.tsx
+++ b/packages/web/src/components/commits/commits-view-toggle.tsx
@@ -17,6 +17,7 @@ export function CommitsViewToggle({ repoId, view }: { repoId: string; view: Comm
{ value: "changes", label: t("viewByChange") },
{ value: "commits", label: t("viewByCommit") },
{ value: "events", label: t("viewEvents") },
+ { value: "review", label: t("viewReview") },
]}
onChange={(next) => router.push(commitsViewHref(repoId, next))}
/>
diff --git a/packages/web/src/components/decisions/decision-detail.tsx b/packages/web/src/components/decisions/decision-detail.tsx
index a7add8855..0e6116dcb 100644
--- a/packages/web/src/components/decisions/decision-detail.tsx
+++ b/packages/web/src/components/decisions/decision-detail.tsx
@@ -56,7 +56,7 @@ export function DecisionDetail({ decision, repoId }: DecisionDetailProps) {
: "";
return `${prefix}/commits${qs}`;
},
- hotspotsHref: () => `${prefix}/code-health?tab=triage`,
+ hotspotsHref: () => `${prefix}/code-health`,
LinkComponent: Link,
};
diff --git a/packages/web/src/components/docs/docs-header.tsx b/packages/web/src/components/docs/docs-header.tsx
index 2ed7027f7..39de82e55 100644
--- a/packages/web/src/components/docs/docs-header.tsx
+++ b/packages/web/src/components/docs/docs-header.tsx
@@ -2,16 +2,21 @@
import Link from "next/link";
import { useParams, usePathname } from "next/navigation";
+import { useTranslations } from "next-intl";
+import useSWR from "swr";
import {
DocsHeader as DocsHeaderShell,
type DocsHeaderTab,
} from "@repowise-dev/ui/docs/docs-header";
+import type { DocDriftResponse } from "@repowise-dev/types/doc-drift";
+import { getDocDrift } from "@/lib/api/doc-drift";
// "Doc freshness", not "Coverage" — coverage means test coverage everywhere
// else in the app; this tab is about documentation staleness.
const TABS = [
- { label: "Explorer", segment: "", icon: "explorer" as const },
- { label: "Doc freshness", segment: "/coverage", icon: "freshness" as const },
+ { labelKey: "explorer", segment: "", icon: "explorer" as const },
+ { labelKey: "freshness", segment: "/coverage", icon: "freshness" as const },
+ { labelKey: "drift", segment: "/drift", icon: "drift" as const },
];
/**
@@ -19,18 +24,30 @@ const TABS = [
* into the presentational ``DocsHeader`` ui shell.
*/
export function DocsHeader({ children }: { children?: React.ReactNode }) {
+ const t = useTranslations("views.docsTabs");
const pathname = usePathname();
const { id } = useParams<{ id: string }>();
const basePath = `/repos/${id}/docs`;
+ // `limit: 1`: the summary counts before the cap, so one row carries the
+ // badge. No badge when the drift pass has not run: the response then
+ // carries a cause rather than a summary, and a 0 would read as clean.
+ const { data: drift } = useSWR<DocDriftResponse>(
+ `doc-drift-badge:${id}`,
+ () => getDocDrift(id, { limit: 1 }),
+ { revalidateOnFocus: false },
+ );
+ const driftCount = drift?.summary?.findings_total;
+
const tabs: DocsHeaderTab[] = TABS.map((tab) => {
const href = `${basePath}${tab.segment}`;
return {
- label: tab.label,
+ label: t(tab.labelKey),
href,
icon: tab.icon,
isActive:
tab.segment === "" ? pathname === basePath : pathname.startsWith(href),
+ ...(tab.icon === "drift" && driftCount !== undefined ? { badge: driftCount } : {}),
};
});
diff --git a/packages/web/src/components/graph/graph-community-panel.tsx b/packages/web/src/components/graph/graph-community-panel.tsx
index b7b1b944f..afad1ada4 100644
--- a/packages/web/src/components/graph/graph-community-panel.tsx
+++ b/packages/web/src/components/graph/graph-community-panel.tsx
@@ -36,7 +36,7 @@ export function GraphCommunityPanel({
// Code Health's triage map takes `?file=` and opens on that row, so a hot
// member gets an exact destination rather than a repo-wide page.
healthHrefFor={(path) =>
- `/repos/${repoId}/code-health?tab=triage&file=${encodeURIComponent(path)}`
+ `/repos/${repoId}/code-health?file=${encodeURIComponent(path)}`
}
deadCodeHref={`/repos/${repoId}/code-health?tab=dead-code`}
codeHealthHref={`/repos/${repoId}/code-health`}
diff --git a/packages/web/src/components/layout/app-shell-skeleton.tsx b/packages/web/src/components/layout/app-shell-skeleton.tsx
index 2753205ac..159862379 100644
--- a/packages/web/src/components/layout/app-shell-skeleton.tsx
+++ b/packages/web/src/components/layout/app-shell-skeleton.tsx
@@ -1,5 +1,17 @@
import { SkeletonRegion, Skeleton } from "@repowise-dev/ui/ui/skeleton";
import { getTranslations } from "next-intl/server";
+import { repoNavGroups } from "./nav-items";
+
+/**
+ * The repo nav's shape, read from the same source the sidebar renders: one
+ * entry per group, its item count, and whether it carries a label row. The
+ * repo id is irrelevant to the shape, so a placeholder stands in.
+ */
+const NAV_SHAPE = repoNavGroups("_").map((g) => ({
+ id: g.id,
+ labelled: Boolean(g.label),
+ rows: g.items.length,
+}));
/**
* The shell itself, waiting. This is the one place with no page layout to
@@ -26,10 +38,16 @@ export async function AppShellSkeleton() {
<Skeleton key={i} className="h-9 w-full" />
))}
</div>
- <Skeleton className="mt-4 h-3 w-24" />
- <div className="space-y-1.5">
- {Array.from({ length: 5 }).map((_, i) => (
- <Skeleton key={i} className="h-9 w-full" />
+ {/* The active repository, expanded: its row, then each nav group. */}
+ <Skeleton className="mt-4 h-9 w-full" />
+ <div className="ml-3.5 space-y-1.5 pl-3">
+ {NAV_SHAPE.map((g) => (
+ <div key={g.id} className="space-y-1.5 pt-1.5">
+ {g.labelled && <Skeleton className="h-3 w-24" />}
+ {Array.from({ length: g.rows }).map((_, i) => (
+ <Skeleton key={i} className="h-7 w-full" />
+ ))}
+ </div>
))}
</div>
</div>
diff --git a/packages/web/src/components/layout/mobile-nav.tsx b/packages/web/src/components/layout/mobile-nav.tsx
index 29709d1b8..7ae391042 100644
--- a/packages/web/src/components/layout/mobile-nav.tsx
+++ b/packages/web/src/components/layout/mobile-nav.tsx
@@ -24,12 +24,8 @@ import { FeedbackButton } from "./feedback-button";
import { LanguageSwitcher } from "./language-switcher";
import { ThemeToggle } from "@repowise-dev/ui/shared/theme-toggle";
import { cn } from "@/lib/utils/cn";
-import {
- GLOBAL_NAV,
- WORKSPACE_NAV,
- repoNavGroups,
- isNavItemActive,
-} from "./nav-items";
+import { GLOBAL_NAV, WORKSPACE_NAV, repoNavGroups } from "./nav-items";
+import { NavGroupList } from "./nav-group-list";
import type { RepoResponse, WorkspaceResponse } from "@/lib/api/types";
interface MobileNavProps {
@@ -216,21 +212,14 @@ export function MobileNav({ repos = [], workspace }: MobileNavProps) {
</button>
{isExpanded && (
<div className="ml-3.5 mt-0.5 space-y-0.5 border-l border-[var(--color-border-default)] pl-3">
- {navGroups.map((group, gi) => (
- <React.Fragment key={group.label ?? gi}>
- {group.label ? (
- <p className="px-2 pt-2 pb-0.5 text-[10px] font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">
- {group.labelKey ? t(group.labelKey) : group.label}
- </p>
- ) : gi > 0 ? (
- <div className="pt-1.5" />
- ) : null}
- {group.items.map((item) => {
+ <NavGroupList
+ groups={navGroups}
+ pathname={pathname}
+ idPrefix={`mobile-repo-${repo.id}`}
+ renderItem={(item, isActive) => {
const Icon = item.icon;
- const isActive = isNavItemActive(item, pathname);
return (
<Link
- key={item.href}
href={item.href}
className={cn(
"flex items-center gap-2.5 rounded-lg px-2 py-1.5 text-xs transition-colors",
@@ -251,9 +240,8 @@ export function MobileNav({ repos = [], workspace }: MobileNavProps) {
{isNew(item.href) && <NewMark />}
</Link>
);
- })}
- </React.Fragment>
- ))}
+ }}
+ />
</div>
)}
</div>
diff --git a/packages/web/src/components/layout/nav-group-list.tsx b/packages/web/src/components/layout/nav-group-list.tsx
new file mode 100644
index 000000000..dfcdb4aab
--- /dev/null
+++ b/packages/web/src/components/layout/nav-group-list.tsx
@@ -0,0 +1,142 @@
+"use client";
+
+import * as React from "react";
+import { useTranslations } from "next-intl";
+import { ChevronDown, ChevronRight } from "lucide-react";
+import { isNavItemActive, type NavGroup, type NavItem } from "./nav-items";
+
+const STORAGE_KEY = "repowise:nav:collapsed-groups";
+
+const GROUP_LABEL =
+ "flex w-full items-center gap-1 px-2 pt-2 pb-0.5 text-[10px] font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]";
+
+function readCollapsed(): Set<string> {
+ try {
+ const raw = window.localStorage.getItem(STORAGE_KEY);
+ const parsed: unknown = raw ? JSON.parse(raw) : [];
+ return new Set(Array.isArray(parsed) ? parsed.filter((v) => typeof v === "string") : []);
+ } catch {
+ return new Set();
+ }
+}
+
+/**
+ * Which labelled nav groups the reader folded away. A per-browser convenience,
+ * so it lives in localStorage; it starts empty (every group open) and is read
+ * after mount so the server and first client render agree.
+ */
+function useCollapsedNavGroups(): [Set<string>, (id: string) => void] {
+ const [collapsed, setCollapsed] = React.useState<Set<string>>(() => new Set());
+ React.useEffect(() => setCollapsed(readCollapsed()), []);
+ const toggle = React.useCallback((id: string) => {
+ setCollapsed((prev) => {
+ const next = new Set(prev);
+ if (next.has(id)) next.delete(id);
+ else next.add(id);
+ try {
+ window.localStorage.setItem(STORAGE_KEY, JSON.stringify([...next]));
+ } catch {
+ // Storage blocked: the fold still works for this page view.
+ }
+ return next;
+ });
+ }, []);
+ return [collapsed, toggle];
+}
+
+/**
+ * A repository's nav groups with collapsible labelled sections, shared by the
+ * desktop sidebar and the mobile sheet so the two cannot drift. The host
+ * renders each item, since the two surfaces size their rows differently.
+ *
+ * A group holding the current page never folds shut: hiding where you are is
+ * a lost reader, not a tidier sidebar.
+ */
+export function NavGroupList({
+ groups,
+ pathname,
+ idPrefix,
+ renderItem,
+}: {
+ groups: NavGroup[];
+ pathname: string;
+ /** Prefix for the groups' element ids, unique per rendered list. */
+ idPrefix: string;
+ renderItem: (item: NavItem, isActive: boolean) => React.ReactNode;
+}) {
+ const t = useTranslations("nav");
+ const [collapsed, toggle] = useCollapsedNavGroups();
+ const label = (group: NavGroup) => (group.labelKey ? t(group.labelKey) : group.label);
+
+ return (
+ <>
+ {groups.map((group, gi) => {
+ const activeHere = group.items.some((item) => isNavItemActive(item, pathname));
+ const open = !group.label || activeHere || !collapsed.has(group.id);
+ const listId = `${idPrefix}-${group.id}`;
+ return (
+ <React.Fragment key={group.id}>
+ {group.label ? (
+ <GroupHeader
+ label={label(group)}
+ listId={listId}
+ open={open}
+ foldable={!activeHere}
+ onToggle={() => toggle(group.id)}
+ />
+ ) : gi > 0 ? (
+ <div className="pt-1.5" />
+ ) : null}
+ {/* Always mounted, so `aria-controls` names an element that exists. */}
+ <div id={listId} hidden={!open} className="space-y-0.5">
+ {open &&
+ group.items.map((item) => (
+ <React.Fragment key={item.href}>
+ {renderItem(item, isNavItemActive(item, pathname))}
+ </React.Fragment>
+ ))}
+ </div>
+ </React.Fragment>
+ );
+ })}
+ </>
+ );
+}
+
+/** A labelled group's header: a fold toggle, or a plain label while it holds the current page. */
+function GroupHeader({
+ label,
+ listId,
+ open,
+ foldable,
+ onToggle,
+}: {
+ label: string | undefined;
+ listId: string;
+ open: boolean;
+ foldable: boolean;
+ onToggle: () => void;
+}) {
+ if (!foldable) {
+ // Not a control while it cannot fold: a live-looking toggle that does
+ // nothing is worse than a plain label.
+ return (
+ <p className={GROUP_LABEL}>
+ <span className="flex-1 truncate">{label}</span>
+ </p>
+ );
+ }
+ const Chevron = open ? ChevronDown : ChevronRight;
+ return (
+ <button
+ type="button"
+ onClick={onToggle}
+ aria-expanded={open}
+ aria-controls={listId}
+ className={`${GROUP_LABEL} rounded-md transition-colors hover:text-[var(--color-text-secondary)]`}
+ >
+ <span className="flex-1 truncate text-left">{label}</span>
+ <Chevron aria-hidden className="h-3 w-3 shrink-0 opacity-60" />
+ </button>
+ );
+}
diff --git a/packages/web/src/components/layout/nav-items.test.ts b/packages/web/src/components/layout/nav-items.test.ts
new file mode 100644
index 000000000..d10eb8a7e
--- /dev/null
+++ b/packages/web/src/components/layout/nav-items.test.ts
@@ -0,0 +1,39 @@
+import { describe, expect, it } from "vitest";
+import { repoNavGroups, repoNavItems } from "./nav-items";
+import en from "../../../messages/en.json";
+import zh from "../../../messages/zh-CN.json";
+
+describe("repoNavGroups", () => {
+ const groups = repoNavGroups("r1");
+
+ it("groups the repo pages by the question a reader brings", () => {
+ expect(groups.map((g) => [g.id, g.items.map((i) => i.label)])).toEqual([
+ ["start", ["Overview", "Chat"]],
+ ["understand", ["Docs", "Architecture", "Knowledge Graph", "Files"]],
+ ["quality", ["Code Health", "Refactoring", "Tests", "Security"]],
+ ["people", ["Contributors", "Commits", "Decisions"]],
+ ["settings", ["Stats", "Usage & savings", "Settings"]],
+ ]);
+ });
+
+ it("labels every group but the first, with unique ids", () => {
+ expect(groups.filter((g) => !g.label).map((g) => g.id)).toEqual(["start"]);
+ expect(new Set(groups.map((g) => g.id)).size).toBe(groups.length);
+ });
+
+ it("has a message for every label in both catalogs", () => {
+ const keys = [
+ ...repoNavItems("r1").map((i) => i.labelKey),
+ ...groups.flatMap((g) => (g.labelKey ? [g.labelKey] : [])),
+ ];
+ for (const nav of [en.nav, zh.nav] as Record<string, string>[]) {
+ expect(keys.filter((k) => !nav[k])).toEqual([]);
+ }
+ });
+
+ it("links Tests and Security to their own pages", () => {
+ const hrefs = repoNavItems("r1").map((i) => i.href);
+ expect(hrefs).toContain("/repos/r1/tests");
+ expect(hrefs).toContain("/repos/r1/security");
+ });
+});
diff --git a/packages/web/src/components/layout/nav-items.ts b/packages/web/src/components/layout/nav-items.ts
index da956b439..1ae02308a 100644
--- a/packages/web/src/components/layout/nav-items.ts
+++ b/packages/web/src/components/layout/nav-items.ts
@@ -2,11 +2,13 @@
* Single source of truth for app navigation. Both the desktop sidebar and
* the mobile nav consume these — the two surfaces must never diverge again.
*
- * Repo IA (3 groups + Settings pinned last):
- * Overview · Chat · Docs · Architecture · Knowledge Graph · Code Health ·
- * Refactoring · Files, then People & History, then Settings.
- * Chat sits second because it is the fastest route to an answer about
- * anything below it, not because it is the second most visited page.
+ * Repo IA: Overview and Chat unlabelled at the top, then four collapsible
+ * groups by the question a reader brings: Understand (Docs, Architecture,
+ * Knowledge Graph, Files), Code quality (Code Health, Refactoring, Tests,
+ * Security), People & History (Contributors, Commits, Decisions), and
+ * Settings pinned last. Chat sits second because it is the fastest route to
+ * an answer about anything below it, not because it is the second most
+ * visited page.
*/
import {
@@ -15,6 +17,7 @@ import {
BookOpen,
Boxes,
DollarSign,
+ FlaskConical,
FolderTree,
GitCommitHorizontal,
GitMerge,
@@ -26,6 +29,7 @@ import {
MessageSquare,
ScanSearch,
Settings,
+ Shield,
ShieldCheck,
Users,
Waypoints,
@@ -47,7 +51,9 @@ export interface NavItem {
}
export interface NavGroup {
- /** Optional section label rendered above the items. */
+ /** Stable id; keys the group's collapsed state in the sidebar. */
+ id: string;
+ /** Optional section label rendered above the items. Labelled groups collapse. */
label?: string;
/** Message key under `nav` for the group label. */
labelKey?: string;
@@ -71,27 +77,46 @@ export function repoNavGroups(repoId: string): NavGroup[] {
const base = `/repos/${repoId}`;
return [
{
+ id: "start",
items: [
{ label: "Overview", labelKey: "overview", href: `${base}/overview`, icon: Activity },
{ label: "Chat", labelKey: "chat", href: `${base}/chat`, icon: MessageSquare },
+ ],
+ },
+ {
+ id: "understand",
+ label: "Understand",
+ labelKey: "groupUnderstand",
+ items: [
{ label: "Docs", labelKey: "docs", href: `${base}/docs`, icon: BookOpen },
{ label: "Architecture", labelKey: "architecture", href: `${base}/architecture`, icon: Boxes },
{ label: "Knowledge Graph", labelKey: "knowledgeGraph", href: `${base}/knowledge-graph`, icon: ScanSearch },
+ { label: "Files", labelKey: "files", href: `${base}/files`, icon: FolderTree },
+ ],
+ },
+ {
+ id: "quality",
+ label: "Code quality",
+ labelKey: "groupCodeQuality",
+ items: [
{ label: "Code Health", labelKey: "codeHealth", href: `${base}/code-health`, icon: HeartPulse },
{ label: "Refactoring", labelKey: "refactoring", href: `${base}/refactoring`, icon: Wrench },
- { label: "Files", labelKey: "files", href: `${base}/files`, icon: FolderTree },
+ { label: "Tests", labelKey: "tests", href: `${base}/tests`, icon: FlaskConical },
+ { label: "Security", labelKey: "security", href: `${base}/security`, icon: Shield },
],
},
{
+ id: "people",
label: "People & History",
labelKey: "groupPeopleAndHistory",
items: [
- { label: "Commits", labelKey: "commits", href: `${base}/commits`, icon: GitCommitHorizontal },
{ label: "Contributors", labelKey: "contributors", href: `${base}/owners`, icon: Users },
+ { label: "Commits", labelKey: "commits", href: `${base}/commits`, icon: GitCommitHorizontal },
{ label: "Decisions", labelKey: "decisions", href: `${base}/decisions`, icon: Lightbulb },
],
},
{
+ id: "settings",
label: "Settings",
labelKey: "groupSettings",
items: [
diff --git a/packages/web/src/components/layout/repo-breadcrumb-label.ts b/packages/web/src/components/layout/repo-breadcrumb-label.ts
index dea0c8340..0b013995a 100644
--- a/packages/web/src/components/layout/repo-breadcrumb-label.ts
+++ b/packages/web/src/components/layout/repo-breadcrumb-label.ts
@@ -5,6 +5,8 @@ const SEGMENT_LABELS: Record<string, string> = {
architecture: "Architecture",
"code-health": "Code Health",
coverage: "Tests",
+ tests: "Tests",
+ drift: "Doc drift",
"refactoring-targets": "Refactoring Targets",
trend: "Trend",
search: "Search",
@@ -45,6 +47,8 @@ export const SEGMENT_MESSAGE_KEYS: Record<string, string> = {
architecture: "architecture",
"code-health": "codeHealth",
coverage: "coverage",
+ tests: "tests",
+ drift: "docDrift",
"refactoring-targets": "refactoringTargets",
trend: "trend",
search: "search",
diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsx
index fd1309f47..943755be6 100644
--- a/packages/web/src/components/layout/sidebar.tsx
+++ b/packages/web/src/components/layout/sidebar.tsx
@@ -25,6 +25,7 @@ import { Separator } from "@repowise-dev/ui/ui/separator";
import { Tooltip, TooltipContent, TooltipTrigger } from "@repowise-dev/ui/ui/tooltip";
import { ThemeToggle } from "@repowise-dev/ui/shared/theme-toggle";
import { AddRepoDialog } from "@/components/repos/add-repo-dialog";
+import { NavGroupList } from "./nav-group-list";
import { VersionFooter } from "./version-footer";
import { NewMark, useNavNewMark } from "./new-mark";
import { FeedbackButton } from "./feedback-button";
@@ -324,7 +325,7 @@ export function Sidebar({
<TooltipContent side="right">{repo.name}</TooltipContent>
</Tooltip>
{navGroups.map((group, gi) => (
- <React.Fragment key={group.label ?? gi}>
+ <React.Fragment key={group.id}>
{gi > 0 && <Separator className="my-1.5" />}
{group.items.map((item) => (
<SidebarNavItem
@@ -390,26 +391,14 @@ export function Sidebar({
</button>
{isExpanded && (
<div id={`sidebar-repo-${repo.id}`} className="ml-3.5 mt-0.5 space-y-0.5 border-l border-[var(--color-border-default)] pl-3">
- {navGroups.map((group, gi) => (
- <React.Fragment key={group.label ?? gi}>
- {group.label ? (
- <p className="px-2 pt-2 pb-0.5 text-[10px] font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">
- {group.labelKey ? t(group.labelKey) : group.label}
- </p>
- ) : gi > 0 ? (
- <div className="pt-1.5" />
- ) : null}
- {group.items.map((item) => (
- <SidebarNavItem
- key={item.href}
- item={item}
- isActive={isNavItemActive(item, pathname)}
- size="sm"
- iconOnly={false}
- />
- ))}
- </React.Fragment>
- ))}
+ <NavGroupList
+ groups={navGroups}
+ pathname={pathname}
+ idPrefix={`sidebar-repo-${repo.id}`}
+ renderItem={(item, active) => (
+ <SidebarNavItem item={item} isActive={active} size="sm" />
+ )}
+ />
</div>
)}
</div>
diff --git a/packages/web/src/components/risk/dead-code-tab.tsx b/packages/web/src/components/risk/dead-code-tab.tsx
index 3122728f9..adeb9785e 100644
--- a/packages/web/src/components/risk/dead-code-tab.tsx
+++ b/packages/web/src/components/risk/dead-code-tab.tsx
@@ -24,6 +24,8 @@ import {
} from "@/lib/api/dead-code";
import { getJob } from "@/lib/api/jobs";
import { useTranslations } from "next-intl";
+import { formatNumber } from "@repowise-dev/ui/lib/format";
+import { useRepoFileCount } from "@/lib/hooks/use-repo";
const POLL_INTERVAL_MS = 3_000;
/** Give up watching after this long; the job may still be running server-side. */
@@ -53,6 +55,7 @@ export function DeadCodeTab({ repoId }: { repoId: string }) {
const t = useTranslations("risk");
const router = useRouter();
const ledeLabels = useLedeLabels();
+ const fileCount = useRepoFileCount(repoId);
const prefix = `/repos/${repoId}`;
const adapter: DeadCodeAdapter = {
@@ -69,7 +72,16 @@ export function DeadCodeTab({ repoId }: { repoId: string }) {
navigate: (href) => router.push(href),
};
- return <DeadCodeView adapter={adapter} ledeLabels={ledeLabels} />;
+ // The clean state names its scope once the file count lands.
+ const clean = {
+ title:
+ fileCount != null
+ ? t("deadCodeClean.titleScoped", { files: formatNumber(fileCount) })
+ : t("deadCodeClean.title"),
+ description: t("deadCodeClean.body"),
+ };
+
+ return <DeadCodeView adapter={adapter} ledeLabels={ledeLabels} clean={clean} />;
}
/** The lede copy from the catalog; exported for its test. */
diff --git a/packages/web/src/components/risk/doc-drift-tab.tsx b/packages/web/src/components/risk/doc-drift-tab.tsx
index 62207d187..315beee74 100644
--- a/packages/web/src/components/risk/doc-drift-tab.tsx
+++ b/packages/web/src/components/risk/doc-drift-tab.tsx
@@ -10,6 +10,7 @@
import { useMemo } from "react";
import { useRouter } from "next/navigation";
+import { useTranslations } from "next-intl";
import { DocDriftView, type DocDriftAdapter } from "@repowise-dev/ui/doc-drift";
import { fileEntityPath } from "@repowise-dev/ui/shared/entity";
import { getDocDrift, getDocDriftReferences } from "@/lib/api/doc-drift";
@@ -37,12 +38,14 @@ export function DocDriftTab({
initialDocument,
}: {
repoId: string;
- /** From `?document=` on the code-health page. */
+ /** From `?document=` on the Docs drift page. */
initialDocument?: string | undefined;
}) {
const adapter = useDocDriftAdapter(repoId);
+ const t = useTranslations("views.docDrift");
return (
<DocDriftView
+ clean={{ title: t("cleanTitle"), description: t("cleanBody") }}
// Remount on a new deep link: the view reads it once, as initial state.
key={initialDocument ?? ""}
adapter={adapter}
diff --git a/packages/web/src/components/risk/security-tab.tsx b/packages/web/src/components/security/security-view.tsx
similarity index 70%
rename from packages/web/src/components/risk/security-tab.tsx
rename to packages/web/src/components/security/security-view.tsx
index cdc2c1b5f..bf9ef49f3 100644
--- a/packages/web/src/components/risk/security-tab.tsx
+++ b/packages/web/src/components/security/security-view.tsx
@@ -1,5 +1,12 @@
"use client";
+/**
+ * Security — the body of `/repos/[id]/security`. Leads with the posture
+ * (counts, where they sit, when the scan ran from `/security/summary`), then
+ * every finding with the agent prompt as each row's primary action, then the
+ * directory matrix. The page's Re-scan action is exported beside it.
+ */
+
import { useMemo, useState, type ReactNode } from "react";
import useSWR from "swr";
import { RotateCw } from "lucide-react";
@@ -11,10 +18,16 @@ import {
SecurityPostureSkeleton,
type SecurityPostureLabels,
} from "@repowise-dev/ui/security/posture";
-import { AiPromptModal, buildSecurityAiPrompt, fileChatContext } from "@repowise-dev/ui/health";
+import {
+ buildSecurityBatchAiPrompt,
+ fileChatContext,
+ useAiPromptAction,
+} from "@repowise-dev/ui/health";
import { Button } from "@repowise-dev/ui/ui/button";
import { OverviewSection } from "@repowise-dev/ui/overview/section";
import { EmptyState } from "@repowise-dev/ui/shared/empty-state";
+import { CleanState } from "@repowise-dev/ui/shared/clean-state";
+import { formatNumber } from "@repowise-dev/ui/lib/format";
import { ApiError } from "@repowise-dev/ui/shared/api-error";
import { formatRelativeTime } from "@repowise-dev/ui/lib/format";
import {
@@ -25,6 +38,7 @@ import {
} from "@/lib/api/security";
import { syncRepo } from "@/lib/api/repos";
import { useFileCardHost } from "@/components/shared/file-card-host";
+import { useRepoFileCount } from "@/lib/hooks/use-repo";
import type { FileCardData } from "@repowise-dev/ui/shared/file-card";
import { toFriendlyMessage } from "@repowise-dev/ui/lib/errors";
import { useTranslations } from "next-intl";
@@ -32,7 +46,34 @@ import { useTranslations } from "next-intl";
/** Request limit for the findings list; at the limit the page says so. */
const LIMIT = 500;
-export function SecurityTab({ repoId }: { repoId: string }) {
+/** Starts a sync, which re-runs the pattern scan. The page header's action. */
+export function SecurityRescanButton({ repoId }: { repoId: string }) {
+ const t = useTranslations("risk");
+ const [rescanning, setRescanning] = useState(false);
+
+ const handleRescan = async () => {
+ setRescanning(true);
+ try {
+ await syncRepo(repoId);
+ toast.success(t("syncStarted"));
+ } catch (err) {
+ toast.error(toFriendlyMessage(err, t("syncFailed")));
+ } finally {
+ setRescanning(false);
+ }
+ };
+
+ return (
+ <Button size="sm" variant="outline" onClick={handleRescan} disabled={rescanning}>
+ <RotateCw
+ className={`h-3.5 w-3.5 mr-1.5 ${rescanning ? "motion-safe:animate-spin" : ""}`}
+ />
+ {rescanning ? t("rescanning") : t("rescan")}
+ </Button>
+ );
+}
+
+export function SecurityView({ repoId }: { repoId: string }) {
const t = useTranslations("risk");
const {
data: findings,
@@ -51,20 +92,20 @@ export function SecurityTab({ repoId }: { repoId: string }) {
() => getSecuritySummary(repoId).catch(() => null),
{ revalidateOnFocus: false },
);
- const [rescanning, setRescanning] = useState(false);
- const [promptFinding, setPromptFinding] = useState<SecurityFinding | null>(null);
-
- const handleRescan = async () => {
- setRescanning(true);
- try {
- await syncRepo(repoId);
- toast.success(t("syncStarted"));
- } catch (err) {
- toast.error(toFriendlyMessage(err, t("syncFailed")));
- } finally {
- setRescanning(false);
- }
+ // One finding from a row, or every finding the table's filters show,
+ // through the shared prompt modal.
+ const { openPrompt, promptModal } = useAiPromptAction();
+ const promptFor = (findings: SecurityFinding[]) => {
+ const one = findings.length === 1 ? findings[0]!.file_path : undefined;
+ openPrompt({
+ title: t("promptTitle"),
+ description: t("promptDescription"),
+ filePath: one ?? null,
+ ...(one ? { chatContext: fileChatContext(one)! } : {}),
+ getPrompt: (flavor) => buildSecurityBatchAiPrompt({ findings, flavor }),
+ });
};
+ const fileCount = useRepoFileCount(repoId);
const { showFile, dialog } = useFileCardHost(repoId);
@@ -104,7 +145,7 @@ export function SecurityTab({ repoId }: { repoId: string }) {
} else if (list.length === 0) {
// Green only when the scan is known to have run; an unknown scan time
// with nothing listed is "not scanned yet", not good news.
- body = <SecurityEmpty scannedAgo={scannedAgo} />;
+ body = <SecurityEmpty scannedAgo={scannedAgo} fileCount={fileCount} />;
} else {
body = (
<SecurityFindingsBody
@@ -113,37 +154,17 @@ export function SecurityTab({ repoId }: { repoId: string }) {
capped={capped}
labels={labels}
onSelect={handleSelect}
- onGeneratePrompt={setPromptFinding}
+ onGeneratePrompt={(f) => promptFor([f])}
+ onGenerateBatchPrompt={promptFor}
/>
);
}
return (
<div className="space-y-6">
- <div className="flex flex-wrap items-center justify-end gap-2">
- <Button size="sm" variant="outline" onClick={handleRescan} disabled={rescanning}>
- <RotateCw
- className={`h-3.5 w-3.5 mr-1.5 ${rescanning ? "motion-safe:animate-spin" : ""}`}
- />
- {rescanning ? "Re-scanning…" : "Re-scan"}
- </Button>
- </div>
-
{body}
- <AiPromptModal
- open={promptFinding !== null}
- onOpenChange={(o) => !o && setPromptFinding(null)}
- getPrompt={
- promptFinding
- ? (flavor) => buildSecurityAiPrompt({ finding: promptFinding, flavor })
- : null
- }
- filePath={promptFinding?.file_path}
- chatContext={fileChatContext(promptFinding?.file_path)}
- title={t("promptTitle")}
- description={t("promptDescription")}
- />
+ {promptModal}
{dialog}
</div>
@@ -174,12 +195,21 @@ function usePostureLabels(): SecurityPostureLabels {
);
}
-function SecurityEmpty({ scannedAgo }: { scannedAgo: string | null }) {
+function SecurityEmpty({
+ scannedAgo,
+ fileCount,
+}: {
+ scannedAgo: string | null;
+ fileCount: number | null;
+}) {
const t = useTranslations("risk");
return scannedAgo ? (
- <EmptyState
- tone="positive"
- title={t("posture.clearTitle")}
+ <CleanState
+ title={
+ fileCount != null
+ ? t("posture.clearTitleScoped", { files: formatNumber(fileCount) })
+ : t("posture.clearTitle")
+ }
description={t("posture.clearBody", { when: scannedAgo })}
/>
) : (
@@ -194,6 +224,7 @@ function SecurityFindingsBody({
labels,
onSelect,
onGeneratePrompt,
+ onGenerateBatchPrompt,
}: {
list: SecurityFinding[];
scannedAgo: string | null;
@@ -201,6 +232,7 @@ function SecurityFindingsBody({
labels: SecurityPostureLabels;
onSelect: (f: SecurityFinding) => void;
onGeneratePrompt: (f: SecurityFinding) => void;
+ onGenerateBatchPrompt: (findings: SecurityFinding[]) => void;
}) {
const t = useTranslations("risk");
return (
@@ -211,6 +243,9 @@ function SecurityFindingsBody({
findings={list}
onSelect={onSelect}
onGeneratePrompt={onGeneratePrompt}
+ promptLabel={t("promptAction")}
+ onGenerateBatchPrompt={onGenerateBatchPrompt}
+ batchPromptLabel={(count) => t("batchPromptAction", { count })}
/>
{capped && (
<p className="text-xs text-[var(--color-text-tertiary)]">
diff --git a/packages/web/src/components/shared/file-card-host.tsx b/packages/web/src/components/shared/file-card-host.tsx
index 2409a485e..2c612d05c 100644
--- a/packages/web/src/components/shared/file-card-host.tsx
+++ b/packages/web/src/components/shared/file-card-host.tsx
@@ -8,6 +8,7 @@ import {
filePageId,
} from "@repowise-dev/ui/shared/entity";
import type { FileCardData, FileCardLinks } from "@repowise-dev/ui/shared/file-card";
+import { commitsViewHref } from "@/lib/changes";
/**
* Stateful host for FileCardDialog. Pages that have a list of files (hotspots,
@@ -37,7 +38,7 @@ export function useFileCardHost(repoId?: string) {
// reader somewhere plausible and wrong.
docs: docsPagePath(`/repos/${repoId}`, filePageId(next.file_path)),
symbols: `/repos/${repoId}/architecture?view=symbols&q=${encodeURIComponent(next.file_path)}`,
- blastRadius: `/repos/${repoId}/code-health?tab=impact&file=${encodeURIComponent(next.file_path)}`,
+ blastRadius: `${commitsViewHref(repoId, "review")}&file=${encodeURIComponent(next.file_path)}`,
deadCode: `/repos/${repoId}/code-health?tab=dead-code`,
decisions: `/repos/${repoId}/decisions?file=${encodeURIComponent(next.file_path)}`,
}
diff --git a/packages/web/src/components/symbols/symbol-drawer-wrapper.tsx b/packages/web/src/components/symbols/symbol-drawer-wrapper.tsx
index 268e4f5de..426c44236 100644
--- a/packages/web/src/components/symbols/symbol-drawer-wrapper.tsx
+++ b/packages/web/src/components/symbols/symbol-drawer-wrapper.tsx
@@ -16,6 +16,7 @@ import { useGraphMetrics, useCallersCallees } from "@/lib/hooks/use-graph";
import { getCoChanges, getGitMetadata } from "@/lib/api/git";
import { listDeadCode } from "@/lib/api/dead-code";
import type { SymbolResponse } from "@/lib/api/types";
+import { commitsViewHref } from "@/lib/changes";
import type { SymbolDetailData } from "@repowise-dev/types/symbols";
interface Props {
@@ -169,7 +170,7 @@ export function SymbolDrawerWrapper({ symbol, repoId, onClose }: Props) {
? {
onOpenBlastRadius: () =>
router.push(
- `/repos/${repoId}/code-health?tab=impact&file=${encodeURIComponent(filePath)}`,
+ `${commitsViewHref(repoId, "review")}&file=${encodeURIComponent(filePath)}`,
),
}
: {})}
diff --git a/packages/web/src/components/tests/tests-view.tsx b/packages/web/src/components/tests/tests-view.tsx
new file mode 100644
index 000000000..27bb96f04
--- /dev/null
+++ b/packages/web/src/components/tests/tests-view.tsx
@@ -0,0 +1,59 @@
+"use client";
+
+/**
+ * Tests host — binds the shared {@link CoverageView} to web's `/api` client
+ * and `/repos/:id` routing, and passes its copy in the reader's language. The
+ * composition lives in `@repowise-dev/ui/health`; this file only injects the
+ * app-specific data fetchers, navigation and strings.
+ */
+
+import { useMemo } from "react";
+import { useRouter } from "next/navigation";
+import { useTranslations } from "next-intl";
+import {
+ CoverageView,
+ type CodeHealthAdapter,
+ type CoverageViewCopy,
+} from "@repowise-dev/ui/health";
+import { fileEntityPath } from "@repowise-dev/ui/shared/entity";
+import { formatNumber } from "@repowise-dev/ui/lib/format";
+import {
+ getHealthCoverage,
+ getTestsReaching,
+ getHealthOverview,
+ getHealthWorkQueue,
+ listHealthFindings,
+ updateFindingStatus,
+} from "@/lib/api/code-health";
+
+export function TestsView({ repoId: id }: { repoId: string }) {
+ const router = useRouter();
+ const t = useTranslations("views.tests");
+ const prefix = `/repos/${id}`;
+
+ const adapter: CodeHealthAdapter = {
+ cacheKey: id,
+ getOverview: (limit) => getHealthOverview(id, limit),
+ listFindings: (opts) => listHealthFindings(id, opts),
+ getHealthWorkQueue: (opts) => getHealthWorkQueue(id, opts),
+ updateFindingStatus: (findingId, status) =>
+ updateFindingStatus(id, findingId, status),
+ getCoverage: (opts) => getHealthCoverage(id, opts),
+ getTestsReaching: (path) => getTestsReaching(id, path),
+ fileHref: (path) => fileEntityPath(prefix, path),
+ navigate: (href) => router.push(href),
+ renderFileDrawer: () => null,
+ };
+
+ const copy = useMemo<CoverageViewCopy>(
+ () => ({
+ promptLabel: t("promptAction"),
+ batchPromptLabel: (count) => t("batchPromptAction", { count }),
+ cleanTitle: (files) => t("cleanTitle", { files: formatNumber(files) }),
+ cleanDescription: t("cleanBody"),
+ }),
+ [t],
+ );
+
+ return <CoverageView adapter={adapter} copy={copy} />;
+}
diff --git a/packages/web/src/lib/changes.test.ts b/packages/web/src/lib/changes.test.ts
index e6f23f71e..2bd952d4f 100644
--- a/packages/web/src/lib/changes.test.ts
+++ b/packages/web/src/lib/changes.test.ts
@@ -78,9 +78,11 @@ describe("Commits page views", () => {
it("reads only the known views and keeps the commit view param-free", () => {
expect(parseCommitsView("changes")).toBe("changes");
expect(parseCommitsView("events")).toBe("events");
+ expect(parseCommitsView("review")).toBe("review");
expect(parseCommitsView(undefined)).toBe("commits");
expect(parseCommitsView("anything")).toBe("commits");
expect(commitsViewHref("r1", "commits")).toBe("/repos/r1/commits");
expect(commitsViewHref("r1", "events")).toBe("/repos/r1/commits?view=events");
+ expect(commitsViewHref("r1", "review")).toBe("/repos/r1/commits?view=review");
});
});
diff --git a/packages/web/src/lib/changes.ts b/packages/web/src/lib/changes.ts
index a21fbf6f4..101830f2f 100644
--- a/packages/web/src/lib/changes.ts
+++ b/packages/web/src/lib/changes.ts
@@ -10,11 +10,12 @@ export function changeLabel(c: Pick<ChangeListItem, "forge_ref" | "id">): string
return c.forge_ref ?? (c.id.length > 19 ? c.id.slice(0, 19) : c.id);
}
-export type CommitsView = "changes" | "commits" | "events";
+export type CommitsView = "changes" | "commits" | "events" | "review";
/**
* The Commits page in one view: `?view=changes` groups by merged change,
- * `?view=events` lists what moved between index runs.
+ * `?view=events` lists what moved between index runs, `?view=review` weighs
+ * a change's blast radius before it lands.
*/
export function commitsViewHref(repoId: string, view: CommitsView): string {
const base = `/repos/${repoId}/commits`;
@@ -23,7 +24,7 @@ export function commitsViewHref(repoId: string, view: CommitsView): string {
/** The view a `?view=` value asks for; anything else is the commit view. */
export function parseCommitsView(raw: string | string[] | undefined): CommitsView {
- return raw === "changes" || raw === "events" ? raw : "commits";
+ return raw === "changes" || raw === "events" || raw === "review" ? raw : "commits";
}
/** Filters and paging of the by-change view, as its query parameters keep them. */
diff --git a/packages/web/src/lib/hooks/use-repo.ts b/packages/web/src/lib/hooks/use-repo.ts
index 27f8b709c..aadc1323e 100644
--- a/packages/web/src/lib/hooks/use-repo.ts
+++ b/packages/web/src/lib/hooks/use-repo.ts
@@ -1,7 +1,7 @@
"use client";
import useSWR from "swr";
-import { getRepo } from "@/lib/api/repos";
+import { getRepo, getRepoStats } from "@/lib/api/repos";
import { ApiClientError } from "@/lib/api/client";
import type { RepoResponse } from "@/lib/api/types";
@@ -29,3 +29,15 @@ export function useRepo(repoId: string | null) {
);
return { repo: data, error, isLoading, mutate };
}
+
+/**
+ * Files in the index, for naming the scope of a clean result ("across 5,612
+ * files"). Null until it lands or when it cannot load, so a caller falls back
+ * to copy without a count rather than claiming a number it never measured.
+ */
+export function useRepoFileCount(repoId: string): number | null {
+ const { data } = useSWR(`repo-stats:${repoId}`, () => getRepoStats(repoId), {
+ revalidateOnFocus: false,
+ });
+ return data?.file_count ?? null;
+}
diff --git a/packages/web/src/lib/route-links.test.ts b/packages/web/src/lib/route-links.test.ts
index 5d40284cc..20f36c1ad 100644
--- a/packages/web/src/lib/route-links.test.ts
+++ b/packages/web/src/lib/route-links.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import { readdirSync, readFileSync, statSync } from "node:fs";
import { join } from "node:path";
+import { CODE_HEALTH_TABS, MOVED_TABS, TAB_ALIASES } from "@/app/repos/[id]/code-health/tabs";
/**
* Drift guard for links into routes that are only redirects.
@@ -56,7 +57,7 @@ function redirectOnlySegments(): Set<string> {
} catch {
continue;
}
- if (page.includes("redirect") && !page.includes("return (")) out.add(entry);
+ if (page.includes("redirect") && !/return\s*\(?\s*</.test(page)) out.add(entry);
}
return out;
}
@@ -100,23 +101,8 @@ describe("route links", () => {
});
it("points at no Code Health tab that only survives as a legacy alias", () => {
- const page = readFileSync(join(ROUTES, "code-health/page.tsx"), "utf8");
-
- const tabs = new Set(
- [...(page.match(/const TABS = \[([\s\S]*?)\] as const/)?.[1] ?? "").matchAll(/"([^"]+)"/g)].map(
- (m) => m[1]!,
- ),
- );
- const aliases = new Set(
- [
- ...(page.match(/const TAB_ALIASES[^{]*\{([\s\S]*?)\n\}/)?.[1] ?? "").matchAll(
- /^\s*"?([a-z-]+)"?:/gm,
- ),
- ].map((m) => m[1]!),
- );
- // The parse has to have found something, or this passes on a rename.
- expect(tabs.size).toBeGreaterThan(3);
- expect(aliases.size).toBeGreaterThan(1);
+ const tabs = new Set<string>(CODE_HEALTH_TABS);
+ const aliases = new Set(Object.keys(TAB_ALIASES));
const offenders: string[] = [];
for (const file of [...walk(WEB_SRC), ...walk(UI_SRC)]) {
@@ -136,6 +122,25 @@ describe("route links", () => {
expect(offenders.sort()).toEqual([]);
});
+ it("points web at the new home of a tab that left Code Health", () => {
+ // Web only: the shared ui package keeps `?tab=coverage` and
+ // `?tab=doc-drift` until the hosted app has `/tests` and `/docs/drift`
+ // (the hosted port); the server redirect carries those links meanwhile.
+ const moved = new Set<string>(MOVED_TABS);
+ const offenders: string[] = [];
+ for (const file of walk(WEB_SRC)) {
+ if (/\.test\.tsx?$/.test(file)) continue;
+ readFileSync(file, "utf8")
+ .split("\n")
+ .forEach((line, i) => {
+ for (const m of line.matchAll(/code-health\?tab=([a-z-]+)/g)) {
+ if (moved.has(m[1]!)) offenders.push(`?tab=${m[1]} <- ${file}:${i + 1}`);
+ }
+ });
+ }
+ expect(offenders.sort()).toEqual([]);
+ });
+
it("still recognises the deep links we keep on purpose", () => {
// If one stops being a redirect its allowance is dead weight, and the
// set should shrink rather than quietly cover a real page.
diff --git a/tests/unit/persistence/test_test_reachability_walk.py b/tests/unit/persistence/test_test_reachability_walk.py
index 89b53f695..909abb14d 100644
--- a/tests/unit/persistence/test_test_reachability_walk.py
+++ b/tests/unit/persistence/test_test_reachability_walk.py
@@ -722,3 +722,30 @@ async def test_any_reach_passes_through_the_package_entry_tests_import(tmp_path,
assert found["src/core/Ky.ts"].tests == ["test/x.test.ts"]
assert found["src/core/Ky.ts"].via == "import-graph"
assert "src/retry.ts" not in found
+
+
+async def test_reached_files_are_walked_once_per_index_state(async_session, monkeypatch):
+ import repowise.core.analysis.test_reachability as tr
+
+ repo = await insert_repo(async_session)
+ await _seed(
+ async_session,
+ repo.id,
+ nodes={"tests/test_a.py": True, "src/a.py": False, "src/b.py": False},
+ edges=[*_calls("tests/test_a.py", "src/a.py")],
+ )
+ loads = 0
+ real = tr.call_graph_from_db
+
+ async def counting(session, repo_id):
+ nonlocal loads
+ loads += 1
+ return await real(session, repo_id)
+
+ monkeypatch.setattr(tr, "call_graph_from_db", counting)
+
+ first = await tr.cached_files_reached_by_tests(async_session, repo.id)
+ second = await tr.cached_files_reached_by_tests(async_session, repo.id)
+
+ assert first == second == frozenset({"src/a.py"})
+ assert loads == 1