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.

Hosted ⇄ Web UI parity (#561)

Swati Ahuja3601198f3141
diff --git a/packages/ui/__tests__/blast-radius/impact-view.test.tsx b/packages/ui/__tests__/blast-radius/impact-view.test.tsx
new file mode 100644
index 000000000..b9a8102a4
--- /dev/null
+++ b/packages/ui/__tests__/blast-radius/impact-view.test.tsx
@@ -0,0 +1,88 @@
+import { describe, it, expect, vi } from "vitest";
+import { render, screen, fireEvent, waitFor } from "@testing-library/react";
+import { SWRConfig } from "swr";
+import type { ReactElement } from "react";
+import { ImpactView } from "../../src/blast-radius/impact-view.js";
+import type { ImpactAdapter } from "../../src/blast-radius/impact-adapter.js";
+import type { BlastRadiusResponse } from "@repowise-dev/types/blast-radius";
+
+const RESULT: BlastRadiusResponse = {
+ overall_risk_score: 0.42,
+ direct_risks: [],
+ transitive_affected: [],
+ cochange_warnings: [],
+ recommended_reviewers: [],
+ test_gaps: [],
+};
+
+function makeAdapter(over: Partial<ImpactAdapter> = {}): ImpactAdapter {
+ return {
+ cacheKey: "repo-1",
+ listHotspots: vi.fn(async () => [{ file_path: "src/hot.ts" }]),
+ searchFiles: vi.fn(async () => []),
+ analyze: vi.fn(async () => RESULT),
+ ...over,
+ };
+}
+
+function renderView(node: ReactElement) {
+ return render(
+ <SWRConfig value={{ provider: () => new Map(), dedupingInterval: 0 }}>
+ {node}
+ </SWRConfig>,
+ );
+}
+
+describe("ImpactView", () => {
+ it("renders hotspot chips from the adapter", async () => {
+ renderView(<ImpactView adapter={makeAdapter()} />);
+ expect(
+ await screen.findByRole("button", { name: "Add src/hot.ts to changed files" }),
+ ).toBeInTheDocument();
+ });
+
+ it("requires at least one path before analyzing", async () => {
+ const adapter = makeAdapter();
+ renderView(<ImpactView adapter={adapter} />);
+
+ fireEvent.click(screen.getByRole("button", { name: "Analyze" }));
+
+ expect(await screen.findByText("Add at least one file path.")).toBeInTheDocument();
+ expect(adapter.analyze).not.toHaveBeenCalled();
+ });
+
+ it("analyzes the selected hotspot and renders the reviewer slot", async () => {
+ const adapter = makeAdapter({
+ renderReviewers: (files) => <div>reviewers for {files.length} paths</div>,
+ });
+ renderView(<ImpactView adapter={adapter} />);
+
+ // Seed a changed file from the hotspot chip, then analyze.
+ fireEvent.click(
+ await screen.findByRole("button", { name: "Add src/hot.ts to changed files" }),
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Analyze" }));
+
+ await waitFor(() =>
+ expect(adapter.analyze).toHaveBeenCalledWith({
+ changedFiles: ["src/hot.ts"],
+ maxDepth: 3,
+ }),
+ );
+ expect(await screen.findByText("reviewers for 1 paths")).toBeInTheDocument();
+ });
+
+ it("degrades gracefully when no reviewer slot is supplied", async () => {
+ const adapter = makeAdapter();
+ renderView(<ImpactView adapter={adapter} />);
+
+ fireEvent.click(
+ await screen.findByRole("button", { name: "Add src/hot.ts to changed files" }),
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Analyze" }));
+
+ // Results still render (risk gauge) without a reviewer panel.
+ await waitFor(() => expect(adapter.analyze).toHaveBeenCalled());
+ expect(screen.queryByText(/reviewers for/)).not.toBeInTheDocument();
+ });
+});
diff --git a/packages/ui/__tests__/c4/arch-tour-button.test.tsx b/packages/ui/__tests__/c4/arch-tour-button.test.tsx
new file mode 100644
index 000000000..bb8d602b1
--- /dev/null
+++ b/packages/ui/__tests__/c4/arch-tour-button.test.tsx
@@ -0,0 +1,53 @@
+/**
+ * ArchTourButton — the promoted "Take the tour" trigger. Both apps mount it
+ * unconditionally; it reads the curated tour off the shared architecture store
+ * and degrades to nothing when there are no steps (or while a tour is running).
+ */
+import { describe, it, expect, beforeEach } from "vitest";
+import { act, render, fireEvent } from "@testing-library/react";
+import { ArchTourButton } from "../../src/c4/panels/ArchTourButton";
+import { useArchitectureStore } from "../../src/c4/store/use-architecture-store";
+import { createMockView } from "./fixtures";
+import type { ArchitectureView } from "../../src/c4/types";
+
+const store = useArchitectureStore;
+
+beforeEach(() => {
+ store.setState(store.getInitialState());
+ localStorage.clear();
+});
+
+function viewWithoutTour(): ArchitectureView {
+ return { ...createMockView(), tour: [] };
+}
+
+describe("ArchTourButton", () => {
+ it("renders nothing before a view loads", () => {
+ const { queryByText } = render(<ArchTourButton />);
+ expect(queryByText("Take the tour")).toBeNull();
+ });
+
+ it("renders nothing when the view carries no tour steps", () => {
+ act(() => {
+ store.getState().setView(viewWithoutTour());
+ });
+ const { queryByText } = render(<ArchTourButton />);
+ expect(queryByText("Take the tour")).toBeNull();
+ });
+
+ it("shows the trigger when the view has a tour and starts it on click", () => {
+ act(() => {
+ store.getState().setView(createMockView()); // fixture carries a tour
+ });
+ const { getByText, queryByText } = render(<ArchTourButton />);
+
+ const trigger = getByText("Take the tour");
+ expect(trigger).toBeDefined();
+
+ fireEvent.click(trigger);
+
+ // The store's tour player is now running and the trigger hides itself.
+ expect(store.getState().tourActive).toBe(true);
+ expect(queryByText("Take the tour")).toBeNull();
+ });
+});
diff --git a/packages/ui/__tests__/dead-code/dead-code-view.test.tsx b/packages/ui/__tests__/dead-code/dead-code-view.test.tsx
new file mode 100644
index 000000000..76d430abe
--- /dev/null
+++ b/packages/ui/__tests__/dead-code/dead-code-view.test.tsx
@@ -0,0 +1,152 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { render, screen, fireEvent, waitFor } from "@testing-library/react";
+import { SWRConfig } from "swr";
+import type { ReactElement } from "react";
+import { DeadCodeView } from "../../src/dead-code/dead-code-view.js";
+import type { DeadCodeAdapter } from "../../src/dead-code/dead-code-adapter.js";
+import type {
+ DeadCodeFinding,
+ DeadCodeSummary,
+} from "@repowise-dev/types/dead-code";
+
+// Capture sonner toasts so we can assert the undo affordance without a Toaster.
+const toastSuccess = vi.fn();
+const toastError = vi.fn();
+const toastWarning = vi.fn();
+vi.mock("sonner", () => ({
+ toast: {
+ success: (...a: unknown[]) => toastSuccess(...a),
+ error: (...a: unknown[]) => toastError(...a),
+ warning: (...a: unknown[]) => toastWarning(...a),
+ },
+}));
+
+const SUMMARY: DeadCodeSummary = {
+ total_findings: 3,
+ confidence_summary: { high: 2, medium: 1, low: 0 },
+ deletable_lines: 120,
+ total_lines: 9000,
+ by_kind: { unreachable_file: 2, unused_export: 1, zombie_package: 0 },
+};
+
+const FINDINGS: DeadCodeFinding[] = [
+ {
+ id: "f1",
+ kind: "unreachable_file",
+ file_path: "src/old/legacy.ts",
+ symbol_name: null,
+ symbol_kind: null,
+ confidence: 0.95,
+ reason: "No importers",
+ lines: 80,
+ safe_to_delete: true,
+ risk_factors: [],
+ primary_owner: "alice",
+ status: "open",
+ note: null,
+ },
+ {
+ id: "f2",
+ kind: "unused_export",
+ file_path: "src/util/helpers.ts",
+ symbol_name: "unusedHelper",
+ symbol_kind: "function",
+ confidence: 0.88,
+ reason: "Export never imported",
+ lines: 40,
+ safe_to_delete: true,
+ risk_factors: [],
+ primary_owner: "bob",
+ status: "open",
+ note: null,
+ },
+ {
+ id: "f3",
+ kind: "unreachable_file",
+ file_path: "src/boot/init.ts",
+ symbol_name: null,
+ symbol_kind: null,
+ confidence: 0.6,
+ reason: "Possibly bootstrap-loaded",
+ lines: 30,
+ safe_to_delete: false,
+ risk_factors: ["bootstrap"],
+ primary_owner: "alice",
+ status: "open",
+ note: null,
+ },
+];
+
+function makeAdapter(over: Partial<DeadCodeAdapter> = {}): DeadCodeAdapter {
+ return {
+ cacheKey: "repo-1",
+ repoId: "repo-1",
+ getSummary: vi.fn(async () => SUMMARY),
+ listFindings: vi.fn(async () => FINDINGS),
+ analyze: vi.fn(async () => undefined),
+ patchFinding: vi.fn(async (id, patch) => {
+ const base = FINDINGS.find((f) => f.id === id)!;
+ return { ...base, status: patch.status };
+ }),
+ fileHref: (p) => `/repos/repo-1/files/${p}`,
+ navigate: vi.fn(),
+ ...over,
+ };
+}
+
+// Fresh SWR cache per render so view-level keys don't bleed across tests.
+function renderView(node: ReactElement) {
+ return render(
+ <SWRConfig value={{ provider: () => new Map(), dedupingInterval: 0 }}>
+ {node}
+ </SWRConfig>,
+ );
+}
+
+beforeEach(() => {
+ toastSuccess.mockClear();
+ toastError.mockClear();
+ toastWarning.mockClear();
+});
+
+describe("DeadCodeView", () => {
+ it("renders the summary and the safe-to-delete pile from adapter data", async () => {
+ renderView(<DeadCodeView adapter={makeAdapter()} />);
+
+ // Summary headline (total findings) + the safe pile punchline.
+ expect(await screen.findByText("Propose cleanup")).toBeInTheDocument();
+ expect(screen.getByText("lines in cleanup candidates")).toBeInTheDocument();
+ // The safe slice (not the unsafe bootstrap file) drives the pile preview.
+ expect(screen.getByText(/legacy\.ts/)).toBeInTheDocument();
+ });
+
+ it("Re-analyze calls the adapter and shows a success toast", async () => {
+ const adapter = makeAdapter();
+ renderView(<DeadCodeView adapter={adapter} />);
+
+ fireEvent.click(screen.getByRole("button", { name: "Re-analyze" }));
+
+ await waitFor(() => expect(adapter.analyze).toHaveBeenCalledTimes(1));
+ expect(toastSuccess).toHaveBeenCalled();
+ });
+
+ it("surfaces a retry affordance when the summary fails to load", async () => {
+ const adapter = makeAdapter({
+ getSummary: vi.fn(async () => {
+ throw new Error("boom");
+ }),
+ });
+ renderView(<DeadCodeView adapter={adapter} />);
+
+ expect(await screen.findByText("Couldn't load summary.")).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Retry" })).toBeInTheDocument();
+ });
+
+ it("opens the AI cleanup prompt seeded with the safe pile", async () => {
+ renderView(<DeadCodeView adapter={makeAdapter()} />);
+
+ fireEvent.click(await screen.findByText("Propose cleanup"));
+
+ expect(await screen.findByText("AI cleanup prompt")).toBeInTheDocument();
+ });
+});
diff --git a/packages/ui/__tests__/decisions/decision-detail.test.tsx b/packages/ui/__tests__/decisions/decision-detail.test.tsx
new file mode 100644
index 000000000..86308b866
--- /dev/null
+++ b/packages/ui/__tests__/decisions/decision-detail.test.tsx
@@ -0,0 +1,135 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { render, screen, fireEvent, waitFor, within } from "@testing-library/react";
+import { SWRConfig } from "swr";
+import type { ReactElement } from "react";
+import { DecisionDetail } from "../../src/decisions/decision-detail.js";
+import type { DecisionDetailAdapter } from "../../src/decisions/decision-detail-adapter.js";
+import type {
+ DecisionLineageEntry,
+ DecisionRecord,
+} from "@repowise-dev/types/decisions";
+
+const toastSuccess = vi.fn();
+const toastError = vi.fn();
+vi.mock("sonner", () => ({
+ toast: {
+ success: (...a: unknown[]) => toastSuccess(...a),
+ error: (...a: unknown[]) => toastError(...a),
+ },
+}));
+
+function makeDecision(over: Partial<DecisionRecord> = {}): DecisionRecord {
+ return {
+ id: "d1",
+ repository_id: "repo-1",
+ title: "Use SWR for client fetching",
+ status: "proposed",
+ context: "We need a caching client.",
+ decision: "Adopt SWR across dashboards.",
+ rationale: "Dedupes requests and revalidates cheaply.",
+ alternatives: ["React Query"],
+ consequences: ["One more peer dependency"],
+ affected_files: ["src/app.tsx"],
+ affected_modules: ["app"],
+ tags: ["frontend"],
+ source: "inline_marker",
+ evidence_commits: ["abcdef123456"],
+ evidence_file: null,
+ evidence_line: null,
+ confidence: 0.8,
+ staleness_score: 0,
+ superseded_by: null,
+ last_code_change: null,
+ created_at: "2026-01-01T00:00:00Z",
+ updated_at: "2026-01-02T00:00:00Z",
+ ...over,
+ };
+}
+
+function makeAdapter(over: Partial<DecisionDetailAdapter> = {}): DecisionDetailAdapter {
+ return {
+ cacheKey: "repo-1:d1",
+ repoId: "repo-1",
+ getLineage: vi.fn(async () => [] as DecisionLineageEntry[]),
+ getEvidence: vi.fn(async () => []),
+ listSiblingIds: vi.fn(async () => ["d1"]),
+ listModuleSuggestions: vi.fn(async () => []),
+ patchDecision: vi.fn(async () => undefined),
+ decisionsHref: () => "/repos/repo-1/decisions",
+ decisionHref: (id) => `/repos/repo-1/decisions/${id}`,
+ commitsHref: (opts) =>
+ `/repos/repo-1/commits${opts?.commit ? `?commit=${opts.commit}` : ""}`,
+ hotspotsHref: () => "/repos/repo-1/code-health?tab=hotspots",
+ ...over,
+ };
+}
+
+function renderView(node: ReactElement) {
+ return render(
+ <SWRConfig value={{ provider: () => new Map(), dedupingInterval: 0 }}>
+ {node}
+ </SWRConfig>,
+ );
+}
+
+beforeEach(() => {
+ toastSuccess.mockClear();
+ toastError.mockClear();
+});
+
+describe("DecisionDetail", () => {
+ it("renders the record body and governance affordances", () => {
+ renderView(<DecisionDetail decision={makeDecision()} adapter={makeAdapter()} />);
+
+ expect(screen.getByRole("heading", { name: "Use SWR for client fetching" })).toBeInTheDocument();
+ expect(screen.getByText("Adopt SWR across dashboards.")).toBeInTheDocument();
+ expect(screen.getByText("React Query")).toBeInTheDocument();
+ expect(screen.getByRole("link", { name: /All decisions/ })).toHaveAttribute(
+ "href",
+ "/repos/repo-1/decisions",
+ );
+ });
+
+ it("confirms a proposed decision through the dialog and patches via the adapter", async () => {
+ const adapter = makeAdapter();
+ renderView(<DecisionDetail decision={makeDecision()} adapter={adapter} />);
+
+ // The action button opens a confirm dialog (shares its label) — scope to it.
+ fireEvent.click(screen.getByRole("button", { name: "Confirm" }));
+ const dialog = await screen.findByRole("dialog");
+ fireEvent.click(within(dialog).getByRole("button", { name: "Confirm" }));
+
+ await waitFor(() =>
+ expect(adapter.patchDecision).toHaveBeenCalledWith({ status: "active" }),
+ );
+ expect(toastSuccess).toHaveBeenCalled();
+ });
+
+ it("renders the evolution timeline when the lineage chain is non-trivial", async () => {
+ const adapter = makeAdapter({
+ getLineage: vi.fn(
+ async (): Promise<DecisionLineageEntry[]> => [
+ { id: "d0", title: "Original", status: "deprecated", source: "cli", relation: "supersedes" },
+ { id: "d1", title: "Use SWR", status: "proposed", source: "inline_marker", relation: null },
+ ],
+ ),
+ });
+ renderView(<DecisionDetail decision={makeDecision()} adapter={adapter} />);
+
+ expect(await screen.findByText("Evolution")).toBeInTheDocument();
+ });
+
+ it("renders a host-supplied linked-issues slot, and nothing when omitted", () => {
+ const withSlot = makeAdapter({
+ renderLinkedIssues: () => <div>JIRA-123 linked</div>,
+ });
+ const { unmount } = renderView(
+ <DecisionDetail decision={makeDecision()} adapter={withSlot} />,
+ );
+ expect(screen.getByText("JIRA-123 linked")).toBeInTheDocument();
+ unmount();
+
+ renderView(<DecisionDetail decision={makeDecision()} adapter={makeAdapter()} />);
+ expect(screen.queryByText("JIRA-123 linked")).not.toBeInTheDocument();
+ });
+});
diff --git a/packages/ui/__tests__/graph/graph-flow.test.tsx b/packages/ui/__tests__/graph/graph-flow.test.tsx
index df2958a6c..db4a7d62c 100644
--- a/packages/ui/__tests__/graph/graph-flow.test.tsx
+++ b/packages/ui/__tests__/graph/graph-flow.test.tsx
@@ -1,24 +1,65 @@
import { describe, it, expect, vi } from "vitest";
-import { render, screen } from "@testing-library/react";
+import { render, screen, fireEvent } from "@testing-library/react";
import { GraphFlow } from "../../src/graph/graph-flow.js";
+// Minimal prop set — no graphs supplied, so the canvas renders its empty state
+// while the toolbar (and its color-mode control) still mounts.
+const baseProps = {
+ moduleGraph: undefined,
+ isLoadingModuleGraph: false,
+ fullGraph: undefined,
+ isLoadingFullGraph: false,
+ architectureGraph: undefined,
+ isLoadingArchitectureGraph: false,
+ deadCodeGraph: undefined,
+ isLoadingDeadCodeGraph: false,
+ hotFilesGraph: undefined,
+ isLoadingHotFilesGraph: false,
+} as const;
describe("GraphFlow shell", () => {
it("renders the empty state when no nodes are layouted", () => {
+ render(<GraphFlow {...baseProps} />);
+ expect(screen.getByText("No graph data")).toBeTruthy();
+ });
+
+ it("reflects a controlled colorMode and reports changes without self-updating", () => {
+ const onColorModeChange = vi.fn();
render(
<GraphFlow
- moduleGraph={undefined}
- isLoadingModuleGraph={false}
- fullGraph={undefined}
- isLoadingFullGraph={false}
- architectureGraph={undefined}
- isLoadingArchitectureGraph={false}
- deadCodeGraph={undefined}
- isLoadingDeadCodeGraph={false}
- hotFilesGraph={undefined}
- isLoadingHotFilesGraph={false}
+ {...baseProps}
+ colorMode="risk"
+ onColorModeChange={onColorModeChange}
/>,
);
- expect(screen.getByText("No graph data")).toBeTruthy();
+
+ // Controlled value wins: Risk is active, Community (the default) is not.
+ expect(screen.getByRole("button", { name: "Risk" }).getAttribute("aria-pressed")).toBe("true");
+ expect(
+ screen.getByRole("button", { name: "Community" }).getAttribute("aria-pressed"),
+ ).toBe("false");
+
+ // Clicking another mode reports out but does NOT change the displayed mode —
+ // the host owns the value and hasn't pushed a new prop yet.
+ fireEvent.click(screen.getByRole("button", { name: "Language" }));
+ expect(onColorModeChange).toHaveBeenCalledWith("language");
+ expect(screen.getByRole("button", { name: "Risk" }).getAttribute("aria-pressed")).toBe("true");
+ expect(
+ screen.getByRole("button", { name: "Language" }).getAttribute("aria-pressed"),
+ ).toBe("false");
+ });
+
+ it("tracks its own colorMode when uncontrolled (seeded by initialColorMode)", () => {
+ render(<GraphFlow {...baseProps} initialColorMode="language" />);
+
+ expect(
+ screen.getByRole("button", { name: "Language" }).getAttribute("aria-pressed"),
+ ).toBe("true");
+
+ fireEvent.click(screen.getByRole("button", { name: "Risk" }));
+ expect(screen.getByRole("button", { name: "Risk" }).getAttribute("aria-pressed")).toBe("true");
+ expect(
+ screen.getByRole("button", { name: "Language" }).getAttribute("aria-pressed"),
+ ).toBe("false");
});
});
diff --git a/packages/ui/__tests__/shared/view-tabs.test.tsx b/packages/ui/__tests__/shared/view-tabs.test.tsx
new file mode 100644
index 000000000..52fc3dada
--- /dev/null
+++ b/packages/ui/__tests__/shared/view-tabs.test.tsx
@@ -0,0 +1,54 @@
+import { describe, it, expect, vi, beforeAll } from "vitest";
+import { render, screen, fireEvent } from "@testing-library/react";
+import { ViewTabs } from "../../src/shared/view-tabs.js";
+
+// jsdom has no layout engine, so the active-tab scroll-into-view is a no-op here.
+beforeAll(() => {
+ Element.prototype.scrollIntoView = vi.fn();
+});
+
+describe("ViewTabs", () => {
+ it("renders tab labels and reports selection", () => {
+ const onValueChange = vi.fn();
+ render(
+ <ViewTabs
+ tabs={[
+ { id: "map", label: "Communities" },
+ { id: "explore", label: "Explore" },
+ ]}
+ value="map"
+ onValueChange={onValueChange}
+ />,
+ );
+
+ expect(screen.getByRole("tab", { name: "Communities" }).getAttribute("aria-selected")).toBe(
+ "true",
+ );
+ fireEvent.click(screen.getByRole("tab", { name: "Explore" }));
+ expect(onValueChange).toHaveBeenCalledWith("explore");
+ });
+
+ it("renders an optional leading icon and stays label-only without one", () => {
+ render(
+ <ViewTabs
+ tabs={[
+ {
+ id: "map",
+ label: "Communities",
+ icon: <svg data-testid="kg-icon" aria-hidden />,
+ },
+ { id: "explore", label: "Explore" },
+ ]}
+ value="map"
+ onValueChange={() => {}}
+ />,
+ );
+
+ // The canonical icon rides along with the tab definition…
+ const iconTab = screen.getByRole("tab", { name: "Communities" });
+ expect(iconTab.querySelector('[data-testid="kg-icon"]')).not.toBeNull();
+ // …and a tab without one renders no icon wrapper.
+ const plainTab = screen.getByRole("tab", { name: "Explore" });
+ expect(plainTab.querySelector("svg")).toBeNull();
+ });
+});
diff --git a/packages/ui/package.json b/packages/ui/package.json
index 2cfc0fa7c..6695f3eb6 100644
--- a/packages/ui/package.json
+++ b/packages/ui/package.json
@@ -149,7 +149,8 @@
"peerDependencies": {
"next-themes": "^0.4.0",
"react": "^19.0.0",
- "react-dom": "^19.0.0"
+ "react-dom": "^19.0.0",
+ "swr": "^2.2.5"
},
"devDependencies": {
"@testing-library/jest-dom": "^6.5.0",
diff --git a/packages/ui/src/blast-radius/impact-adapter.ts b/packages/ui/src/blast-radius/impact-adapter.ts
new file mode 100644
index 000000000..60676c36d
--- /dev/null
+++ b/packages/ui/src/blast-radius/impact-adapter.ts
@@ -0,0 +1,37 @@
+import type { ReactNode } from "react";
+import type { BlastRadiusResponse } from "@repowise-dev/types/blast-radius";
+
+/** A hotspot suggestion chip — only the path is rendered. */
+export interface ImpactHotspot {
+ file_path: string;
+}
+
+/**
+ * App-injected data + slots for the shared {@link ImpactView}.
+ *
+ * The view owns the analyzer composition — the searchable file picker, hotspot
+ * chips, depth control, and the blast-radius results. The host supplies *how*
+ * to fetch/analyze and an optional reviewer panel, so web and hosted render the
+ * same view from one source.
+ */
+export interface ImpactAdapter {
+ /** Seeds the view's SWR cache keys — keep it stable per repo/snapshot. */
+ cacheKey: string;
+
+ /** Top churn/risk hotspots offered as one-click changed-file chips. */
+ listHotspots(limit: number): Promise<ImpactHotspot[]>;
+ /** Typeahead source for the file picker — resolves a query to candidate paths. */
+ searchFiles(query: string): Promise<string[]>;
+ /** Run the blast-radius analysis for the proposed change. */
+ analyze(input: {
+ changedFiles: string[];
+ maxDepth: number;
+ }): Promise<BlastRadiusResponse>;
+
+ /**
+ * Rich reviewer panel for the analyzed changeset. Kept as a slot so each app
+ * supplies its own reviewer fetch (or omits it entirely — hosted may have no
+ * reviewer endpoint, which degrades to no panel rather than an error).
+ */
+ renderReviewers?(changedFiles: string[]): ReactNode;
+}
diff --git a/packages/ui/src/blast-radius/impact-view.tsx b/packages/ui/src/blast-radius/impact-view.tsx
new file mode 100644
index 000000000..f3f10c0bf
--- /dev/null
+++ b/packages/ui/src/blast-radius/impact-view.tsx
@@ -0,0 +1,172 @@
+"use client";
+
+/**
+ * Impact view — the blast-radius analyzer. Type-to-search the file index (or
+ * paste a PR diff), seed from top hotspots, pick a traversal depth, then render
+ * the risk gauge, impact graph, and detail tables. The reviewer panel is a slot
+ * the host supplies or no-ops.
+ *
+ * Presentation + orchestration only: the host injects data fetching, the
+ * analysis call, and the reviewer slot through an {@link ImpactAdapter}, so web
+ * and hosted render the same view from one source.
+ */
+
+import { useState } from "react";
+import useSWR from "swr";
+import { Plus, Flame } from "lucide-react";
+import type { BlastRadiusResponse } from "@repowise-dev/types/blast-radius";
+
+import { Button } from "../ui/button";
+import { Card, CardHeader, CardTitle, CardContent } from "../ui/card";
+import { Skeleton } from "../ui/skeleton";
+import { FilePathPicker } from "../health/file-path-picker";
+import { BlastRadiusResults } from "./blast-radius-results";
+import type { ImpactAdapter } from "./impact-adapter";
+
+export function ImpactView({ adapter }: { adapter: ImpactAdapter }) {
+ const [selected, setSelected] = useState<string[]>([]);
+ const [maxDepth, setMaxDepth] = useState(3);
+ const [loading, setLoading] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [result, setResult] = useState<BlastRadiusResponse | null>(null);
+ // The changed-files snapshot the current result was analyzed for — feeds the
+ // reviewer slot so editing the selection (before re-analyzing) doesn't churn it.
+ const [analyzedFiles, setAnalyzedFiles] = useState<string[]>([]);
+
+ const { data: hotspotSuggestions, isLoading: hotspotSuggestionsLoading } = useSWR(
+ `blast-radius-suggestions:${adapter.cacheKey}`,
+ () => adapter.listHotspots(8),
+ { revalidateOnFocus: false },
+ );
+
+ const addPaths = (paths: string[]) => {
+ setSelected((prev) => {
+ const set = new Set(prev);
+ for (const p of paths) {
+ const trimmed = p.trim();
+ if (trimmed) set.add(trimmed);
+ }
+ return [...set];
+ });
+ };
+ const removePath = (path: string) =>
+ setSelected((prev) => prev.filter((p) => p !== path));
+ const useAllHotspots = () => {
+ if (!hotspotSuggestions) return;
+ addPaths(hotspotSuggestions.map((h) => h.file_path));
+ };
+
+ const handleAnalyze = async () => {
+ if (selected.length === 0) {
+ setError("Add at least one file path.");
+ return;
+ }
+ setLoading(true);
+ setError(null);
+ setResult(null);
+ try {
+ const data = await adapter.analyze({ changedFiles: selected, maxDepth });
+ setResult(data);
+ setAnalyzedFiles(selected);
+ } catch (err) {
+ setError(err instanceof Error ? err.message : "Analysis failed.");
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ return (
+ <div className="space-y-6">
+ <Card>
+ <CardHeader className="pb-3">
+ <CardTitle className="text-sm">Impact Analyzer</CardTitle>
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ Estimate the blast radius of a proposed change — direct and transitive risks,
+ reviewer suggestions, and test gaps.
+ </p>
+ </CardHeader>
+ <CardContent className="pt-0 space-y-4">
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ Type to search the file index, paste a list of paths (your PR diff),
+ click a hotspot below, or{" "}
+ <button
+ type="button"
+ onClick={useAllHotspots}
+ className="underline underline-offset-2 hover:text-[var(--color-text-primary)]"
+ disabled={!hotspotSuggestions || hotspotSuggestions.length === 0}
+ >
+ use top hotspots
+ </button>
+ .
+ </p>
+
+ {hotspotSuggestionsLoading && !hotspotSuggestions && (
+ <div className="flex flex-wrap gap-2">
+ {Array.from({ length: 6 }).map((_, i) => (
+ <Skeleton key={i} className="h-7 w-32 rounded-full" />
+ ))}
+ </div>
+ )}
+
+ {hotspotSuggestions && hotspotSuggestions.length > 0 && (
+ <div className="flex flex-wrap gap-2">
+ {hotspotSuggestions.map((h) => (
+ <button
+ key={h.file_path}
+ type="button"
+ onClick={() => addPaths([h.file_path])}
+ className="inline-flex items-center gap-1 rounded-full border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2.5 py-1 text-xs font-mono text-[var(--color-text-secondary)] hover:border-[var(--color-accent-primary)] hover:text-[var(--color-text-primary)] transition-colors"
+ title={h.file_path}
+ aria-label={`Add ${h.file_path} to changed files`}
+ >
+ <Flame className="h-3 w-3 text-[var(--color-warning)]" />
+ <span className="truncate max-w-[260px]">{h.file_path}</span>
+ <Plus className="h-3 w-3 opacity-60" />
+ </button>
+ ))}
+ </div>
+ )}
+
+ <FilePathPicker
+ selected={selected}
+ onAdd={addPaths}
+ onRemove={removePath}
+ onSearch={(q) => adapter.searchFiles(q)}
+ />
+
+ <div className="flex items-center gap-4 flex-wrap">
+ <label className="flex items-center gap-2 text-xs text-[var(--color-text-secondary)]">
+ Max depth
+ <input
+ type="number"
+ min={1}
+ max={10}
+ value={maxDepth}
+ onChange={(e) => setMaxDepth(Math.max(1, Math.min(10, Number(e.target.value))))}
+ className="w-16 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2 py-1 text-xs text-[var(--color-text-primary)] focus:outline-none focus:ring-1 focus:ring-[var(--color-accent-primary)]"
+ aria-label="Maximum dependency depth (1–10)"
+ />
+ </label>
+ <Button onClick={handleAnalyze} disabled={loading} size="sm">
+ {loading ? "Analyzing…" : "Analyze"}
+ </Button>
+ {selected.length > 0 && (
+ <Button onClick={() => setSelected([])} disabled={loading} size="sm" variant="outline">
+ Clear
+ </Button>
+ )}
+ </div>
+ {error && <p className="text-xs text-[var(--color-error)]">{error}</p>}
+ </CardContent>
+ </Card>
+
+ {result && (
+ <BlastRadiusResults
+ result={result}
+ changedFiles={selected}
+ reviewersSlot={adapter.renderReviewers?.(analyzedFiles)}
+ />
+ )}
+ </div>
+ );
+}
diff --git a/packages/ui/src/blast-radius/index.ts b/packages/ui/src/blast-radius/index.ts
index b67809724..0b99e27b7 100644
--- a/packages/ui/src/blast-radius/index.ts
+++ b/packages/ui/src/blast-radius/index.ts
@@ -9,3 +9,5 @@ export * from "./reviewers-table";
export * from "./test-gaps-list";
export * from "./blast-radius-summary";
export * from "./blast-radius-results";
+export * from "./impact-adapter";
+export * from "./impact-view";
diff --git a/packages/ui/src/c4/index.ts b/packages/ui/src/c4/index.ts
index 3cf7f1747..de1194c83 100644
--- a/packages/ui/src/c4/index.ts
+++ b/packages/ui/src/c4/index.ts
@@ -79,6 +79,7 @@ export {
ArchBreadcrumb,
ArchLegend,
PersonaSelector,
+ ArchTourButton,
CodeViewer,
getLanguageFromPath,
NodeTooltip,
diff --git a/packages/ui/src/c4/panels/ArchTourButton.tsx b/packages/ui/src/c4/panels/ArchTourButton.tsx
new file mode 100644
index 000000000..ab5dedde1
--- /dev/null
+++ b/packages/ui/src/c4/panels/ArchTourButton.tsx
@@ -0,0 +1,54 @@
+"use client";
+
+import { useCallback, useEffect, useState } from "react";
+import { Compass } from "lucide-react";
+import { useArchitectureStore } from "../store/use-architecture-store";
+
+// First-visit discoverability flag: the pill stays highlighted until the tour
+// has been taken once on this device.
+const TOUR_SEEN_KEY = "repowise:arch-tour-seen";
+
+/**
+ * "Take the tour" trigger for the layered architecture view.
+ *
+ * Promoted out of the per-app host so both apps get the same walkthrough from
+ * one source: it reads the curated tour off the shared architecture store and
+ * drives the store's tour player. Renders nothing when the view has no tour
+ * steps (or while a tour is already running), so a host whose view carries no
+ * tour degrades to no button rather than erroring — the host just mounts it
+ * unconditionally next to the other view controls.
+ */
+export function ArchTourButton() {
+ const view = useArchitectureStore((s) => s.view);
+ const tourActive = useArchitectureStore((s) => s.tourActive);
+ const startTour = useArchitectureStore((s) => s.startTour);
+
+ // Highlighted until first taken (localStorage flag). Defaults to "seen" so the
+ // accent treatment never flashes before the flag is read on the client.
+ const [tourSeen, setTourSeen] = useState(true);
+ useEffect(() => {
+ setTourSeen(localStorage.getItem(TOUR_SEEN_KEY) === "1");
+ }, []);
+
+ const handleStartTour = useCallback(() => {
+ localStorage.setItem(TOUR_SEEN_KEY, "1");
+ setTourSeen(true);
+ startTour();
+ }, [startTour]);
+
+ if (!view || view.tour.length === 0 || tourActive) return null;
+
+ return (
+ <button
+ onClick={handleStartTour}
+ className={`flex items-center gap-1.5 rounded-full border px-3 py-1 text-xs font-medium transition-colors ${
+ tourSeen
+ ? "border-[var(--color-border-default)] text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] hover:bg-[var(--color-bg-elevated)]"
+ : "border-[var(--color-accent-primary)]/50 bg-[var(--color-accent-primary)]/10 text-[var(--color-accent-primary)] hover:bg-[var(--color-accent-primary)]/20"
+ }`}
+ >
+ <Compass className="h-3.5 w-3.5" />
+ Take the tour
+ </button>
+ );
+}
diff --git a/packages/ui/src/c4/panels/index.ts b/packages/ui/src/c4/panels/index.ts
index 2c7e6e756..3b85589de 100644
--- a/packages/ui/src/c4/panels/index.ts
+++ b/packages/ui/src/c4/panels/index.ts
@@ -25,6 +25,7 @@ export { FilterPanel } from "./FilterPanel";
export { NodeTypeCategoryFilters } from "./NodeTypeCategoryFilters";
export { LearnPanel } from "./LearnPanel";
export { PersonaSelector } from "./PersonaSelector";
+export { ArchTourButton } from "./ArchTourButton";
export { CodeViewer, getLanguageFromPath } from "./CodeViewer";
export type { CodeViewerProps } from "./CodeViewer";
export { PathFinderModal } from "./PathFinderModal";
diff --git a/packages/ui/src/dead-code/dead-code-adapter.ts b/packages/ui/src/dead-code/dead-code-adapter.ts
new file mode 100644
index 000000000..d59012884
--- /dev/null
+++ b/packages/ui/src/dead-code/dead-code-adapter.ts
@@ -0,0 +1,38 @@
+import type {
+ DeadCodeFinding,
+ DeadCodePatchInput,
+ DeadCodeSummary,
+} from "@repowise-dev/types/dead-code";
+
+/**
+ * App-injected data + navigation for the shared {@link DeadCodeView}.
+ *
+ * The view owns the composition — the safe-to-delete pile, the cluster
+ * rollups, the drill-down table, the optimistic patch/undo toast, bulk
+ * resolve, the "Propose cleanup" agent brief, and Re-analyze. The host
+ * supplies *how* to fetch/mutate and *where* file links go, so web and hosted
+ * render the same view from one source.
+ *
+ * Fetch methods are keyed off `cacheKey` for SWR, so a page-level fetch that
+ * shares a key dedupes onto the same request.
+ */
+export interface DeadCodeAdapter {
+ /** Seeds the view's SWR cache keys — keep it stable per repo/snapshot. */
+ cacheKey: string;
+ /** Repo base used by the findings table to build per-row action links. */
+ repoId: string;
+
+ getSummary(): Promise<DeadCodeSummary>;
+ listFindings(opts?: { limit?: number }): Promise<DeadCodeFinding[]>;
+ /** Kick off a fresh analysis pass (host owns auth + job dispatch). */
+ analyze(): Promise<void>;
+ patchFinding(
+ findingId: string,
+ patch: DeadCodePatchInput,
+ ): Promise<DeadCodeFinding>;
+
+ /** Build an href to a file detail page. */
+ fileHref(path: string): string;
+ /** Navigate to an href (host wires this to its router). */
+ navigate(href: string): void;
+}
diff --git a/packages/ui/src/dead-code/dead-code-view.tsx b/packages/ui/src/dead-code/dead-code-view.tsx
new file mode 100644
index 000000000..ee3684588
--- /dev/null
+++ b/packages/ui/src/dead-code/dead-code-view.tsx
@@ -0,0 +1,232 @@
+"use client";
+
+/**
+ * Dead Code view — the safe-to-delete pile (the "what do I delete" punchline),
+ * optional cluster rollups behind progressive disclosure, and the full
+ * drill-down table with its single confidence control. Carries the optimistic
+ * row patch + Undo toast, bulk resolve, the "Propose cleanup" agent brief, and
+ * Re-analyze.
+ *
+ * Presentation + orchestration only: the host injects data fetching,
+ * mutations, links, and navigation through a {@link DeadCodeAdapter}, so web
+ * and hosted render the same view from one source.
+ */
+
+import { useState } from "react";
+import useSWR from "swr";
+import { toast } from "sonner";
+import type {
+ DeadCodeFinding,
+ DeadCodeStatus,
+ DeadCodeSummary,
+} from "@repowise-dev/types/dead-code";
+
+import { Button } from "../ui/button";
+import { Skeleton } from "../ui/skeleton";
+import { CollapsibleSection } from "../shared/collapsible-section";
+import { AiPromptModal } from "../health/ai-prompt-modal";
+import { buildDeadCodeAiPrompt } from "../health/ai-prompt-builder";
+
+import { SummaryBar } from "./summary-bar";
+import { SafeToDeletePile } from "./safe-to-delete-pile";
+import { OwnerLeaderboard } from "./owner-leaderboard";
+import { FindingsBreakdownGrid } from "./findings-breakdown-grid";
+import { FindingsTable } from "./findings-table";
+import type { DeadCodeAdapter } from "./dead-code-adapter";
+
+export function DeadCodeView({ adapter }: { adapter: DeadCodeAdapter }) {
+ const [analyzing, setAnalyzing] = useState(false);
+ const [promptIds, setPromptIds] = useState<string[] | null>(null);
+
+ const {
+ data: summary,
+ isLoading: loadingSummary,
+ error: summaryError,
+ mutate: mutateSummary,
+ } = useSWR<DeadCodeSummary>(
+ `dead-code-summary:${adapter.cacheKey}`,
+ () => adapter.getSummary(),
+ { revalidateOnFocus: false },
+ );
+
+ // Single findings fetch feeds the pile, the cluster views, AND the drill-down
+ // table (which filters this slice client-side) — no second fetch.
+ const { data: findings, isLoading: loadingFindings } = useSWR<DeadCodeFinding[]>(
+ `dead-code-findings:${adapter.cacheKey}:all`,
+ () => adapter.listFindings({ limit: 500 }),
+ { revalidateOnFocus: false },
+ );
+
+ const findingsList = findings ?? [];
+ const safeFindings = findingsList.filter((f) => f.safe_to_delete);
+
+ // "Propose cleanup" opens the shared AI-prompt modal seeded with the safe
+ // pile — same agent-flavor picker (incl. repowise MCP) and copy affordance as
+ // every other AI action in the dashboard.
+ const handlePropose = (findingIds: string[]) => setPromptIds(findingIds);
+
+ const promptFindings = promptIds
+ ? safeFindings.filter((f) => promptIds.includes(f.id))
+ : [];
+
+ const handleAnalyze = async () => {
+ setAnalyzing(true);
+ try {
+ await adapter.analyze();
+ toast.success("Analysis started — results will appear shortly.");
+ } catch (err) {
+ toast.error(
+ err instanceof Error
+ ? `Couldn't start analysis: ${err.message}`
+ : "Couldn't start analysis",
+ );
+ } finally {
+ setAnalyzing(false);
+ }
+ };
+
+ // Row-level patch with optimistic undo toast; injected into the table.
+ const handlePatch = async (id: string, patch: { status: DeadCodeStatus }) => {
+ const finding = findingsList.find((f) => f.id === id);
+ const previousStatus: DeadCodeStatus = finding?.status ?? "open";
+ const updated = await adapter.patchFinding(id, patch);
+ toast.success(`Finding ${patch.status.replace(/_/g, " ")}`, {
+ action: {
+ label: "Undo",
+ onClick: async () => {
+ try {
+ await adapter.patchFinding(id, { status: previousStatus });
+ } catch (err) {
+ toast.error(
+ err instanceof Error ? `Couldn't undo: ${err.message}` : "Couldn't undo",
+ );
+ }
+ },
+ },
+ duration: 6000,
+ });
+ return updated;
+ };
+
+ const handleBulkResolve = async (ids: string[]) => {
+ const succeededIds: string[] = [];
+ for (const id of ids) {
+ try {
+ await adapter.patchFinding(id, { status: "resolved" });
+ succeededIds.push(id);
+ } catch {
+ // continue; report partial below
+ }
+ }
+ const succeeded = succeededIds.length;
+ if (succeeded === ids.length) {
+ toast.success(`Resolved ${succeeded} finding${succeeded === 1 ? "" : "s"}`);
+ } else if (succeeded > 0) {
+ toast.warning(`Resolved ${succeeded} of ${ids.length}; some failed`);
+ } else {
+ toast.error("Couldn't resolve findings");
+ }
+ return succeededIds;
+ };
+
+ return (
+ <div className="space-y-6">
+ <div className="flex items-center justify-end">
+ <Button size="sm" variant="outline" onClick={handleAnalyze} disabled={analyzing}>
+ {analyzing ? "Starting…" : "Re-analyze"}
+ </Button>
+ </div>
+
+ {loadingSummary ? (
+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
+ {Array.from({ length: 4 }).map((_, i) => (
+ <Skeleton key={i} className="h-24 w-full rounded-lg" />
+ ))}
+ </div>
+ ) : summary ? (
+ <SummaryBar summary={summary} />
+ ) : summaryError ? (
+ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-4 text-sm text-[var(--color-text-secondary)] flex items-center justify-between gap-2">
+ <span>Couldn&apos;t load summary.</span>
+ <Button size="sm" variant="outline" onClick={() => mutateSummary()}>
+ Retry
+ </Button>
+ </div>
+ ) : null}
+
+ {/* Act now: the single "what do I delete" surface. */}
+ {findings && safeFindings.length > 0 && (
+ <SafeToDeletePile
+ findings={safeFindings}
+ onPropose={handlePropose}
+ onSelect={(f) => adapter.navigate(adapter.fileHref(f.file_path))}
+ {...(summary ? { reclaimableLines: summary.deletable_lines } : {})}
+ />
+ )}
+
+ {/* Where it clusters — optional rollups, collapsed by default so the spine
+ stays pile → drill-down. */}
+ {findingsList.length > 0 && (
+ <CollapsibleSection
+ title="Where it clusters"
+ hint="By owner and confidence × kind"
+ defaultOpen={false}
+ >
+ <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
+ <div>
+ <p className="mb-2 text-xs text-[var(--color-text-tertiary)]">
+ Reclaimable lines per primary contributor — who has the most cleanup leverage.
+ </p>
+ <OwnerLeaderboard findings={findingsList} safeOnly />
+ </div>
+ <div>
+ <p className="mb-2 text-xs text-[var(--color-text-tertiary)]">
+ Where findings concentrate — start with high-confidence cells.
+ </p>
+ <FindingsBreakdownGrid findings={findingsList} />
+ </div>
+ </div>
+ </CollapsibleSection>
+ )}
+
+ {/* Drill-down: the full interactive table, the single confidence control. */}
+ <CollapsibleSection
+ title="All findings"
+ hint={`${findingsList.length} findings`}
+ defaultOpen={false}
+ >
+ <FindingsTable
+ findings={findingsList}
+ repoId={adapter.repoId}
+ onPatch={handlePatch}
+ onBulkResolve={handleBulkResolve}
+ isLoading={loadingFindings}
+ />
+ </CollapsibleSection>
+
+ <AiPromptModal
+ open={promptIds !== null}
+ onOpenChange={(o) => !o && setPromptIds(null)}
+ getPrompt={
+ promptFindings.length > 0
+ ? (flavor) =>
+ buildDeadCodeAiPrompt({
+ findings: promptFindings.map((f) => ({
+ file_path: f.file_path,
+ symbol_name: f.symbol_name,
+ kind: f.kind,
+ reason: f.reason,
+ lines: f.lines,
+ confidence: f.confidence,
+ risk_factors: f.risk_factors ?? null,
+ })),
+ flavor,
+ })
+ : null
+ }
+ title="AI cleanup prompt"
+ description="A ready-to-paste prompt that has your AI agent verify and remove this dead-code pile safely, in reviewable commits."
+ />
+ </div>
+ );
+}
diff --git a/packages/ui/src/dead-code/index.ts b/packages/ui/src/dead-code/index.ts
index d43404fe3..61c0f0dcd 100644
--- a/packages/ui/src/dead-code/index.ts
+++ b/packages/ui/src/dead-code/index.ts
@@ -4,3 +4,5 @@ export * from "./owner-leaderboard";
export * from "./findings-breakdown-grid";
export * from "./findings-table";
export * from "./finding-row";
+export * from "./dead-code-adapter";
+export * from "./dead-code-view";
diff --git a/packages/ui/src/decisions/decision-detail-adapter.ts b/packages/ui/src/decisions/decision-detail-adapter.ts
new file mode 100644
index 000000000..ed2cebb27
--- /dev/null
+++ b/packages/ui/src/decisions/decision-detail-adapter.ts
@@ -0,0 +1,56 @@
+import type { ElementType, ReactNode } from "react";
+import type {
+ DecisionEvidence,
+ DecisionLineageEntry,
+ DecisionStatusUpdate,
+} from "@repowise-dev/types/decisions";
+
+/** Link element the host injects (e.g. `next/link`); defaults to `<a>`. */
+export type DecisionLinkComponent = ElementType<{
+ href: string;
+ className?: string;
+ "aria-label"?: string;
+ children: ReactNode;
+}>;
+
+/**
+ * App-injected data + navigation + slots for the shared {@link DecisionDetail}.
+ *
+ * The view owns the composition — the markdown body, evolution lineage, the
+ * writable module-link editor, the evidence drawer, the AI verification prompt,
+ * and the confirm/undo status actions. The host supplies *how* to fetch/mutate,
+ * *where* links go, and an optional linked-issues panel (e.g. Jira), so web and
+ * hosted render the same view from one source.
+ */
+export interface DecisionDetailAdapter {
+ /** Seeds the view's SWR cache keys — keep it stable per repo + decision. */
+ cacheKey: string;
+ repoId: string;
+ /** Prefix for the evolution lineage links; defaults to `/repos/{repoId}`. */
+ linkPrefix?: string;
+
+ /** Supersession/evolution chain, ordered root -> current. */
+ getLineage(): Promise<DecisionLineageEntry[]>;
+ /** Evidence rows backing the decision — fetched lazily when the drawer opens. */
+ getEvidence(): Promise<DecisionEvidence[]>;
+ /** Sibling ids in list order, for prev/next navigation. */
+ listSiblingIds(): Promise<string[]>;
+ /** Module-path suggestions for the linkage editor autocomplete. */
+ listModuleSuggestions(): Promise<string[]>;
+ /** Persist a status and/or linkage change. */
+ patchDecision(patch: DecisionStatusUpdate): Promise<void>;
+
+ /** href to the decisions list. */
+ decisionsHref(): string;
+ /** href to a sibling decision. */
+ decisionHref(decisionId: string): string;
+ /** href to the commits view, optionally filtered to a commit or sort. */
+ commitsHref(opts?: { commit?: string; sort?: string }): string;
+ /** href to the hotspots/churn view for the affected areas. */
+ hotspotsHref(): string;
+
+ /** Link element for internal navigation. Defaults to `<a>`. */
+ LinkComponent?: DecisionLinkComponent;
+ /** Optional linked-issues panel (e.g. Jira). Host supplies or omits. */
+ renderLinkedIssues?(): ReactNode;
+}
diff --git a/packages/ui/src/decisions/decision-detail.tsx b/packages/ui/src/decisions/decision-detail.tsx
new file mode 100644
index 000000000..c0933bd9f
--- /dev/null
+++ b/packages/ui/src/decisions/decision-detail.tsx
@@ -0,0 +1,522 @@
+"use client";
+
+/**
+ * Decision detail view — the full record: markdown body (context / decision /
+ * rationale / alternatives / consequences), evolution lineage, a writable
+ * module-link editor, the evidence drawer, the AI verification prompt, and the
+ * confirm/undo status actions (confirm-proposed, deprecate-active).
+ *
+ * Presentation + orchestration only: the host injects data fetching,
+ * mutations, links, and an optional linked-issues panel through a
+ * {@link DecisionDetailAdapter}, so web and hosted render the same view.
+ */
+
+import * as React from "react";
+import ReactMarkdown from "react-markdown";
+import remarkGfm from "remark-gfm";
+import useSWR from "swr";
+import { toast } from "sonner";
+import {
+ ChevronLeft,
+ ChevronRight,
+ FileSearch,
+ Flame,
+ GitCommitHorizontal,
+} from "lucide-react";
+import type {
+ DecisionRecord,
+ DecisionStatus,
+} from "@repowise-dev/types/decisions";
+
+import { Badge } from "../ui/badge";
+import { ConfirmDialog } from "../ui/confirm-dialog";
+import { stripMarkdown } from "../lib/format";
+import { AiPromptButton } from "../health/ai-prompt-button";
+import { AiPromptModal } from "../health/ai-prompt-modal";
+import { buildDecisionAiPrompt } from "../health/ai-prompt-builder";
+
+import { ModuleLinkEditor } from "./module-link-editor";
+import { VerificationBadge } from "./verification-badge";
+import { DecisionEvidenceDrawer } from "./decision-evidence-drawer";
+import { DecisionLineage } from "./decision-lineage";
+import type {
+ DecisionDetailAdapter,
+ DecisionLinkComponent,
+} from "./decision-detail-adapter";
+
+const STATUS_VARIANT: Record<
+ string,
+ "default" | "fresh" | "stale" | "outdated" | "outline" | "accent"
+> = {
+ active: "fresh",
+ proposed: "accent",
+ deprecated: "outdated",
+ superseded: "outline",
+};
+
+const CONFIRM_COPY: Record<
+ string,
+ { title: string; description: string; confirmLabel: string; destructive: boolean }
+> = {
+ active: {
+ title: "Confirm decision?",
+ description: "Mark this decision as active.",
+ confirmLabel: "Confirm",
+ destructive: false,
+ },
+ deprecated: {
+ title: "Deprecate decision?",
+ description:
+ "This will mark the decision as deprecated. Existing references remain but it will no longer be considered current.",
+ confirmLabel: "Deprecate",
+ destructive: true,
+ },
+};
+
+export interface DecisionDetailProps {
+ decision: DecisionRecord;
+ adapter: DecisionDetailAdapter;
+}
+
+export function DecisionDetail({ decision, adapter }: DecisionDetailProps) {
+ const Link: DecisionLinkComponent = adapter.LinkComponent ?? "a";
+
+ const [status, setStatus] = React.useState<DecisionStatus>(decision.status);
+ const [loading, setLoading] = React.useState(false);
+ const [pendingStatus, setPendingStatus] = React.useState<DecisionStatus | null>(null);
+ const [linkedModules, setLinkedModules] = React.useState(decision.affected_modules);
+ const [linkedFiles, setLinkedFiles] = React.useState(decision.affected_files);
+ const [linkageSaving, setLinkageSaving] = React.useState(false);
+ const [evidenceOpen, setEvidenceOpen] = React.useState(false);
+ const [promptOpen, setPromptOpen] = React.useState(false);
+
+ // Lineage: cheap, load eagerly so the Evolution timeline renders when present.
+ const { data: lineage } = useSWR(
+ `decision-lineage:${adapter.cacheKey}`,
+ () => adapter.getLineage(),
+ { revalidateOnFocus: false },
+ );
+
+ // Evidence: lazy — only fetched once the drawer is opened.
+ const {
+ data: evidence,
+ error: evidenceError,
+ isLoading: evidenceLoading,
+ } = useSWR(
+ evidenceOpen ? `decision-evidence:${adapter.cacheKey}` : null,
+ () => adapter.getEvidence(),
+ { revalidateOnFocus: false },
+ );
+
+ // Sibling list for prev/next navigation — same ordering as the list page.
+ const { data: siblings } = useSWR(
+ `decisions-siblings:${adapter.repoId}`,
+ () => adapter.listSiblingIds(),
+ { revalidateOnFocus: false },
+ );
+ const { prevId, nextId } = React.useMemo(() => {
+ const ids = siblings ?? [];
+ const idx = ids.indexOf(decision.id);
+ return {
+ prevId: idx > 0 ? ids[idx - 1] : null,
+ nextId: idx >= 0 && idx < ids.length - 1 ? ids[idx + 1] : null,
+ };
+ }, [siblings, decision.id]);
+
+ // Suggestions for the module autocomplete — top-level modules indexed for
+ // this repo. Loaded once; cheap to cache.
+ const { data: moduleSuggestions } = useSWR(
+ `module-health-suggestions:${adapter.repoId}`,
+ () => adapter.listModuleSuggestions(),
+ { revalidateOnFocus: false },
+ );
+
+ const saveLinkage = async (next: { modules: string[]; files: string[] }) => {
+ const previousModules = linkedModules;
+ const previousFiles = linkedFiles;
+ setLinkageSaving(true);
+ try {
+ await adapter.patchDecision({
+ affected_modules: next.modules,
+ affected_files: next.files,
+ });
+ setLinkedModules(next.modules);
+ setLinkedFiles(next.files);
+ toast.success("Decision linkage updated", {
+ action: {
+ label: "Undo",
+ onClick: async () => {
+ try {
+ await adapter.patchDecision({
+ affected_modules: previousModules,
+ affected_files: previousFiles,
+ });
+ setLinkedModules(previousModules);
+ setLinkedFiles(previousFiles);
+ } catch (err) {
+ toast.error(
+ err instanceof Error ? `Couldn't undo: ${err.message}` : "Couldn't undo",
+ );
+ }
+ },
+ },
+ duration: 6000,
+ });
+ } catch (err) {
+ toast.error(
+ err instanceof Error
+ ? `Couldn't save linkage: ${err.message}`
+ : "Couldn't save linkage",
+ );
+ } finally {
+ setLinkageSaving(false);
+ }
+ };
+
+ const applyStatusChange = async (newStatus: DecisionStatus) => {
+ const previous = status;
+ setLoading(true);
+ try {
+ await adapter.patchDecision({ status: newStatus });
+ setStatus(newStatus);
+ setPendingStatus(null);
+ toast.success(`Decision marked ${newStatus.replace(/_/g, " ")}`, {
+ action: {
+ label: "Undo",
+ onClick: async () => {
+ try {
+ await adapter.patchDecision({ status: previous });
+ setStatus(previous);
+ } catch (err) {
+ toast.error(
+ err instanceof Error ? `Couldn't undo: ${err.message}` : "Couldn't undo",
+ );
+ }
+ },
+ },
+ duration: 6000,
+ });
+ } catch (err) {
+ toast.error(
+ err instanceof Error
+ ? `Couldn't update decision: ${err.message}`
+ : "Couldn't update decision",
+ );
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ const handleStatusChange = (newStatus: DecisionStatus) => {
+ if (CONFIRM_COPY[newStatus]) {
+ setPendingStatus(newStatus);
+ } else {
+ void applyStatusChange(newStatus);
+ }
+ };
+
+ const confirmConfig = pendingStatus ? CONFIRM_COPY[pendingStatus] : null;
+ const linkedIssues = adapter.renderLinkedIssues?.();
+
+ return (
+ <div className="space-y-6">
+ <div className="flex items-center justify-between gap-2">
+ <Link
+ href={adapter.decisionsHref()}
+ className="inline-flex items-center gap-1 text-xs text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)]"
+ >
+ <ChevronLeft className="h-3.5 w-3.5" />
+ All decisions
+ </Link>
+ <div className="flex items-center gap-1">
+ <PrevNextLink
+ Link={Link}
+ href={prevId ? adapter.decisionHref(prevId) : null}
+ label="Previous decision"
+ >
+ <ChevronLeft className="h-3.5 w-3.5" /> Prev
+ </PrevNextLink>
+ <PrevNextLink
+ Link={Link}
+ href={nextId ? adapter.decisionHref(nextId) : null}
+ label="Next decision"
+ >
+ Next <ChevronRight className="h-3.5 w-3.5" />
+ </PrevNextLink>
+ </div>
+ </div>
+ {/* Header */}
+ <div className="space-y-2">
+ <div className="flex flex-wrap items-center gap-3">
+ <h1 className="text-xl font-semibold text-[var(--color-text-primary)]">
+ {stripMarkdown(decision.title)}
+ </h1>
+ <Badge variant={STATUS_VARIANT[status] ?? "outline"}>{status}</Badge>
+ {decision.verification && (
+ <VerificationBadge verification={decision.verification} />
+ )}
+ <AiPromptButton
+ label={status === "proposed" ? "Verify & confirm with AI" : "Verify with AI"}
+ onClick={() => setPromptOpen(true)}
+ className="ml-auto"
+ />
+ <button
+ type="button"
+ onClick={() => setEvidenceOpen(true)}
+ className="inline-flex items-center gap-1.5 rounded-md border border-[var(--color-border-default)] px-2.5 py-1 text-xs text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)]"
+ >
+ <FileSearch className="h-3.5 w-3.5" />
+ Evidence
+ </button>
+ </div>
+ <div className="flex gap-4 text-sm text-[var(--color-text-tertiary)]">
+ <span>Source: {decision.source}</span>
+ <span>Confidence: {Math.round(decision.confidence * 100)}%</span>
+ {decision.staleness_score > 0 && (
+ <span className={decision.staleness_score > 0.5 ? "text-[var(--color-error)]" : ""}>
+ Staleness: {decision.staleness_score.toFixed(2)}
+ </span>
+ )}
+ <span>Created: {new Date(decision.created_at).toLocaleDateString()}</span>
+ </div>
+ </div>
+
+ {/* Stale warning */}
+ {decision.staleness_score > 0.5 && (
+ <div className="rounded-md border border-[var(--color-warning)]/30 bg-[var(--color-warning)]/10 px-4 py-3 text-sm text-[var(--color-warning)]">
+ This decision may be stale — affected files have changed significantly since it was recorded.
+ </div>
+ )}
+
+ {/* Evolution / lineage chain */}
+ {lineage && lineage.length > 1 && (
+ <DecisionLineage
+ lineage={lineage}
+ repoId={adapter.repoId}
+ LinkComponent={Link}
+ {...(adapter.linkPrefix ? { linkPrefix: adapter.linkPrefix } : {})}
+ />
+ )}
+
+ {/* Content sections */}
+ <div className="space-y-4">
+ {decision.context && <Section title="Context" text={decision.context} />}
+ {decision.decision && <Section title="Decision" text={decision.decision} />}
+ {decision.rationale && <Section title="Rationale" text={decision.rationale} />}
+ {decision.alternatives.length > 0 && (
+ <ListSection title="Alternatives Rejected" items={decision.alternatives} />
+ )}
+ {decision.consequences.length > 0 && (
+ <ListSection title="Consequences & Tradeoffs" items={decision.consequences} />
+ )}
+ </div>
+
+ {/* Governance linkage — writable editor + evidence card */}
+ <div className="grid gap-4 sm:grid-cols-2">
+ <ModuleLinkEditor
+ modules={linkedModules}
+ files={linkedFiles}
+ suggestions={moduleSuggestions ?? []}
+ saving={linkageSaving}
+ onSave={saveLinkage}
+ />
+
+ {/* The full evidence rows live in the drawer (Evidence button); this
+ card answers "what happened to the governed code since?". */}
+ <div className="rounded-lg border border-[var(--color-border-default)] p-4">
+ <h3 className="mb-2 text-sm font-medium text-[var(--color-text-secondary)]">
+ Since this decision
+ </h3>
+ <div className="space-y-2 text-sm">
+ {decision.last_code_change && (
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ Affected files last changed{" "}
+ {new Date(decision.last_code_change).toLocaleDateString()}.
+ </p>
+ )}
+ <div className="flex flex-col gap-1.5">
+ <Link
+ href={adapter.commitsHref({ sort: "date" })}
+ className="inline-flex items-center gap-1.5 text-xs text-[var(--color-text-secondary)] hover:text-[var(--color-accent-primary)] hover:underline"
+ >
+ <GitCommitHorizontal className="h-3.5 w-3.5" />
+ Recent commits to this repo
+ </Link>
+ <Link
+ href={adapter.hotspotsHref()}
+ className="inline-flex items-center gap-1.5 text-xs text-[var(--color-text-secondary)] hover:text-[var(--color-accent-primary)] hover:underline"
+ >
+ <Flame className="h-3.5 w-3.5" />
+ Hotspots &amp; churn in affected areas
+ </Link>
+ </div>
+ {decision.evidence_commits.length > 0 && (
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ Evidence commits:{" "}
+ {decision.evidence_commits.slice(0, 4).map((c, i) => (
+ <React.Fragment key={c}>
+ {i > 0 && ", "}
+ <Link
+ href={adapter.commitsHref({ commit: c })}
+ className="font-mono hover:text-[var(--color-accent-primary)] hover:underline"
+ >
+ {c.slice(0, 8)}
+ </Link>
+ </React.Fragment>
+ ))}
+ </p>
+ )}
+ </div>
+ </div>
+ </div>
+
+ {/* Optional linked issues (e.g. Jira) — host supplies or omits. */}
+ {linkedIssues}
+
+ {/* Tags */}
+ {decision.tags.length > 0 && (
+ <div className="flex flex-wrap gap-1.5">
+ {decision.tags.map((tag) => (
+ <span
+ key={tag}
+ className="inline-block rounded-full bg-[var(--color-bg-elevated)] px-2.5 py-0.5 text-xs font-medium text-[var(--color-text-secondary)]"
+ >
+ {tag}
+ </span>
+ ))}
+ </div>
+ )}
+
+ {/* Actions */}
+ <div className="flex gap-2 border-t border-[var(--color-border-default)] pt-4">
+ {status === "proposed" && (
+ <>
+ <button
+ onClick={() => handleStatusChange("active")}
+ disabled={loading}
+ className="rounded-md bg-[var(--color-success)] px-3 py-1.5 text-sm font-medium text-[var(--color-text-inverse)] hover:opacity-90 disabled:opacity-50"
+ >
+ Confirm
+ </button>
+ <button
+ onClick={() => handleStatusChange("deprecated")}
+ disabled={loading}
+ className="rounded-md border border-[var(--color-border-default)] px-3 py-1.5 text-sm text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] disabled:opacity-50"
+ >
+ Dismiss
+ </button>
+ </>
+ )}
+ {status === "active" && (
+ <button
+ onClick={() => handleStatusChange("deprecated")}
+ disabled={loading}
+ className="rounded-md border border-[var(--color-error)]/40 px-3 py-1.5 text-sm text-[var(--color-error)] hover:bg-[var(--color-error)]/10 disabled:opacity-50"
+ >
+ Deprecate
+ </button>
+ )}
+ </div>
+ {confirmConfig && (
+ <ConfirmDialog
+ open={pendingStatus !== null}
+ onOpenChange={(o) => !o && setPendingStatus(null)}
+ title={confirmConfig.title}
+ description={confirmConfig.description}
+ confirmLabel={confirmConfig.confirmLabel}
+ destructive={confirmConfig.destructive}
+ loading={loading}
+ onConfirm={() => void applyStatusChange(pendingStatus!)}
+ />
+ )}
+
+ <DecisionEvidenceDrawer
+ open={evidenceOpen}
+ onClose={() => setEvidenceOpen(false)}
+ evidence={evidence}
+ isLoading={evidenceLoading}
+ error={evidenceError}
+ decisionTitle={decision.title}
+ />
+
+ <AiPromptModal
+ open={promptOpen}
+ onOpenChange={setPromptOpen}
+ getPrompt={(flavor) =>
+ buildDecisionAiPrompt({
+ decision: {
+ title: decision.title,
+ status,
+ context: decision.context,
+ decision: decision.decision,
+ rationale: decision.rationale,
+ alternatives: decision.alternatives,
+ consequences: decision.consequences,
+ affected_modules: linkedModules,
+ affected_files: linkedFiles,
+ staleness_score: decision.staleness_score,
+ confidence: decision.confidence,
+ },
+ flavor,
+ })
+ }
+ filePath={stripMarkdown(decision.title)}
+ title="AI decision verification"
+ description="A ready-to-paste prompt that has your AI agent check this decision against the current code and recommend whether to keep, update, or retire it."
+ />
+ </div>
+ );
+}
+
+function PrevNextLink({
+ Link,
+ href,
+ label,
+ children,
+}: {
+ Link: DecisionLinkComponent;
+ href: string | null;
+ label: string;
+ children: React.ReactNode;
+}) {
+ if (!href) {
+ return (
+ <span className="inline-flex items-center gap-0.5 rounded-md border border-[var(--color-border-default)] px-2 py-1 text-xs text-[var(--color-text-tertiary)] opacity-50">
+ {children}
+ </span>
+ );
+ }
+ return (
+ <Link
+ href={href}
+ aria-label={label}
+ className="inline-flex items-center gap-0.5 rounded-md border border-[var(--color-border-default)] px-2 py-1 text-xs text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]"
+ >
+ {children}
+ </Link>
+ );
+}
+
+function Section({ title, text }: { title: string; text: string }) {
+ return (
+ <div>
+ <h3 className="mb-1 text-sm font-medium text-[var(--color-text-secondary)]">{title}</h3>
+ <div className="text-sm text-[var(--color-text-primary)] leading-relaxed prose prose-sm prose-invert max-w-none [&>p]:mb-2 [&>p:last-child]:mb-0">
+ <ReactMarkdown remarkPlugins={[remarkGfm]}>{text}</ReactMarkdown>
+ </div>
+ </div>
+ );
+}
+
+function ListSection({ title, items }: { title: string; items: string[] }) {
+ return (
+ <div>
+ <h3 className="mb-1 text-sm font-medium text-[var(--color-text-secondary)]">{title}</h3>
+ <ul className="list-disc space-y-0.5 pl-5 text-sm text-[var(--color-text-primary)]">
+ {items.map((item, i) => (
+ <li key={i}>{item}</li>
+ ))}
+ </ul>
+ </div>
+ );
+}
diff --git a/packages/ui/src/decisions/index.ts b/packages/ui/src/decisions/index.ts
index c0d4878b1..676704866 100644
--- a/packages/ui/src/decisions/index.ts
+++ b/packages/ui/src/decisions/index.ts
@@ -4,3 +4,5 @@ export * from "./verification-badge";
export * from "./decision-evidence-drawer";
export * from "./decision-lineage";
export * from "./decision-graph-view";
+export * from "./decision-detail-adapter";
+export * from "./decision-detail";
diff --git a/packages/ui/src/graph/graph-flow.tsx b/packages/ui/src/graph/graph-flow.tsx
index 6dd903d4b..a66fc10b5 100644
--- a/packages/ui/src/graph/graph-flow.tsx
+++ b/packages/ui/src/graph/graph-flow.tsx
@@ -102,9 +102,15 @@ export interface GraphFlowProps {
communities?: CommunitySummaryItem[];
executionFlows?: ExecutionFlows;
initialViewMode?: ViewMode;
- /** Initial node color mode. Hosts derive this from their URL state instead
- * of the component reading window.location. */
+ /** Initial node color mode (uncontrolled seed). Hosts derive this from their
+ * URL state instead of the component reading window.location. Ignored when
+ * {@link colorMode} is supplied. */
initialColorMode?: ColorMode;
+ /** Controlled node color mode. When supplied, the host owns the value (and
+ * typically URL-syncs it); the component reflects it directly and reports
+ * user changes via {@link onColorModeChange}. Omit to let the component
+ * track its own color mode seeded by {@link initialColorMode}. */
+ colorMode?: ColorMode;
initialSelectedNode?: string | null;
onViewModeChange?: (mode: ViewMode) => void;
/** Fired when the node color mode changes (toolbar or 1/2/3 shortcut) so
@@ -162,6 +168,7 @@ export function GraphFlow(props: GraphFlowProps) {
executionFlows,
initialViewMode,
initialColorMode,
+ colorMode: controlledColorMode,
initialSelectedNode,
onViewModeChange,
onColorModeChange,
@@ -183,7 +190,21 @@ export function GraphFlow(props: GraphFlowProps) {
// ---- Core state ----
// Default scope is the constellation (radial Knowledge Graph).
const [viewMode, setViewMode] = useState<ViewMode>(initialViewMode ?? "architecture");
- const [colorMode, setColorMode] = useState<ColorMode>(initialColorMode ?? "community");
+ // Color mode is controlled by the host when `colorMode` is supplied
+ // (URL-synced); otherwise the component tracks it locally, seeded by
+ // `initialColorMode`. The wrapped setter routes through the host callback in
+ // controlled mode and falls back to local state in uncontrolled mode.
+ const [colorModeState, setColorModeState] = useState<ColorMode>(
+ initialColorMode ?? "community",
+ );
+ const colorMode = controlledColorMode ?? colorModeState;
+ const setColorMode = useCallback(
+ (next: ColorMode) => {
+ if (onColorModeChange) onColorModeChange(next);
+ else setColorModeState(next);
+ },
+ [onColorModeChange],
+ );
const [highlightedPath, setHighlightedPath] = useState<Set<string>>(new Set());
const [highlightedEdges, setHighlightedEdges] = useState<Set<string>>(new Set());
const [showPathFinder, setShowPathFinder] = useState(false);
@@ -861,18 +882,6 @@ export function GraphFlow(props: GraphFlowProps) {
onToggleHelp: handleToggleShortcutHelp,
});
- // Surface color-mode changes (toolbar or 1/2/3 shortcut) to the host so it
- // can sync the URL. Skip the mount-time report — only real changes count.
- const colorModeReported = useRef(false);
- useEffect(() => {
- if (!colorModeReported.current) {
- colorModeReported.current = true;
- return;
- }
- onColorModeChange?.(colorMode);
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [colorMode]);
-
const handlePathFound = useCallback(
(pathNodes: string[]) => {
setHighlightedPath(new Set(pathNodes));
diff --git a/packages/ui/src/graph/use-graph-keyboard-shortcuts.ts b/packages/ui/src/graph/use-graph-keyboard-shortcuts.ts
index 445d99bb1..e20c03b7a 100644
--- a/packages/ui/src/graph/use-graph-keyboard-shortcuts.ts
+++ b/packages/ui/src/graph/use-graph-keyboard-shortcuts.ts
@@ -10,7 +10,10 @@ interface GraphKeyboardShortcutOptions {
setSearchQuery: Dispatch<SetStateAction<string>>;
setCtxMenu: Dispatch<SetStateAction<GraphCtxMenu | null>>;
setCommunityPanelId: Dispatch<SetStateAction<number | null>>;
- setColorMode: Dispatch<SetStateAction<ColorMode>>;
+ /** Sets the active color mode. Accepts a concrete mode only (the shortcuts
+ * always pass a literal), so it composes with both the local state setter
+ * and a host-controlled setter. */
+ setColorMode: (mode: ColorMode) => void;
/** Optional Escape pre-handler. Return true to consume the keystroke and skip
* the default clear. Used to dismiss the top UI layer first: clear an open
* selection/panel, else collapse the most recent constellation hub. */
diff --git a/packages/ui/src/health/biomarker-list.tsx b/packages/ui/src/health/biomarker-list.tsx
index 8bd57ffa7..081d18f11 100644
--- a/packages/ui/src/health/biomarker-list.tsx
+++ b/packages/ui/src/health/biomarker-list.tsx
@@ -57,6 +57,16 @@ export interface BiomarkerListProps {
onPartnerHref?: ((path: string) => string) | undefined;
}
+/**
+ * Stable, collision-proof React key for a finding row. The API's `id` is not
+ * guaranteed unique within a list (the same symbol/file can surface more than
+ * once), so we compose it with the distinguishing fields and the render index
+ * as a final tiebreaker. Rows are stateless, so an index in the key is safe.
+ */
+function findingKey(f: BiomarkerFinding, index: number): string {
+ return `${f.id}:${f.biomarker_type}:${f.file_path}:${f.function_name ?? ""}:${index}`;
+}
+
export function BiomarkerList({
findings,
grouped = false,
@@ -84,9 +94,9 @@ export function BiomarkerList({
if (!grouped) {
return (
<ul className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] divide-y divide-[var(--color-border-default)]">
- {filtered.map((f) => (
+ {filtered.map((f, i) => (
<FindingRow
- key={f.id}
+ key={findingKey(f, i)}
finding={f}
onSelect={onSelect}
onPartnerSelect={onPartnerSelect}
@@ -144,12 +154,23 @@ function BiomarkerGroup({
const sevCounts = { critical: 0, high: 0, medium: 0, low: 0 } as Record<Severity, number>;
for (const f of findings) sevCounts[f.severity]++;
const visible = expanded ? findings : findings.slice(0, maxPerGroup);
+ const toggle = () => setExpanded((e) => !e);
return (
<div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)]">
- <button
- type="button"
- onClick={() => setExpanded((e) => !e)}
- className="flex w-full items-center gap-2 px-3 py-2 text-left hover:bg-[var(--color-bg-elevated)] transition-colors"
+ {/* role="button" rather than a real <button>: the header hosts an InfoTip,
+ which renders its own <button>, and a button can't nest a button. */}
+ <div
+ role="button"
+ tabIndex={0}
+ onClick={toggle}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" || e.key === " ") {
+ e.preventDefault();
+ toggle();
+ }
+ }}
+ aria-expanded={expanded}
+ className="flex w-full items-center gap-2 px-3 py-2 text-left cursor-pointer rounded-t-lg hover:bg-[var(--color-bg-elevated)] transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
>
{expanded ? (
<ChevronDown className="h-4 w-4 text-[var(--color-text-tertiary)]" />
@@ -182,11 +203,11 @@ function BiomarkerGroup({
{findings.length}
</span>
</span>
- </button>
+ </div>
<ul className="divide-y divide-[var(--color-border-default)] border-t border-[var(--color-border-default)]">
- {visible.map((f) => (
+ {visible.map((f, i) => (
<FindingRow
- key={f.id}
+ key={findingKey(f, i)}
finding={f}
onSelect={onSelect}
hideBiomarker
diff --git a/packages/ui/src/health/code-health-adapter.ts b/packages/ui/src/health/code-health-adapter.ts
new file mode 100644
index 000000000..10866c468
--- /dev/null
+++ b/packages/ui/src/health/code-health-adapter.ts
@@ -0,0 +1,78 @@
+import type { ReactNode } from "react";
+import type {
+ HealthCoverageResponse,
+ HealthFilesQuery,
+ HealthFilesResponse,
+ HealthFinding,
+ HealthOverviewResponse,
+ RefactoringQuery,
+ RefactoringTargetsResponse,
+} from "@repowise-dev/types/health";
+
+/** Subset of the findings list query the shared views need. */
+export interface CodeHealthFindingsQuery {
+ biomarker_type?: string;
+ file_path?: string;
+ min_severity?: string;
+ dimension?: string;
+ limit?: number;
+}
+
+export type FindingStatusValue =
+ | "open"
+ | "acknowledged"
+ | "resolved"
+ | "false_positive";
+
+/**
+ * App-injected data + navigation + slots for the shared Code Health views.
+ *
+ * The views own their layout, filter state, and fetch orchestration; the host
+ * supplies *how* to fetch and *where* links go. Web binds this to its `/api`
+ * client + `/repos/:id` routing; hosted binds it to the snapshot client + its
+ * own routing. One view, two adapters — no second copy.
+ *
+ * `repoId`/`getOverview` are bound by the host so the views never reference an
+ * app-specific data module. The methods are keyed off `cacheKey` for SWR, so
+ * page-level and view-level fetches that share a key dedupe onto one request.
+ */
+export interface CodeHealthAdapter {
+ /**
+ * Seeds the views' SWR cache keys. Keep it stable per repo/snapshot and
+ * identical to any key the host uses at the page level (e.g. a shared
+ * overview fetch) so the requests dedupe instead of doubling up.
+ */
+ cacheKey: string;
+
+ getOverview(limit: number): Promise<HealthOverviewResponse>;
+ listFindings(opts?: CodeHealthFindingsQuery): Promise<HealthFinding[]>;
+ listFiles(opts?: HealthFilesQuery): Promise<HealthFilesResponse>;
+ getRefactoringTargets(
+ opts?: RefactoringQuery,
+ ): Promise<RefactoringTargetsResponse>;
+ updateFindingStatus(
+ findingId: string,
+ status: FindingStatusValue,
+ ): Promise<HealthFinding>;
+ getCoverage(opts?: {
+ file_path?: string;
+ limit?: number;
+ }): Promise<HealthCoverageResponse>;
+
+ /** Build an href to a file detail page. */
+ fileHref(path: string): string;
+ /** Build an href to a symbol detail page, or `undefined` if not linkable. */
+ symbolHref?(symbolId: string): string | undefined;
+ /** Navigate to an href (host wires this to its router). */
+ navigate(href: string): void;
+
+ /**
+ * Render the app's file-detail drawer for the inspected path. Kept as a slot
+ * so each app supplies its own data fetch + toast wiring; pass `null` for
+ * `filePath` to render nothing.
+ */
+ renderFileDrawer(args: {
+ filePath: string | null;
+ onClose: () => void;
+ }): ReactNode;
+}
diff --git a/packages/ui/src/health/coverage-view.tsx b/packages/ui/src/health/coverage-view.tsx
new file mode 100644
index 000000000..7c3b3936f
--- /dev/null
+++ b/packages/ui/src/health/coverage-view.tsx
@@ -0,0 +1,388 @@
+"use client";
+
+/**
+ * Coverage view — test-coverage summary, risk × coverage scatter, untested
+ * hotspots (with the dependents/commit context from the findings), module
+ * rollup, and the per-file table. Rows link to the file page's coverage tab
+ * (line-level heatmap).
+ *
+ * Presentation + orchestration only: the host injects data fetching, links,
+ * and navigation through a {@link CodeHealthAdapter}.
+ */
+
+import { useMemo, useState } from "react";
+import { ArrowUpRight, Sparkles } from "lucide-react";
+import useSWR from "swr";
+import type {
+ CoverageFileRow,
+ HealthCoverageResponse,
+ HealthFinding,
+} from "@repowise-dev/types/health";
+
+import { Skeleton } from "../ui/skeleton";
+import { EmptyState } from "../shared/empty-state";
+import { ResponsiveTable, type ResponsiveColumn } from "../shared/responsive-table";
+import { MetricCard } from "../shared/metric-card";
+import { CollapsibleSection } from "../shared/collapsible-section";
+
+import { AiPromptModal } from "./ai-prompt-modal";
+import { CoverageBar } from "./coverage-bar";
+import { ModuleCoverageList } from "./module-coverage-list";
+import {
+ UntestedHotspotWarning,
+ type UntestedHotspotEntry,
+} from "./untested-hotspot-warning";
+import { RiskCoverageScatter } from "./risk-coverage-scatter";
+import {
+ buildCoverageAiPrompt,
+ type CoverageFilePromptInput,
+} from "./ai-prompt-builder";
+import { scoreBadgeClass } from "./tokens";
+import type { CodeHealthAdapter } from "./code-health-adapter";
+
+export function CoverageView({ adapter }: { adapter: CodeHealthAdapter }) {
+ const [promptRow, setPromptRow] = useState<CoverageFilePromptInput | null>(null);
+
+ const { data, isLoading, error } = useSWR<HealthCoverageResponse>(
+ `code-health-coverage:${adapter.cacheKey}`,
+ () => adapter.getCoverage({ limit: 1000 }),
+ { revalidateOnFocus: false },
+ );
+
+ // The untested_hotspot findings carry dependents_count / commit_count_90d
+ // in their details — join them into the warning entries.
+ const { data: untestedFindings } = useSWR<HealthFinding[]>(
+ `code-health-untested-findings:${adapter.cacheKey}`,
+ () =>
+ adapter
+ .listFindings({ biomarker_type: "untested_hotspot", limit: 50 })
+ .catch(() => []),
+ { revalidateOnFocus: false },
+ );
+
+ const openFilePage = (path: string) =>
+ adapter.navigate(`${adapter.fileHref(path)}?tab=coverage`);
+
+ return (
+ <div className="space-y-6">
+ {isLoading ? (
+ <CoverageSkeleton />
+ ) : error ? (
+ <EmptyState
+ title="Couldn't load coverage data"
+ description="The coverage endpoint returned an error. Try refreshing, or re-run the health pass."
+ />
+ ) : !data || data.summary.file_count === 0 ? (
+ <NoCoverageState />
+ ) : (
+ <CoverageBody
+ data={data}
+ untestedFindings={untestedFindings ?? []}
+ onOpenFile={openFilePage}
+ onGeneratePrompt={(r) => setPromptRow(r)}
+ />
+ )}
+
+ <AiPromptModal
+ open={promptRow !== null}
+ onOpenChange={(open) => {
+ if (!open) setPromptRow(null);
+ }}
+ filePath={promptRow?.file_path ?? null}
+ 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
+ }
+ />
+ </div>
+ );
+}
+
+function CoverageBody({
+ data,
+ untestedFindings,
+ onOpenFile,
+ onGeneratePrompt,
+}: {
+ data: HealthCoverageResponse;
+ untestedFindings: HealthFinding[];
+ onOpenFile: (path: string) => void;
+ onGeneratePrompt: (row: CoverageFilePromptInput) => void;
+}) {
+ const { summary, files, modules } = data;
+ const [search, setSearch] = useState("");
+
+ const num = (v: unknown): number | null =>
+ typeof v === "number" && Number.isFinite(v) ? v : null;
+
+ // 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 untested = useMemo<UntestedHotspotEntry[]>(() => {
+ const covByPath = new Map(files.map((f) => [f.file_path, f]));
+ if (untestedFindings.length > 0) {
+ return untestedFindings.slice(0, 10).map((f) => {
+ const cov = covByPath.get(f.file_path);
+ const d = f.details ?? {};
+ const entry: UntestedHotspotEntry = {
+ file_path: f.file_path,
+ line_coverage_pct:
+ num(d.line_coverage_pct) ?? cov?.line_coverage_pct ?? null,
+ commit_count_90d: num(d.commit_count_90d),
+ };
+ const dependents = num(d.dependents_count);
+ if (dependents != null) entry.dependents_count = dependents;
+ if (cov?.health_score != null) entry.health_score = cov.health_score;
+ return entry;
+ });
+ }
+ return files
+ .filter(
+ (f) =>
+ f.line_coverage_pct != null &&
+ f.line_coverage_pct < 30 &&
+ (f.health_score == null || f.health_score < 6),
+ )
+ .slice(0, 10)
+ .map((f) => {
+ const entry: UntestedHotspotEntry = {
+ file_path: f.file_path,
+ line_coverage_pct: f.line_coverage_pct,
+ };
+ if (f.health_score != null) entry.health_score = f.health_score;
+ return entry;
+ });
+ }, [files, untestedFindings]);
+
+ const scatterPoints = useMemo(
+ () =>
+ files
+ .filter((f) => f.health_score != null && f.line_coverage_pct != null)
+ .map((f) => ({
+ file_path: f.file_path,
+ health_score: f.health_score!,
+ line_coverage_pct: f.line_coverage_pct,
+ nloc: f.nloc ?? 0,
+ })),
+ [files],
+ );
+
+ const filteredFiles = useMemo(() => {
+ if (!search) return files;
+ const s = search.toLowerCase();
+ return files.filter((f) => f.file_path.toLowerCase().includes(s));
+ }, [files, search]);
+
+ const columns: ResponsiveColumn<CoverageFileRow>[] = [
+ {
+ key: "file_path",
+ header: "File",
+ priority: 1,
+ render: (f) => (
+ <span className="inline-flex items-center gap-1.5 font-mono text-xs text-[var(--color-text-primary)]">
+ <span className="truncate max-w-[420px]" title={f.file_path}>
+ {f.file_path}
+ </span>
+ <ArrowUpRight className="h-3 w-3 shrink-0 text-[var(--color-text-tertiary)]" />
+ </span>
+ ),
+ },
+ {
+ key: "line_coverage_pct",
+ header: "Line coverage",
+ priority: 1,
+ render: (f) => <CoverageBar value={f.line_coverage_pct} size="sm" />,
+ },
+ {
+ key: "branch_coverage_pct",
+ header: "Branch",
+ priority: 3,
+ align: "right",
+ render: (f) => (
+ <span className="tabular-nums text-[var(--color-text-secondary)]">
+ {f.branch_coverage_pct == null ? "—" : `${f.branch_coverage_pct.toFixed(0)}%`}
+ </span>
+ ),
+ },
+ {
+ key: "total_coverable_lines",
+ header: "Lines",
+ priority: 3,
+ align: "right",
+ render: (f) => (
+ <span className="tabular-nums text-[var(--color-text-tertiary)]">
+ {f.total_coverable_lines}
+ </span>
+ ),
+ },
+ {
+ key: "health_score",
+ header: "Health",
+ priority: 2,
+ align: "right",
+ render: (f) =>
+ f.health_score == null ? (
+ <span className="text-[var(--color-text-tertiary)]">—</span>
+ ) : (
+ <span
+ className={`inline-block rounded px-1.5 py-0.5 text-xs font-semibold ${scoreBadgeClass(f.health_score)}`}
+ >
+ {f.health_score.toFixed(1)}
+ </span>
+ ),
+ },
+ {
+ key: "actions",
+ header: "",
+ 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-success)] hover:bg-[var(--color-success)]/10 transition-colors"
+ >
+ <Sparkles className="h-3.5 w-3.5" />
+ </button>
+ ),
+ },
+ ];
+
+ return (
+ <div className="space-y-6">
+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-4">
+ <MetricCard label="Files" value={summary.file_count.toLocaleString()} />
+ <MetricCard
+ label="Line coverage"
+ value={
+ summary.line_coverage_pct == null
+ ? "—"
+ : `${summary.line_coverage_pct.toFixed(1)}%`
+ }
+ distBar={
+ <span className="text-xs tabular-nums text-[var(--color-text-tertiary)]">
+ {summary.covered_lines.toLocaleString()} /{" "}
+ {summary.total_lines.toLocaleString()} lines
+ </span>
+ }
+ />
+ <MetricCard
+ label="Branch coverage"
+ value={
+ summary.branch_coverage_pct == null
+ ? "—"
+ : `${summary.branch_coverage_pct.toFixed(1)}%`
+ }
+ />
+ <MetricCard
+ label="Source"
+ value={
+ <span className="text-lg uppercase">{summary.source_format ?? "—"}</span>
+ }
+ distBar={
+ <span className="text-xs text-[var(--color-text-tertiary)]">
+ {summary.ingested_at
+ ? new Date(summary.ingested_at).toLocaleString()
+ : "never"}
+ </span>
+ }
+ />
+ </div>
+
+ <RiskCoverageScatter points={scatterPoints} onSelect={(p) => onOpenFile(p.file_path)} />
+
+ {untested.length > 0 ? <UntestedHotspotWarning entries={untested} /> : null}
+
+ <section className="space-y-2">
+ <h2 className="text-sm font-semibold text-[var(--color-text-primary)]">
+ Module coverage ({modules.length})
+ </h2>
+ <ModuleCoverageList modules={modules} />
+ </section>
+
+ <CollapsibleSection
+ title={`Files (${filteredFiles.length.toLocaleString()})`}
+ defaultOpen={false}
+ >
+ <div className="flex items-center gap-2">
+ <span className="mr-auto text-xs text-[var(--color-text-tertiary)]">
+ Per-file coverage — click a row for the line-level heatmap.
+ </span>
+ <input
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ placeholder="Filter path…"
+ className="text-xs px-2 py-1.5 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] w-56 focus:outline-none focus:border-[var(--color-border-strong)]"
+ />
+ </div>
+ <ResponsiveTable
+ columns={columns}
+ rows={filteredFiles}
+ rowKey={(f) => f.file_path}
+ onRowClick={(f) => onOpenFile(f.file_path)}
+ stacked="sm"
+ empty={
+ <EmptyState
+ title="No files match"
+ description="Adjust the path filter to see coverage rows."
+ />
+ }
+ />
+ </CollapsibleSection>
+ </div>
+ );
+}
+
+function NoCoverageState() {
+ return (
+ <div className="rounded-lg border border-dashed border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-8">
+ <div className="max-w-xl mx-auto text-center space-y-3">
+ <h2 className="text-base font-semibold text-[var(--color-text-primary)]">
+ No coverage data ingested yet
+ </h2>
+ <p className="text-sm text-[var(--color-text-secondary)]">
+ Run your test suite with coverage enabled, then ingest the report.
+ You&apos;ll see a risk × coverage map, untested-hotspot warnings, and a
+ per-module breakdown.
+ </p>
+ <pre className="inline-block px-4 py-2 rounded bg-[var(--color-bg-muted)] text-left text-xs font-mono">
+ pytest --cov --cov-report=lcov{"\n"}
+ repowise health --coverage coverage.lcov
+ </pre>
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ Supported formats: LCOV · Cobertura · Clover.
+ </p>
+ </div>
+ </div>
+ );
+}
+
+function CoverageSkeleton() {
+ return (
+ <div className="space-y-6">
+ <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
+ {Array.from({ length: 4 }).map((_, i) => (
+ <Skeleton key={i} className="h-24 w-full rounded-lg" />
+ ))}
+ </div>
+ <Skeleton className="h-72 w-full rounded-lg" />
+ <Skeleton className="h-48 w-full rounded-lg" />
+ </div>
+ );
+}
diff --git a/packages/ui/src/health/index.ts b/packages/ui/src/health/index.ts
index 394673a92..b4bdbe001 100644
--- a/packages/ui/src/health/index.ts
+++ b/packages/ui/src/health/index.ts
@@ -36,3 +36,7 @@ export * from "./hot-functions-panel";
export * from "./hidden-coupling-list";
export * from "./recalibration-banner";
export * from "./defect-accuracy-card";
+export * from "./code-health-adapter";
+export * from "./triage-view";
+export * from "./coverage-view";
+export * from "./trend-view";
diff --git a/packages/ui/src/health/trend-view.tsx b/packages/ui/src/health/trend-view.tsx
new file mode 100644
index 000000000..4e6c3a6a1
--- /dev/null
+++ b/packages/ui/src/health/trend-view.tsx
@@ -0,0 +1,155 @@
+"use client";
+
+/**
+ * Trend view — KPI history over recent indexes. Handles the single-snapshot
+ * case explicitly (no misleading flat chart) and renders per-file score
+ * movement as a slope chart. Trend data is fetched once by the host and passed
+ * in, so it isn't double-fetched alongside the KPI sparklines.
+ */
+
+import { AlertTriangle, TrendingUp } from "lucide-react";
+import type { HealthTrendResponse } from "@repowise-dev/types/health";
+
+import { Skeleton } from "../ui/skeleton";
+import { MetricCard } from "../shared/metric-card";
+import { EmptyState } from "../shared/empty-state";
+
+import { TrendChart } from "./trend-chart";
+import { TrendSlopeChart } from "./trend-slope-chart";
+import { deltaColor, formatDelta } from "./tokens";
+
+export function TrendView({
+ data,
+ isLoading,
+ error,
+}: {
+ data: HealthTrendResponse | undefined;
+ isLoading: boolean;
+ error: unknown;
+}) {
+ if (isLoading) return <Skeleton className="h-64 w-full rounded-lg" />;
+ if (error || !data) {
+ return (
+ <EmptyState
+ title="Couldn't load trend data"
+ description="The trend endpoint returned an error. Try refreshing."
+ />
+ );
+ }
+
+ const singleSnapshot = data.snapshot_count <= 1;
+
+ return (
+ <div className="space-y-6">
+ <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
+ <DeltaMetric
+ label="Average health"
+ current={data.summary.current_average_health}
+ previous={data.summary.previous_average_health}
+ delta={data.summary.average_delta}
+ />
+ <DeltaMetric
+ label="Hotspot health"
+ current={data.summary.current_hotspot_health}
+ previous={data.summary.previous_hotspot_health}
+ delta={data.summary.hotspot_delta}
+ />
+ <MetricCard
+ label="Snapshots"
+ value={data.snapshot_count}
+ distBar={
+ <span className="text-xs text-[var(--color-text-tertiary)]">
+ rolling window: 50 max
+ </span>
+ }
+ />
+ </div>
+
+ {data.alerts.length > 0 ? (
+ <div className="space-y-2">
+ {data.alerts.map((a, i) => (
+ <div
+ key={i}
+ className={`rounded-lg border p-3 flex items-start gap-2 ${
+ a.kind === "declining"
+ ? "border-[var(--color-error)]/40 bg-[var(--color-error)]/5"
+ : "border-[var(--color-warning)]/40 bg-[var(--color-warning)]/5"
+ }`}
+ >
+ <AlertTriangle
+ className={`h-4 w-4 mt-0.5 ${a.kind === "declining" ? "text-[var(--color-error)]" : "text-[var(--color-warning)]"}`}
+ />
+ <div className="text-sm">
+ <p className="font-medium text-[var(--color-text-primary)]">
+ {a.kind === "declining" ? "Declining health" : "Predicted decline"}
+ </p>
+ <p className="text-xs text-[var(--color-text-secondary)]">{a.message}</p>
+ </div>
+ </div>
+ ))}
+ </div>
+ ) : null}
+
+ {singleSnapshot ? (
+ <EmptyState
+ icon={<TrendingUp className="h-6 w-6" />}
+ title="One snapshot so far"
+ description="The trend lines appear once a second snapshot lands. Run repowise update (or wait for the next sync) and this page fills in."
+ />
+ ) : (
+ <TrendChart history={[...data.history].reverse()} />
+ )}
+
+ <section className="space-y-2">
+ <h2 className="text-sm font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">
+ Largest score changes since last index
+ </h2>
+ {data.file_deltas.length === 0 ? (
+ <EmptyState
+ {...(singleSnapshot
+ ? {
+ title: "No comparison available yet",
+ description: "Per-file deltas compare the last two snapshots.",
+ }
+ : { title: "No per-file changes between the last two snapshots" })}
+ />
+ ) : (
+ <TrendSlopeChart points={data.file_deltas} />
+ )}
+ </section>
+ </div>
+ );
+}
+
+function DeltaMetric({
+ label,
+ current,
+ previous,
+ delta,
+}: {
+ label: string;
+ current: number;
+ previous: number | null;
+ delta: number | null;
+}) {
+ return (
+ <MetricCard
+ label={label}
+ value={
+ <>
+ {current.toFixed(1)}
+ <span className="text-base font-normal text-[var(--color-text-secondary)]">
+ /10
+ </span>
+ </>
+ }
+ distBar={
+ <span className={`text-xs tabular-nums ${deltaColor(delta)}`}>
+ {delta == null
+ ? "no prior snapshot"
+ : `${formatDelta(delta)} vs. ${previous?.toFixed(1) ?? "—"}`}
+ </span>
+ }
+ />
+ );
+}
diff --git a/packages/ui/src/health/triage-view.tsx b/packages/ui/src/health/triage-view.tsx
new file mode 100644
index 000000000..b257407ee
--- /dev/null
+++ b/packages/ui/src/health/triage-view.tsx
@@ -0,0 +1,724 @@
+"use client";
+
+/**
+ * Triage view — the "what do I fix next" surface. KPI strip, the master–detail
+ * Code Health map + inspector rail, the ranked fix-next queue (refactoring
+ * targets + file inventory), a severity-coordinated findings sidebar, and the
+ * function-level panels.
+ *
+ * Presentation + orchestration only: the host injects data, links, and the
+ * file-detail drawer through a {@link CodeHealthAdapter}, so web and hosted
+ * render the same view from different backends.
+ */
+
+import { useCallback, useMemo, useRef, useState } from "react";
+import useSWR from "swr";
+import { Gauge, Search } from "lucide-react";
+import type {
+ HealthFinding,
+ HealthFilesResponse,
+ HealthOverviewResponse,
+ HealthTrendResponse,
+ RefactoringQuery,
+ RefactoringTargetsResponse,
+} from "@repowise-dev/types/health";
+
+import { Skeleton } from "../ui/skeleton";
+import { Button } from "../ui/button";
+import { EmptyState } from "../shared/empty-state";
+import { CollapsibleSection } from "../shared/collapsible-section";
+
+import { AiPromptModal } from "./ai-prompt-modal";
+import { HealthKpiCards } from "./kpi-cards";
+import { HealthFileTable, type FileSortField } from "./file-table";
+import { BiomarkerList } from "./biomarker-list";
+import { HotFunctionsPanel } from "./hot-functions-panel";
+import { HiddenCouplingList } from "./hidden-coupling-list";
+import {
+ CodeHealthMap,
+ type CodeHealthMapFile,
+ type CodeHealthOverlay,
+} from "./code-health-map";
+import { RecalibrationBanner } from "./recalibration-banner";
+import {
+ RefactoringTargetList,
+ type FindingStatus,
+ type RefactoringTarget,
+} from "./refactoring-target-list";
+import { DefectAccuracyCard } from "./defect-accuracy-card";
+import {
+ FileSpotlight,
+ FilterSelect,
+ FilterChip,
+ ViewToggle,
+} from "./code-health-controls";
+import { ImpactEffortQuadrant } from "./impact-effort-quadrant";
+import { biomarkerLabel } from "./biomarker-glossary";
+import { buildAiPrompt } from "./ai-prompt-builder";
+import { type Severity } from "./tokens";
+import type { CodeHealthAdapter } from "./code-health-adapter";
+
+export type HealthPillar = "all" | "defect" | "maintainability" | "performance";
+
+const PAGE_SIZE = 50;
+const QUEUE_PAGE = 200;
+const QUEUE_MAX = 500;
+
+type GroupBy = "none" | "biomarker" | "module" | "effort";
+type QueueView = "queue" | "files";
+
+const EFFORT_LABEL: Record<string, string> = {
+ S: "Small (≤40 NLOC)",
+ M: "Medium (≤150 NLOC)",
+ L: "Large (≤400 NLOC)",
+ XL: "Extra large (>400 NLOC)",
+};
+
+export function TriageView({
+ adapter,
+ trend,
+ overlay = "health",
+ onOverlayChange,
+ mapFiles,
+ overlayLoading,
+ pillar: controlledPillar,
+ onPillarChange,
+}: {
+ adapter: CodeHealthAdapter;
+ /** Trend fetched once by the host — feeds the KPI sparklines. */
+ trend?: HealthTrendResponse;
+ /** Active map lens, owned by the host so the spine is shared across tabs. */
+ overlay?: CodeHealthOverlay;
+ onOverlayChange?: (overlay: CodeHealthOverlay) => void;
+ /** Map files fetched once by the host (shared across overlays). */
+ mapFiles?: HealthFilesResponse;
+ /** The active lens's per-file signal is still loading (e.g. churn). */
+ overlayLoading?: boolean;
+ /**
+ * Findings pillar filter. Controlled by the host when it wants to URL-sync
+ * the value (so the Overview + KPI tiles can deep-link into a dimension);
+ * falls back to local state otherwise.
+ */
+ pillar?: HealthPillar;
+ onPillarChange?: (pillar: HealthPillar) => void;
+}) {
+ const { cacheKey } = adapter;
+ const { data: overview, isLoading, error, mutate } = useSWR<HealthOverviewResponse>(
+ `code-health-overview:${cacheKey}`,
+ () => adapter.getOverview(25),
+ { revalidateOnFocus: false },
+ );
+ const { data: hotFunctionFindings } = useSWR<HealthFinding[]>(
+ `code-health-hot-functions:${cacheKey}`,
+ async () => {
+ const types = [
+ "function_hotspot",
+ "code_age_volatility",
+ "complex_conditional",
+ ] as const;
+ const batches = await Promise.all(
+ types.map((t) =>
+ adapter.listFindings({ biomarker_type: t, limit: 100 }).catch(
+ () => [] as HealthFinding[],
+ ),
+ ),
+ );
+ return batches.flat();
+ },
+ { revalidateOnFocus: false },
+ );
+
+ const { data: couplingFindings } = useSWR<HealthFinding[]>(
+ `code-health-hidden-coupling:${cacheKey}`,
+ () =>
+ adapter
+ .listFindings({ biomarker_type: "hidden_coupling", limit: 100 })
+ .catch(() => []),
+ { revalidateOnFocus: false },
+ );
+
+ // Every open performance-pillar finding (the cross-function N+1 / I/O-in-loop
+ // moat), for the dedicated Performance risks panel.
+ const { data: perfFindings } = useSWR<HealthFinding[]>(
+ `code-health-perf-findings:${cacheKey}`,
+ () =>
+ adapter
+ .listFindings({ dimension: "performance", limit: 200 })
+ .catch(() => [] as HealthFinding[]),
+ { revalidateOnFocus: false },
+ );
+
+ // ---- One filter set coordinates the queue AND the findings sidebar ----
+ const [minSeverity, setMinSeverity] = useState<Severity | "all">("all");
+ const [biomarker, setBiomarker] = useState<string>("all");
+ const [maxEffort, setMaxEffort] = useState<string>("all");
+ const [sort, setSort] = useState<RefactoringQuery["sort"]>("impact_per_effort");
+ const [groupBy, setGroupBy] = useState<GroupBy>("none");
+ const [queueLimit, setQueueLimit] = useState(QUEUE_PAGE);
+ const [view, setView] = useState<QueueView>("queue");
+ const [selectedFile, setSelectedFile] = useState<string | null>(null);
+ const [promptTarget, setPromptTarget] = useState<RefactoringTarget | null>(null);
+
+ // ---- Map-driven UI: rail spotlight + filename dim + collapsible list ----
+ const [hoverFile, setHoverFile] = useState<CodeHealthMapFile | null>(null);
+ const [mapQuery, setMapQuery] = useState("");
+
+ // ---- Pillar filter — controlled by the host (URL-synced) when supplied,
+ // otherwise local. Lets the Overview + KPI tiles deep-link a dimension. ----
+ const [pillarState, setPillarState] = useState<HealthPillar>("all");
+ const pillar = controlledPillar ?? pillarState;
+ const findingsRef = useRef<HTMLDivElement | null>(null);
+ const setPillar = useCallback(
+ (next: HealthPillar) => {
+ if (onPillarChange) onPillarChange(next);
+ else setPillarState(next);
+ },
+ [onPillarChange],
+ );
+ const focusPillar = useCallback(
+ (next: "defect" | "maintainability" | "performance") => {
+ setPillar(next);
+ findingsRef.current?.scrollIntoView({ behavior: "smooth", block: "start" });
+ },
+ [setPillar],
+ );
+
+ const queueKey = useMemo(
+ () =>
+ JSON.stringify({ cacheKey, biomarker, minSeverity, maxEffort, sort, queueLimit }),
+ [cacheKey, biomarker, minSeverity, maxEffort, sort, queueLimit],
+ );
+ const {
+ data: queue,
+ isLoading: queueLoading,
+ mutate: mutateQueue,
+ } = useSWR<RefactoringTargetsResponse>(
+ overview ? `code-health-queue:${queueKey}` : null,
+ () =>
+ adapter.getRefactoringTargets({
+ limit: queueLimit,
+ ...(biomarker !== "all" && { biomarker }),
+ ...(minSeverity !== "all" && { min_severity: minSeverity }),
+ ...(maxEffort !== "all" && { max_effort: maxEffort }),
+ ...(sort && { sort }),
+ }),
+ { revalidateOnFocus: false, keepPreviousData: true },
+ );
+
+ // ---- All-files inventory view ----
+ const [sortField, setSortField] = useState<FileSortField>("score");
+ const [sortOrder, setSortOrder] = useState<"asc" | "desc">("asc");
+ const [search, setSearch] = useState("");
+ const [onlyHotspots, setOnlyHotspots] = useState(false);
+ const [onlyUntested, setOnlyUntested] = useState(false);
+ const [onlyFailing, setOnlyFailing] = useState(false);
+ const [offset, setOffset] = useState(0);
+
+ const filesKey = useMemo(
+ () =>
+ JSON.stringify({
+ cacheKey,
+ sortField,
+ sortOrder,
+ search,
+ onlyHotspots,
+ onlyUntested,
+ onlyFailing,
+ offset,
+ }),
+ [cacheKey, sortField, sortOrder, search, onlyHotspots, onlyUntested, onlyFailing, offset],
+ );
+
+ const { data: files, isLoading: filesLoading } = useSWR<HealthFilesResponse>(
+ overview && view === "files" ? `code-health-files:${filesKey}` : null,
+ () =>
+ adapter.listFiles({
+ sort: sortField,
+ order: sortOrder,
+ ...(search && { search }),
+ ...(onlyHotspots && { only_hotspots: true }),
+ ...(onlyUntested && { only_untested: true }),
+ ...(onlyFailing && { only_failing: true }),
+ offset,
+ limit: PAGE_SIZE,
+ }),
+ { revalidateOnFocus: false, keepPreviousData: true },
+ );
+
+ const handleSort = (field: FileSortField) => {
+ if (field === sortField) {
+ setSortOrder((o) => (o === "asc" ? "desc" : "asc"));
+ } else {
+ setSortField(field);
+ // Score: asc (worst first). Counts: desc. Path: asc.
+ setSortOrder(["score", "line_coverage_pct", "file_path"].includes(field) ? "asc" : "desc");
+ }
+ setOffset(0);
+ };
+
+ const handleStatus = async (findingId: string, status: FindingStatus) => {
+ await adapter.updateFindingStatus(findingId, status);
+ mutateQueue();
+ };
+
+ const biomarkerOptions = useMemo(() => {
+ const set = new Set<string>();
+ (overview?.biomarkers ?? []).forEach((b) => set.add(b.biomarker_type));
+ (queue?.targets ?? []).forEach((t) => t.biomarkers.forEach((b) => set.add(b)));
+ return [...set].sort();
+ }, [overview, queue]);
+
+ // Grouped queue — group order follows the user's sort (first occurrence),
+ // not group size, so "Leverage" sorted stays leverage-led inside and out.
+ const grouped = useMemo(() => {
+ const targets = queue?.targets ?? [];
+ if (groupBy === "none") return [{ key: "All", targets }];
+ const groups = new Map<string, typeof targets>();
+ for (const t of targets) {
+ let key = "—";
+ if (groupBy === "biomarker") key = biomarkerLabel(t.primary_biomarker);
+ else if (groupBy === "module") key = t.module ?? "(no module)";
+ else if (groupBy === "effort") key = EFFORT_LABEL[t.effort_bucket] ?? t.effort_bucket;
+ if (!groups.has(key)) groups.set(key, []);
+ groups.get(key)!.push(t);
+ }
+ return [...groups.entries()].map(([key, targets]) => ({ key, targets }));
+ }, [queue, groupBy]);
+
+ // Severity + pillar drive the sidebar findings list; omit unset filters
+ // rather than passing `undefined` (strict optional props in the shared lib).
+ const sidebarFilter: {
+ minSeverity?: Severity;
+ dimension?: "defect" | "maintainability" | "performance";
+ } = {};
+ if (minSeverity !== "all") sidebarFilter.minSeverity = minSeverity;
+ if (pillar !== "all") sidebarFilter.dimension = pillar;
+
+ const avgSeries = trend?.history?.slice().reverse().map((p) => p.average_health);
+ const hotspotSeries = trend?.history?.slice().reverse().map((p) => p.hotspot_health);
+ const worstSeries = trend?.history
+ ?.slice()
+ .reverse()
+ .map((p) => p.worst_performer_score ?? 0);
+
+ // KPI trend inputs are all optional in the shared card; include only the
+ // ones the host actually fetched (no `undefined` under strict optionals).
+ const kpiTrend: {
+ averageHistory?: number[];
+ hotspotHistory?: number[];
+ worstHistory?: number[];
+ averageDelta?: number;
+ hotspotDelta?: number;
+ } = {};
+ if (avgSeries) kpiTrend.averageHistory = avgSeries;
+ if (hotspotSeries) kpiTrend.hotspotHistory = hotspotSeries;
+ if (worstSeries) kpiTrend.worstHistory = worstSeries;
+ if (trend?.summary?.average_delta != null)
+ kpiTrend.averageDelta = trend.summary.average_delta;
+ if (trend?.summary?.hotspot_delta != null)
+ kpiTrend.hotspotDelta = trend.summary.hotspot_delta;
+
+ // CodeHealthMap's lens controls are optional; omit when the host doesn't
+ // own the lens (hosted before it wires the shared spine).
+ const mapExtra: {
+ onOverlayChange?: (overlay: CodeHealthOverlay) => void;
+ overlayLoading?: boolean;
+ } = {};
+ if (onOverlayChange) mapExtra.onOverlayChange = onOverlayChange;
+ if (overlayLoading !== undefined) mapExtra.overlayLoading = overlayLoading;
+
+ return (
+ <div className="space-y-6">
+ {isLoading ? (
+ <div className="space-y-3">
+ <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
+ {Array.from({ length: 3 }).map((_, i) => (
+ <Skeleton key={i} className="h-28 w-full rounded-xl" />
+ ))}
+ </div>
+ <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
+ {Array.from({ length: 4 }).map((_, i) => (
+ <Skeleton key={i} className="h-20 w-full rounded-lg" />
+ ))}
+ </div>
+ </div>
+ ) : error ? (
+ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-4 text-sm text-[var(--color-text-secondary)] flex items-center justify-between gap-2">
+ <span>Couldn&apos;t load health data. Run <code>repowise init</code> to populate.</span>
+ <Button size="sm" variant="outline" onClick={() => mutate()}>Retry</Button>
+ </div>
+ ) : overview ? (
+ <>
+ <RecalibrationBanner repoId={cacheKey} />
+ <HealthKpiCards
+ summary={overview.summary}
+ distribution={overview.distribution ?? null}
+ {...kpiTrend}
+ onSelectPillar={focusPillar}
+ />
+
+ {overview.defect_accuracy ? (
+ <DefectAccuracyCard data={overview.defect_accuracy} collapsible />
+ ) : null}
+
+ {/* Hero: the Code Health Map — modules as nested bubbles, files
+ sized by lines of code and colored by health. The centerpiece. */}
+ <div className="grid grid-cols-1 lg:grid-cols-[minmax(0,1fr)_320px] gap-6">
+ <div className="space-y-2">
+ <div className="flex flex-wrap items-baseline gap-2">
+ <h2 className="text-base font-semibold text-[var(--color-text-primary)]">
+ Code health map
+ </h2>
+ <span className="text-xs text-[var(--color-text-tertiary)]">
+ {mapFiles ? `${mapFiles.total.toLocaleString()} files` : "loading…"} · click a module to
+ zoom, a file to open
+ </span>
+ </div>
+ {!mapFiles ? (
+ <Skeleton className="w-full rounded-xl" style={{ height: 664 }} />
+ ) : (
+ <CodeHealthMap
+ files={mapFiles.files}
+ search={mapQuery}
+ selectedPath={selectedFile}
+ onSelectFile={(p) => setSelectedFile(p)}
+ onHoverFile={setHoverFile}
+ minHeight={664}
+ overlay={overlay}
+ {...mapExtra}
+ />
+ )}
+ </div>
+
+ {/* Inspector rail — height-matched to the map (master–detail).
+ Search + the file you're inspecting sit on top; the findings
+ list scrolls in place so the rail never outgrows the map. */}
+ <aside className="flex flex-col gap-3 lg:sticky lg:top-4 lg:h-[700px]">
+ <div className="relative">
+ <Search className="absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-[var(--color-text-tertiary)]" />
+ <input
+ value={mapQuery}
+ onChange={(e) => setMapQuery(e.target.value)}
+ placeholder="Find a file in the map…"
+ className="w-full text-xs pl-7 pr-2 py-1.5 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] focus:outline-none focus:border-[var(--color-border-strong)]"
+ />
+ </div>
+
+ <FileSpotlight file={hoverFile} onOpen={(p) => setSelectedFile(p)} />
+
+ <div ref={findingsRef} className="flex items-center gap-2 scroll-mt-4">
+ <h2 className="text-sm font-medium uppercase tracking-wider text-[var(--color-text-tertiary)] mr-auto">
+ Findings
+ </h2>
+ <select
+ value={pillar}
+ onChange={(e) => setPillar(e.target.value as HealthPillar)}
+ aria-label="Health pillar"
+ className="text-xs px-2 py-1 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)]"
+ >
+ <option value="all">All pillars</option>
+ <option value="defect">Defect risk</option>
+ <option value="maintainability">Maintainability</option>
+ <option value="performance">Performance</option>
+ </select>
+ <select
+ value={minSeverity}
+ onChange={(e) => setMinSeverity(e.target.value as Severity | "all")}
+ aria-label="Minimum severity (filters the queue too)"
+ className="text-xs px-2 py-1 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)]"
+ >
+ <option value="all">All severities</option>
+ <option value="low">Low+</option>
+ <option value="medium">Medium+</option>
+ <option value="high">High+</option>
+ <option value="critical">Critical</option>
+ </select>
+ </div>
+ <div className="min-h-0 flex-1 overflow-y-auto pr-1 lg:pb-0 pb-1">
+ <BiomarkerList
+ findings={overview.top_findings}
+ grouped
+ {...sidebarFilter}
+ onSelect={(f) => setSelectedFile(f.file_path)}
+ />
+ </div>
+ </aside>
+ </div>
+
+ {/* Performance risks — the cross-function N+1 / I/O-in-loop moat,
+ given a dedicated home. Only rendered when risks actually exist
+ (high precision, low recall), so a clean repo stays uncluttered. */}
+ {perfFindings && perfFindings.length > 0 ? (
+ <CollapsibleSection
+ title={
+ <span className="inline-flex items-center gap-2">
+ <Gauge className="h-4 w-4 text-[var(--color-info)]" />
+ Performance risks
+ </span>
+ }
+ hint={`${perfFindings.length} ${perfFindings.length === 1 ? "risk" : "risks"}`}
+ defaultOpen
+ >
+ <div className="space-y-3">
+ <p className="text-xs text-[var(--color-text-secondary)]">
+ Static performance risk: a DB, network, filesystem, or subprocess call
+ per loop iteration, detected across function boundaries via the call
+ graph. High precision, low recall, never blended into the defect score.
+ </p>
+ <BiomarkerList
+ findings={perfFindings}
+ grouped
+ onSelect={(f) => setSelectedFile(f.file_path)}
+ />
+ </div>
+ </CollapsibleSection>
+ ) : null}
+
+ {/* Collapsible: the full ranked queue + file inventory. The severity
+ filter is shared with the rail above (one control, no duplicate). */}
+ <CollapsibleSection
+ title="Targets &amp; findings list"
+ hint={queue?.total != null ? `${queue.total} candidates` : ""}
+ defaultOpen={false}
+ >
+ <div className="space-y-3">
+ <div className="flex flex-wrap items-center gap-2">
+ <h3 className="text-sm font-medium uppercase tracking-wider text-[var(--color-text-tertiary)] mr-auto">
+ Fix next
+ </h3>
+ <ViewToggle
+ value={view}
+ onChange={setView}
+ options={[
+ { value: "queue", label: "Queue" },
+ { value: "files", label: "All files" },
+ ]}
+ />
+ </div>
+
+ {view === "queue" ? (
+ <>
+ <div className="flex flex-wrap items-center gap-2">
+ <FilterSelect
+ label="Biomarker"
+ value={biomarker}
+ onChange={setBiomarker}
+ options={[
+ { value: "all", label: "All biomarkers" },
+ ...biomarkerOptions.map((b) => ({ value: b, label: biomarkerLabel(b) })),
+ ]}
+ />
+ <FilterSelect
+ label="Max effort"
+ value={maxEffort}
+ onChange={setMaxEffort}
+ options={[
+ { value: "all", label: "Any effort" },
+ { value: "S", label: "Small only" },
+ { value: "M", label: "Medium+" },
+ { value: "L", label: "Large+" },
+ ]}
+ />
+ <FilterSelect
+ label="Sort"
+ value={sort ?? "impact_per_effort"}
+ onChange={(v) => setSort(v as RefactoringQuery["sort"])}
+ options={[
+ { value: "impact_per_effort", label: "Leverage (impact ÷ effort)" },
+ { value: "total_impact", label: "Total impact" },
+ { value: "score", label: "Worst score" },
+ { value: "finding_count", label: "Finding count" },
+ ]}
+ />
+ <FilterSelect
+ label="Group"
+ value={groupBy}
+ onChange={(v) => setGroupBy(v as GroupBy)}
+ options={[
+ { value: "none", label: "Flat list" },
+ { value: "biomarker", label: "By biomarker" },
+ { value: "module", label: "By module" },
+ { value: "effort", label: "By effort" },
+ ]}
+ />
+ </div>
+
+ {queueLoading && !queue ? (
+ <div className="grid gap-3">
+ {Array.from({ length: 4 }).map((_, i) => (
+ <Skeleton key={i} className="h-28 w-full" />
+ ))}
+ </div>
+ ) : !queue || queue.targets.length === 0 ? (
+ <EmptyState
+ title="No findings match the current filters"
+ description="Try widening the severity or effort filters, or run repowise health to populate findings."
+ />
+ ) : (
+ <>
+ {/* Leverage at a glance — impact vs effort, click a dot
+ to open the file. Replaces the text-dense ranking as
+ the first read of the queue. */}
+ <ImpactEffortQuadrant
+ points={(queue?.targets ?? []).map((t) => ({
+ file_path: t.file_path,
+ total_impact: t.total_impact,
+ effort_bucket: t.effort_bucket,
+ nloc: t.nloc,
+ score: t.score,
+ }))}
+ onSelect={(p) => setSelectedFile(p.file_path)}
+ />
+ <div className="space-y-6">
+ {grouped.map((g) => (
+ <section key={g.key} className="space-y-2">
+ {groupBy !== "none" ? (
+ <h3 className="text-xs font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">
+ {g.key}{" "}
+ <span className="text-[var(--color-text-secondary)]">
+ ({g.targets.length})
+ </span>
+ </h3>
+ ) : null}
+ <RefactoringTargetList
+ targets={g.targets}
+ onSelect={(t) => setSelectedFile(t.file_path)}
+ onStatusChange={handleStatus}
+ onGeneratePrompt={(t) => setPromptTarget(t)}
+ />
+ </section>
+ ))}
+ </div>
+
+ <div className="flex items-center justify-between gap-2 text-xs text-[var(--color-text-tertiary)]">
+ <span>
+ Showing {queue.targets.length} of {queue.total} candidates
+ </span>
+ {queue.total > queue.targets.length && queueLimit < QUEUE_MAX ? (
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={() => setQueueLimit(QUEUE_MAX)}
+ >
+ Load more
+ </Button>
+ ) : null}
+ </div>
+ </>
+ )}
+ </>
+ ) : (
+ <>
+ <div className="flex flex-wrap items-center gap-2">
+ <div className="relative">
+ <Search className="absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-[var(--color-text-tertiary)]" />
+ <input
+ value={search}
+ onChange={(e) => {
+ setSearch(e.target.value);
+ setOffset(0);
+ }}
+ placeholder="Filter path…"
+ className="text-xs pl-7 pr-2 py-1.5 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] w-56 focus:outline-none focus:border-[var(--color-border-strong)]"
+ />
+ </div>
+ <FilterChip active={onlyHotspots} onClick={() => { setOnlyHotspots((v) => !v); setOffset(0); }}>
+ Hotspots
+ </FilterChip>
+ <FilterChip active={onlyUntested} onClick={() => { setOnlyUntested((v) => !v); setOffset(0); }}>
+ Untested
+ </FilterChip>
+ <FilterChip active={onlyFailing} onClick={() => { setOnlyFailing((v) => !v); setOffset(0); }}>
+ Failing
+ </FilterChip>
+ <span className="text-xs text-[var(--color-text-tertiary)] ml-auto">
+ {files?.total != null ? `${files.total.toLocaleString()} files` : ""}
+ </span>
+ </div>
+
+ {filesLoading && !files ? (
+ <Skeleton className="h-64 w-full rounded-lg" />
+ ) : (
+ <HealthFileTable
+ files={files?.files ?? []}
+ sortField={sortField}
+ sortOrder={sortOrder}
+ onSort={handleSort}
+ onSelect={(f) => setSelectedFile(f.file_path)}
+ selectedPath={selectedFile}
+ />
+ )}
+
+ {files && files.total > PAGE_SIZE ? (
+ <div className="flex items-center justify-between gap-2 text-xs text-[var(--color-text-tertiary)]">
+ <span>
+ Showing {offset + 1}–{Math.min(offset + PAGE_SIZE, files.total)} of {files.total}
+ </span>
+ <div className="flex gap-1">
+ <Button
+ size="sm"
+ variant="outline"
+ disabled={offset === 0}
+ onClick={() => setOffset(Math.max(0, offset - PAGE_SIZE))}
+ >
+ Prev
+ </Button>
+ <Button
+ size="sm"
+ variant="outline"
+ disabled={offset + PAGE_SIZE >= files.total}
+ onClick={() => setOffset(offset + PAGE_SIZE)}
+ >
+ Next
+ </Button>
+ </div>
+ </div>
+ ) : null}
+ </>
+ )}
+ </div>
+ </CollapsibleSection>
+
+ {hotFunctionFindings && hotFunctionFindings.length >= 3 ? (
+ <HotFunctionsPanel
+ findings={hotFunctionFindings}
+ collapsible
+ onSelect={(f) => setSelectedFile(f.file_path)}
+ symbolHrefFor={(f) =>
+ f.symbol_id ? adapter.symbolHref?.(f.symbol_id) : undefined
+ }
+ />
+ ) : null}
+
+ {couplingFindings && couplingFindings.length >= 3 ? (
+ <HiddenCouplingList
+ findings={couplingFindings}
+ collapsible
+ onSelect={(path) => setSelectedFile(path)}
+ />
+ ) : null}
+ </>
+ ) : null}
+
+ {adapter.renderFileDrawer({
+ filePath: selectedFile,
+ onClose: () => setSelectedFile(null),
+ })}
+
+ <AiPromptModal
+ open={promptTarget !== null}
+ onOpenChange={(open) => {
+ if (!open) setPromptTarget(null);
+ }}
+ filePath={promptTarget?.file_path ?? null}
+ title="AI fix prompt"
+ description="A ready-to-paste prompt that gives your AI coding agent every biomarker, line range, score deduction, and constraint needed to refactor this file in one focused pass."
+ getPrompt={
+ promptTarget
+ ? (flavor) => buildAiPrompt({ target: promptTarget, flavor })
+ : null
+ }
+ />
+ </div>
+ );
+}
diff --git a/packages/ui/src/shared/view-tabs.tsx b/packages/ui/src/shared/view-tabs.tsx
index 8de70c21c..c840ab97b 100644
--- a/packages/ui/src/shared/view-tabs.tsx
+++ b/packages/ui/src/shared/view-tabs.tsx
@@ -7,6 +7,11 @@ export interface ViewTab {
id: string;
label: string;
badge?: number;
+ /** Optional leading icon. Lets a host carry a canonical icon for a tab (e.g.
+ * the Architecture/Knowledge-Graph surface) so both apps render the same
+ * glyph from one tab definition instead of hand-rolling their own toggle.
+ * Omit it and the tab is label-only. */
+ icon?: React.ReactNode;
}
export interface ViewTabsProps {
@@ -90,6 +95,11 @@ export function ViewTabs({
: "text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]",
)}
>
+ {tab.icon != null && (
+ <span className="inline-flex shrink-0 items-center" aria-hidden>
+ {tab.icon}
+ </span>
+ )}
{tab.label}
{typeof tab.badge === "number" && (
<span className="inline-flex min-w-[1.25rem] items-center justify-center rounded-full bg-[var(--color-bg-elevated)] px-1.5 py-0.5 text-xs font-medium tabular-nums text-[var(--color-text-secondary)]">
diff --git a/packages/web/src/components/architecture/c4-view.tsx b/packages/web/src/components/architecture/c4-view.tsx
index 2617642a7..35dd885cd 100644
--- a/packages/web/src/components/architecture/c4-view.tsx
+++ b/packages/web/src/components/architecture/c4-view.tsx
@@ -7,7 +7,7 @@
* refresh + share preserve the view state.
*/
-import { useCallback, useEffect, useRef, useState } from "react";
+import { useCallback, useEffect, useRef } from "react";
import { useQueryState, parseAsString, parseAsStringLiteral } from "nuqs";
import {
ArchCanvas,
@@ -17,6 +17,7 @@ import {
SearchBar,
ArchBreadcrumb,
PersonaSelector,
+ ArchTourButton,
NodeTypeCategoryFilters,
FilterPanel,
CodeViewer,
@@ -26,10 +27,6 @@ import {
import { ReactFlowProvider, useReactFlow, type Node } from "@xyflow/react";
import { useArchitectureView } from "@/lib/hooks/use-architecture";
import { ArchDetailPanelHost } from "@/components/c4/arch-detail-panel-host";
-import { Compass } from "lucide-react";
-
-// First-visit discoverability flag for the guided tour.
-const TOUR_SEEN_KEY = "repowise:arch-tour-seen";
const VIEW_VALUES = ["overview", "groups", "detail"] as const;
const PERSONA_VALUES = ["overview", "learn", "deep-dive"] as const;
@@ -97,19 +94,6 @@ function ArchitectureViewInner({
const setPersona = useArchitectureStore((s) => s.setPersona);
const setReactFlowInstance = useArchitectureStore((s) => s.setReactFlowInstance);
const pathFinderOpen = useArchitectureStore((s) => s.pathFinderOpen);
- const tourActive = useArchitectureStore((s) => s.tourActive);
- const startTour = useArchitectureStore((s) => s.startTour);
-
- // "Take the tour" is highlighted until first taken (localStorage flag).
- const [tourSeen, setTourSeen] = useState(true);
- useEffect(() => {
- setTourSeen(localStorage.getItem(TOUR_SEEN_KEY) === "1");
- }, []);
- const handleStartTour = useCallback(() => {
- localStorage.setItem(TOUR_SEEN_KEY, "1");
- setTourSeen(true);
- startTour();
- }, [startTour]);
useEffect(() => {
if (view) setView(view);
@@ -271,19 +255,7 @@ function ArchitectureViewInner({
<span aria-hidden />
)}
<div className="flex items-center gap-3">
- {view && view.tour.length > 0 && !tourActive && (
- <button
- onClick={handleStartTour}
- className={`flex items-center gap-1.5 rounded-full border px-3 py-1 text-xs font-medium transition-colors ${
- tourSeen
- ? "border-[var(--color-border-default)] text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] hover:bg-[var(--color-bg-elevated)]"
- : "border-[var(--color-accent-primary)]/50 bg-[var(--color-accent-primary)]/10 text-[var(--color-accent-primary)] hover:bg-[var(--color-accent-primary)]/20"
- }`}
- >
- <Compass className="h-3.5 w-3.5" />
- Take the tour
- </button>
- )}
+ <ArchTourButton />
<PersonaSelector />
<NodeTypeCategoryFilters />
</div>
diff --git a/packages/web/src/components/architecture/graph-view.tsx b/packages/web/src/components/architecture/graph-view.tsx
index 1e0fefb75..45c576a79 100644
--- a/packages/web/src/components/architecture/graph-view.tsx
+++ b/packages/web/src/components/architecture/graph-view.tsx
@@ -179,7 +179,10 @@ export function GraphView({
key={flowKey}
repoId={repoId}
initialViewMode={forcedViewMode ?? mountViewMode}
- initialColorMode={initialColorMode}
+ // Color mode is controlled here so the URL (?colorMode=) is the single
+ // source of truth — back/forward and shared links restore it. Defaults
+ // to community coloring, matching the canvas's own default.
+ colorMode={initialColorMode ?? "community"}
initialSelectedNode={initialNode}
// Communities locks to the constellation; Explore drops the
// constellation scope (it lives in the Knowledge Graph view) so the
diff --git a/packages/web/src/components/code-health/coverage-tab.tsx b/packages/web/src/components/code-health/coverage-tab.tsx
index f1eaa0440..af9322602 100644
--- a/packages/web/src/components/code-health/coverage-tab.tsx
+++ b/packages/web/src/components/code-health/coverage-tab.tsx
@@ -1,381 +1,40 @@
"use client";
/**
- * Coverage tab — test-coverage summary, risk × coverage scatter, untested
- * hotspots (with the dependents/commit context from the findings), module
- * rollup, and the per-file table. Rows link to the file page's coverage tab
- * (line-level heatmap).
+ * 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 { useMemo, useState } from "react";
-import { ArrowUpRight, Sparkles } from "lucide-react";
import { useRouter } from "next/navigation";
-import useSWR from "swr";
-
-import {
- AiPromptModal,
- CoverageBar,
- ModuleCoverageList,
- UntestedHotspotWarning,
- RiskCoverageScatter,
- buildCoverageAiPrompt,
- scoreBadgeClass,
- type CoverageFilePromptInput,
-} from "@repowise-dev/ui/health";
-import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
-import { EmptyState } from "@repowise-dev/ui/shared/empty-state";
-import { ResponsiveTable, type ResponsiveColumn } from "@repowise-dev/ui/shared";
-import { MetricCard } from "@repowise-dev/ui/shared/metric-card";
-import { CollapsibleSection } from "@repowise-dev/ui/shared/collapsible-section";
+import { CoverageView, type CodeHealthAdapter } from "@repowise-dev/ui/health";
import { fileEntityPath } from "@repowise-dev/ui/shared/entity";
-
import {
getHealthCoverage,
+ getHealthOverview,
+ getRefactoringTargets,
+ listHealthFiles,
listHealthFindings,
- type CoverageFileRow,
- type HealthCoverageResponse,
- type HealthFinding,
+ updateFindingStatus,
} from "@/lib/api/code-health";
export function CoverageTab({ repoId: id }: { repoId: string }) {
const router = useRouter();
- const [promptRow, setPromptRow] = useState<CoverageFilePromptInput | null>(null);
-
- const { data, isLoading, error } = useSWR<HealthCoverageResponse>(
- `code-health-coverage:${id}`,
- () => getHealthCoverage(id, { limit: 1000 }),
- { revalidateOnFocus: false },
- );
-
- // The untested_hotspot findings carry dependents_count / commit_count_90d
- // in their details — join them into the warning entries.
- const { data: untestedFindings } = useSWR<HealthFinding[]>(
- `code-health-untested-findings:${id}`,
- () =>
- listHealthFindings(id, { biomarker_type: "untested_hotspot", limit: 50 }).catch(
- () => [],
- ),
- { revalidateOnFocus: false },
- );
-
- const openFilePage = (path: string) =>
- router.push(`${fileEntityPath(`/repos/${id}`, path)}?tab=coverage`);
-
- return (
- <div className="space-y-6">
- {isLoading ? (
- <CoverageSkeleton />
- ) : error ? (
- <EmptyState
- title="Couldn't load coverage data"
- description="The coverage endpoint returned an error. Try refreshing, or re-run the health pass."
- />
- ) : !data || data.summary.file_count === 0 ? (
- <NoCoverageState />
- ) : (
- <CoverageView
- data={data}
- untestedFindings={untestedFindings ?? []}
- onOpenFile={openFilePage}
- onGeneratePrompt={(r) => setPromptRow(r)}
- />
- )}
-
- <AiPromptModal
- open={promptRow !== null}
- onOpenChange={(open) => {
- if (!open) setPromptRow(null);
- }}
- filePath={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
- }
- />
- </div>
- );
-}
-
-function CoverageView({
- data,
- untestedFindings,
- onOpenFile,
- onGeneratePrompt,
-}: {
- data: HealthCoverageResponse;
- untestedFindings: HealthFinding[];
- onOpenFile: (path: string) => void;
- onGeneratePrompt: (row: CoverageFilePromptInput) => void;
-}) {
- const { summary, files, modules } = data;
- const [search, setSearch] = useState("");
-
- const num = (v: unknown): number | null =>
- typeof v === "number" && Number.isFinite(v) ? v : null;
-
- // 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 untested = useMemo(() => {
- const covByPath = new Map(files.map((f) => [f.file_path, f]));
- if (untestedFindings.length > 0) {
- return untestedFindings.slice(0, 10).map((f) => {
- const cov = covByPath.get(f.file_path);
- const d = f.details ?? {};
- return {
- file_path: f.file_path,
- line_coverage_pct:
- num(d.line_coverage_pct) ?? cov?.line_coverage_pct ?? null,
- dependents_count: num(d.dependents_count) ?? undefined,
- commit_count_90d: num(d.commit_count_90d),
- health_score: cov?.health_score,
- };
- });
- }
- return files
- .filter(
- (f) =>
- f.line_coverage_pct != null &&
- f.line_coverage_pct < 30 &&
- (f.health_score == null || f.health_score < 6),
- )
- .slice(0, 10)
- .map((f) => ({
- file_path: f.file_path,
- line_coverage_pct: f.line_coverage_pct,
- health_score: f.health_score,
- }));
- }, [files, untestedFindings]);
-
- const scatterPoints = useMemo(
- () =>
- files
- .filter((f) => f.health_score != null && f.line_coverage_pct != null)
- .map((f) => ({
- file_path: f.file_path,
- health_score: f.health_score!,
- line_coverage_pct: f.line_coverage_pct,
- nloc: f.nloc ?? 0,
- })),
- [files],
- );
-
- const filteredFiles = useMemo(() => {
- if (!search) return files;
- const s = search.toLowerCase();
- return files.filter((f) => f.file_path.toLowerCase().includes(s));
- }, [files, search]);
-
- const columns: ResponsiveColumn<CoverageFileRow>[] = [
- {
- key: "file_path",
- header: "File",
- priority: 1,
- render: (f) => (
- <span className="inline-flex items-center gap-1.5 font-mono text-xs text-[var(--color-text-primary)]">
- <span className="truncate max-w-[420px]" title={f.file_path}>
- {f.file_path}
- </span>
- <ArrowUpRight className="h-3 w-3 shrink-0 text-[var(--color-text-tertiary)]" />
- </span>
- ),
- },
- {
- key: "line_coverage_pct",
- header: "Line coverage",
- priority: 1,
- render: (f) => <CoverageBar value={f.line_coverage_pct} size="sm" />,
- },
- {
- key: "branch_coverage_pct",
- header: "Branch",
- priority: 3,
- align: "right",
- render: (f) => (
- <span className="tabular-nums text-[var(--color-text-secondary)]">
- {f.branch_coverage_pct == null ? "—" : `${f.branch_coverage_pct.toFixed(0)}%`}
- </span>
- ),
- },
- {
- key: "total_coverable_lines",
- header: "Lines",
- priority: 3,
- align: "right",
- render: (f) => (
- <span className="tabular-nums text-[var(--color-text-tertiary)]">
- {f.total_coverable_lines}
- </span>
- ),
- },
- {
- key: "health_score",
- header: "Health",
- priority: 2,
- align: "right",
- render: (f) =>
- f.health_score == null ? (
- <span className="text-[var(--color-text-tertiary)]">—</span>
- ) : (
- <span
- className={`inline-block rounded px-1.5 py-0.5 text-xs font-semibold ${scoreBadgeClass(f.health_score)}`}
- >
- {f.health_score.toFixed(1)}
- </span>
- ),
- },
- {
- key: "actions",
- header: "",
- 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,
- 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-success)] hover:bg-[var(--color-success)]/10 transition-colors"
- >
- <Sparkles className="h-3.5 w-3.5" />
- </button>
- ),
- },
- ];
-
- return (
- <div className="space-y-6">
- <div className="grid grid-cols-1 gap-3 sm:grid-cols-4">
- <MetricCard label="Files" value={summary.file_count.toLocaleString()} />
- <MetricCard
- label="Line coverage"
- value={
- summary.line_coverage_pct == null
- ? "—"
- : `${summary.line_coverage_pct.toFixed(1)}%`
- }
- distBar={
- <span className="text-xs tabular-nums text-[var(--color-text-tertiary)]">
- {summary.covered_lines.toLocaleString()} /{" "}
- {summary.total_lines.toLocaleString()} lines
- </span>
- }
- />
- <MetricCard
- label="Branch coverage"
- value={
- summary.branch_coverage_pct == null
- ? "—"
- : `${summary.branch_coverage_pct.toFixed(1)}%`
- }
- />
- <MetricCard
- label="Source"
- value={
- <span className="text-lg uppercase">{summary.source_format ?? "—"}</span>
- }
- distBar={
- <span className="text-xs text-[var(--color-text-tertiary)]">
- {summary.ingested_at
- ? new Date(summary.ingested_at).toLocaleString()
- : "never"}
- </span>
- }
- />
- </div>
-
- <RiskCoverageScatter points={scatterPoints} onSelect={(p) => onOpenFile(p.file_path)} />
-
- {untested.length > 0 ? <UntestedHotspotWarning entries={untested} /> : null}
-
- <section className="space-y-2">
- <h2 className="text-sm font-semibold text-[var(--color-text-primary)]">
- Module coverage ({modules.length})
- </h2>
- <ModuleCoverageList modules={modules} />
- </section>
-
- <CollapsibleSection
- title={`Files (${filteredFiles.length.toLocaleString()})`}
- defaultOpen={false}
- >
- <div className="flex items-center gap-2">
- <span className="mr-auto text-xs text-[var(--color-text-tertiary)]">
- Per-file coverage — click a row for the line-level heatmap.
- </span>
- <input
- value={search}
- onChange={(e) => setSearch(e.target.value)}
- placeholder="Filter path…"
- className="text-xs px-2 py-1.5 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] w-56 focus:outline-none focus:border-[var(--color-border-strong)]"
- />
- </div>
- <ResponsiveTable
- columns={columns}
- rows={filteredFiles}
- rowKey={(f) => f.file_path}
- onRowClick={(f) => onOpenFile(f.file_path)}
- stacked="sm"
- empty={
- <EmptyState
- title="No files match"
- description="Adjust the path filter to see coverage rows."
- />
- }
- />
- </CollapsibleSection>
- </div>
- );
-}
-
-function NoCoverageState() {
- return (
- <div className="rounded-lg border border-dashed border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-8">
- <div className="max-w-xl mx-auto text-center space-y-3">
- <h2 className="text-base font-semibold text-[var(--color-text-primary)]">
- No coverage data ingested yet
- </h2>
- <p className="text-sm text-[var(--color-text-secondary)]">
- Run your test suite with coverage enabled, then ingest the report.
- You&apos;ll see a risk × coverage map, untested-hotspot warnings, and a
- per-module breakdown.
- </p>
- <pre className="inline-block px-4 py-2 rounded bg-[var(--color-bg-muted)] text-left text-xs font-mono">
- pytest --cov --cov-report=lcov{"\n"}
- repowise health --coverage coverage.lcov
- </pre>
- <p className="text-xs text-[var(--color-text-tertiary)]">
- Supported formats: LCOV · Cobertura · Clover.
- </p>
- </div>
- </div>
- );
-}
-
-function CoverageSkeleton() {
- return (
- <div className="space-y-6">
- <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
- {Array.from({ length: 4 }).map((_, i) => (
- <Skeleton key={i} className="h-24 w-full rounded-lg" />
- ))}
- </div>
- <Skeleton className="h-72 w-full rounded-lg" />
- <Skeleton className="h-48 w-full rounded-lg" />
- </div>
- );
+ const prefix = `/repos/${id}`;
+
+ const adapter: CodeHealthAdapter = {
+ cacheKey: id,
+ getOverview: (limit) => getHealthOverview(id, limit),
+ listFindings: (opts) => listHealthFindings(id, opts),
+ listFiles: (opts) => listHealthFiles(id, opts),
+ getRefactoringTargets: (opts) => getRefactoringTargets(id, opts),
+ updateFindingStatus: (findingId, status) =>
+ updateFindingStatus(id, findingId, status),
+ getCoverage: (opts) => getHealthCoverage(id, opts),
+ fileHref: (path) => fileEntityPath(prefix, path),
+ navigate: (href) => router.push(href),
+ renderFileDrawer: () => null,
+ };
+
+ return <CoverageView adapter={adapter} />;
}
diff --git a/packages/web/src/components/code-health/trend-tab.tsx b/packages/web/src/components/code-health/trend-tab.tsx
index b10622eea..c9638af7a 100644
--- a/packages/web/src/components/code-health/trend-tab.tsx
+++ b/packages/web/src/components/code-health/trend-tab.tsx
@@ -1,162 +1,10 @@
"use client";
/**
- * Trend section — KPI history over recent indexes. Handles the single-snapshot
- * case explicitly (no misleading flat chart) and renders per-file score
- * movement as a slope chart. Trend data is fetched once on the page and passed
- * in, so it isn't double-fetched alongside the KPI sparklines.
+ * Trend section — now the shared {@link TrendView} from `@repowise-dev/ui`.
+ * It is purely presentational (data fetched once at the page level and passed
+ * in), so web and hosted render the same surface with no host wiring. Kept as
+ * a re-export under the original name so the page import is unchanged.
*/
-import { AlertTriangle, TrendingUp } from "lucide-react";
-
-import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
-import {
- TrendChart,
- TrendSlopeChart,
- deltaColor,
- formatDelta,
-} from "@repowise-dev/ui/health";
-import { MetricCard } from "@repowise-dev/ui/shared/metric-card";
-import { EmptyState } from "@repowise-dev/ui/shared/empty-state";
-
-import { type HealthTrendResponse } from "@/lib/api/code-health";
-
-export function TrendSection({
- data,
- isLoading,
- error,
-}: {
- data: HealthTrendResponse | undefined;
- isLoading: boolean;
- error: unknown;
-}) {
- if (isLoading) return <Skeleton className="h-64 w-full rounded-lg" />;
- if (error || !data) {
- return (
- <EmptyState
- title="Couldn't load trend data"
- description="The trend endpoint returned an error. Try refreshing."
- />
- );
- }
-
- const singleSnapshot = data.snapshot_count <= 1;
-
- return (
- <div className="space-y-6">
- <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
- <DeltaMetric
- label="Average health"
- current={data.summary.current_average_health}
- previous={data.summary.previous_average_health}
- delta={data.summary.average_delta}
- />
- <DeltaMetric
- label="Hotspot health"
- current={data.summary.current_hotspot_health}
- previous={data.summary.previous_hotspot_health}
- delta={data.summary.hotspot_delta}
- />
- <MetricCard
- label="Snapshots"
- value={data.snapshot_count}
- distBar={
- <span className="text-xs text-[var(--color-text-tertiary)]">
- rolling window: 50 max
- </span>
- }
- />
- </div>
-
- {data.alerts.length > 0 ? (
- <div className="space-y-2">
- {data.alerts.map((a, i) => (
- <div
- key={i}
- className={`rounded-lg border p-3 flex items-start gap-2 ${
- a.kind === "declining"
- ? "border-[var(--color-error)]/40 bg-[var(--color-error)]/5"
- : "border-[var(--color-warning)]/40 bg-[var(--color-warning)]/5"
- }`}
- >
- <AlertTriangle
- className={`h-4 w-4 mt-0.5 ${a.kind === "declining" ? "text-[var(--color-error)]" : "text-[var(--color-warning)]"}`}
- />
- <div className="text-sm">
- <p className="font-medium text-[var(--color-text-primary)]">
- {a.kind === "declining" ? "Declining health" : "Predicted decline"}
- </p>
- <p className="text-xs text-[var(--color-text-secondary)]">{a.message}</p>
- </div>
- </div>
- ))}
- </div>
- ) : null}
-
- {singleSnapshot ? (
- <EmptyState
- icon={<TrendingUp className="h-6 w-6" />}
- title="One snapshot so far"
- description="The trend lines appear once a second snapshot lands. Run repowise update (or wait for the next sync) and this page fills in."
- />
- ) : (
- <TrendChart history={[...data.history].reverse()} />
- )}
-
- <section className="space-y-2">
- <h2 className="text-sm font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">
- Largest score changes since last index
- </h2>
- {data.file_deltas.length === 0 ? (
- <EmptyState
- title={
- singleSnapshot
- ? "No comparison available yet"
- : "No per-file changes between the last two snapshots"
- }
- description={
- singleSnapshot
- ? "Per-file deltas compare the last two snapshots."
- : undefined
- }
- />
- ) : (
- <TrendSlopeChart points={data.file_deltas} />
- )}
- </section>
- </div>
- );
-}
-
-function DeltaMetric({
- label,
- current,
- previous,
- delta,
-}: {
- label: string;
- current: number;
- previous: number | null;
- delta: number | null;
-}) {
- return (
- <MetricCard
- label={label}
- value={
- <>
- {current.toFixed(1)}
- <span className="text-base font-normal text-[var(--color-text-secondary)]">
- /10
- </span>
- </>
- }
- distBar={
- <span className={`text-xs tabular-nums ${deltaColor(delta)}`}>
- {delta == null
- ? "no prior snapshot"
- : `${formatDelta(delta)} vs. ${previous?.toFixed(1) ?? "—"}`}
- </span>
- }
- />
- );
-}
+export { TrendView as TrendSection } from "@repowise-dev/ui/health";
diff --git a/packages/web/src/components/code-health/triage-tab.tsx b/packages/web/src/components/code-health/triage-tab.tsx
index e1e303e97..a0240bb53 100644
--- a/packages/web/src/components/code-health/triage-tab.tsx
+++ b/packages/web/src/components/code-health/triage-tab.tsx
@@ -1,75 +1,33 @@
"use client";
/**
- * Triage tab — the "what do I fix next" queue. KPI strip, the ranked
- * fix-next list (refactoring-target ranking + file inventory merged into one
- * view), a findings sidebar coordinated by the same severity filter, and the
- * function-level panels.
+ * Triage host — binds the shared {@link TriageView} to web's `/api` client,
+ * `/repos/:id` routing, and the file-detail drawer. The composition itself
+ * lives in `@repowise-dev/ui/health`; this file only injects the app-specific
+ * pieces so web and hosted render the same view.
*/
-import { useCallback, useMemo, useRef, useState } from "react";
+import { useCallback } from "react";
import { useRouter, useSearchParams } from "next/navigation";
-import useSWR from "swr";
-import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
-import { Button } from "@repowise-dev/ui/ui/button";
-import { EmptyState } from "@repowise-dev/ui/shared/empty-state";
-import { symbolEntityPath } from "@repowise-dev/ui/shared/entity";
import {
- AiPromptModal,
- HealthKpiCards,
- HealthFileTable,
- BiomarkerList,
- HotFunctionsPanel,
- HiddenCouplingList,
- CodeHealthMap,
- RecalibrationBanner,
- RefactoringTargetList,
- DefectAccuracyCard,
- FileSpotlight,
- FilterSelect,
- FilterChip,
- ViewToggle,
- ImpactEffortQuadrant,
- biomarkerLabel,
- buildAiPrompt,
- type CodeHealthMapFile,
+ TriageView,
+ type CodeHealthAdapter,
type CodeHealthOverlay,
- type FileSortField,
- type FindingStatus,
- type RefactoringTarget,
- type Severity,
+ type HealthPillar,
} from "@repowise-dev/ui/health";
-import { CollapsibleSection } from "@repowise-dev/ui/shared/collapsible-section";
-import { Gauge, Search } from "lucide-react";
+import { fileEntityPath, symbolEntityPath } from "@repowise-dev/ui/shared/entity";
import {
getHealthOverview,
getRefactoringTargets,
listHealthFiles,
listHealthFindings,
+ getHealthCoverage,
updateFindingStatus,
- type HealthFinding,
- type HealthOverviewResponse,
type HealthTrendResponse,
type HealthFilesResponse,
- type RefactoringTargetsResponse,
- type RefactoringQuery,
} from "@/lib/api/code-health";
import { HealthFileDrawerHost } from "@/components/health/health-file-drawer-host";
-const PAGE_SIZE = 50;
-const QUEUE_PAGE = 200;
-const QUEUE_MAX = 500;
-
-type GroupBy = "none" | "biomarker" | "module" | "effort";
-type QueueView = "queue" | "files";
-
-const EFFORT_LABEL: Record<string, string> = {
- S: "Small (≤40 NLOC)",
- M: "Medium (≤150 NLOC)",
- L: "Large (≤400 NLOC)",
- XL: "Extra large (>400 NLOC)",
-};
-
export function TriageTab({
repoId: id,
trend,
@@ -89,81 +47,20 @@ export function TriageTab({
/** The active lens's per-file signal is still loading (e.g. churn). */
overlayLoading?: boolean;
}) {
- const { data: overview, isLoading, error, mutate } = useSWR<HealthOverviewResponse>(
- `code-health-overview:${id}`,
- () => getHealthOverview(id, 25),
- { revalidateOnFocus: false },
- );
- const { data: hotFunctionFindings } = useSWR<HealthFinding[]>(
- `code-health-hot-functions:${id}`,
- async () => {
- const types = [
- "function_hotspot",
- "code_age_volatility",
- "complex_conditional",
- ] as const;
- const batches = await Promise.all(
- types.map((t) =>
- listHealthFindings(id, { biomarker_type: t, limit: 100 }).catch(
- () => [] as HealthFinding[],
- ),
- ),
- );
- return batches.flat();
- },
- { revalidateOnFocus: false },
- );
-
- const { data: couplingFindings } = useSWR<HealthFinding[]>(
- `code-health-hidden-coupling:${id}`,
- () =>
- listHealthFindings(id, {
- biomarker_type: "hidden_coupling",
- limit: 100,
- }).catch(() => []),
- { revalidateOnFocus: false },
- );
-
- // Every open performance-pillar finding (the cross-function N+1 / I/O-in-loop
- // moat), for the dedicated Performance risks panel.
- const { data: perfFindings } = useSWR<HealthFinding[]>(
- `code-health-perf-findings:${id}`,
- () =>
- listHealthFindings(id, { dimension: "performance", limit: 200 }).catch(
- () => [] as HealthFinding[],
- ),
- { revalidateOnFocus: false },
- );
-
- // ---- One filter set coordinates the queue AND the findings sidebar ----
- const [minSeverity, setMinSeverity] = useState<Severity | "all">("all");
- const [biomarker, setBiomarker] = useState<string>("all");
- const [maxEffort, setMaxEffort] = useState<string>("all");
- const [sort, setSort] = useState<RefactoringQuery["sort"]>("impact_per_effort");
- const [groupBy, setGroupBy] = useState<GroupBy>("none");
- const [queueLimit, setQueueLimit] = useState(QUEUE_PAGE);
- const [view, setView] = useState<QueueView>("queue");
- const [selectedFile, setSelectedFile] = useState<string | null>(null);
- const [promptTarget, setPromptTarget] = useState<RefactoringTarget | null>(null);
-
- // ---- Map-driven UI: rail spotlight + filename dim + collapsible list ----
- const [hoverFile, setHoverFile] = useState<CodeHealthMapFile | null>(null);
- const [mapQuery, setMapQuery] = useState("");
-
- // ---- Pillar filter is URL-synced (?pillar=) so the Overview + KPI tiles can
- // deep-link straight into a single dimension's findings. ----
const router = useRouter();
const searchParams = useSearchParams();
+
+ // Pillar is URL-synced (?pillar=) so the Overview + KPI tiles can deep-link
+ // straight into a single dimension's findings.
const rawPillar = searchParams.get("pillar");
- const pillar: "all" | "defect" | "maintainability" | "performance" =
+ const pillar: HealthPillar =
rawPillar === "defect" ||
rawPillar === "maintainability" ||
rawPillar === "performance"
? rawPillar
: "all";
- const findingsRef = useRef<HTMLDivElement | null>(null);
- const setPillar = useCallback(
- (next: "all" | "defect" | "maintainability" | "performance") => {
+ const onPillarChange = useCallback(
+ (next: HealthPillar) => {
const sp = new URLSearchParams(searchParams.toString());
if (next === "all") sp.delete("pillar");
else sp.set("pillar", next);
@@ -172,529 +69,35 @@ export function TriageTab({
},
[router, searchParams],
);
- const focusPillar = useCallback(
- (next: "defect" | "maintainability" | "performance") => {
- setPillar(next);
- findingsRef.current?.scrollIntoView({ behavior: "smooth", block: "start" });
- },
- [setPillar],
- );
- const queueKey = useMemo(
- () => JSON.stringify({ id, biomarker, minSeverity, maxEffort, sort, queueLimit }),
- [id, biomarker, minSeverity, maxEffort, sort, queueLimit],
- );
- const {
- data: queue,
- isLoading: queueLoading,
- mutate: mutateQueue,
- } = useSWR<RefactoringTargetsResponse>(
- overview ? `code-health-queue:${queueKey}` : null,
- () =>
- getRefactoringTargets(id, {
- limit: queueLimit,
- biomarker: biomarker === "all" ? undefined : biomarker,
- min_severity: minSeverity === "all" ? undefined : minSeverity,
- max_effort: maxEffort === "all" ? undefined : maxEffort,
- sort,
- }),
- { revalidateOnFocus: false, keepPreviousData: true },
- );
-
- // ---- All-files inventory view ----
- const [sortField, setSortField] = useState<FileSortField>("score");
- const [sortOrder, setSortOrder] = useState<"asc" | "desc">("asc");
- const [search, setSearch] = useState("");
- const [onlyHotspots, setOnlyHotspots] = useState(false);
- const [onlyUntested, setOnlyUntested] = useState(false);
- const [onlyFailing, setOnlyFailing] = useState(false);
- const [offset, setOffset] = useState(0);
-
- const filesKey = useMemo(
- () =>
- JSON.stringify({
- id,
- sortField,
- sortOrder,
- search,
- onlyHotspots,
- onlyUntested,
- onlyFailing,
- offset,
- }),
- [id, sortField, sortOrder, search, onlyHotspots, onlyUntested, onlyFailing, offset],
- );
-
- const { data: files, isLoading: filesLoading } = useSWR<HealthFilesResponse>(
- overview && view === "files" ? `code-health-files:${filesKey}` : null,
- () =>
- listHealthFiles(id, {
- sort: sortField,
- order: sortOrder,
- search: search || undefined,
- only_hotspots: onlyHotspots || undefined,
- only_untested: onlyUntested || undefined,
- only_failing: onlyFailing || undefined,
- offset,
- limit: PAGE_SIZE,
- }),
- { revalidateOnFocus: false, keepPreviousData: true },
- );
-
- const handleSort = (field: FileSortField) => {
- if (field === sortField) {
- setSortOrder((o) => (o === "asc" ? "desc" : "asc"));
- } else {
- setSortField(field);
- // Score: asc (worst first). Counts: desc. Path: asc.
- setSortOrder(["score", "line_coverage_pct", "file_path"].includes(field) ? "asc" : "desc");
- }
- setOffset(0);
- };
-
- const handleStatus = async (findingId: string, status: FindingStatus) => {
- await updateFindingStatus(id, findingId, status);
- mutateQueue();
+ const prefix = `/repos/${id}`;
+ const adapter: CodeHealthAdapter = {
+ cacheKey: id,
+ getOverview: (limit) => getHealthOverview(id, limit),
+ listFindings: (opts) => listHealthFindings(id, opts),
+ listFiles: (opts) => listHealthFiles(id, opts),
+ getRefactoringTargets: (opts) => getRefactoringTargets(id, opts),
+ updateFindingStatus: (findingId, status) =>
+ updateFindingStatus(id, findingId, status),
+ getCoverage: (opts) => getHealthCoverage(id, opts),
+ fileHref: (path) => fileEntityPath(prefix, path),
+ symbolHref: (symbolId) => symbolEntityPath(prefix, symbolId),
+ navigate: (href) => router.push(href),
+ renderFileDrawer: ({ filePath, onClose }) => (
+ <HealthFileDrawerHost repoId={id} filePath={filePath} onClose={onClose} />
+ ),
};
- const biomarkerOptions = useMemo(() => {
- const set = new Set<string>();
- (overview?.biomarkers ?? []).forEach((b) => set.add(b.biomarker_type));
- (queue?.targets ?? []).forEach((t) => t.biomarkers.forEach((b) => set.add(b)));
- return [...set].sort();
- }, [overview, queue]);
-
- // Grouped queue — group order follows the user's sort (first occurrence),
- // not group size, so "Leverage" sorted stays leverage-led inside and out.
- const grouped = useMemo(() => {
- const targets = queue?.targets ?? [];
- if (groupBy === "none") return [{ key: "All", targets }];
- const groups = new Map<string, typeof targets>();
- for (const t of targets) {
- let key = "—";
- if (groupBy === "biomarker") key = biomarkerLabel(t.primary_biomarker);
- else if (groupBy === "module") key = t.module ?? "(no module)";
- else if (groupBy === "effort") key = EFFORT_LABEL[t.effort_bucket] ?? t.effort_bucket;
- if (!groups.has(key)) groups.set(key, []);
- groups.get(key)!.push(t);
- }
- return [...groups.entries()].map(([key, targets]) => ({ key, targets }));
- }, [queue, groupBy]);
-
- const avgSeries = trend?.history?.slice().reverse().map((p) => p.average_health);
- const hotspotSeries = trend?.history?.slice().reverse().map((p) => p.hotspot_health);
- const worstSeries = trend?.history
- ?.slice()
- .reverse()
- .map((p) => p.worst_performer_score ?? 0);
-
return (
- <div className="space-y-6">
- {isLoading ? (
- <div className="space-y-3">
- <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
- {Array.from({ length: 3 }).map((_, i) => (
- <Skeleton key={i} className="h-28 w-full rounded-xl" />
- ))}
- </div>
- <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
- {Array.from({ length: 4 }).map((_, i) => (
- <Skeleton key={i} className="h-20 w-full rounded-lg" />
- ))}
- </div>
- </div>
- ) : error ? (
- <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-4 text-sm text-[var(--color-text-secondary)] flex items-center justify-between gap-2">
- <span>Couldn&apos;t load health data. Run <code>repowise init</code> to populate.</span>
- <Button size="sm" variant="outline" onClick={() => mutate()}>Retry</Button>
- </div>
- ) : overview ? (
- <>
- <RecalibrationBanner repoId={id} />
- <HealthKpiCards
- summary={overview.summary}
- distribution={overview.distribution}
- averageHistory={avgSeries}
- hotspotHistory={hotspotSeries}
- worstHistory={worstSeries}
- averageDelta={trend?.summary?.average_delta ?? undefined}
- hotspotDelta={trend?.summary?.hotspot_delta ?? undefined}
- onSelectPillar={focusPillar}
- />
-
- {overview.defect_accuracy ? (
- <DefectAccuracyCard data={overview.defect_accuracy} collapsible />
- ) : null}
-
- {/* Hero: the Code Health Map — modules as nested bubbles, files
- sized by lines of code and colored by health. The centerpiece. */}
- <div className="grid grid-cols-1 lg:grid-cols-[minmax(0,1fr)_320px] gap-6">
- <div className="space-y-2">
- <div className="flex flex-wrap items-baseline gap-2">
- <h2 className="text-base font-semibold text-[var(--color-text-primary)]">
- Code health map
- </h2>
- <span className="text-xs text-[var(--color-text-tertiary)]">
- {mapFiles ? `${mapFiles.total.toLocaleString()} files` : "loading…"} · click a module to
- zoom, a file to open
- </span>
- </div>
- {!mapFiles ? (
- <Skeleton className="w-full rounded-xl" style={{ height: 664 }} />
- ) : (
- <CodeHealthMap
- files={mapFiles.files}
- search={mapQuery}
- selectedPath={selectedFile}
- onSelectFile={(p) => setSelectedFile(p)}
- onHoverFile={setHoverFile}
- minHeight={664}
- overlay={overlay}
- onOverlayChange={onOverlayChange}
- overlayLoading={overlayLoading}
- />
- )}
- </div>
-
- {/* Inspector rail — height-matched to the map (master–detail).
- Search + the file you're inspecting sit on top; the findings
- list scrolls in place so the rail never outgrows the map. */}
- <aside className="flex flex-col gap-3 lg:sticky lg:top-4 lg:h-[700px]">
- <div className="relative">
- <Search className="absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-[var(--color-text-tertiary)]" />
- <input
- value={mapQuery}
- onChange={(e) => setMapQuery(e.target.value)}
- placeholder="Find a file in the map…"
- className="w-full text-xs pl-7 pr-2 py-1.5 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] focus:outline-none focus:border-[var(--color-border-strong)]"
- />
- </div>
-
- <FileSpotlight file={hoverFile} onOpen={(p) => setSelectedFile(p)} />
-
- <div ref={findingsRef} className="flex items-center gap-2 scroll-mt-4">
- <h2 className="text-sm font-medium uppercase tracking-wider text-[var(--color-text-tertiary)] mr-auto">
- Findings
- </h2>
- <select
- value={pillar}
- onChange={(e) =>
- setPillar(
- e.target.value as
- | "all"
- | "defect"
- | "maintainability"
- | "performance",
- )
- }
- aria-label="Health pillar"
- className="text-xs px-2 py-1 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)]"
- >
- <option value="all">All pillars</option>
- <option value="defect">Defect risk</option>
- <option value="maintainability">Maintainability</option>
- <option value="performance">Performance</option>
- </select>
- <select
- value={minSeverity}
- onChange={(e) => setMinSeverity(e.target.value as Severity | "all")}
- aria-label="Minimum severity (filters the queue too)"
- className="text-xs px-2 py-1 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)]"
- >
- <option value="all">All severities</option>
- <option value="low">Low+</option>
- <option value="medium">Medium+</option>
- <option value="high">High+</option>
- <option value="critical">Critical</option>
- </select>
- </div>
- <div className="min-h-0 flex-1 overflow-y-auto pr-1 lg:pb-0 pb-1">
- <BiomarkerList
- findings={overview.top_findings}
- grouped
- minSeverity={minSeverity === "all" ? undefined : minSeverity}
- dimension={pillar === "all" ? undefined : pillar}
- onSelect={(f) => setSelectedFile(f.file_path)}
- />
- </div>
- </aside>
- </div>
-
- {/* Performance risks — the cross-function N+1 / I/O-in-loop moat,
- given a dedicated home. Only rendered when risks actually exist
- (high precision, low recall), so a clean repo stays uncluttered. */}
- {perfFindings && perfFindings.length > 0 ? (
- <CollapsibleSection
- title={
- <span className="inline-flex items-center gap-2">
- <Gauge className="h-4 w-4 text-[var(--color-info)]" />
- Performance risks
- </span>
- }
- hint={`${perfFindings.length} ${perfFindings.length === 1 ? "risk" : "risks"}`}
- defaultOpen
- >
- <div className="space-y-3">
- <p className="text-xs text-[var(--color-text-secondary)]">
- Static performance risk: a DB, network, filesystem, or subprocess call
- per loop iteration, detected across function boundaries via the call
- graph. High precision, low recall, never blended into the defect score.
- </p>
- <BiomarkerList
- findings={perfFindings}
- grouped
- onSelect={(f) => setSelectedFile(f.file_path)}
- />
- </div>
- </CollapsibleSection>
- ) : null}
-
- {/* Collapsible: the full ranked queue + file inventory. The severity
- filter is shared with the rail above (one control, no duplicate). */}
- <CollapsibleSection
- title="Targets &amp; findings list"
- hint={queue?.total != null ? `${queue.total} candidates` : ""}
- defaultOpen={false}
- >
- <div className="space-y-3">
- <div className="flex flex-wrap items-center gap-2">
- <h3 className="text-sm font-medium uppercase tracking-wider text-[var(--color-text-tertiary)] mr-auto">
- Fix next
- </h3>
- <ViewToggle
- value={view}
- onChange={setView}
- options={[
- { value: "queue", label: "Queue" },
- { value: "files", label: "All files" },
- ]}
- />
- </div>
-
- {view === "queue" ? (
- <>
- <div className="flex flex-wrap items-center gap-2">
- <FilterSelect
- label="Biomarker"
- value={biomarker}
- onChange={setBiomarker}
- options={[
- { value: "all", label: "All biomarkers" },
- ...biomarkerOptions.map((b) => ({ value: b, label: biomarkerLabel(b) })),
- ]}
- />
- <FilterSelect
- label="Max effort"
- value={maxEffort}
- onChange={setMaxEffort}
- options={[
- { value: "all", label: "Any effort" },
- { value: "S", label: "Small only" },
- { value: "M", label: "Medium+" },
- { value: "L", label: "Large+" },
- ]}
- />
- <FilterSelect
- label="Sort"
- value={sort ?? "impact_per_effort"}
- onChange={(v) => setSort(v as RefactoringQuery["sort"])}
- options={[
- { value: "impact_per_effort", label: "Leverage (impact ÷ effort)" },
- { value: "total_impact", label: "Total impact" },
- { value: "score", label: "Worst score" },
- { value: "finding_count", label: "Finding count" },
- ]}
- />
- <FilterSelect
- label="Group"
- value={groupBy}
- onChange={(v) => setGroupBy(v as GroupBy)}
- options={[
- { value: "none", label: "Flat list" },
- { value: "biomarker", label: "By biomarker" },
- { value: "module", label: "By module" },
- { value: "effort", label: "By effort" },
- ]}
- />
- </div>
-
- {queueLoading && !queue ? (
- <div className="grid gap-3">
- {Array.from({ length: 4 }).map((_, i) => (
- <Skeleton key={i} className="h-28 w-full" />
- ))}
- </div>
- ) : !queue || queue.targets.length === 0 ? (
- <EmptyState
- title="No findings match the current filters"
- description="Try widening the severity or effort filters, or run repowise health to populate findings."
- />
- ) : (
- <>
- {/* Leverage at a glance — impact vs effort, click a dot
- to open the file. Replaces the text-dense ranking as
- the first read of the queue. */}
- <ImpactEffortQuadrant
- points={(queue?.targets ?? []).map((t) => ({
- file_path: t.file_path,
- total_impact: t.total_impact,
- effort_bucket: t.effort_bucket,
- nloc: t.nloc,
- score: t.score,
- }))}
- onSelect={(p) => setSelectedFile(p.file_path)}
- />
- <div className="space-y-6">
- {grouped.map((g) => (
- <section key={g.key} className="space-y-2">
- {groupBy !== "none" ? (
- <h3 className="text-xs font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">
- {g.key}{" "}
- <span className="text-[var(--color-text-secondary)]">
- ({g.targets.length})
- </span>
- </h3>
- ) : null}
- <RefactoringTargetList
- targets={g.targets}
- onSelect={(t) => setSelectedFile(t.file_path)}
- onStatusChange={handleStatus}
- onGeneratePrompt={(t) => setPromptTarget(t)}
- />
- </section>
- ))}
- </div>
-
- <div className="flex items-center justify-between gap-2 text-xs text-[var(--color-text-tertiary)]">
- <span>
- Showing {queue.targets.length} of {queue.total} candidates
- </span>
- {queue.total > queue.targets.length && queueLimit < QUEUE_MAX ? (
- <Button
- size="sm"
- variant="outline"
- onClick={() => setQueueLimit(QUEUE_MAX)}
- >
- Load more
- </Button>
- ) : null}
- </div>
- </>
- )}
- </>
- ) : (
- <>
- <div className="flex flex-wrap items-center gap-2">
- <div className="relative">
- <Search className="absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-[var(--color-text-tertiary)]" />
- <input
- value={search}
- onChange={(e) => {
- setSearch(e.target.value);
- setOffset(0);
- }}
- placeholder="Filter path…"
- className="text-xs pl-7 pr-2 py-1.5 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] w-56 focus:outline-none focus:border-[var(--color-border-strong)]"
- />
- </div>
- <FilterChip active={onlyHotspots} onClick={() => { setOnlyHotspots((v) => !v); setOffset(0); }}>
- Hotspots
- </FilterChip>
- <FilterChip active={onlyUntested} onClick={() => { setOnlyUntested((v) => !v); setOffset(0); }}>
- Untested
- </FilterChip>
- <FilterChip active={onlyFailing} onClick={() => { setOnlyFailing((v) => !v); setOffset(0); }}>
- Failing
- </FilterChip>
- <span className="text-xs text-[var(--color-text-tertiary)] ml-auto">
- {files?.total != null ? `${files.total.toLocaleString()} files` : ""}
- </span>
- </div>
-
- {filesLoading && !files ? (
- <Skeleton className="h-64 w-full rounded-lg" />
- ) : (
- <HealthFileTable
- files={files?.files ?? []}
- sortField={sortField}
- sortOrder={sortOrder}
- onSort={handleSort}
- onSelect={(f) => setSelectedFile(f.file_path)}
- selectedPath={selectedFile}
- />
- )}
-
- {files && files.total > PAGE_SIZE ? (
- <div className="flex items-center justify-between gap-2 text-xs text-[var(--color-text-tertiary)]">
- <span>
- Showing {offset + 1}–{Math.min(offset + PAGE_SIZE, files.total)} of {files.total}
- </span>
- <div className="flex gap-1">
- <Button
- size="sm"
- variant="outline"
- disabled={offset === 0}
- onClick={() => setOffset(Math.max(0, offset - PAGE_SIZE))}
- >
- Prev
- </Button>
- <Button
- size="sm"
- variant="outline"
- disabled={offset + PAGE_SIZE >= files.total}
- onClick={() => setOffset(offset + PAGE_SIZE)}
- >
- Next
- </Button>
- </div>
- </div>
- ) : null}
- </>
- )}
- </div>
- </CollapsibleSection>
-
- {hotFunctionFindings && hotFunctionFindings.length >= 3 ? (
- <HotFunctionsPanel
- findings={hotFunctionFindings}
- collapsible
- onSelect={(f) => setSelectedFile(f.file_path)}
- symbolHrefFor={(f) =>
- f.symbol_id ? symbolEntityPath(`/repos/${id}`, f.symbol_id) : undefined
- }
- />
- ) : null}
-
- {couplingFindings && couplingFindings.length >= 3 ? (
- <HiddenCouplingList
- findings={couplingFindings}
- collapsible
- onSelect={(path) => setSelectedFile(path)}
- />
- ) : null}
- </>
- ) : null}
-
- <HealthFileDrawerHost
- repoId={id}
- filePath={selectedFile}
- onClose={() => setSelectedFile(null)}
- />
-
- <AiPromptModal
- open={promptTarget !== null}
- onOpenChange={(open) => {
- if (!open) setPromptTarget(null);
- }}
- filePath={promptTarget?.file_path}
- title="AI fix prompt"
- description="A ready-to-paste prompt that gives your AI coding agent every biomarker, line range, score deduction, and constraint needed to refactor this file in one focused pass."
- getPrompt={
- promptTarget
- ? (flavor) => buildAiPrompt({ target: promptTarget, flavor })
- : null
- }
- />
- </div>
+ <TriageView
+ adapter={adapter}
+ trend={trend}
+ overlay={overlay}
+ onOverlayChange={onOverlayChange}
+ mapFiles={mapFiles}
+ overlayLoading={overlayLoading}
+ pillar={pillar}
+ onPillarChange={onPillarChange}
+ />
);
}
diff --git a/packages/web/src/components/decisions/decision-detail.tsx b/packages/web/src/components/decisions/decision-detail.tsx
index 727b1702c..15577e706 100644
--- a/packages/web/src/components/decisions/decision-detail.tsx
+++ b/packages/web/src/components/decisions/decision-detail.tsx
@@ -1,20 +1,18 @@
"use client";
-import * as React from "react";
-import ReactMarkdown from "react-markdown";
-import remarkGfm from "remark-gfm";
-import useSWR from "swr";
-import { toast } from "sonner";
+/**
+ * Decision detail host — binds the shared {@link SharedDecisionDetail} to web's
+ * `/api` client, `/repos/:id` routing, and `next/link`. The composition
+ * (markdown body, lineage, module-link editor, evidence drawer, AI prompt,
+ * confirm/undo status actions) lives in `@repowise-dev/ui/decisions`; this file
+ * only injects the app-specific pieces so web and hosted render the same view.
+ */
+
import Link from "next/link";
-import { ChevronLeft, ChevronRight, FileSearch, Flame, GitCommitHorizontal } from "lucide-react";
-import { Badge } from "@repowise-dev/ui/ui/badge";
-import { stripMarkdown } from "@repowise-dev/ui/lib/format";
-import { ConfirmDialog } from "@repowise-dev/ui/ui/confirm-dialog";
-import { ModuleLinkEditor } from "@repowise-dev/ui/decisions/module-link-editor";
-import { VerificationBadge } from "@repowise-dev/ui/decisions/verification-badge";
-import { DecisionEvidenceDrawer } from "@repowise-dev/ui/decisions/decision-evidence-drawer";
-import { DecisionLineage } from "@repowise-dev/ui/decisions/decision-lineage";
-import { AiPromptButton, AiPromptModal, buildDecisionAiPrompt } from "@repowise-dev/ui/health";
+import {
+ DecisionDetail as SharedDecisionDetail,
+ type DecisionDetailAdapter,
+} from "@repowise-dev/ui/decisions";
import {
getDecisionEvidence,
getDecisionLineage,
@@ -24,467 +22,43 @@ import {
import { listModuleHealth } from "@/lib/api/modules";
import type { DecisionRecordResponse } from "@/lib/api/types";
-const STATUS_VARIANT: Record<string, "default" | "fresh" | "stale" | "outdated" | "outline" | "accent"> = {
- active: "fresh",
- proposed: "accent",
- deprecated: "outdated",
- superseded: "outline",
-};
-
interface DecisionDetailProps {
decision: DecisionRecordResponse;
repoId: string;
}
-const CONFIRM_COPY: Record<string, { title: string; description: string; confirmLabel: string; destructive: boolean }> = {
- active: {
- title: "Confirm decision?",
- description: "Mark this decision as active.",
- confirmLabel: "Confirm",
- destructive: false,
- },
- deprecated: {
- title: "Deprecate decision?",
- description: "This will mark the decision as deprecated. Existing references remain but it will no longer be considered current.",
- confirmLabel: "Deprecate",
- destructive: true,
- },
-};
-
export function DecisionDetail({ decision, repoId }: DecisionDetailProps) {
- const [status, setStatus] = React.useState(decision.status);
- const [loading, setLoading] = React.useState(false);
- const [pendingStatus, setPendingStatus] = React.useState<string | null>(null);
- const [linkedModules, setLinkedModules] = React.useState(decision.affected_modules);
- const [linkedFiles, setLinkedFiles] = React.useState(decision.affected_files);
- const [linkageSaving, setLinkageSaving] = React.useState(false);
- const [evidenceOpen, setEvidenceOpen] = React.useState(false);
- const [promptOpen, setPromptOpen] = React.useState(false);
-
- // Lineage: cheap, load eagerly so the Evolution timeline renders when present.
- const { data: lineage } = useSWR(
- `decision-lineage:${repoId}:${decision.id}`,
- () => getDecisionLineage(repoId, decision.id),
- { revalidateOnFocus: false },
- );
-
- // Evidence: lazy — only fetched once the drawer is opened.
- const {
- data: evidence,
- error: evidenceError,
- isLoading: evidenceLoading,
- } = useSWR(
- evidenceOpen ? `decision-evidence:${repoId}:${decision.id}` : null,
- () => getDecisionEvidence(repoId, decision.id),
- { revalidateOnFocus: false },
- );
-
- // Sibling list for prev/next navigation — same ordering as the list page.
- const { data: siblings } = useSWR(
- `decisions-siblings:${repoId}`,
- () => listDecisions(repoId, { include_proposed: true, limit: 100 }),
- { revalidateOnFocus: false },
- );
- const { prevId, nextId } = React.useMemo(() => {
- const ids = (siblings ?? []).map((d) => d.id);
- const idx = ids.indexOf(decision.id);
- return {
- prevId: idx > 0 ? ids[idx - 1] : null,
- nextId: idx >= 0 && idx < ids.length - 1 ? ids[idx + 1] : null,
- };
- }, [siblings, decision.id]);
-
- // Suggestions for the module autocomplete — top-level modules indexed for
- // this repo. Loaded once; cheap to cache.
- const { data: moduleHealth } = useSWR(
- `module-health-suggestions:${repoId}`,
- () => listModuleHealth(repoId, { sort: "file_count", limit: 500 }),
- { revalidateOnFocus: false },
- );
- const moduleSuggestions = React.useMemo(
- () => (moduleHealth?.items ?? []).map((m) => m.module_path),
- [moduleHealth],
- );
-
- const saveLinkage = async (next: { modules: string[]; files: string[] }) => {
- const previousModules = linkedModules;
- const previousFiles = linkedFiles;
- setLinkageSaving(true);
- try {
- await patchDecision(repoId, decision.id, {
- affected_modules: next.modules,
- affected_files: next.files,
- });
- setLinkedModules(next.modules);
- setLinkedFiles(next.files);
- toast.success("Decision linkage updated", {
- action: {
- label: "Undo",
- onClick: async () => {
- try {
- await patchDecision(repoId, decision.id, {
- affected_modules: previousModules,
- affected_files: previousFiles,
- });
- setLinkedModules(previousModules);
- setLinkedFiles(previousFiles);
- } catch (err) {
- toast.error(
- err instanceof Error ? `Couldn't undo: ${err.message}` : "Couldn't undo",
- );
- }
- },
- },
- duration: 6000,
- });
- } catch (err) {
- toast.error(
- err instanceof Error
- ? `Couldn't save linkage: ${err.message}`
- : "Couldn't save linkage",
- );
- } finally {
- setLinkageSaving(false);
- }
- };
-
- const applyStatusChange = async (newStatus: string) => {
- const previous = status;
- setLoading(true);
- try {
- await patchDecision(repoId, decision.id, { status: newStatus });
- setStatus(newStatus as typeof status);
- setPendingStatus(null);
- toast.success(`Decision marked ${newStatus.replace(/_/g, " ")}`, {
- action: {
- label: "Undo",
- onClick: async () => {
- try {
- await patchDecision(repoId, decision.id, { status: previous });
- setStatus(previous);
- } catch (err) {
- toast.error(
- err instanceof Error ? `Couldn't undo: ${err.message}` : "Couldn't undo",
- );
- }
- },
- },
- duration: 6000,
- });
- } catch (err) {
- toast.error(
- err instanceof Error
- ? `Couldn't update decision: ${err.message}`
- : "Couldn't update decision",
- );
- } finally {
- setLoading(false);
- }
+ const prefix = `/repos/${repoId}`;
+
+ const adapter: DecisionDetailAdapter = {
+ cacheKey: `${repoId}:${decision.id}`,
+ repoId,
+ getLineage: () => getDecisionLineage(repoId, decision.id),
+ getEvidence: () => getDecisionEvidence(repoId, decision.id),
+ listSiblingIds: () =>
+ listDecisions(repoId, { include_proposed: true, limit: 100 }).then((rows) =>
+ rows.map((d) => d.id),
+ ),
+ listModuleSuggestions: () =>
+ listModuleHealth(repoId, { sort: "file_count", limit: 500 }).then((m) =>
+ m.items.map((x) => x.module_path),
+ ),
+ patchDecision: async (patch) => {
+ await patchDecision(repoId, decision.id, patch);
+ },
+ decisionsHref: () => `${prefix}/decisions`,
+ decisionHref: (id) => `${prefix}/decisions/${id}`,
+ commitsHref: (opts) => {
+ const qs = opts?.commit
+ ? `?commit=${opts.commit}`
+ : opts?.sort
+ ? `?sort=${opts.sort}`
+ : "";
+ return `${prefix}/commits${qs}`;
+ },
+ hotspotsHref: () => `${prefix}/code-health?tab=hotspots`,
+ LinkComponent: Link,
};
- const handleStatusChange = (newStatus: string) => {
- if (CONFIRM_COPY[newStatus]) {
- setPendingStatus(newStatus);
- } else {
- void applyStatusChange(newStatus);
- }
- };
-
- const confirmConfig = pendingStatus ? CONFIRM_COPY[pendingStatus] : null;
-
- return (
- <div className="space-y-6">
- <div className="flex items-center justify-between gap-2">
- <Link
- href={`/repos/${repoId}/decisions`}
- className="inline-flex items-center gap-1 text-xs text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)]"
- >
- <ChevronLeft className="h-3.5 w-3.5" />
- All decisions
- </Link>
- <div className="flex items-center gap-1">
- <PrevNextLink
- href={prevId ? `/repos/${repoId}/decisions/${prevId}` : null}
- label="Previous decision"
- >
- <ChevronLeft className="h-3.5 w-3.5" /> Prev
- </PrevNextLink>
- <PrevNextLink
- href={nextId ? `/repos/${repoId}/decisions/${nextId}` : null}
- label="Next decision"
- >
- Next <ChevronRight className="h-3.5 w-3.5" />
- </PrevNextLink>
- </div>
- </div>
- {/* Header */}
- <div className="space-y-2">
- <div className="flex flex-wrap items-center gap-3">
- <h1 className="text-xl font-semibold text-[var(--color-text-primary)]">
- {stripMarkdown(decision.title)}
- </h1>
- <Badge variant={STATUS_VARIANT[status] ?? "outline"}>{status}</Badge>
- {decision.verification && (
- <VerificationBadge verification={decision.verification} />
- )}
- <AiPromptButton
- label={status === "proposed" ? "Verify & confirm with AI" : "Verify with AI"}
- onClick={() => setPromptOpen(true)}
- className="ml-auto"
- />
- <button
- type="button"
- onClick={() => setEvidenceOpen(true)}
- className="inline-flex items-center gap-1.5 rounded-md border border-[var(--color-border-default)] px-2.5 py-1 text-xs text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)]"
- >
- <FileSearch className="h-3.5 w-3.5" />
- Evidence
- </button>
- </div>
- <div className="flex gap-4 text-sm text-[var(--color-text-tertiary)]">
- <span>Source: {decision.source}</span>
- <span>Confidence: {Math.round(decision.confidence * 100)}%</span>
- {decision.staleness_score > 0 && (
- <span className={decision.staleness_score > 0.5 ? "text-[var(--color-error)]" : ""}>
- Staleness: {decision.staleness_score.toFixed(2)}
- </span>
- )}
- <span>Created: {new Date(decision.created_at).toLocaleDateString()}</span>
- </div>
- </div>
-
- {/* Stale warning */}
- {decision.staleness_score > 0.5 && (
- <div className="rounded-md border border-[var(--color-warning)]/30 bg-[var(--color-warning)]/10 px-4 py-3 text-sm text-[var(--color-warning)]">
- This decision may be stale — affected files have changed significantly since it was recorded.
- </div>
- )}
-
- {/* Evolution / lineage chain */}
- {lineage && lineage.length > 1 && (
- <DecisionLineage lineage={lineage} repoId={repoId} LinkComponent={Link} />
- )}
-
- {/* Content sections */}
- <div className="space-y-4">
- {decision.context && (
- <Section title="Context" text={decision.context} />
- )}
- {decision.decision && (
- <Section title="Decision" text={decision.decision} />
- )}
- {decision.rationale && (
- <Section title="Rationale" text={decision.rationale} />
- )}
- {decision.alternatives.length > 0 && (
- <ListSection title="Alternatives Rejected" items={decision.alternatives} />
- )}
- {decision.consequences.length > 0 && (
- <ListSection title="Consequences & Tradeoffs" items={decision.consequences} />
- )}
- </div>
-
- {/* Governance linkage — writable editor + evidence card */}
- <div className="grid gap-4 sm:grid-cols-2">
- <ModuleLinkEditor
- modules={linkedModules}
- files={linkedFiles}
- suggestions={moduleSuggestions}
- saving={linkageSaving}
- onSave={saveLinkage}
- />
-
- {/* The full evidence rows live in the drawer (Evidence button); this
- card answers "what happened to the governed code since?". */}
- <div className="rounded-lg border border-[var(--color-border-default)] p-4">
- <h3 className="mb-2 text-sm font-medium text-[var(--color-text-secondary)]">
- Since this decision
- </h3>
- <div className="space-y-2 text-sm">
- {decision.last_code_change && (
- <p className="text-xs text-[var(--color-text-tertiary)]">
- Affected files last changed{" "}
- {new Date(decision.last_code_change).toLocaleDateString()}.
- </p>
- )}
- <div className="flex flex-col gap-1.5">
- <Link
- href={`/repos/${repoId}/commits?sort=date`}
- className="inline-flex items-center gap-1.5 text-xs text-[var(--color-text-secondary)] hover:text-[var(--color-accent-primary)] hover:underline"
- >
- <GitCommitHorizontal className="h-3.5 w-3.5" />
- Recent commits to this repo
- </Link>
- <Link
- href={`/repos/${repoId}/code-health?tab=hotspots`}
- className="inline-flex items-center gap-1.5 text-xs text-[var(--color-text-secondary)] hover:text-[var(--color-accent-primary)] hover:underline"
- >
- <Flame className="h-3.5 w-3.5" />
- Hotspots &amp; churn in affected areas
- </Link>
- </div>
- {decision.evidence_commits.length > 0 && (
- <p className="text-xs text-[var(--color-text-tertiary)]">
- Evidence commits:{" "}
- {decision.evidence_commits.slice(0, 4).map((c, i) => (
- <React.Fragment key={c}>
- {i > 0 && ", "}
- <Link
- href={`/repos/${repoId}/commits?commit=${c}`}
- className="font-mono hover:text-[var(--color-accent-primary)] hover:underline"
- >
- {c.slice(0, 8)}
- </Link>
- </React.Fragment>
- ))}
- </p>
- )}
- </div>
- </div>
- </div>
-
- {/* Tags */}
- {decision.tags.length > 0 && (
- <div className="flex flex-wrap gap-1.5">
- {decision.tags.map((tag) => (
- <span
- key={tag}
- className="inline-block rounded-full bg-[var(--color-bg-elevated)] px-2.5 py-0.5 text-xs font-medium text-[var(--color-text-secondary)]"
- >
- {tag}
- </span>
- ))}
- </div>
- )}
-
- {/* Actions */}
- <div className="flex gap-2 border-t border-[var(--color-border-default)] pt-4">
- {status === "proposed" && (
- <>
- <button
- onClick={() => handleStatusChange("active")}
- disabled={loading}
- className="rounded-md bg-[var(--color-success)] px-3 py-1.5 text-sm font-medium text-[var(--color-text-inverse)] hover:opacity-90 disabled:opacity-50"
- >
- Confirm
- </button>
- <button
- onClick={() => handleStatusChange("deprecated")}
- disabled={loading}
- className="rounded-md border border-[var(--color-border-default)] px-3 py-1.5 text-sm text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] disabled:opacity-50"
- >
- Dismiss
- </button>
- </>
- )}
- {status === "active" && (
- <button
- onClick={() => handleStatusChange("deprecated")}
- disabled={loading}
- className="rounded-md border border-[var(--color-error)]/40 px-3 py-1.5 text-sm text-[var(--color-error)] hover:bg-[var(--color-error)]/10 disabled:opacity-50"
- >
- Deprecate
- </button>
- )}
- </div>
- {confirmConfig && (
- <ConfirmDialog
- open={pendingStatus !== null}
- onOpenChange={(o) => !o && setPendingStatus(null)}
- title={confirmConfig.title}
- description={confirmConfig.description}
- confirmLabel={confirmConfig.confirmLabel}
- destructive={confirmConfig.destructive}
- loading={loading}
- onConfirm={() => applyStatusChange(pendingStatus!)}
- />
- )}
-
- <DecisionEvidenceDrawer
- open={evidenceOpen}
- onClose={() => setEvidenceOpen(false)}
- evidence={evidence}
- isLoading={evidenceLoading}
- error={evidenceError}
- decisionTitle={decision.title}
- />
-
- <AiPromptModal
- open={promptOpen}
- onOpenChange={setPromptOpen}
- getPrompt={(flavor) =>
- buildDecisionAiPrompt({
- decision: {
- title: decision.title,
- status,
- context: decision.context,
- decision: decision.decision,
- rationale: decision.rationale,
- alternatives: decision.alternatives,
- consequences: decision.consequences,
- affected_modules: linkedModules,
- affected_files: linkedFiles,
- staleness_score: decision.staleness_score,
- confidence: decision.confidence,
- },
- flavor,
- })
- }
- filePath={stripMarkdown(decision.title)}
- title="AI decision verification"
- description="A ready-to-paste prompt that has your AI agent check this decision against the current code and recommend whether to keep, update, or retire it."
- />
- </div>
- );
-}
-
-function PrevNextLink({
- href,
- label,
- children,
-}: {
- href: string | null;
- label: string;
- children: React.ReactNode;
-}) {
- if (!href) {
- return (
- <span className="inline-flex items-center gap-0.5 rounded-md border border-[var(--color-border-default)] px-2 py-1 text-xs text-[var(--color-text-tertiary)] opacity-50">
- {children}
- </span>
- );
- }
- return (
- <Link
- href={href}
- aria-label={label}
- className="inline-flex items-center gap-0.5 rounded-md border border-[var(--color-border-default)] px-2 py-1 text-xs text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]"
- >
- {children}
- </Link>
- );
-}
-
-function Section({ title, text }: { title: string; text: string }) {
- return (
- <div>
- <h3 className="mb-1 text-sm font-medium text-[var(--color-text-secondary)]">{title}</h3>
- <div className="text-sm text-[var(--color-text-primary)] leading-relaxed prose prose-sm prose-invert max-w-none [&>p]:mb-2 [&>p:last-child]:mb-0">
- <ReactMarkdown remarkPlugins={[remarkGfm]}>{text}</ReactMarkdown>
- </div>
- </div>
- );
-}
-
-function ListSection({ title, items }: { title: string; items: string[] }) {
- return (
- <div>
- <h3 className="mb-1 text-sm font-medium text-[var(--color-text-secondary)]">{title}</h3>
- <ul className="list-disc space-y-0.5 pl-5 text-sm text-[var(--color-text-primary)]">
- {items.map((item, i) => (
- <li key={i}>{item}</li>
- ))}
- </ul>
- </div>
- );
+ return <SharedDecisionDetail decision={decision} adapter={adapter} />;
}
diff --git a/packages/web/src/components/graph/graph-flow.tsx b/packages/web/src/components/graph/graph-flow.tsx
index 3171418ef..95b25bc8b 100644
--- a/packages/web/src/components/graph/graph-flow.tsx
+++ b/packages/web/src/components/graph/graph-flow.tsx
@@ -37,6 +37,8 @@ export interface GraphFlowProps {
repoName?: string;
initialViewMode?: ViewMode;
initialColorMode?: GraphFlowShellProps["initialColorMode"];
+ /** Controlled node color mode — the page URL-syncs it and passes it down. */
+ colorMode?: GraphFlowShellProps["colorMode"];
initialSelectedNode?: string | null;
onNodeClick?: GraphFlowShellProps["onNodeClick"];
onNodeViewDocs?: GraphFlowShellProps["onNodeViewDocs"];
@@ -59,6 +61,7 @@ export function GraphFlow({
repoName,
initialViewMode,
initialColorMode,
+ colorMode,
initialSelectedNode,
onNodeClick,
onNodeViewDocs,
@@ -136,6 +139,7 @@ export function GraphFlow({
executionFlows={executionFlowsData as ExecutionFlows | undefined}
initialViewMode={initialViewMode}
initialColorMode={initialColorMode}
+ colorMode={colorMode}
initialSelectedNode={initialSelectedNode}
onViewModeChange={(mode) => {
setViewMode(mode);
diff --git a/packages/web/src/components/risk/dead-code-tab.tsx b/packages/web/src/components/risk/dead-code-tab.tsx
index 991a08950..9b67cd423 100644
--- a/packages/web/src/components/risk/dead-code-tab.tsx
+++ b/packages/web/src/components/risk/dead-code-tab.tsx
@@ -1,209 +1,39 @@
"use client";
-import { useState } from "react";
+/**
+ * Dead Code host — binds the shared {@link DeadCodeView} to web's `/api`
+ * client and `/repos/:id` routing. The composition (safe-to-delete pile,
+ * cluster rollups, drill-down table, patch/undo, bulk resolve, Propose
+ * cleanup, Re-analyze) lives in `@repowise-dev/ui/dead-code`; this file only
+ * injects the app-specific pieces so web and hosted render the same view.
+ */
+
import { useRouter } from "next/navigation";
-import useSWR from "swr";
-import { toast } from "sonner";
+import { DeadCodeView, type DeadCodeAdapter } from "@repowise-dev/ui/dead-code";
import { fileEntityPath } from "@repowise-dev/ui/shared/entity";
-import { Button } from "@repowise-dev/ui/ui/button";
-import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
-import { CollapsibleSection } from "@repowise-dev/ui/shared/collapsible-section";
-import { SummaryBar } from "@repowise-dev/ui/dead-code/summary-bar";
-import { SafeToDeletePile } from "@repowise-dev/ui/dead-code/safe-to-delete-pile";
-import { OwnerLeaderboard } from "@repowise-dev/ui/dead-code/owner-leaderboard";
-import { FindingsBreakdownGrid } from "@repowise-dev/ui/dead-code/findings-breakdown-grid";
-import { FindingsTable } from "@repowise-dev/ui/dead-code/findings-table";
-import { AiPromptModal, buildDeadCodeAiPrompt } from "@repowise-dev/ui/health";
-import { getDeadCodeSummary, listDeadCode, analyzeDeadCode, patchDeadCodeFinding } from "@/lib/api/dead-code";
-import type { DeadCodeFindingResponse, DeadCodeSummaryResponse } from "@/lib/api/types";
-import type { DeadCodeStatus } from "@repowise-dev/types/dead-code";
+import {
+ getDeadCodeSummary,
+ listDeadCode,
+ analyzeDeadCode,
+ patchDeadCodeFinding,
+} from "@/lib/api/dead-code";
export function DeadCodeTab({ repoId }: { repoId: string }) {
const router = useRouter();
- const [analyzing, setAnalyzing] = useState(false);
- const [promptIds, setPromptIds] = useState<string[] | null>(null);
-
- const { data: summary, isLoading: loadingSummary, error: summaryError, mutate: mutateSummary } =
- useSWR<DeadCodeSummaryResponse>(
- `dead-code-summary:${repoId}`,
- () => getDeadCodeSummary(repoId),
- { revalidateOnFocus: false },
- );
-
- // Single findings fetch feeds the pile, the cluster views, AND the drill-down
- // table (which filters this slice client-side) — no second fetch.
- const { data: findings, isLoading: loadingFindings } = useSWR<DeadCodeFindingResponse[]>(
- `dead-code-findings:${repoId}:all`,
- () => listDeadCode(repoId, { limit: 500 }),
- { revalidateOnFocus: false },
- );
-
- const findingsList = findings ?? [];
- const safeFindings = findingsList.filter((f) => f.safe_to_delete);
-
- // "Propose cleanup" opens the shared AI-prompt modal seeded with the safe
- // pile — same agent-flavor picker (incl. repowise MCP) and copy affordance as
- // every other AI action in the dashboard.
- const handlePropose = (findingIds: string[]) => setPromptIds(findingIds);
-
- const promptFindings = promptIds
- ? safeFindings.filter((f) => promptIds.includes(f.id))
- : [];
-
- const handleAnalyze = async () => {
- setAnalyzing(true);
- try {
+ const prefix = `/repos/${repoId}`;
+
+ const adapter: DeadCodeAdapter = {
+ cacheKey: repoId,
+ repoId,
+ getSummary: () => getDeadCodeSummary(repoId),
+ listFindings: (opts) => listDeadCode(repoId, opts),
+ analyze: async () => {
await analyzeDeadCode(repoId);
- toast.success("Analysis started — results will appear shortly.");
- } catch (err) {
- toast.error(
- err instanceof Error ? `Couldn't start analysis: ${err.message}` : "Couldn't start analysis",
- );
- } finally {
- setAnalyzing(false);
- }
- };
-
- // Row-level patch with optimistic undo toast; injected into the ui table.
- const handlePatch = async (id: string, patch: { status: DeadCodeStatus }) => {
- const finding = findingsList.find((f) => f.id === id);
- const previousStatus: DeadCodeStatus = finding?.status ?? "open";
- const updated = await patchDeadCodeFinding(id, patch);
- toast.success(`Finding ${patch.status.replace(/_/g, " ")}`, {
- action: {
- label: "Undo",
- onClick: async () => {
- try {
- await patchDeadCodeFinding(id, { status: previousStatus });
- } catch (err) {
- toast.error(err instanceof Error ? `Couldn't undo: ${err.message}` : "Couldn't undo");
- }
- },
- },
- duration: 6000,
- });
- return updated;
- };
-
- const handleBulkResolve = async (ids: string[]) => {
- const succeededIds: string[] = [];
- for (const id of ids) {
- try {
- await patchDeadCodeFinding(id, { status: "resolved" });
- succeededIds.push(id);
- } catch {
- // continue; report partial below
- }
- }
- const succeeded = succeededIds.length;
- if (succeeded === ids.length) {
- toast.success(`Resolved ${succeeded} finding${succeeded === 1 ? "" : "s"}`);
- } else if (succeeded > 0) {
- toast.warning(`Resolved ${succeeded} of ${ids.length}; some failed`);
- } else {
- toast.error("Couldn't resolve findings");
- }
- return succeededIds;
+ },
+ patchFinding: (findingId, patch) => patchDeadCodeFinding(findingId, patch),
+ fileHref: (path) => fileEntityPath(prefix, path),
+ navigate: (href) => router.push(href),
};
- return (
- <div className="space-y-6">
- <div className="flex items-center justify-end">
- <Button size="sm" variant="outline" onClick={handleAnalyze} disabled={analyzing}>
- {analyzing ? "Starting…" : "Re-analyze"}
- </Button>
- </div>
-
- {loadingSummary ? (
- <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
- {Array.from({ length: 4 }).map((_, i) => (
- <Skeleton key={i} className="h-24 w-full rounded-lg" />
- ))}
- </div>
- ) : summary ? (
- <SummaryBar summary={summary} />
- ) : summaryError ? (
- <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-4 text-sm text-[var(--color-text-secondary)] flex items-center justify-between gap-2">
- <span>Couldn&apos;t load summary.</span>
- <Button size="sm" variant="outline" onClick={() => mutateSummary()}>
- Retry
- </Button>
- </div>
- ) : null}
-
- {/* Act now: the single "what do I delete" surface. */}
- {findings && safeFindings.length > 0 && (
- <SafeToDeletePile
- findings={safeFindings}
- reclaimableLines={summary?.deletable_lines}
- onPropose={handlePropose}
- onSelect={(f) => router.push(fileEntityPath(`/repos/${repoId}`, f.file_path))}
- />
- )}
-
- {/* Where it clusters — optional rollups, collapsed by default so the spine
- stays pile → drill-down. */}
- {findingsList.length > 0 && (
- <CollapsibleSection
- title="Where it clusters"
- hint="By owner and confidence × kind"
- defaultOpen={false}
- >
- <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
- <div>
- <p className="mb-2 text-xs text-[var(--color-text-tertiary)]">
- Reclaimable lines per primary contributor — who has the most cleanup leverage.
- </p>
- <OwnerLeaderboard findings={findingsList} safeOnly />
- </div>
- <div>
- <p className="mb-2 text-xs text-[var(--color-text-tertiary)]">
- Where findings concentrate — start with high-confidence cells.
- </p>
- <FindingsBreakdownGrid findings={findingsList} />
- </div>
- </div>
- </CollapsibleSection>
- )}
-
- {/* Drill-down: the full interactive table, the single confidence control. */}
- <CollapsibleSection
- title="All findings"
- hint={`${findingsList.length} findings`}
- defaultOpen={false}
- >
- <FindingsTable
- findings={findingsList}
- repoId={repoId}
- onPatch={handlePatch}
- onBulkResolve={handleBulkResolve}
- isLoading={loadingFindings}
- />
- </CollapsibleSection>
-
- <AiPromptModal
- open={promptIds !== null}
- onOpenChange={(o) => !o && setPromptIds(null)}
- getPrompt={
- promptFindings.length > 0
- ? (flavor) =>
- buildDeadCodeAiPrompt({
- findings: promptFindings.map((f) => ({
- file_path: f.file_path,
- symbol_name: f.symbol_name,
- kind: f.kind,
- reason: f.reason,
- lines: f.lines,
- confidence: f.confidence,
- risk_factors: f.risk_factors,
- })),
- flavor,
- })
- : null
- }
- title="AI cleanup prompt"
- description="A ready-to-paste prompt that has your AI agent verify and remove this dead-code pile safely, in reviewable commits."
- />
- </div>
- );
+ return <DeadCodeView adapter={adapter} />;
}
diff --git a/packages/web/src/components/risk/impact-tab.tsx b/packages/web/src/components/risk/impact-tab.tsx
index 71a27b4f1..e63790662 100644
--- a/packages/web/src/components/risk/impact-tab.tsx
+++ b/packages/web/src/components/risk/impact-tab.tsx
@@ -1,175 +1,54 @@
"use client";
-import { useState } from "react";
+/**
+ * Impact host — binds the shared {@link ImpactView} to web's `/api` client and
+ * supplies the reviewer-suggestions panel as the analyzer's reviewer slot. The
+ * composition (file picker, hotspot chips, depth control, blast-radius results)
+ * lives in `@repowise-dev/ui/blast-radius`; this file only injects the
+ * app-specific pieces so web and hosted render the same view.
+ */
+
import useSWR from "swr";
-import { Plus, Flame } from "lucide-react";
-import { Button } from "@repowise-dev/ui/ui/button";
-import { Card, CardHeader, CardTitle, CardContent } from "@repowise-dev/ui/ui/card";
-import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
-import { FilePathPicker } from "@repowise-dev/ui/health";
-import { BlastRadiusResults } from "@repowise-dev/ui/blast-radius";
+import { ImpactView, type ImpactAdapter } from "@repowise-dev/ui/blast-radius";
import { ReviewerSuggestions } from "@repowise-dev/ui/git/reviewer-suggestions";
-import type { BlastRadiusResponse } from "@repowise-dev/types/blast-radius";
-import type { ReviewerSuggestion } from "@repowise-dev/types/modules";
import { analyzeBlastRadius } from "@/lib/api/blast-radius";
import { getHotspots, getReviewerSuggestions } from "@/lib/api/git";
import { searchNodes } from "@/lib/api/graph";
-export function ImpactTab({ repoId }: { repoId: string }) {
- const [selected, setSelected] = useState<string[]>([]);
- const [maxDepth, setMaxDepth] = useState(3);
- const [loading, setLoading] = useState(false);
- const [error, setError] = useState<string | null>(null);
- const [result, setResult] = useState<BlastRadiusResponse | null>(null);
- const [reviewers, setReviewers] = useState<ReviewerSuggestion[] | null>(null);
-
- const { data: hotspotSuggestions, isLoading: hotspotSuggestionsLoading } = useSWR(
- repoId ? ["blast-radius-suggestions", repoId] : null,
- () => getHotspots(repoId, 8),
+/**
+ * Reviewer slot — fetches suggestions for the analyzed changeset and renders
+ * the rich panel, or nothing when there are none (graceful degradation).
+ */
+function ReviewersPanel({ repoId, files }: { repoId: string; files: string[] }) {
+ const { data } = useSWR(
+ files.length ? ["impact-reviewers", repoId, files.join("\n")] : null,
+ () =>
+ getReviewerSuggestions(repoId, files, 8)
+ .then((r) => r.suggestions)
+ .catch(() => []),
+ { revalidateOnFocus: false },
);
-
- const addPaths = (paths: string[]) => {
- setSelected((prev) => {
- const set = new Set(prev);
- for (const p of paths) {
- const trimmed = p.trim();
- if (trimmed) set.add(trimmed);
- }
- return [...set];
- });
- };
- const removePath = (path: string) =>
- setSelected((prev) => prev.filter((p) => p !== path));
- const useAllHotspots = () => {
- if (!hotspotSuggestions) return;
- addPaths(hotspotSuggestions.map((h) => h.file_path));
- };
-
- const handleAnalyze = async () => {
- if (selected.length === 0) {
- setError("Add at least one file path.");
- return;
- }
- setLoading(true);
- setError(null);
- setResult(null);
- setReviewers(null);
- try {
- const [data, suggestions] = await Promise.all([
- analyzeBlastRadius(repoId, { changed_files: selected, max_depth: maxDepth }),
- getReviewerSuggestions(repoId, selected, 8).catch(() => null),
- ]);
- setResult(data);
- setReviewers(suggestions?.suggestions ?? null);
- } catch (err) {
- setError(err instanceof Error ? err.message : "Analysis failed.");
- } finally {
- setLoading(false);
- }
- };
-
+ if (!data || data.length === 0) return null;
return (
- <div className="space-y-6">
- <Card>
- <CardHeader className="pb-3">
- <CardTitle className="text-sm">Impact Analyzer</CardTitle>
- <p className="text-xs text-[var(--color-text-tertiary)]">
- Estimate the blast radius of a proposed change — direct and transitive risks,
- reviewer suggestions, and test gaps.
- </p>
- </CardHeader>
- <CardContent className="pt-0 space-y-4">
- <p className="text-xs text-[var(--color-text-tertiary)]">
- Type to search the file index, paste a list of paths (your PR diff),
- click a hotspot below, or{" "}
- <button
- type="button"
- onClick={useAllHotspots}
- className="underline underline-offset-2 hover:text-[var(--color-text-primary)]"
- disabled={!hotspotSuggestions || hotspotSuggestions.length === 0}
- >
- use top hotspots
- </button>
- .
- </p>
-
- {hotspotSuggestionsLoading && !hotspotSuggestions && (
- <div className="flex flex-wrap gap-2">
- {Array.from({ length: 6 }).map((_, i) => (
- <Skeleton key={i} className="h-7 w-32 rounded-full" />
- ))}
- </div>
- )}
-
- {hotspotSuggestions && hotspotSuggestions.length > 0 && (
- <div className="flex flex-wrap gap-2">
- {hotspotSuggestions.map((h) => (
- <button
- key={h.file_path}
- type="button"
- onClick={() => addPaths([h.file_path])}
- className="inline-flex items-center gap-1 rounded-full border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2.5 py-1 text-xs font-mono text-[var(--color-text-secondary)] hover:border-[var(--color-accent-primary)] hover:text-[var(--color-text-primary)] transition-colors"
- title={h.file_path}
- aria-label={`Add ${h.file_path} to changed files`}
- >
- <Flame className="h-3 w-3 text-[var(--color-warning)]" />
- <span className="truncate max-w-[260px]">{h.file_path}</span>
- <Plus className="h-3 w-3 opacity-60" />
- </button>
- ))}
- </div>
- )}
-
- <FilePathPicker
- selected={selected}
- onAdd={addPaths}
- onRemove={removePath}
- onSearch={async (q) => {
- const results = await searchNodes(repoId, q, 8);
- return results.map((r) => r.node_id);
- }}
- />
+ <ReviewerSuggestions
+ suggestions={data}
+ subtitle={`Based on authorship and co-change history for ${files.length} changed paths`}
+ />
+ );
+}
- <div className="flex items-center gap-4 flex-wrap">
- <label className="flex items-center gap-2 text-xs text-[var(--color-text-secondary)]">
- Max depth
- <input
- type="number"
- min={1}
- max={10}
- value={maxDepth}
- onChange={(e) => setMaxDepth(Math.max(1, Math.min(10, Number(e.target.value))))}
- className="w-16 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2 py-1 text-xs text-[var(--color-text-primary)] focus:outline-none focus:ring-1 focus:ring-[var(--color-accent-primary)]"
- aria-label="Maximum dependency depth (1–10)"
- />
- </label>
- <Button onClick={handleAnalyze} disabled={loading} size="sm">
- {loading ? "Analyzing…" : "Analyze"}
- </Button>
- {selected.length > 0 && (
- <Button onClick={() => setSelected([])} disabled={loading} size="sm" variant="outline">
- Clear
- </Button>
- )}
- </div>
- {error && <p className="text-xs text-[var(--color-error)]">{error}</p>}
- </CardContent>
- </Card>
+export function ImpactTab({ repoId }: { repoId: string }) {
+ const adapter: ImpactAdapter = {
+ cacheKey: repoId,
+ listHotspots: (limit) => getHotspots(repoId, limit),
+ searchFiles: async (q) => {
+ const results = await searchNodes(repoId, q, 8);
+ return results.map((r) => r.node_id);
+ },
+ analyze: ({ changedFiles, maxDepth }) =>
+ analyzeBlastRadius(repoId, { changed_files: changedFiles, max_depth: maxDepth }),
+ renderReviewers: (files) => <ReviewersPanel repoId={repoId} files={files} />,
+ };
- {result && (
- <BlastRadiusResults
- result={result}
- changedFiles={selected}
- reviewersSlot={
- reviewers && reviewers.length > 0 ? (
- <ReviewerSuggestions
- suggestions={reviewers}
- subtitle={`Based on authorship and co-change history for ${selected.length} changed paths`}
- />
- ) : undefined
- }
- />
- )}
- </div>
- );
+ return <ImpactView adapter={adapter} />;
}