Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
UX overhaul: airier, diagram-first web UI on a shared composition backbone (#504)
Swati Ahujaf5f359a803a1
diff --git a/packages/types/src/dead-code.ts b/packages/types/src/dead-code.tsindex c78e00f31..673884060 100644--- a/packages/types/src/dead-code.ts+++ b/packages/types/src/dead-code.ts@@ -7,7 +7,7 @@* optional so consumer adapters don't lose information when normalising.*/-export type DeadCodeStatus = "open" | "wont_fix" | "deleted" | (string & {});+export type DeadCodeStatus = "open" | "acknowledged" | "resolved" | "false_positive";export interface DeadCodeFinding {id: string;diff --git a/packages/types/src/symbols.ts b/packages/types/src/symbols.tsindex f505e7cb2..03dde68a5 100644--- a/packages/types/src/symbols.ts+++ b/packages/types/src/symbols.ts@@ -111,6 +111,97 @@ export interface SymbolList {symbols: CodeSymbol[];}+// ---------------------------------------------------------------------------+// Unified symbol-detail shape (drawer + route render the same body)+// ---------------------------------------------------------------------------++/** A caller/callee edge in the normalized symbol body. */+export interface SymbolBodyCall {+ symbol_id: string;+ name: string;+ file: string;+ edge_type: string;+ confidence?: number | null;+}++/** Graph-intelligence block for the unified body (optional — degrades when absent). */+export interface SymbolBodyGraph {+ in_degree: number;+ out_degree: number;+ callers: SymbolBodyCall[];+ callees: SymbolBodyCall[];+ pagerank_percentile?: number | null;+ betweenness_percentile?: number | null;+ community_label?: string | null;+ entry_point_score?: number | null;+}++/** File-level git intelligence for the unified body (optional). */+export interface SymbolBodyGit {+ primary_owner_name: string | null;+ primary_owner_commit_pct?: number | null;+ recent_owner_name?: string | null;+ bus_factor?: number | null;+ contributor_count?: number | null;+ commit_count_90d?: number | null;+ is_hotspot?: boolean | null;+ churn_percentile?: number | null;+}++export interface SymbolBodyCoChange {+ file_path: string;+ co_change_count: number;+}++export interface SymbolBodyDeadFinding {+ id: string;+ kind: string;+ reason: string;+ lines: number;+ safe_to_delete: boolean;+}++/**+ * The single normalized shape rendered by `SymbolDetailBody`. Both the drawer+ * (`CodeSymbol` + graph/git APIs) and the route (`SymbolDetailResponse`)+ * normalize into this so they expose the same capabilities. Every block beyond+ * `identity` is optional so a surface that lacks a feed degrades gracefully.+ */+export interface SymbolDetailData {+ identity: {+ name: string;+ qualified_name?: string | null;+ kind: SymbolKind;+ visibility?: SymbolVisibility | null;+ language?: string | null;+ is_async?: boolean | null;+ file_path: string;+ start_line: number;+ parent_name?: string | null;+ file_is_hotspot?: boolean | null;+ };+ signature?: string | null;+ docstring?: string | null;+ importance_score?: number | null;+ complexity_estimate?: number | null;+ blame_mod_count?: number | null;+ blame_recent_mod_count?: number | null;+ blame_median_author_time?: number | null;+ blame_owner_name?: string | null;+ blame_owner_line_pct?: number | null;+ graph?: SymbolBodyGraph | null;+ /** Heritage relations (extends/implements + extended-by). Renders when present. */+ heritage?: SymbolHeritage | null;+ git?: SymbolBodyGit | null;+ co_changes?: SymbolBodyCoChange[];+ dead_code?: SymbolBodyDeadFinding[];+ governing_decisions?: { id: string; title: string; status: string }[];+ file_context?: {+ health_score?: number | null;+ language?: string | null;+ } | null;+}+// ---------------------------------------------------------------------------// Heritage (extends / implements / trait_impl / mixin / overrides)// ---------------------------------------------------------------------------diff --git a/packages/ui/__tests__/blast-radius/blast-radius.test.tsx b/packages/ui/__tests__/blast-radius/blast-radius.test.tsxindex c5813822b..36ce9802a 100644--- a/packages/ui/__tests__/blast-radius/blast-radius.test.tsx+++ b/packages/ui/__tests__/blast-radius/blast-radius.test.tsx@@ -106,19 +106,21 @@ describe("BlastRadiusSummary", () => {});describe("BlastRadiusResults", () => {- it("composes the full results stack", () => {- render(<BlastRadiusResults result={fixture} />);+ it("composes the risk gauge, summary, impact map, and collapsible sections", () => {+ render(<BlastRadiusResults result={fixture} changedFiles={["src/auth/login.py"]} />);expect(screen.getByText("High Risk")).toBeTruthy();- // "Direct Risks" / "Co-change Warnings" / "Test Gaps" appear twice- // (summary stat label + TableSection title) — use getAllByText.- expect(screen.getAllByText("Direct Risks").length).toBe(2);- expect(screen.getByText("Transitive Affected Files")).toBeTruthy();- expect(screen.getAllByText("Co-change Warnings").length).toBe(2);- expect(screen.getByText("Recommended Reviewers")).toBeTruthy();- expect(screen.getAllByText("Test Gaps").length).toBe(2);+ // Summary stat label (capitalized) is distinct from the collapsible toggle+ // title (sentence case), so each appears once.+ expect(screen.getByText("Direct Risks")).toBeTruthy();+ expect(screen.getByText("Direct risks")).toBeTruthy();+ expect(screen.getByText("Transitive affected files")).toBeTruthy();+ expect(screen.getByText("Co-change warnings")).toBeTruthy();+ expect(screen.getByText("Recommended reviewers")).toBeTruthy();+ expect(screen.getByText("Test gaps")).toBeTruthy();+ expect(screen.getByText("Impact map")).toBeTruthy();});- it("shows 'None' for empty sections", () => {+ it("shows an empty impact map when nothing is affected", () => {const empty: BlastRadiusResponse = {direct_risks: [],transitive_affected: [],@@ -128,7 +130,7 @@ describe("BlastRadiusResults", () => {overall_risk_score: 1.5,};render(<BlastRadiusResults result={empty} />);- expect(screen.getAllByText("None").length).toBe(5);+ expect(screen.getByText("No downstream impact found")).toBeTruthy();expect(screen.getByText("Low Risk")).toBeTruthy();});});diff --git a/packages/ui/__tests__/decisions/decision-health-widget.test.tsx b/packages/ui/__tests__/decisions/decision-health-widget.test.tsxdeleted file mode 100644index ad44a8296..000000000--- a/packages/ui/__tests__/decisions/decision-health-widget.test.tsx+++ /dev/null@@ -1,28 +0,0 @@-import { describe, it, expect } from "vitest";-import { render, screen } from "@testing-library/react";-import { DecisionHealthWidget } from "../../src/decisions/decision-health-widget.js";-import type { DecisionHealth } from "@repowise-dev/types/decisions";--const HEALTH: DecisionHealth = {- summary: { active: 12, proposed: 3, deprecated: 1, superseded: 2, stale: 4 },- stale_decisions: [],- proposed_awaiting_review: [],- ungoverned_hotspots: [],-};--describe("DecisionHealthWidget", () => {- it("renders nothing while health is undefined", () => {- const { container } = render(<DecisionHealthWidget health={undefined} />);- expect(container.firstChild).toBeNull();- });-- it("renders three stat cards with the summary counts", () => {- render(<DecisionHealthWidget health={HEALTH} />);- expect(screen.getByText("Active Decisions")).toBeInTheDocument();- expect(screen.getByText("12")).toBeInTheDocument();- expect(screen.getByText("Proposed")).toBeInTheDocument();- expect(screen.getByText("3")).toBeInTheDocument();- expect(screen.getByText("Stale")).toBeInTheDocument();- expect(screen.getByText("4")).toBeInTheDocument();- });-});diff --git a/packages/ui/__tests__/git/churn-bar.test.tsx b/packages/ui/__tests__/git/churn-bar.test.tsxindex ec9acdc4e..72557da0b 100644--- a/packages/ui/__tests__/git/churn-bar.test.tsx+++ b/packages/ui/__tests__/git/churn-bar.test.tsx@@ -3,14 +3,18 @@ import { render } from "@testing-library/react";import { ChurnBar } from "../../src/git/churn-bar.js";describe("ChurnBar", () => {- it("renders with red fill at high percentile", () => {+ it("renders with error fill at high percentile", () => {const { container } = render(<ChurnBar percentile={85} />);- expect(container.querySelector(".bg-red-500")).not.toBeNull();+ expect(+ container.querySelector(".bg-\\[var\\(--color-error\\)\\]"),+ ).not.toBeNull();});it("clamps width to 0–100%", () => {const { container } = render(<ChurnBar percentile={150} />);- const inner = container.querySelector(".bg-red-500") as HTMLElement;+ const inner = container.querySelector(+ ".bg-\\[var\\(--color-error\\)\\]",+ ) as HTMLElement;expect(inner.style.width).toBe("100%");});});diff --git a/packages/ui/__tests__/health/code-health-map.test.tsx b/packages/ui/__tests__/health/code-health-map.test.tsxnew file mode 100644index 000000000..e6212b1f6--- /dev/null+++ b/packages/ui/__tests__/health/code-health-map.test.tsx@@ -0,0 +1,121 @@+import { describe, it, expect, vi, beforeAll } from "vitest";+import { render, fireEvent } from "@testing-library/react";+import {+ CodeHealthMap,+ groupByModule,+ type CodeHealthMapFile,+} from "../../src/health/code-health-map.js";++function f(+ file_path: string,+ nloc: number,+ module: string | null,+ score = 7,+): CodeHealthMapFile {+ return { file_path, nloc, score, module, line_coverage_pct: null, has_test_file: false };+}++// jsdom has no layout engine → stub ResizeObserver so the map can size itself.+beforeAll(() => {+ class RO {+ cb: ResizeObserverCallback;+ constructor(cb: ResizeObserverCallback) {+ this.cb = cb;+ }+ observe() {+ this.cb(+ [{ contentRect: { width: 800, height: 600 } } as ResizeObserverEntry],+ this as unknown as ResizeObserver,+ );+ }+ unobserve() {}+ disconnect() {}+ }+ vi.stubGlobal("ResizeObserver", RO);+});++describe("groupByModule", () => {+ it("groups files by module, sums NLOC, sorts files biggest-first", () => {+ const galaxies = groupByModule([+ f("a/x.py", 100, "core"),+ f("a/y.py", 40, "core"),+ f("b/z.py", 60, "ui"),+ ]);+ const core = galaxies.find((g) => g.module === "core");+ expect(core?.files).toHaveLength(2);+ expect(core?.totalNloc).toBe(140);+ expect(core?.maxNloc).toBe(100);+ expect(core?.files.map((x) => x.nloc)).toEqual([100, 40]); // desc+ // Galaxies themselves are ordered by total size (core 140 > ui 60).+ expect(galaxies[0]?.module).toBe("core");+ });++ it("drops zero-NLOC files and buckets a null module as (ungrouped)", () => {+ const galaxies = groupByModule([f("a.py", 0, "core"), f("b.py", 20, null)]);+ expect(galaxies.find((g) => g.module === "core")).toBeUndefined();+ expect(galaxies.find((g) => g.module === "(ungrouped)")?.files).toHaveLength(1);+ });+});++describe("CodeHealthMap", () => {+ it("renders the empty state when there are no files", () => {+ const { getByText } = render(<CodeHealthMap files={[]} />);+ expect(getByText(/No files to map yet/i)).toBeInTheDocument();+ });++ it("renders file nodes and opens a file on click", () => {+ const onSelectFile = vi.fn();+ const files = [+ f("core/a.py", 120, "core", 3),+ f("core/b.py", 60, "core", 8),+ f("ui/c.py", 40, "ui", 6),+ ];+ const { container } = render(<CodeHealthMap files={files} onSelectFile={onSelectFile} />);+ // Nodes carry a <title> with the path; pick one and click its circle.+ const titles = Array.from(container.querySelectorAll("title"));+ const target = titles.find((t) => t.textContent?.startsWith("core/a.py"));+ expect(target).toBeTruthy();+ fireEvent.click(target!.parentElement!);+ expect(onSelectFile).toHaveBeenCalledWith("core/a.py");+ });++ it("zooms into a galaxy and Escape returns to the overview", () => {+ const files = [f("core/a.py", 120, "core"), f("ui/c.py", 40, "ui")];+ const { getByText, queryByText, container } = render(<CodeHealthMap files={files} />);+ // Click a galaxy nebula (a blurred blob) to focus it.+ const blob = container.querySelector('circle[filter="url(#ch-nebula)"]');+ expect(blob).toBeTruthy();+ fireEvent.click(blob!);+ expect(getByText("← Overview")).toBeInTheDocument();+ fireEvent.keyDown(window, { key: "Escape" });+ expect(queryByText("← Overview")).not.toBeInTheDocument();+ });++ it("shows the on-canvas health legend", () => {+ const { getByText } = render(<CodeHealthMap files={[f("a.py", 30, "core")]} />);+ expect(getByText("Health")).toBeInTheDocument();+ expect(getByText(/galaxy = module/i)).toBeInTheDocument();+ });++ it("renders the coverage legend under the coverage lens", () => {+ const { getByText } = render(+ <CodeHealthMap files={[f("a.py", 30, "core")]} overlay="coverage" />,+ );+ // Coverage caption + a coverage-specific legend band identify the lens.+ expect(getByText(/line coverage/i)).toBeInTheDocument();+ expect(getByText("≥80%")).toBeInTheDocument();+ });++ it("fires onOverlayChange when a lens-switch button is clicked", () => {+ const onOverlayChange = vi.fn();+ const { getByRole } = render(+ <CodeHealthMap+ files={[f("a.py", 30, "core")]}+ onOverlayChange={onOverlayChange}+ />,+ );+ // The lens switcher renders one toggle button per lens; click "Churn".+ fireEvent.click(getByRole("button", { name: "Churn" }));+ expect(onOverlayChange).toHaveBeenCalledWith("churn");+ });+});diff --git a/packages/ui/src/blast-radius/blast-radius-results.tsx b/packages/ui/src/blast-radius/blast-radius-results.tsxindex eb962e911..7da54ee7f 100644--- a/packages/ui/src/blast-radius/blast-radius-results.tsx+++ b/packages/ui/src/blast-radius/blast-radius-results.tsx@@ -2,59 +2,111 @@ import type { ReactNode } from "react";import type { BlastRadiusResponse } from "@repowise-dev/types/blast-radius";import { RiskScoreCard } from "./risk-score-card";import { BlastRadiusSummary } from "./blast-radius-summary";-import { TableSection } from "./table-section";+import { ImpactGraph } from "./impact-graph";import { DirectRisksTable } from "./direct-risks-table";import { TransitiveTable } from "./transitive-table";import { CochangeTable } from "./cochange-table";import { ReviewersTable } from "./reviewers-table";import { TestGapsList } from "./test-gaps-list";+import { CollapsibleSection } from "../shared/collapsible-section";+import { EmptyState } from "../shared/empty-state";interface BlastRadiusResultsProps {result: BlastRadiusResponse;+ /** The files the user proposed changing — graph centre. */+ changedFiles?: string[];/** Rich reviewer panel (e.g. `ReviewerSuggestions` fed by the* reviewer-suggestions endpoint). Replaces the thin email table. */reviewersSlot?: ReactNode | undefined;}-/** Composes the full results stack — score gauge, summary, all five tables. */-export function BlastRadiusResults({ result, reviewersSlot }: BlastRadiusResultsProps) {+/**+ * Airy blast-radius results: a risk gauge + summary, then a single impact-graph+ * canvas, with the detail tables demoted behind collapsible sections instead of+ * five stacked bordered cards.+ */+export function BlastRadiusResults({+ result,+ changedFiles = [],+ reviewersSlot,+}: BlastRadiusResultsProps) {return (- <div className="space-y-4">+ <div className="space-y-6"><div className="grid grid-cols-1 gap-4 sm:grid-cols-4"><RiskScoreCard score={result.overall_risk_score} /><BlastRadiusSummary result={result} /></div>- <TableSection title="Direct Risks" empty={result.direct_risks.length === 0}>- <DirectRisksTable rows={result.direct_risks} />- </TableSection>+ {/* One picture: changed files → direct → transitive. */}+ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-4">+ <p className="mb-2 text-xs font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">+ Impact map+ </p>+ {result.direct_risks.length === 0 &&+ result.transitive_affected.length === 0 ? (+ <EmptyState+ title="No downstream impact found"+ description="No files depend on the changed paths within the selected depth."+ />+ ) : (+ <ImpactGraph result={result} changedFiles={changedFiles} />+ )}+ </div>++ <CollapsibleSection+ title="Direct risks"+ hint={result.direct_risks.length || undefined}+ defaultOpen={result.direct_risks.length > 0}+ >+ {result.direct_risks.length > 0 ? (+ <DirectRisksTable rows={result.direct_risks} />+ ) : (+ <EmptyState title="No direct risks" description="Nothing depends directly on the changed files." />+ )}+ </CollapsibleSection>- <TableSection- title="Transitive Affected Files"- empty={result.transitive_affected.length === 0}+ <CollapsibleSection+ title="Transitive affected files"+ hint={result.transitive_affected.length || undefined}>- <TransitiveTable rows={result.transitive_affected} />- </TableSection>+ {result.transitive_affected.length > 0 ? (+ <TransitiveTable rows={result.transitive_affected} />+ ) : (+ <EmptyState title="No transitive impact" description="No deeper dependents within the selected depth." />+ )}+ </CollapsibleSection>- <TableSection- title="Co-change Warnings"- empty={result.cochange_warnings.length === 0}+ <CollapsibleSection+ title="Co-change warnings"+ hint={result.cochange_warnings.length || undefined}>- <CochangeTable rows={result.cochange_warnings} />- </TableSection>+ {result.cochange_warnings.length > 0 ? (+ <CochangeTable rows={result.cochange_warnings} />+ ) : (+ <EmptyState title="No co-change warnings" description="No historical co-change partners are missing from this change." />+ )}+ </CollapsibleSection>{reviewersSlot ?? (- <TableSection- title="Recommended Reviewers"- empty={result.recommended_reviewers.length === 0}+ <CollapsibleSection+ title="Recommended reviewers"+ hint={result.recommended_reviewers.length || undefined}>- <ReviewersTable rows={result.recommended_reviewers} />- </TableSection>+ {result.recommended_reviewers.length > 0 ? (+ <ReviewersTable rows={result.recommended_reviewers} />+ ) : (+ <EmptyState title="No reviewer suggestions" description="No owners matched the changed files." />+ )}+ </CollapsibleSection>)}- <TableSection title="Test Gaps" empty={result.test_gaps.length === 0}>- <TestGapsList gaps={result.test_gaps} />- </TableSection>+ <CollapsibleSection title="Test gaps" hint={result.test_gaps.length || undefined}>+ {result.test_gaps.length > 0 ? (+ <TestGapsList gaps={result.test_gaps} />+ ) : (+ <EmptyState title="No test gaps" description="Affected files have associated tests." />+ )}+ </CollapsibleSection></div>);}diff --git a/packages/ui/src/blast-radius/impact-graph.tsx b/packages/ui/src/blast-radius/impact-graph.tsxnew file mode 100644index 000000000..9da667bc8--- /dev/null+++ b/packages/ui/src/blast-radius/impact-graph.tsx@@ -0,0 +1,160 @@+"use client";++import { useMemo } from "react";+import type { BlastRadiusResponse } from "@repowise-dev/types/blast-radius";++interface ImpactGraphProps {+ result: BlastRadiusResponse;+ /** The files the user proposed changing (graph centre). */+ changedFiles: string[];+}++const WIDTH = 520;+const HEIGHT = 320;+const CX = WIDTH / 2;+const CY = HEIGHT / 2;+const INNER_R = 96;+const OUTER_R = 144;++function basename(path: string): string {+ return path.split("/").pop() || path;+}++/** Health-band ink for a direct-risk node, mirroring the coupling vocabulary. */+function riskInk(risk: number): string {+ if (risk >= 0.66) return "var(--color-error)";+ if (risk >= 0.33) return "var(--color-warning)";+ return "var(--color-success)";+}++interface PlacedNode {+ key: string;+ label: string;+ full: string;+ x: number;+ y: number;+ r: number;+ fill: string;+}++/**+ * A compact impact graph: the changed files at the centre, direct risks on an+ * inner ring (health-banded), and transitive-affected files on an outer ring.+ * Edges are quiet hairlines, reusing the coupling diagram's dot/edge idiom so+ * the blast radius reads as a picture before the detail tables.+ */+export function ImpactGraph({ result, changedFiles }: ImpactGraphProps) {+ const { centre, direct, transitive } = useMemo(() => {+ const directRows = result.direct_risks.slice(0, 10);+ const transitiveRows = result.transitive_affected.slice(0, 14);++ const centreNodes: PlacedNode[] = changedFiles.slice(0, 6).map((path, i, arr) => {+ const angle = arr.length === 1 ? -Math.PI / 2 : (i / arr.length) * 2 * Math.PI - Math.PI / 2;+ const spread = arr.length === 1 ? 0 : 26;+ return {+ key: `c-${path}`,+ label: basename(path),+ full: path,+ x: CX + Math.cos(angle) * spread,+ y: CY + Math.sin(angle) * spread,+ r: 7,+ fill: "var(--color-accent-primary)",+ };+ });++ const directNodes: PlacedNode[] = directRows.map((d, i) => {+ const angle = (i / Math.max(1, directRows.length)) * 2 * Math.PI - Math.PI / 2;+ return {+ key: `d-${d.path}`,+ label: basename(d.path),+ full: d.path,+ x: CX + Math.cos(angle) * INNER_R,+ y: CY + Math.sin(angle) * INNER_R,+ r: 4 + d.centrality * 4,+ fill: riskInk(d.risk_score),+ };+ });++ const transitiveNodes: PlacedNode[] = transitiveRows.map((t, i) => {+ const angle = (i / Math.max(1, transitiveRows.length)) * 2 * Math.PI - Math.PI / 2 + 0.2;+ return {+ key: `t-${t.path}`,+ label: basename(t.path),+ full: t.path,+ x: CX + Math.cos(angle) * OUTER_R,+ y: CY + Math.sin(angle) * OUTER_R,+ r: 3,+ fill: "var(--color-text-tertiary)",+ };+ });++ return { centre: centreNodes, direct: directNodes, transitive: transitiveNodes };+ }, [result, changedFiles]);++ const hasNodes = centre.length > 0 || direct.length > 0 || transitive.length > 0;+ if (!hasNodes) return null;++ return (+ <svg+ viewBox={`0 0 ${WIDTH} ${HEIGHT}`}+ className="mx-auto h-auto w-full max-w-[560px]"+ role="img"+ aria-label="Impact graph: changed files at centre, direct and transitive affected files around them"+ >+ {/* Edges: centre → direct (quiet), direct ring → transitive (quieter) */}+ {direct.map((d) => (+ <line+ key={`e-${d.key}`}+ x1={CX}+ y1={CY}+ x2={d.x}+ y2={d.y}+ stroke="var(--color-text-tertiary)"+ strokeOpacity={0.25}+ strokeWidth={1}+ />+ ))}+ {transitive.map((t) => (+ <line+ key={`e-${t.key}`}+ x1={CX}+ y1={CY}+ x2={t.x}+ y2={t.y}+ stroke="var(--color-text-tertiary)"+ strokeOpacity={0.1}+ strokeWidth={0.75}+ />+ ))}++ {[...transitive, ...direct, ...centre].map((n) => (+ <g key={n.key}>+ <circle+ cx={n.x}+ cy={n.y}+ r={n.r}+ fill={n.fill}+ stroke="var(--color-bg-surface)"+ strokeWidth={1}+ >+ <title>{n.full}</title>+ </circle>+ </g>+ ))}++ {/* Label only the centre + direct nodes to keep the canvas legible. */}+ {[...centre, ...direct].map((n) => (+ <text+ key={`l-${n.key}`}+ x={n.x}+ y={n.y - n.r - 3}+ textAnchor="middle"+ className="fill-[var(--color-text-secondary)]"+ style={{ fontSize: 10 }}+ >+ {n.label.length > 18 ? `${n.label.slice(0, 17)}…` : n.label}+ </text>+ ))}+ </svg>+ );+}diff --git a/packages/ui/src/blast-radius/index.ts b/packages/ui/src/blast-radius/index.tsindex 70404df98..da2fcae92 100644--- a/packages/ui/src/blast-radius/index.ts+++ b/packages/ui/src/blast-radius/index.ts@@ -1,4 +1,5 @@export * from "./risk-score-card";+export * from "./impact-graph";export * from "./table-section";export * from "./direct-risks-table";export * from "./transitive-table";diff --git a/packages/ui/src/blast-radius/risk-score-card.tsx b/packages/ui/src/blast-radius/risk-score-card.tsxindex 761b04c27..1c9781e8e 100644--- a/packages/ui/src/blast-radius/risk-score-card.tsx+++ b/packages/ui/src/blast-radius/risk-score-card.tsx@@ -7,21 +7,30 @@ interface RiskScoreCardProps {}export function RiskScoreCard({ score }: RiskScoreCardProps) {- const color =+ const tone =score >= 7- ? "text-red-500 border-red-500/30 bg-red-500/5"+ ? {+ text: "text-[var(--color-error)]",+ card: "border-[var(--color-error)]/30 bg-[var(--color-error)]/5",+ }: score >= 4- ? "text-amber-500 border-amber-500/30 bg-amber-500/5"- : "text-emerald-500 border-emerald-500/30 bg-emerald-500/5";+ ? {+ text: "text-[var(--color-warning)]",+ card: "border-[var(--color-warning)]/30 bg-[var(--color-warning)]/5",+ }+ : {+ text: "text-[var(--color-success)]",+ card: "border-[var(--color-success)]/30 bg-[var(--color-success)]/5",+ };const label = score >= 7 ? "High Risk" : score >= 4 ? "Medium Risk" : "Low Risk";return (- <Card className={cn("border", color)}>+ <Card className={cn("border", tone.card)}><CardContent className="flex flex-col items-center justify-center py-8 gap-2">- <span className={cn("text-6xl font-bold tabular-nums", color.split(" ")[0])}>+ <span className={cn("text-5xl font-bold tabular-nums", tone.text)}>{score.toFixed(1)}</span>- <span className={cn("text-sm font-medium", color.split(" ")[0])}>{label}</span>+ <span className={cn("text-sm font-medium", tone.text)}>{label}</span><span className="text-xs text-[var(--color-text-tertiary)]">Overall Risk Score (0–10)</span>diff --git a/packages/ui/src/c4/ArchCanvas.tsx b/packages/ui/src/c4/ArchCanvas.tsxnew file mode 100644index 000000000..515f4ecbe--- /dev/null+++ b/packages/ui/src/c4/ArchCanvas.tsx@@ -0,0 +1,141 @@+"use client";++import * as React from "react";+import {+ Controls,+ MiniMap,+ ReactFlow,+ type Edge,+ type Node,+ type NodeMouseHandler,+ type ReactFlowInstance,+} from "@xyflow/react";+import "@xyflow/react/dist/style.css";+import { AlertTriangle } from "lucide-react";+import { archNodeTypes } from "./nodes";+import { archEdgeTypes } from "../graph-primitives";+import { ArchLegend } from "./panels";+import { KEYFRAMES } from "./theme/theme-variables";+import { EmptyState } from "../shared/empty-state";+import { OwlLoader } from "../shared/owl-loader";++export interface ArchCanvasProps {+ nodes: Node[];+ edges: Edge[];+ loading?: boolean;+ error?: { message: string } | null;+ /** Weak aggregated edges hidden to keep the diagram legible. */+ hiddenEdgeCount?: number;+ onInit?: ((instance: ReactFlowInstance) => void) | undefined;+ onNodeClick?: NodeMouseHandler<Node> | undefined;+ onNodeDoubleClick?: NodeMouseHandler<Node> | undefined;+ onPaneClick?: (() => void) | undefined;+ /** Empty-state copy for the canvas (kept generic so the term lives on the+ * hosting route, not the diagram). */+ errorTitle?: string;+ loadingLabel?: string;+ /** Web-owned overlays (detail panel host, filter panel, code viewer,+ * path-finder modal) layered above the canvas. */+ children?: React.ReactNode;+}++/**+ * The layered-architecture ReactFlow canvas. Owns the diagram chrome that used+ * to be stranded in the web route (Controls, MiniMap, the "laying out" owl chip,+ * the "+N weaker links" chip, and the ArchLegend placement) so the layered view+ * upgrades via a package bump. Deliberately airy: no grid background and no+ * canvas fill behind the diagram.+ */+export function ArchCanvas({+ nodes,+ edges,+ loading = false,+ error = null,+ hiddenEdgeCount = 0,+ onInit,+ onNodeClick,+ onNodeDoubleClick,+ onPaneClick,+ errorTitle = "Couldn't load the architecture layers",+ loadingLabel = "Loading layers…",+ children,+}: ArchCanvasProps) {+ return (+ <>+ <style>{KEYFRAMES.accentPulse}{KEYFRAMES.edgeFlow}{`+ /* Zoom-into-tier feel: nodes glide to their next slot. */+ @media (prefers-reduced-motion: no-preference) {+ .react-flow__node { transition: transform 180ms ease; }+ }+ `}</style>+ <div className="relative h-full min-h-0 w-full">+ {error && (+ <div className="absolute inset-0 z-10 flex items-center justify-center">+ <EmptyState+ icon={<AlertTriangle className="h-5 w-5" aria-hidden />}+ title={errorTitle}+ description={error.message}+ className="max-w-md p-8"+ />+ </div>+ )}+ {loading && nodes.length === 0 && !error && (+ <div className="pointer-events-none absolute inset-0 z-10 flex items-center justify-center">+ <OwlLoader size={120} label={loadingLabel} className="min-h-0" />+ </div>+ )}+ {/* Re-layout feedback: ELK stage-2 on big layers used to freeze silently+ — a small owl chip says the canvas is still thinking. */}+ {loading && nodes.length > 0 && !error && (+ <div className="pointer-events-none absolute left-1/2 top-3 z-10 -translate-x-1/2 rounded-full border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]/95 px-3 py-1 shadow-sm">+ <OwlLoader+ size={28}+ label="Laying out…"+ className="min-h-0 flex-row gap-2 text-[10px]"+ />+ </div>+ )}++ <ReactFlow+ nodes={nodes}+ edges={edges}+ nodeTypes={archNodeTypes}+ edgeTypes={archEdgeTypes}+ {...(onNodeClick ? { onNodeClick } : {})}+ {...(onNodeDoubleClick ? { onNodeDoubleClick } : {})}+ {...(onPaneClick ? { onPaneClick } : {})}+ {...(onInit ? { onInit } : {})}+ fitView+ fitViewOptions={{ padding: 0.2 }}+ minZoom={0.1}+ maxZoom={3}+ proOptions={{ hideAttribution: true }}+ nodesDraggable={false}+ nodesConnectable={false}+ >+ {/* No grid background and no canvas fill — the diagram breathes on the+ page background (the Lines grid was removed per the airy directive). */}+ <Controls showInteractive={false} />+ {/* maskColor comes from --xy-minimap-mask-background (theme-aware). */}+ <MiniMap pannable zoomable />+ </ReactFlow>++ {hiddenEdgeCount > 0 && (+ <div+ className="absolute bottom-4 left-14 z-10 rounded-full border border-[var(--color-border-default)] bg-[var(--color-bg-secondary)]/90 px-3 py-1 text-xs text-[var(--color-text-secondary)]"+ title="Weakest aggregated connections are hidden to keep the view legible. Drill in to see them."+ >+ +{hiddenEdgeCount} weaker link{hiddenEdgeCount === 1 ? "" : "s"} hidden+ </div>+ )}++ {/* Decoder ring — collapsible, every tier. */}+ <div className="absolute bottom-4 right-[224px] z-10">+ <ArchLegend />+ </div>++ {children}+ </div>+ </>+ );+}diff --git a/packages/ui/src/c4/index.ts b/packages/ui/src/c4/index.tsindex 57fe621ce..3cf7f1747 100644--- a/packages/ui/src/c4/index.ts+++ b/packages/ui/src/c4/index.ts@@ -9,6 +9,9 @@export { C4Diagram } from "./C4Diagram";export type { C4DiagramProps } from "./C4Diagram";+export { ArchCanvas } from "./ArchCanvas";+export type { ArchCanvasProps } from "./ArchCanvas";+export { useC4Store } from "./store/use-c4-store";export type { C4Store, C4StoreState, UseC4StoreOptions } from "./store/use-c4-store";diff --git a/packages/ui/src/chat/artifacts.tsx b/packages/ui/src/chat/artifacts.tsxindex 5df4a14f4..e9ea207e2 100644--- a/packages/ui/src/chat/artifacts.tsx+++ b/packages/ui/src/chat/artifacts.tsx@@ -192,7 +192,7 @@ export function RiskReportRenderer({ data }: { data: RiskReportArtifactData }) {{t.file_path}</span>{t.is_hotspot && (- <span className="inline-flex items-center gap-1 rounded bg-amber-500/10 px-1.5 py-0.5 text-[9px] font-medium uppercase tracking-wider text-amber-400">+ <span className="inline-flex items-center gap-1 rounded bg-[var(--color-warning)]/10 px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wider text-[var(--color-warning)]"><AlertTriangle className="h-2.5 w-2.5" /> hotspot</span>)}@@ -300,7 +300,7 @@ export function GraphPathRenderer({ data }: { data: GraphPathArtifactData }) {key={`${node}:${i}`}className="flex items-center gap-2 text-xs">- <span className="flex h-4 w-4 shrink-0 items-center justify-center rounded-full bg-[var(--color-bg-elevated)] border border-[var(--color-border-default)] text-[9px] font-mono tabular-nums text-[var(--color-text-tertiary)]">+ <span className="flex h-4 w-4 shrink-0 items-center justify-center rounded-full bg-[var(--color-bg-elevated)] border border-[var(--color-border-default)] text-[10px] font-mono tabular-nums text-[var(--color-text-tertiary)]">{i + 1}</span><span className="font-mono text-[var(--color-text-secondary)] truncate">@@ -399,7 +399,7 @@ export function DecisionsRenderer({ data }: { data: DecisionsArtifactData }) {{r.decision}</p>{r.rationale && (- <p className="text-[11px] text-[var(--color-text-tertiary)] leading-relaxed">+ <p className="text-xs text-[var(--color-text-tertiary)] leading-relaxed">{r.rationale}</p>)}@@ -491,7 +491,7 @@ function DeadCodeRow({)}{finding.safe_to_delete && <> · cleanup-ready</>}</div>- <p className="text-[11px] text-[var(--color-text-secondary)] mt-1 line-clamp-2">+ <p className="text-xs text-[var(--color-text-secondary)] mt-1 line-clamp-2">{finding.reason}</p></div>diff --git a/packages/ui/src/chat/chat-interface.tsx b/packages/ui/src/chat/chat-interface.tsxindex 2317a949e..028093fc8 100644--- a/packages/ui/src/chat/chat-interface.tsx+++ b/packages/ui/src/chat/chat-interface.tsx@@ -180,8 +180,9 @@ export function ChatInterface({return (<div className="flex h-full flex-col min-h-0">- {/* Header bar (active conversation) */}- {!isEmpty && (+ {/* Header bar — the single home for model + history (both empty and+ active states), so the controls don't render twice. */}+ {(historySlot || modelSelectorSlot) && (<div className="flex items-center justify-between px-4 py-2.5 border-b border-[var(--color-border-default)] shrink-0 bg-[var(--color-bg-surface)]/95 backdrop-blur-sm"><div className="flex items-center gap-2">{historySlot}</div><div className="flex items-center gap-2">@@ -214,7 +215,7 @@ export function ChatInterface({<BrandMarkdarkSrc={emptyStateLogoSrc}size={48}- className="drop-shadow-[0_0_12px_rgba(245,149,32,0.35)]"+ className="drop-shadow-[0_0_8px_rgba(245,149,32,0.18)]"/></div><h2 className="text-xl font-semibold text-[var(--color-text-primary)]">@@ -242,16 +243,6 @@ export function ChatInterface({</button>))}</div>-- <div className="flex items-center gap-3">- {modelSelectorSlot && (- <span className="text-xs text-[var(--color-text-tertiary)]">- Using:- </span>- )}- {modelSelectorSlot}- {historySlot}- </div></div>) : (<ScrollArea className="h-full">@@ -268,7 +259,7 @@ export function ChatInterface({/>))}{error && (- <div className="rounded-lg border border-red-500/30 bg-red-500/10 px-4 py-2.5 text-sm text-red-400">+ <div className="rounded-lg border border-[var(--color-error)]/30 bg-[var(--color-error)]/10 px-4 py-2.5 text-sm text-[var(--color-error)]">{error}</div>)}@@ -294,7 +285,6 @@ export function ChatInterface({<divclassName={cn("flex items-end gap-2 rounded-2xl border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-4 py-3",- isEmpty && "shadow-lg shadow-black/20",sendDisabled && "opacity-60",)}>@@ -331,7 +321,7 @@ export function ChatInterface({</Button></div>{isEmpty && (- <p className="text-center text-[11px] text-[var(--color-text-tertiary)] mt-2.5">+ <p className="text-center text-xs text-[var(--color-text-tertiary)] mt-2.5">Shift+Enter for newline · Enter to send</p>)}diff --git a/packages/ui/src/chat/chat-markdown.tsx b/packages/ui/src/chat/chat-markdown.tsxindex db04d7d5b..4bd67dc4b 100644--- a/packages/ui/src/chat/chat-markdown.tsx+++ b/packages/ui/src/chat/chat-markdown.tsx@@ -1,9 +1,17 @@"use client";+import { lazy, Suspense } from "react";import ReactMarkdown from "react-markdown";import remarkGfm from "remark-gfm";import type { Components } from "react-markdown";+// Mermaid pulls a heavy renderer that is strictly client-side. Lazy-load it so+// it never enters the chat bundle (or SSR pass) unless a reply actually contains+// an inline ```mermaid block — parity with the wiki/docs reader.+const MermaidDiagram = lazy(() =>+ import("../wiki/mermaid-diagram").then((m) => ({ default: m.MermaidDiagram })),+);+const components: Components = {h1: ({ children }) => (<h1 className="text-base font-semibold text-[var(--color-text-primary)] mt-4 mb-2">@@ -39,6 +47,23 @@ const components: Components = {code: ({ className, children, ...props }) => {const isBlock = className?.includes("language-");if (isBlock) {+ const isMermaid = className?.includes("language-mermaid");+ if (isMermaid) {+ const chart = String(children ?? "").replace(/\n$/, "");+ return (+ <Suspense+ fallback={+ <pre className="my-2 rounded-md bg-[var(--color-bg-inset)] border border-[var(--color-border-default)] p-3 overflow-x-auto">+ <code className="text-xs font-mono text-[var(--color-text-primary)]">+ {chart}+ </code>+ </pre>+ }+ >+ <MermaidDiagram chart={chart} />+ </Suspense>+ );+ }return (<pre className="my-2 rounded-md bg-[var(--color-bg-inset)] border border-[var(--color-border-default)] p-3 overflow-x-auto"><codediff --git a/packages/ui/src/chat/chat-message.tsx b/packages/ui/src/chat/chat-message.tsxindex f3fe77664..ecf0ba86f 100644--- a/packages/ui/src/chat/chat-message.tsx+++ b/packages/ui/src/chat/chat-message.tsx@@ -3,7 +3,7 @@import { User } from "lucide-react";import { cn } from "../lib/cn";import { BrandMark } from "../shared/brand-mark";-import { ToolCallBlock } from "./tool-call-block";+import { ToolCallGroup } from "./tool-call-group";import { ChatMarkdown } from "./chat-markdown";import { SourceCitations, type SourceReference } from "./source-citations";import type { ChatUIMessage } from "@repowise-dev/types/chat";@@ -46,7 +46,7 @@ export function ChatMessage({<BrandMarkdarkSrc={assistantAvatarSrc}size={22}- className="drop-shadow-[0_0_4px_rgba(245,149,32,0.25)]"+ className="drop-shadow-[0_0_3px_rgba(245,149,32,0.15)]"/>)}</div>@@ -66,22 +66,10 @@ export function ChatMessage({{!isUser && (<div className="max-w-full space-y-1.5">{message.toolCalls.length > 0 && (- <div className="space-y-1">- {message.toolCalls.map((tc) => {- const artifact = tc.artifact;- const handler =- artifact && onViewArtifact- ? () => onViewArtifact(artifact)- : undefined;- return (- <ToolCallBlock- key={tc.id}- toolCall={tc}- {...(handler ? { onViewArtifact: handler } : {})}- />- );- })}- </div>+ <ToolCallGroup+ toolCalls={message.toolCalls}+ {...(onViewArtifact ? { onViewArtifact } : {})}+ />)}{message.text && (diff --git a/packages/ui/src/chat/conversation-history.tsx b/packages/ui/src/chat/conversation-history.tsxindex 709657d88..7457c6902 100644--- a/packages/ui/src/chat/conversation-history.tsx+++ b/packages/ui/src/chat/conversation-history.tsx@@ -130,7 +130,7 @@ export function ConversationHistory({e.stopPropagation();void onDelete(conv.id);}}- className="opacity-0 group-hover:opacity-100 p-1 text-[var(--color-text-tertiary)] hover:text-red-400 transition-all"+ className="opacity-0 group-hover:opacity-100 p-1 text-[var(--color-text-tertiary)] hover:text-[var(--color-error)] transition-all"aria-label="Delete conversation"><Trash2 className="h-3 w-3" />diff --git a/packages/ui/src/chat/index.ts b/packages/ui/src/chat/index.tsindex 66c1caed3..bea5c0133 100644--- a/packages/ui/src/chat/index.ts+++ b/packages/ui/src/chat/index.ts@@ -8,3 +8,4 @@ export * from "./model-selector";export * from "./source-citation";export * from "./source-citations";export * from "./tool-call-block";+export * from "./tool-call-group";diff --git a/packages/ui/src/chat/source-citation.tsx b/packages/ui/src/chat/source-citation.tsxindex faef5b290..76652bf71 100644--- a/packages/ui/src/chat/source-citation.tsx+++ b/packages/ui/src/chat/source-citation.tsx@@ -32,14 +32,14 @@ export function SourceCitation({const inner = (<>{typeof index === "number" && (- <span className="flex items-center justify-center h-3.5 w-3.5 rounded-sm bg-[var(--color-bg-overlay)] text-[9px] font-bold text-[var(--color-text-tertiary)] shrink-0">+ <span className="flex items-center justify-center h-3.5 w-3.5 rounded-sm bg-[var(--color-bg-overlay)] text-[10px] font-bold text-[var(--color-text-tertiary)] shrink-0">{index}</span>)}<FileCode className="h-3 w-3 shrink-0 opacity-60" /><span className="truncate max-w-[220px] font-mono">{label}</span>{citation.start_line != null && (- <span className="text-[9px] tabular-nums text-[var(--color-text-tertiary)] shrink-0">+ <span className="text-[10px] tabular-nums text-[var(--color-text-tertiary)] shrink-0">L{citation.start_line}{citation.end_line != null && citation.end_line !== citation.start_line? `-${citation.end_line}`diff --git a/packages/ui/src/chat/source-citations.tsx b/packages/ui/src/chat/source-citations.tsxindex 81c353436..56a5a72c0 100644--- a/packages/ui/src/chat/source-citations.tsx+++ b/packages/ui/src/chat/source-citations.tsx@@ -171,13 +171,13 @@ export function SourceCitations({href={buildHref ? buildHref(source) : defaultBuildHref(source, prefix)}className="group inline-flex items-center gap-1.5 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2 py-1 text-[10px] text-[var(--color-text-secondary)] hover:border-[var(--color-accent-primary)] hover:text-[var(--color-accent-primary)] hover:bg-[var(--color-accent-muted)] transition-all">- <span className="flex items-center justify-center h-3.5 w-3.5 rounded-sm bg-[var(--color-bg-overlay)] text-[9px] font-bold text-[var(--color-text-tertiary)] group-hover:bg-[var(--color-accent-primary)] group-hover:text-white shrink-0 transition-colors">+ <span className="flex items-center justify-center h-3.5 w-3.5 rounded-sm bg-[var(--color-bg-overlay)] text-[10px] font-bold text-[var(--color-text-tertiary)] group-hover:bg-[var(--color-accent-primary)] group-hover:text-white shrink-0 transition-colors">{idx + 1}</span><SourceIcon pageType={source.pageType} className="h-3 w-3 shrink-0 opacity-60" /><span className="truncate max-w-[160px] font-medium">{source.title}</span>{source.score != null && (- <span className="text-[9px] text-[var(--color-text-tertiary)] tabular-nums">+ <span className="text-[10px] text-[var(--color-text-tertiary)] tabular-nums">{(source.score * 100).toFixed(0)}%</span>)}diff --git a/packages/ui/src/chat/tool-call-block.tsx b/packages/ui/src/chat/tool-call-block.tsxindex 34ebf9ff9..9d72f22a8 100644--- a/packages/ui/src/chat/tool-call-block.tsx+++ b/packages/ui/src/chat/tool-call-block.tsx@@ -38,7 +38,7 @@ export function ToolCallBlock({ toolCall, onViewArtifact }: ToolCallBlockProps){isRunning ? (<Loader2 className="h-3.5 w-3.5 animate-spin text-[var(--color-accent-primary)] shrink-0" />) : (- <CheckCircle2 className="h-3.5 w-3.5 text-green-400 shrink-0" />+ <CheckCircle2 className="h-3.5 w-3.5 text-[var(--color-success)] shrink-0" />)}<span className="font-medium text-[var(--color-text-secondary)]">{label}</span>{toolCall.summary && !isRunning && (diff --git a/packages/ui/src/chat/tool-call-group.tsx b/packages/ui/src/chat/tool-call-group.tsxnew file mode 100644index 000000000..b3855439f--- /dev/null+++ b/packages/ui/src/chat/tool-call-group.tsx@@ -0,0 +1,79 @@+"use client";++import { useState } from "react";+import { ChevronDown, ChevronRight, Loader2, Sparkles } from "lucide-react";+import { ToolCallBlock } from "./tool-call-block";+import type { ChatUIToolCall } from "@repowise-dev/types/chat";++interface ToolCallGroupProps {+ toolCalls: ChatUIToolCall[];+ onViewArtifact?: (artifact: { type: string; data: Record<string, unknown> }) => void;+}++/**+ * Collapses a run of tool calls into a single "thinking" group instead of N+ * stacked bordered boxes. Auto-expands while any step is running so progress+ * stays visible; collapses to a one-line summary once the work is done.+ */+export function ToolCallGroup({ toolCalls, onViewArtifact }: ToolCallGroupProps) {+ const running = toolCalls.some((tc) => tc.status === "running");+ const [expanded, setExpanded] = useState(false);++ if (toolCalls.length === 0) return null;++ // A lone tool call doesn't need a group wrapper.+ if (toolCalls.length === 1) {+ const tc = toolCalls[0]!;+ const artifact = tc.artifact;+ const handler = artifact && onViewArtifact ? () => onViewArtifact(artifact) : undefined;+ return <ToolCallBlock toolCall={tc} {...(handler ? { onViewArtifact: handler } : {})} />;+ }++ const open = expanded || running;++ return (+ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] text-xs overflow-hidden">+ <button+ type="button"+ className="flex w-full items-center gap-2 px-3 py-2 text-left hover:bg-[var(--color-bg-overlay)] transition-colors"+ onClick={() => setExpanded((e) => !e)}+ aria-expanded={open}+ >+ {running ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin text-[var(--color-accent-primary)] shrink-0" />+ ) : (+ <Sparkles className="h-3.5 w-3.5 text-[var(--color-text-tertiary)] shrink-0" />+ )}+ <span className="font-medium text-[var(--color-text-secondary)]">+ {running ? "Working" : "Thinking"}+ </span>+ <span className="text-[var(--color-text-tertiary)]">+ · {toolCalls.length} steps+ </span>+ <span className="ml-auto shrink-0">+ {open ? (+ <ChevronDown className="h-3 w-3 text-[var(--color-text-tertiary)]" />+ ) : (+ <ChevronRight className="h-3 w-3 text-[var(--color-text-tertiary)]" />+ )}+ </span>+ </button>+ {open && (+ <div className="border-t border-[var(--color-border-default)] p-1.5 space-y-1">+ {toolCalls.map((tc) => {+ const artifact = tc.artifact;+ const handler =+ artifact && onViewArtifact ? () => onViewArtifact(artifact) : undefined;+ return (+ <ToolCallBlock+ key={tc.id}+ toolCall={tc}+ {...(handler ? { onViewArtifact: handler } : {})}+ />+ );+ })}+ </div>+ )}+ </div>+ );+}diff --git a/packages/ui/src/commits/commit-detail-card.tsx b/packages/ui/src/commits/commit-detail-card.tsxindex ce86bd996..155eca543 100644--- a/packages/ui/src/commits/commit-detail-card.tsx+++ b/packages/ui/src/commits/commit-detail-card.tsx@@ -98,7 +98,7 @@ export function CommitDetailCard({ commit, className }: CommitDetailCardProps) {{c.short_sha}</span>{c.is_fix && (- <span className="inline-flex items-center gap-1 text-xs text-red-400">+ <span className="inline-flex items-center gap-1 text-xs text-[var(--color-error)]"><Bug className="h-3 w-3" />fix</span>@@ -127,7 +127,7 @@ export function CommitDetailCard({ commit, className }: CommitDetailCardProps) {{c.committed_at && <span>{formatDateTime(c.committed_at)}</span>}</div>{c.agent_name && c.agent_channel && (- <p className="text-[10px] text-[var(--color-text-tertiary)]">+ <p className="text-xs text-[var(--color-text-tertiary)]">Attribution channel: {c.agent_channel}{c.agent_confidence ? ` · ${c.agent_confidence} confidence` : ""}</p>@@ -205,7 +205,7 @@ export function CommitDetailCard({ commit, className }: CommitDetailCardProps) {<p className="mb-1 text-xs font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">Why this score</p>- <p className="mb-2 text-[10px] text-[var(--color-text-tertiary)]">+ <p className="mb-2 text-xs text-[var(--color-text-tertiary)]">Each driver compares this change to the model's baseline commit.Red raised the raw score; green lowered it.</p>diff --git a/packages/ui/src/commits/commit-table.tsx b/packages/ui/src/commits/commit-table.tsxindex 2132a359e..8d68b3a81 100644--- a/packages/ui/src/commits/commit-table.tsx+++ b/packages/ui/src/commits/commit-table.tsx@@ -215,10 +215,10 @@ export function CommitTable({</td><td className="px-3 py-2.5 min-w-[200px] max-w-[460px]"><div className="flex items-center gap-2">- <span className="font-mono text-[11px] text-[var(--color-text-tertiary)] shrink-0">+ <span className="font-mono text-xs text-[var(--color-text-tertiary)] shrink-0">{c.short_sha}</span>- {c.is_fix && <Bug className="h-3 w-3 shrink-0 text-red-400" />}+ {c.is_fix && <Bug className="h-3 w-3 shrink-0 text-[var(--color-error)]" />}<spanclassName="truncate text-xs text-[var(--color-text-primary)]"title={c.subject}@@ -244,8 +244,8 @@ export function CommitTable({{c.committed_at ? formatRelativeTime(c.committed_at) : "—"}</td><td className="px-3 py-2.5 text-xs tabular-nums hidden lg:table-cell">- <span className="text-green-400">+{formatLOC(c.lines_added)}</span>{" "}- <span className="text-red-400">-{formatLOC(c.lines_deleted)}</span>+ <span className="text-[var(--color-success)]">+{formatLOC(c.lines_added)}</span>{" "}+ <span className="text-[var(--color-error)]">-{formatLOC(c.lines_deleted)}</span></td><td className="px-3 py-2.5"><div className="flex items-center gap-2">@@ -257,7 +257,7 @@ export function CommitTable({</div></td><td- className="px-3 py-2.5 text-[11px] text-[var(--color-text-tertiary)] hidden xl:table-cell max-w-[220px] truncate"+ className="px-3 py-2.5 text-xs text-[var(--color-text-tertiary)] hidden xl:table-cell max-w-[220px] truncate"title={c.top_driver ?? undefined}>{c.top_driver ?? "—"}diff --git a/packages/ui/src/commits/priority-badge.tsx b/packages/ui/src/commits/priority-badge.tsxindex 60a845869..ea92f187d 100644--- a/packages/ui/src/commits/priority-badge.tsx+++ b/packages/ui/src/commits/priority-badge.tsx@@ -5,10 +5,10 @@ import type { ReviewPriority } from "@repowise-dev/types/git";// "Typical" are calm (this commit is not unusual for the repo); only "Elevated"// — the top third of the repo's own distribution — draws the eye.const STYLES: Record<ReviewPriority, string> = {- high: "bg-amber-500/15 text-amber-400 border-amber-500/25",+ high: "bg-[var(--color-warning)]/15 text-[var(--color-warning)] border-[var(--color-warning)]/25",moderate:"bg-[var(--color-bg-elevated)] text-[var(--color-text-secondary)] border-[var(--color-border-default)]",- low: "bg-green-500/15 text-green-400 border-green-500/25",+ low: "bg-[var(--color-success)]/15 text-[var(--color-success)] border-[var(--color-success)]/25",};// Repo-relative tercile wording — where the commit sits in *its own repo's*diff --git a/packages/ui/src/commits/risk-driver-breakdown.tsx b/packages/ui/src/commits/risk-driver-breakdown.tsxindex edd504430..67823b3c0 100644--- a/packages/ui/src/commits/risk-driver-breakdown.tsx+++ b/packages/ui/src/commits/risk-driver-breakdown.tsx@@ -37,7 +37,7 @@ export function RiskDriverBreakdown({ drivers, className }: RiskDriverBreakdownP<divclassName={cn("absolute inset-y-0 rounded",- raises ? "bg-red-500/60" : "bg-green-500/60",+ raises ? "bg-[var(--color-error)]/60" : "bg-[var(--color-success)]/60",)}style={raises@@ -49,7 +49,7 @@ export function RiskDriverBreakdown({ drivers, className }: RiskDriverBreakdownP<spanclassName={cn("w-12 shrink-0 text-right tabular-nums",- raises ? "text-red-400" : "text-green-400",+ raises ? "text-[var(--color-error)]" : "text-[var(--color-success)]",)}>{raises ? "+" : ""}diff --git a/packages/ui/src/costs/cache-hit-ratio-card.tsx b/packages/ui/src/costs/cache-hit-ratio-card.tsxdeleted file mode 100644index 2e45965d0..000000000--- a/packages/ui/src/costs/cache-hit-ratio-card.tsx+++ /dev/null@@ -1,91 +0,0 @@-"use client";--import { Zap } from "lucide-react";-import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";-import { formatCost } from "../lib/format";--export interface CacheHitRatioCardProps {- /** Optional metric — when missing, the card renders a neutral "not yet wired" state. */- metrics?: {- hits: number;- misses: number;- estimated_savings_usd: number;- };-}--export function CacheHitRatioCard({ metrics }: CacheHitRatioCardProps) {- const total = metrics ? metrics.hits + metrics.misses : 0;- const ratio = total > 0 ? (metrics!.hits / total) * 100 : 0;- const dasharray = `${(ratio / 100) * 188.5} 188.5`;-- return (- <Card>- <CardHeader className="pb-2">- <CardTitle className="text-sm flex items-center gap-2">- <Zap className="h-4 w-4 text-yellow-500" />- Cache hits & savings- </CardTitle>- </CardHeader>- <CardContent className="pt-0">- <div className="flex items-center gap-5">- <svg width={80} height={80} viewBox="0 0 80 80" className="shrink-0 -rotate-90">- <circle- cx={40}- cy={40}- r={30}- fill="none"- strokeWidth={10}- stroke="var(--color-bg-inset)"- />- {metrics && (- <circle- cx={40}- cy={40}- r={30}- fill="none"- strokeWidth={10}- stroke="var(--color-accent-primary)"- strokeDasharray={dasharray}- strokeLinecap="round"- />- )}- <text- x={40}- y={45}- textAnchor="middle"- transform="rotate(90 40 40)"- className="fill-[var(--color-text-primary)]"- fontSize={metrics ? 16 : 11}- fontWeight={600}- >- {metrics ? `${Math.round(ratio)}%` : "—"}- </text>- </svg>- <div className="space-y-1 min-w-0">- {metrics ? (- <>- <div className="text-xs text-[var(--color-text-secondary)]">- <span className="font-medium text-[var(--color-text-primary)] tabular-nums">- {metrics.hits.toLocaleString()}- </span>{" "}- hits / {total.toLocaleString()} calls- </div>- <div className="text-xs text-[var(--color-text-secondary)]">- Estimated savings:{" "}- <span className="font-medium text-green-500 tabular-nums">- {formatCost(metrics.estimated_savings_usd)}- </span>- </div>- </>- ) : (- <p className="text-xs text-[var(--color-text-tertiary)] leading-snug max-w-[260px]">- Cache analytics not wired yet — once provider cache stats land we'll show- hit ratio and dollar savings here.- </p>- )}- </div>- </div>- </CardContent>- </Card>- );-}diff --git a/packages/ui/src/costs/cost-heatmap.tsx b/packages/ui/src/costs/cost-heatmap.tsxindex 0c8ec29db..b76f22153 100644--- a/packages/ui/src/costs/cost-heatmap.tsx+++ b/packages/ui/src/costs/cost-heatmap.tsx@@ -58,12 +58,14 @@ export function CostHeatmap({ groups, title = "Cost concentration", emptyHint }:flexBasis: basis,flexGrow: 1,height,- backgroundColor: `rgba(244, 63, 94, ${intensity.toFixed(3)})`,+ backgroundColor: `color-mix(in srgb, var(--color-error) ${Math.round(+ intensity * 100,+ )}%, transparent)`,}}title={`${g.group} — ${formatCost(g.cost_usd)} (${g.calls} calls)`}>- <span className="text-[10px] font-mono text-white/90 truncate">{g.group}</span>- <span className="text-[10px] text-white/80 tabular-nums">{formatCost(g.cost_usd)}</span>+ <span className="text-[10px] font-mono text-[var(--color-text-primary)] truncate">{g.group}</span>+ <span className="text-[10px] text-[var(--color-text-secondary)] tabular-nums">{formatCost(g.cost_usd)}</span></div>);})}diff --git a/packages/ui/src/costs/daily-spend-chart.tsx b/packages/ui/src/costs/daily-spend-chart.tsxnew file mode 100644index 000000000..c579a44e5--- /dev/null+++ b/packages/ui/src/costs/daily-spend-chart.tsx@@ -0,0 +1,64 @@+"use client";++import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer } from "recharts";+import { formatCost } from "../lib/format";++export interface DailySpendChartProps {+ /** Day-grouped cost rows ({ group: "YYYY-MM-DD", cost_usd }). Caller fetches. */+ groups: Array<{ group: string; cost_usd: number }>;+ height?: number;+}++/**+ * Daily generation-spend bars. A peer of OperationBreakdown / ProviderComparison+ * so the Costs page composes all charts from `ui` and they restyle on a bump.+ */+export function DailySpendChart({ groups, height = 220 }: DailySpendChartProps) {+ if (groups.length === 0) {+ return (+ <p className="text-sm text-[var(--color-text-secondary)] py-8 text-center">+ No cost data available.+ </p>+ );+ }++ const data = [...groups].sort((a, b) => a.group.localeCompare(b.group));++ return (+ <ResponsiveContainer width="100%" height={height}>+ <BarChart data={data} margin={{ top: 8, right: 8, bottom: 0, left: 0 }}>+ <XAxis+ dataKey="group"+ tick={{ fill: "var(--color-text-tertiary)", fontSize: 11 }}+ axisLine={false}+ tickLine={false}+ interval="preserveStartEnd"+ minTickGap={24}+ tickFormatter={(v: string) => {+ const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(v);+ return m ? `${Number(m[2])}/${Number(m[3])}` : v;+ }}+ />+ <YAxis+ tick={{ fill: "var(--color-text-tertiary)", fontSize: 10 }}+ axisLine={false}+ tickLine={false}+ tickFormatter={(v: number) => `$${v.toFixed(3)}`}+ />+ <Tooltip+ cursor={{ fill: "var(--color-bg-elevated)" }}+ contentStyle={{+ background: "var(--color-bg-overlay)",+ border: "1px solid var(--color-border-default)",+ borderRadius: "6px",+ fontSize: "12px",+ color: "var(--color-text-primary)",+ }}+ formatter={(value) => [formatCost(Number(value)), "Cost"]}+ labelFormatter={(label) => `Date: ${String(label)}`}+ />+ <Bar dataKey="cost_usd" fill="var(--color-accent-primary)" radius={[4, 4, 0, 0]} />+ </BarChart>+ </ResponsiveContainer>+ );+}diff --git a/packages/ui/src/costs/distill-savings-card.tsx b/packages/ui/src/costs/distill-savings-card.tsxindex 3faff79d8..7461ecbfd 100644--- a/packages/ui/src/costs/distill-savings-card.tsx+++ b/packages/ui/src/costs/distill-savings-card.tsx@@ -84,7 +84,7 @@ export function DistillSavingsCard({ data }: DistillSavingsCardProps) {<Card><CardContent className="py-8"><div className="flex items-center gap-3">- <Scissors className="h-5 w-5 shrink-0 text-cyan-500" />+ <Scissors className="h-5 w-5 shrink-0 text-[var(--color-savings-distill)]" /><div><p className="text-sm font-medium text-[var(--color-text-primary)]">No agent token savings recorded yet@@ -127,14 +127,14 @@ export function DistillSavingsCard({ data }: DistillSavingsCardProps) {<div className="flex flex-wrap items-end justify-between gap-4"><div><div className="flex items-center gap-2 text-xs font-medium uppercase tracking-wide text-[var(--color-text-tertiary)]">- <Sparkles className="h-3.5 w-3.5 text-cyan-500" />+ <Sparkles className="h-3.5 w-3.5 text-[var(--color-savings-distill)]" />Tokens saved for your agent</div><div className="mt-1 flex items-baseline gap-3"><span className="text-4xl font-semibold tabular-nums text-[var(--color-text-primary)]">{formatTokens(total)}</span>- <span className="text-2xl font-semibold tabular-nums text-green-500">+ <span className="text-2xl font-semibold tabular-nums text-[var(--color-success)]">{formatCost(data.estimated_usd_saved)}</span></div>@@ -158,7 +158,7 @@ export function DistillSavingsCard({ data }: DistillSavingsCardProps) {<div className="text-lg font-semibold tabular-nums text-[var(--color-text-primary)]">{formatTokens(distillSaved)}</div>- <div className="text-[11px] text-[var(--color-text-tertiary)]">+ <div className="text-xs text-[var(--color-text-tertiary)]">distill · {data.events.toLocaleString()} event{data.events === 1 ? "" : "s"}</div></div>@@ -166,7 +166,7 @@ export function DistillSavingsCard({ data }: DistillSavingsCardProps) {<div className="text-lg font-semibold tabular-nums text-[var(--color-text-primary)]">{formatTokens(mcpSaved)}</div>- <div className="text-[11px] text-[var(--color-text-tertiary)]">{mcpCaption}</div>+ <div className="text-xs text-[var(--color-text-tertiary)]">{mcpCaption}</div></div></div></div>@@ -175,25 +175,25 @@ export function DistillSavingsCard({ data }: DistillSavingsCardProps) {<div className="mt-4 flex h-2.5 w-full overflow-hidden rounded-full bg-[var(--color-bg-inset)]">{distillSaved > 0 && (<div- className="h-full bg-cyan-500"+ className="h-full bg-[var(--color-savings-distill)]"style={{ width: `${distillPct}%` }}title={`Distill — ${formatTokens(distillSaved)} (${distillPct}%)`}/>)}{mcpSaved > 0 && (<div- className="h-full bg-violet-500"+ className="h-full bg-[var(--color-savings-mcp)]"style={{ width: `${mcpPct}%` }}title={`MCP tools — ${formatTokens(mcpSaved)} (${mcpPct}%)`}/>)}</div>- <div className="mt-1.5 flex items-center gap-4 text-[11px] text-[var(--color-text-secondary)]">+ <div className="mt-1.5 flex items-center gap-4 text-xs text-[var(--color-text-secondary)]"><span className="flex items-center gap-1.5">- <span className="h-2 w-2 rounded-full bg-cyan-500" /> Distill {distillPct}%+ <span className="h-2 w-2 rounded-full bg-[var(--color-savings-distill)]" /> Distill {distillPct}%</span><span className="flex items-center gap-1.5">- <span className="h-2 w-2 rounded-full bg-violet-500" /> MCP tools {mcpPct}%+ <span className="h-2 w-2 rounded-full bg-[var(--color-savings-mcp)]" /> MCP tools {mcpPct}%</span></div>@@ -207,7 +207,7 @@ export function DistillSavingsCard({ data }: DistillSavingsCardProps) {tokens: f.saved_tokens,}))}max={distillSaved}- barClass="bg-cyan-500"+ barClass="bg-[var(--color-savings-distill)]"/>)}{topTools.length > 0 && (@@ -215,7 +215,7 @@ export function DistillSavingsCard({ data }: DistillSavingsCardProps) {title="MCP — by tool"rows={topTools.map((t) => ({ label: t.tool, tokens: t.tokens }))}max={mcpSaved}- barClass="bg-violet-500"+ barClass="bg-[var(--color-savings-mcp)]"/>)}</div>@@ -226,11 +226,11 @@ export function DistillSavingsCard({ data }: DistillSavingsCardProps) {href={DISTILL_DOCS}target="_blank"rel="noreferrer"- className="mt-5 flex items-center gap-3 rounded-lg border border-amber-500/30 bg-amber-500/5 px-3 py-2.5 transition-colors hover:bg-amber-500/10"+ className="mt-5 flex items-center gap-3 rounded-lg border border-[var(--color-warning)]/30 bg-[var(--color-warning)]/5 px-3 py-2.5 transition-colors hover:bg-[var(--color-warning)]/10">- <Zap className="h-4 w-4 shrink-0 text-amber-500" />+ <Zap className="h-4 w-4 shrink-0 text-[var(--color-warning)]" /><div className="text-xs text-[var(--color-text-secondary)]">- <span className="font-medium text-amber-500">+ <span className="font-medium text-[var(--color-warning)]">Unlock ~{formatTokens(data.missed_tokens_est ?? 0)} more</span>{" "}— {(data.missed_events ?? 0).toLocaleString()} raw command@@ -240,7 +240,7 @@ export function DistillSavingsCard({ data }: DistillSavingsCardProps) {</a>)}- <p className="mt-3 text-[10px] leading-snug text-[var(--color-text-tertiary)]">+ <p className="mt-3 text-xs leading-snug text-[var(--color-text-tertiary)]">Distill counts <code>repowise distill</code> command/hook savings; MCP counts the rawfile exploration each tool answer replaced (plus any over-budget content trimmed). Savedtokens are agent input, priced at the agent's input rate. Everything stays on this@@ -269,7 +269,7 @@ function SurfaceDetail({}) {return (<div className="space-y-1.5">- <div className="text-[11px] font-medium uppercase tracking-wide text-[var(--color-text-tertiary)]">+ <div className="text-xs font-medium uppercase tracking-wide text-[var(--color-text-tertiary)]">{title}</div>{rows.map((row) => {diff --git a/packages/ui/src/costs/index.ts b/packages/ui/src/costs/index.tsindex 5cc9f8915..070e63f8e 100644--- a/packages/ui/src/costs/index.ts+++ b/packages/ui/src/costs/index.ts@@ -4,8 +4,8 @@ export { ProviderComparison } from "./provider-comparison";export type { ProviderComparisonProps } from "./provider-comparison";export { CostHeatmap } from "./cost-heatmap";export type { CostHeatmapProps } from "./cost-heatmap";-export { CacheHitRatioCard } from "./cache-hit-ratio-card";-export type { CacheHitRatioCardProps } from "./cache-hit-ratio-card";+export { DailySpendChart } from "./daily-spend-chart";+export type { DailySpendChartProps } from "./daily-spend-chart";export { DistillSavingsCard } from "./distill-savings-card";export type {DistillSavingsCardProps,diff --git a/packages/ui/src/coupling/coupling-graph.tsx b/packages/ui/src/coupling/coupling-graph.tsxindex b523173b9..78c8821cb 100644--- a/packages/ui/src/coupling/coupling-graph.tsx+++ b/packages/ui/src/coupling/coupling-graph.tsx@@ -175,7 +175,7 @@ export function CouplingGraph({if (!layout) {return (<div- className="flex items-center justify-center rounded-xl border border-dashed border-[var(--color-border-default)] bg-[var(--color-bg-surface)] text-center text-sm text-[var(--color-text-tertiary)]"+ className="flex items-center justify-center rounded-xl border border-dashed border-[var(--color-border-default)] text-center text-sm text-[var(--color-text-tertiary)]"style={{ minHeight: size * 0.6 }}>Not enough shared git history to map coupling yet. Files need to have@@ -187,6 +187,33 @@ export function CouplingGraph({const { radius, leaves, drawn, degree, maxNloc, maxStrength, groups } = layout;const c = size / 2;+ // Top-degree hubs are always labelled; the rest reveal on hover. This replaces+ // the all-or-nothing 36-node gate with a curated set that stays legible even+ // on a dense ring.+ const TOP_HUB_LABELS = 14;+ const hubPaths = new Set(+ [...degree.entries()]+ .sort((a, b) => b[1] - a[1])+ .slice(0, TOP_HUB_LABELS)+ .map(([path]) => path),+ );++ // Disambiguate basename collisions: when two files share a basename, prepend+ // the immediate parent dir so the ring labels stay distinct.+ const basenameCounts = new Map<string, number>();+ for (const n of nodes) {+ const base = n.file_path.split("/").pop() ?? n.file_path;+ basenameCounts.set(base, (basenameCounts.get(base) ?? 0) + 1);+ }+ const labelFor = (full: string) => {+ const segs = full.split("/");+ const base = segs.at(-1) ?? full;+ if ((basenameCounts.get(base) ?? 0) > 1 && segs.length > 1) {+ return `${segs.at(-2)}/${base}`;+ }+ return base;+ };+// Neighbors of the focused file (for dimming + dot emphasis).const neighbors = new Set<string>();if (focus) {@@ -199,25 +226,8 @@ export function CouplingGraph({const dotR = (n: CouplingNode) =>2 + Math.sqrt(n.nloc / maxNloc) * 2.4 + Math.min((degree.get(n.file_path) ?? 0) / 6, 2.6);- const labelFor = (full: string) => full.split("/").pop() ?? full;-return (- <div className="rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-4">- <div className="mb-1 flex items-baseline justify-between gap-3">- <h3 className="text-sm font-semibold tracking-tight text-[var(--color-text-primary)]">- Change coupling- </h3>- <span className="text-xs text-[var(--color-text-tertiary)]">- {totalEdges && totalEdges > drawn.length- ? `showing ${drawn.length} of ${totalEdges} couplings`- : `${drawn.length} couplings`}- </span>- </div>- <p className="mb-2 text-xs text-[var(--color-text-tertiary)]">- Files that tend to change in the same commit. A temporal hint, not a- verified dependency.- </p>-+ <div><svgviewBox={`0 0 ${size} ${size}`}width="100%"@@ -226,15 +236,16 @@ export function CouplingGraph({onMouseLeave={() => setFocus(null)}><g transform={`translate(${c},${c})`}>- {/* Module arc bands + labels around the perimeter. */}+ {/* Module arc bands + labels around the perimeter. Tiny (≈single+ file) arcs are left unlabelled so their names don't pile up near+ 12 o'clock; the remaining module labels are angularly well spread. */}{[...groups.entries()].map(([name, g]) => {const mid = (g.a0 + g.a1) / 2;- const [lx, ly] = project(mid, radius + 30);- const deg = (mid * 180) / Math.PI - 90;- const flip = mid > Math.PI;+ const [lx, ly] = project(mid, radius + 34);const [x0, y0] = project(g.a0 - 0.012, radius + 12);const [x1, y1] = project(g.a1 + 0.012, radius + 12);const large = g.a1 - g.a0 > Math.PI ? 1 : 0;+ const span = g.a1 - g.a0;return (<g key={name}><path@@ -246,17 +257,18 @@ export function CouplingGraph({strokeWidth={1.5}strokeLinecap="round"/>- <text- x={lx}- y={ly}- fontSize={10}- textAnchor="middle"- dominantBaseline="middle"- transform={`rotate(${flip ? deg + 180 : deg} ${lx} ${ly})`}- className="fill-[var(--color-text-tertiary)] font-medium uppercase tracking-wider"- >- {name}- </text>+ {span >= 0.07 && (+ <text+ x={lx}+ y={ly}+ fontSize={11}+ textAnchor="middle"+ dominantBaseline="middle"+ className="fill-[var(--color-text-secondary)] font-medium uppercase tracking-wider"+ >+ {name}+ </text>+ )}</g>);})}@@ -294,10 +306,15 @@ export function CouplingGraph({const isFocus = focus === n.file_path;const isNeighbor = neighbors.has(n.file_path);const dim = focus != null && !isFocus && !isNeighbor;- const showLabel = isFocus || isNeighbor || (focus == null && leaves.length <= 36);- const deg = (leaf.x! * 180) / Math.PI - 90;- const flip = leaf.x! > Math.PI;- const [lx, ly] = project(leaf.x!, leaf.y! + 8);+ const isHub = hubPaths.has(n.file_path);+ // Always label the top hubs; reveal the rest on hover (focus ++ // neighbors). No more all-or-nothing 36-node gate.+ const showLabel = isFocus || isNeighbor || (focus == null && isHub);+ // Labels radiate along each file's own spoke so angularly-adjacent+ // hubs fan out instead of stacking on a shared baseline. Flip the+ // left half so the text never renders upside-down.+ const onLeft = leaf.x! >= Math.PI;+ const labelRot = (leaf.x! * 180) / Math.PI - 90;return (<gkey={n.file_path}@@ -318,14 +335,12 @@ export function CouplingGraph({</circle>{showLabel ? (<text- x={lx}- y={ly}- fontSize={9}- textAnchor={flip ? "end" : "start"}- dominantBaseline="middle"- transform={`rotate(${flip ? deg + 180 : deg} ${lx} ${ly})`}+ transform={`rotate(${labelRot}) translate(${leaf.y! + 8},0)${onLeft ? " rotate(180)" : ""}`}+ dy="0.31em"+ fontSize={11.5}+ textAnchor={onLeft ? "end" : "start"}className={- isFocus+ isFocus || isHub? "fill-[var(--color-text-primary)] font-medium": "fill-[var(--color-text-secondary)]"}@@ -341,7 +356,7 @@ export function CouplingGraph({</svg>{/* Legend */}- <div className="mt-1 flex flex-wrap items-center gap-x-4 gap-y-1 text-[11px] text-[var(--color-text-tertiary)]">+ <div className="mt-1 flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-[var(--color-text-tertiary)]"><span className="inline-flex items-center gap-1.5"><span className="h-2 w-2 rounded-full bg-[var(--color-success)]" /> healthy</span>@@ -351,7 +366,12 @@ export function CouplingGraph({<span className="inline-flex items-center gap-1.5"><span className="h-2 w-2 rounded-full bg-[var(--color-error)]" /> alert</span>- <span className="ml-auto">dot size = lines + couplings · line opacity = strength</span>+ <span className="ml-auto">+ {totalEdges && totalEdges > drawn.length+ ? `showing ${drawn.length} of ${totalEdges} couplings · `+ : `${drawn.length} couplings · `}+ dot size = lines + couplings · line opacity = strength+ </span></div></div>);diff --git a/packages/ui/src/coupling/index.ts b/packages/ui/src/coupling/index.tsindex a0962c0de..16c2707ba 100644--- a/packages/ui/src/coupling/index.ts+++ b/packages/ui/src/coupling/index.ts@@ -1,2 +1,10 @@export { CouplingGraph, type CouplingGraphProps } from "./coupling-graph";export { CouplingTable } from "./coupling-table";++/**+ * The single canonical disclaimer for every change-coupling surface. Co-change+ * is a temporal work-pattern hint drawn from git history, never a verified+ * technical dependency — say it once, reuse it everywhere.+ */+export const COUPLING_DISCLAIMER =+ "Files that tend to change together in the same commit. A temporal hint for hidden relationships, not a verified code dependency.";diff --git a/packages/ui/src/coverage/drift-banner.tsx b/packages/ui/src/coverage/drift-banner.tsxindex 57d1584ee..22d744346 100644--- a/packages/ui/src/coverage/drift-banner.tsx+++ b/packages/ui/src/coverage/drift-banner.tsx@@ -18,9 +18,9 @@ export function DriftBanner({ pages, threshold = 0 }: DriftBannerProps) {return (<divrole="status"- className="flex items-start gap-3 rounded-lg border border-amber-500/40 bg-amber-500/10 px-4 py-3"+ className="flex items-start gap-3 rounded-lg border border-[var(--color-warning)]/40 bg-[var(--color-warning)]/10 px-4 py-3">- <AlertTriangle className="h-5 w-5 text-amber-400 shrink-0 mt-0.5" />+ <AlertTriangle className="h-5 w-5 text-[var(--color-warning)] shrink-0 mt-0.5" /><div className="text-sm text-[var(--color-text-primary)]"><p className="font-medium">{drift} outdated · {stale} stalediff --git a/packages/ui/src/coverage/freshness-table.tsx b/packages/ui/src/coverage/freshness-table.tsxindex 28d51f542..1ea48bed6 100644--- a/packages/ui/src/coverage/freshness-table.tsx+++ b/packages/ui/src/coverage/freshness-table.tsx@@ -139,10 +139,10 @@ export function FreshnessTable({ pages, onRegenerate }: FreshnessTableProps) {<spanclassName={cn(page.confidence >= 0.8- ? "text-green-500"+ ? "text-[var(--color-success)]": page.confidence >= 0.6- ? "text-yellow-500"- : "text-red-500",+ ? "text-[var(--color-warning)]"+ : "text-[var(--color-error)]",)}>{formatConfidence(page.confidence)}diff --git a/packages/ui/src/dashboard/attention-panel.tsx b/packages/ui/src/dashboard/attention-panel.tsxindex ea5862b7b..4b867179c 100644--- a/packages/ui/src/dashboard/attention-panel.tsx+++ b/packages/ui/src/dashboard/attention-panel.tsx@@ -11,6 +11,7 @@ import {import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";import { Badge } from "../ui/badge";import { stripMarkdown } from "../lib/format";+import { fileEntityPath } from "../shared/entity/routes";export type AttentionItemType =| "stale_decision"@@ -25,6 +26,9 @@ export interface AttentionItem {title: string;description: string;severity: "high" | "medium" | "low";+ /** What the item points at — a decision id, file path, owner, … Used to+ * deep-link straight to the offending entity. */+ target_id?: string;href?: string;}@@ -59,14 +63,23 @@ interface AttentionPanelProps {}function getDefaultHref(item: AttentionItem, prefix: string): string {+ const target = item.target_id;switch (item.type) {case "stale_decision":case "proposed_decision":- return `${prefix}/decisions`;+ // Deep-link to the specific decision when we know which one.+ return target+ ? `${prefix}/decisions/${encodeURIComponent(target)}`+ : `${prefix}/decisions`;case "knowledge_silo":- return `${prefix}/owners`;+ // The silo target is the owning module/path — surface it on the owners+ // view so the offending area is preselected.+ return target+ ? `${prefix}/owners?path=${encodeURIComponent(target)}`+ : `${prefix}/owners`;case "ungoverned_hotspot":- return `${prefix}/code-health?tab=hotspots`;+ // Target is the hotspot's file path → open its file entity page.+ return target ? fileEntityPath(prefix, target) : `${prefix}/code-health?tab=hotspots`;case "dead_code":return `${prefix}/code-health?tab=dead-code`;default:@@ -131,7 +144,7 @@ export function AttentionPanel({{TYPE_LABELS[item.type]}</span></div>- <p className="text-[11px] text-[var(--color-text-tertiary)] truncate">+ <p className="text-xs text-[var(--color-text-tertiary)] truncate">{item.description}</p></div>@@ -142,7 +155,7 @@ export function AttentionPanel({<buttontype="button"onClick={() => setExpanded((v) => !v)}- className="block w-full text-[11px] text-[var(--color-accent-primary)] hover:underline text-center pt-1"+ className="block w-full text-xs text-[var(--color-accent-primary)] hover:underline text-center pt-1">{expanded? "Show fewer"diff --git a/packages/ui/src/dashboard/commits-mini.tsx b/packages/ui/src/dashboard/commits-mini.tsxindex 17657fcd7..9903fab7d 100644--- a/packages/ui/src/dashboard/commits-mini.tsx+++ b/packages/ui/src/dashboard/commits-mini.tsx@@ -76,7 +76,7 @@ export function CommitsMini({ commits, repoId, linkPrefix, previewCount = 8 }: C}`}title={c.change_risk_level ? `${c.change_risk_level} change risk` : undefined}/>- <span className="text-[11px] font-mono text-[var(--color-text-tertiary)] shrink-0">+ <span className="text-xs font-mono text-[var(--color-text-tertiary)] shrink-0">{c.short_sha}</span><span className="text-xs text-[var(--color-text-primary)] truncate flex-1 min-w-0">diff --git a/packages/ui/src/dashboard/community-summary-grid.tsx b/packages/ui/src/dashboard/community-summary-grid.tsxindex f24e2b51f..9015cf4ab 100644--- a/packages/ui/src/dashboard/community-summary-grid.tsx+++ b/packages/ui/src/dashboard/community-summary-grid.tsx@@ -75,14 +75,14 @@ function DetailPanel({ detail, isLoading, onClose, memberHref }: DetailPanelProp{memberHref ? (<ahref={memberHref(m.path)}- className="text-[11px] font-mono text-[var(--color-text-secondary)] truncate hover:text-[var(--color-accent-primary)] hover:underline"+ className="text-xs font-mono text-[var(--color-text-secondary)] truncate hover:text-[var(--color-accent-primary)] hover:underline"title={m.path}>{truncatePath(m.path)}</a>) : (<span- className="text-[11px] font-mono text-[var(--color-text-secondary)] truncate"+ className="text-xs font-mono text-[var(--color-text-secondary)] truncate"title={m.path}>{truncatePath(m.path)}@@ -94,7 +94,7 @@ function DetailPanel({ detail, isLoading, onClose, memberHref }: DetailPanelPropEP</Badge>)}- <span className="text-[9px] font-mono text-[var(--color-text-tertiary)] tabular-nums">+ <span className="text-[10px] font-mono text-[var(--color-text-tertiary)] tabular-nums">{m.pagerank.toFixed(4)}</span></div>@@ -119,11 +119,11 @@ function DetailPanel({ detail, isLoading, onClose, memberHref }: DetailPanelProp<div key={n.community_id} className="flex items-center justify-between gap-2"><div className="flex items-center gap-1.5 min-w-0"><ArrowRight className="h-2.5 w-2.5 shrink-0 text-[var(--color-text-tertiary)]" />- <span className="text-[11px] text-[var(--color-text-secondary)] truncate">+ <span className="text-xs text-[var(--color-text-secondary)] truncate">{n.label}</span></div>- <Badge variant="outline" className="text-[9px] h-4 shrink-0">+ <Badge variant="outline" className="text-[10px] h-4 shrink-0">{n.cross_edge_count} edges</Badge></div>diff --git a/packages/ui/src/dashboard/decisions-timeline.tsx b/packages/ui/src/dashboard/decisions-timeline.tsxindex e3ade8c95..c4753b625 100644--- a/packages/ui/src/dashboard/decisions-timeline.tsx+++ b/packages/ui/src/dashboard/decisions-timeline.tsx@@ -89,7 +89,7 @@ export function DecisionsTimeline({ decisions, repoId, linkPrefix }: DecisionsTi</span><Badgevariant="outline"- className={`text-[9px] h-4 shrink-0 ${STATUS_BADGE_VARIANT[d.status] ?? ""}`}+ className={`text-[10px] h-4 shrink-0 ${STATUS_BADGE_VARIANT[d.status] ?? ""}`}>{d.status}</Badge>diff --git a/packages/ui/src/dashboard/dependency-heatmap.tsx b/packages/ui/src/dashboard/dependency-heatmap.tsxindex 2da63ef3f..03a157c34 100644--- a/packages/ui/src/dashboard/dependency-heatmap.tsx+++ b/packages/ui/src/dashboard/dependency-heatmap.tsx@@ -164,7 +164,7 @@ export function DependencyHeatmap({ moduleGraph }: DependencyHeatmapProps) {{/* Row label */}<div className="flex items-center justify-end pr-2.5 min-w-[60px]"><span- className="text-[11px] text-[var(--color-text-tertiary)] font-mono truncate max-w-[110px]"+ className="text-xs text-[var(--color-text-tertiary)] font-mono truncate max-w-[110px]"title={rowMod}>{displayLabel(rowMod)}diff --git a/packages/ui/src/dashboard/execution-flows-panel.tsx b/packages/ui/src/dashboard/execution-flows-panel.tsxindex 6dde29ce9..ed1ae8e1b 100644--- a/packages/ui/src/dashboard/execution-flows-panel.tsx+++ b/packages/ui/src/dashboard/execution-flows-panel.tsx@@ -1,10 +1,9 @@"use client";-import { useState } from "react";+import { useState, type CSSProperties } from "react";import { ChevronRight, ChevronDown, Workflow } from "lucide-react";import { Badge } from "../ui/badge";import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";-import { cn } from "../lib/cn";import { EmptyState } from "../shared/empty-state";import type { ExecutionFlowEntry } from "@repowise-dev/types/graph";@@ -17,12 +16,24 @@ interface ExecutionFlowsPanelProps {function FlowRow({ flow }: { flow: ExecutionFlowEntry }) {const [expanded, setExpanded] = useState(false);- const scoreColor =+ const scoreStyle: CSSProperties =flow.entry_point_score >= 0.7- ? "text-green-400 bg-green-400/10 border-green-400/20"+ ? {+ color: "var(--color-success)",+ background: "color-mix(in srgb, var(--color-success) 12%, transparent)",+ borderColor: "color-mix(in srgb, var(--color-success) 25%, transparent)",+ }: flow.entry_point_score >= 0.4- ? "text-yellow-400 bg-yellow-400/10 border-yellow-400/20"- : "text-[var(--color-text-tertiary)] bg-[var(--color-bg-elevated)] border-[var(--color-border-default)]";+ ? {+ color: "var(--color-warning)",+ background: "color-mix(in srgb, var(--color-warning) 12%, transparent)",+ borderColor: "color-mix(in srgb, var(--color-warning) 25%, transparent)",+ }+ : {+ color: "var(--color-text-tertiary)",+ background: "var(--color-bg-elevated)",+ borderColor: "var(--color-border-default)",+ };return (<div className="border-b border-[var(--color-border-default)] last:border-0">@@ -40,7 +51,10 @@ function FlowRow({ flow }: { flow: ExecutionFlowEntry }) {{flow.entry_point_name}</span>- <span className={cn("text-[10px] font-mono px-1.5 py-0.5 rounded border shrink-0", scoreColor)}>+ <span+ className="text-[10px] font-mono px-1.5 py-0.5 rounded border shrink-0"+ style={scoreStyle}+ >{(flow.entry_point_score * 100).toFixed(0)}</span>@@ -49,7 +63,7 @@ function FlowRow({ flow }: { flow: ExecutionFlowEntry }) {</span>{flow.crosses_community && (- <Badge variant="outline" className="text-[9px] shrink-0 h-4">+ <Badge variant="outline" className="text-[10px] shrink-0 h-4">cross-community</Badge>)}@@ -57,16 +71,20 @@ function FlowRow({ flow }: { flow: ExecutionFlowEntry }) {{expanded && flow.trace.length > 1 && (<div className="px-3 pb-3 pl-8">- <div className="flex flex-wrap items-center gap-1">+ <div className="flex flex-wrap items-center gap-y-2">{flow.trace.slice(0, 12).map((sym, i) => {const name = sym.includes("::") ? sym.split("::").pop() : sym.split("/").pop();return (- <span key={i} className="flex items-center gap-1">+ <span key={i} className="flex items-center">{i > 0 && (- <ChevronRight className="h-2.5 w-2.5 text-[var(--color-text-tertiary)]" />+ <span+ aria-hidden+ className="h-px w-3 shrink-0"+ style={{ background: "var(--color-border-hover)" }}+ />)}<span- className="text-[10px] font-mono text-[var(--color-text-secondary)] px-1 py-0.5 rounded bg-[var(--color-bg-elevated)]"+ className="rounded-full border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2 py-0.5 font-mono text-[10px] text-[var(--color-text-secondary)]"title={sym}>{name}@@ -75,7 +93,7 @@ function FlowRow({ flow }: { flow: ExecutionFlowEntry }) {);})}{flow.trace.length > 12 && (- <span className="text-[10px] text-[var(--color-text-tertiary)]">+ <span className="ml-1 text-[10px] text-[var(--color-text-tertiary)]">+{flow.trace.length - 12} more</span>)}diff --git a/packages/ui/src/dashboard/health-overview-card.tsx b/packages/ui/src/dashboard/health-overview-card.tsxindex e573f3e87..ba703d702 100644--- a/packages/ui/src/dashboard/health-overview-card.tsx+++ b/packages/ui/src/dashboard/health-overview-card.tsx@@ -65,7 +65,7 @@ function TrendChip({ delta }: { delta: number | null | undefined }) {const Icon = up ? TrendingUp : TrendingDown;return (<span- className="inline-flex items-center gap-0.5 text-[11px] font-medium tabular-nums"+ className="inline-flex items-center gap-0.5 text-xs font-medium tabular-nums"style={{ color: up ? "var(--color-success)" : "var(--color-error)" }}title={`${up ? "+" : ""}${delta.toFixed(2)} vs previous snapshot`}>@@ -112,6 +112,66 @@ function Sparkline({ points }: { points: number[] }) {);}+/** Severity-mix donut whose center is the open-findings headline count. */+function SeverityDonut({+ segments,+ total,+ count,+}: {+ segments: { key: string; count: number; color: string }[];+ total: number;+ count: number;+}) {+ const size = 88;+ const stroke = 10;+ const radius = (size - stroke) / 2;+ const circ = 2 * Math.PI * radius;+ let offset = 0;++ return (+ <div className="relative shrink-0" style={{ width: size, height: size }}>+ <svg width={size} height={size} className="-rotate-90">+ <circle+ cx={size / 2}+ cy={size / 2}+ r={radius}+ fill="none"+ stroke="var(--color-bg-inset)"+ strokeWidth={stroke}+ />+ {total > 0 &&+ segments.map((s) => {+ const len = (s.count / total) * circ;+ const dash = `${len} ${circ - len}`;+ const el = (+ <circle+ key={s.key}+ cx={size / 2}+ cy={size / 2}+ r={radius}+ fill="none"+ stroke={s.color}+ strokeWidth={stroke}+ strokeDasharray={dash}+ strokeDashoffset={-offset}+ />+ );+ offset += len;+ return el;+ })}+ </svg>+ <div className="absolute inset-0 flex flex-col items-center justify-center">+ <span className="text-lg font-bold tabular-nums leading-none text-[var(--color-text-primary)]">+ {count.toLocaleString()}+ </span>+ <span className="text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">+ findings+ </span>+ </div>+ </div>+ );+}+function MetricTile({icon,label,@@ -129,7 +189,7 @@ function MetricTile({}) {return (<div className="flex flex-col gap-1.5 px-4 py-3.5">- <div className="flex items-center gap-1.5 text-[11px] font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">+ <div className="flex items-center gap-1.5 text-xs font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">{icon}{label}</div>@@ -147,7 +207,7 @@ function MetricTile({<div className="flex items-center justify-between gap-2">{b && (<span- className="text-[11px] font-medium uppercase tracking-wide"+ className="text-xs font-medium uppercase tracking-wide"style={{ color: b.color }}>{b.label}@@ -191,7 +251,7 @@ export function HealthOverviewCard({const hasData = avg != null || hot != null;return (- <Card className={`overflow-hidden shadow-sm ${className ?? ""}`}>+ <Card className={`overflow-hidden ${className ?? ""}`}><CardHeader className="pb-2"><CardTitle className="text-sm flex items-center justify-between"><span className="flex items-center gap-2">@@ -200,7 +260,7 @@ export function HealthOverviewCard({</span><ahref={reportHref}- className="inline-flex items-center gap-1 text-[11px] font-normal text-[var(--color-accent-primary)] hover:underline"+ className="inline-flex items-center gap-1 text-xs font-normal text-[var(--color-accent-primary)] hover:underline">View report <ArrowRight className="h-3 w-3" /></a>@@ -236,36 +296,26 @@ export function HealthOverviewCard({{/* Findings + worst performer */}<div className="px-4 py-3.5 space-y-3">- <div className="flex items-center justify-between gap-3">- <span className="flex items-center gap-1.5 text-[11px] font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">- <ShieldAlert className="h-3 w-3" />- Open findings- </span>- <a- href={`${reportHref}?tab=triage`}- className="text-sm font-bold tabular-nums text-[var(--color-text-primary)] hover:text-[var(--color-accent-primary)] transition-colors"- >- {data.open_findings.toLocaleString()}- </a>- </div>+ <a+ href={`${reportHref}?tab=triage`}+ className="flex items-center gap-1.5 text-xs font-medium uppercase tracking-wider text-[var(--color-text-tertiary)] hover:text-[var(--color-accent-primary)] transition-colors"+ >+ <ShieldAlert className="h-3 w-3" />+ Open findings+ </a>{severityTotal > 0 ? (- <>- <div className="flex h-2 w-full overflow-hidden rounded-full bg-[var(--color-bg-inset)]">- {severities.map((s) => (- <div- key={s.key}- className="h-full"- style={{ width: `${(s.count / severityTotal) * 100}%`, background: s.color }}- title={`${s.count} ${s.key}`}- />- ))}- </div>- <div className="flex flex-wrap items-center gap-x-4 gap-y-1">+ <div className="flex items-center gap-4">+ <SeverityDonut+ segments={severities}+ total={severityTotal}+ count={data.open_findings}+ />+ <div className="flex flex-col gap-1">{severities.map((s) => (<spankey={s.key}- className="flex items-center gap-1.5 text-[11px] text-[var(--color-text-secondary)] capitalize"+ className="flex items-center gap-1.5 text-xs text-[var(--color-text-secondary)] capitalize"><span className="h-2 w-2 rounded-full" style={{ background: s.color }} />{s.key}@@ -273,9 +323,9 @@ export function HealthOverviewCard({</span>))}</div>- </>+ </div>) : (- <p className="text-[11px] text-[var(--color-success)]">No open findings — clean bill of health.</p>+ <p className="text-xs text-[var(--color-success)]">No open findings — clean bill of health.</p>)}{data.worst_performer_path && data.worst_performer_score != null && (@@ -288,12 +338,12 @@ export function HealthOverviewCard({<span className="text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)] shrink-0">Worst file</span>- <span className="truncate font-mono text-[11px] text-[var(--color-text-secondary)] group-hover:text-[var(--color-accent-primary)] transition-colors">+ <span className="truncate font-mono text-xs text-[var(--color-text-secondary)] group-hover:text-[var(--color-accent-primary)] transition-colors">{truncatePath(data.worst_performer_path, 40)}</span></span><span- className="shrink-0 text-[11px] font-bold tabular-nums"+ className="shrink-0 text-xs font-bold tabular-nums"style={{ color: band(data.worst_performer_score).color }}>{data.worst_performer_score.toFixed(1)}/10diff --git a/packages/ui/src/dashboard/health-score-badge.tsx b/packages/ui/src/dashboard/health-score-badge.tsxdeleted file mode 100644index 4acda7833..000000000--- a/packages/ui/src/dashboard/health-score-badge.tsx+++ /dev/null@@ -1,174 +0,0 @@-"use client";--import { useEffect, useRef, useState } from "react";-import { HelpCircle } from "lucide-react";-import type { HealthScoreComponent } from "./health-score-ring";--export interface HealthSparklinePoint {- taken_at: string | null;- /** Code-health average on the 1–10 scale. */- average_health: number;-}--interface HealthScoreBadgeProps {- /** Composite repo score, 0–100. */- score: number;- components?: HealthScoreComponent[];- note?: string;- /** Code-health snapshot history rendered as a small trend sparkline. */- history?: HealthSparklinePoint[];-}--function getScoreColor(score: number): string {- if (score >= 75) return "var(--color-success)";- if (score >= 50) return "var(--color-warning)";- return "var(--color-error)";-}--function getScoreLabel(score: number): string {- if (score >= 80) return "Excellent";- if (score >= 65) return "Good";- if (score >= 50) return "Fair";- if (score >= 30) return "Needs Work";- return "Critical";-}--function Sparkline({ points }: { points: HealthSparklinePoint[] }) {- const w = 64;- const h = 20;- const values = points.map((p) => p.average_health);- const min = Math.min(...values);- const max = Math.max(...values);- const span = max - min || 1;- const step = values.length > 1 ? w / (values.length - 1) : w;- const path = values- .map((v, i) => {- const x = i * step;- const y = h - 2 - ((v - min) / span) * (h - 4);- return `${i === 0 ? "M" : "L"}${x.toFixed(1)},${y.toFixed(1)}`;- })- .join(" ");- const latest = values[values.length - 1] ?? 0;- return (- <svg- width={w}- height={h}- className="shrink-0"- role="img"- aria-label={`Code health trend, latest ${latest.toFixed(1)}/10`}- >- <title>{`Code health (avg) trend — latest ${latest.toFixed(1)}/10`}</title>- <path- d={path}- fill="none"- stroke="var(--color-accent-primary)"- strokeWidth={1.5}- strokeLinecap="round"- />- </svg>- );-}--/**- * Compact header twin of `HealthScoreRing`: score chip + label, an optional- * code-health trend sparkline, and the same "Why this score?" breakdown in a- * click-toggled dropdown. Used where the full ring would dominate the layout.- */-export function HealthScoreBadge({ score, components, note, history }: HealthScoreBadgeProps) {- const [open, setOpen] = useState(false);- const rootRef = useRef<HTMLDivElement>(null);- const color = getScoreColor(score);- const hasBreakdown = !!components && components.length > 0;-- useEffect(() => {- if (!open) return;- const onPointerDown = (e: PointerEvent) => {- if (rootRef.current && !rootRef.current.contains(e.target as Node)) setOpen(false);- };- const onKey = (e: KeyboardEvent) => {- if (e.key === "Escape") setOpen(false);- };- document.addEventListener("pointerdown", onPointerDown);- document.addEventListener("keydown", onKey);- return () => {- document.removeEventListener("pointerdown", onPointerDown);- document.removeEventListener("keydown", onKey);- };- }, [open]);-- return (- <div ref={rootRef} className="relative inline-flex items-center gap-2">- <button- type="button"- onClick={() => hasBreakdown && setOpen((v) => !v)}- aria-expanded={open}- aria-haspopup={hasBreakdown ? "dialog" : undefined}- className={`inline-flex items-center gap-2 rounded-full border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2.5 py-1 ${- hasBreakdown ? "hover:border-[var(--color-accent-primary)] transition-colors" : "cursor-default"- }`}- >- <span className="text-sm font-bold tabular-nums" style={{ color }}>- {Math.round(score)}- </span>- <span className="text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">- {getScoreLabel(score)}- </span>- {history && history.length >= 2 && <Sparkline points={history} />}- {hasBreakdown && (- <HelpCircle className="h-3 w-3 text-[var(--color-text-tertiary)]" aria-hidden />- )}- </button>-- {open && hasBreakdown && (- <div- role="dialog"- aria-label="Score breakdown"- className="absolute left-0 top-full z-30 mt-2 w-72 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-3 text-xs space-y-2 shadow-lg"- >- <p className="text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">- Score = weighted average of {components!.length} components- </p>- {note && (- <p className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-2 py-1.5 text-[11px] leading-snug text-[var(--color-text-secondary)]">- {note}- </p>- )}- <ul className="space-y-2">- {components!.map((c) => {- const barColor =- c.score >= 75- ? "var(--color-success)"- : c.score >= 50- ? "var(--color-warning)"- : "var(--color-error)";- return (- <li key={c.key} className="space-y-1">- <div className="flex items-baseline justify-between gap-3">- <span className="text-[var(--color-text-primary)]">- {c.label}{" "}- <span className="text-[var(--color-text-tertiary)]">- ({Math.round(c.weight * 100)}%)- </span>- </span>- <span className="tabular-nums text-[var(--color-text-secondary)]">- {Math.round(c.score)}/100- </span>- </div>- <div className="h-1 w-full overflow-hidden rounded-full bg-[var(--color-bg-surface)]">- <div- className="h-full transition-[width] duration-300"- style={{ width: `${c.score}%`, background: barColor }}- />- </div>- {c.detail && (- <p className="text-[10px] text-[var(--color-text-tertiary)]">{c.detail}</p>- )}- </li>- );- })}- </ul>- </div>- )}- </div>- );-}diff --git a/packages/ui/src/dashboard/health-score-ring.tsx b/packages/ui/src/dashboard/health-score-ring.tsxindex 79327e65f..bc9b7ff36 100644--- a/packages/ui/src/dashboard/health-score-ring.tsx+++ b/packages/ui/src/dashboard/health-score-ring.tsx@@ -116,7 +116,7 @@ export function HealthScoreRing({ score, size = 160, components, note }: HealthSScore = weighted average of {components.length} components</p>{note && (- <p className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-2 py-1.5 text-[11px] leading-snug text-[var(--color-text-secondary)]">+ <p className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-2 py-1.5 text-xs leading-snug text-[var(--color-text-secondary)]">{note}</p>)}diff --git a/packages/ui/src/dashboard/hotspots-mini.tsx b/packages/ui/src/dashboard/hotspots-mini.tsxindex e654cb11c..c1e1cc456 100644--- a/packages/ui/src/dashboard/hotspots-mini.tsx+++ b/packages/ui/src/dashboard/hotspots-mini.tsx@@ -93,7 +93,7 @@ export function HotspotsMini({</div></div><div className="min-w-0 flex-1">- <p className="text-[11px] font-mono text-[var(--color-text-primary)] truncate">+ <p className="text-xs font-mono text-[var(--color-text-primary)] truncate">{truncatePath(h.file_path, 40)}</p></div>diff --git a/packages/ui/src/dashboard/index.ts b/packages/ui/src/dashboard/index.tsindex f9c1650ed..e57c5a960 100644--- a/packages/ui/src/dashboard/index.ts+++ b/packages/ui/src/dashboard/index.ts@@ -1,10 +1,10 @@export * from "./attention-panel";+export * from "./kpi-strip";+export * from "./overview-grid";export * from "./commits-mini";export * from "./decisions-timeline";-export * from "./health-score-badge";export * from "./health-overview-card";export * from "./savings-mini";-export * from "./where-to-start";export * from "./dependency-heatmap";export * from "./execution-flows-panel";export * from "./health-score-ring";diff --git a/packages/ui/src/dashboard/kpi-strip.tsx b/packages/ui/src/dashboard/kpi-strip.tsxnew file mode 100644index 000000000..3cdeade6d--- /dev/null+++ b/packages/ui/src/dashboard/kpi-strip.tsx@@ -0,0 +1,85 @@+import * as React from "react";+import { MetricCard } from "../shared/metric-card";++export interface KpiItem {+ label: string;+ value: string;+ href: string;+ /**+ * `positive` is a *good-vs-bad* flag (green/up vs red/down), NOT up-vs-down:+ * a metric can grow while still being neutral or bad. Set `neutral` to render+ * the delta uncolored for metrics where a change carries no value judgement+ * (e.g. file-count growth).+ */+ delta?: { value: string; positive: boolean; neutral?: boolean };+ /** 0–100 fill for a mini gauge bar beneath the value (e.g. coverage %). */+ gauge?: number;+}++/**+ * Builds a signed delta descriptor from a raw numeric change.+ *+ * `neutral` renders the delta uncolored — use it when a positive change is not+ * inherently "good" (the color semantics are good-vs-bad, not up-vs-down).+ */+export function kpiDelta(+ delta: number | null | undefined,+ neutral = false,+): KpiItem["delta"] {+ if (delta == null || delta === 0) return undefined;+ return {+ value: `${delta > 0 ? "+" : ""}${delta}`,+ positive: delta > 0,+ ...(neutral ? { neutral: true } : {}),+ };+}++function Gauge({ value }: { value: number }) {+ const clamped = Math.max(0, Math.min(100, value));+ return (+ <div className="h-1.5 w-full overflow-hidden rounded-full bg-[var(--color-bg-inset)]">+ <div+ className="h-full rounded-full bg-[var(--color-accent-fill)]"+ style={{ width: `${clamped}%` }}+ />+ </div>+ );+}++export interface KpiStripProps {+ items: KpiItem[];+ /** Injected link component (e.g. Next's Link); defaults to a plain anchor. */+ LinkComponent?: React.ElementType<{+ href: string;+ className?: string;+ children: React.ReactNode;+ }>;+ className?: string;+}++/**+ * Airy KPI bar — gap-separated stat tiles (no divider chrome), each rendered+ * with the canonical `MetricCard`. Percentage metrics carry a mini gauge.+ * Fully presentational: data and the link component arrive via props.+ */+export function KpiStrip({ items, LinkComponent, className }: KpiStripProps) {+ return (+ <div+ className={`grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-5 ${className ?? ""}`}+ >+ {items.map((kpi) => (+ <MetricCard+ key={kpi.label}+ label={kpi.label}+ value={kpi.value}+ href={kpi.href}+ {...(kpi.delta ? { delta: kpi.delta } : {})}+ {...(LinkComponent ? { LinkComponent } : {})}+ {...(typeof kpi.gauge === "number"+ ? { distBar: <Gauge value={kpi.gauge} /> }+ : {})}+ />+ ))}+ </div>+ );+}diff --git a/packages/ui/src/dashboard/language-donut.tsx b/packages/ui/src/dashboard/language-donut.tsxindex a150fb477..02382eb4b 100644--- a/packages/ui/src/dashboard/language-donut.tsx+++ b/packages/ui/src/dashboard/language-donut.tsx@@ -94,7 +94,7 @@ export function LanguageDonut({ distribution, viewAllHref }: LanguageDonutProps)</div><div className="space-y-1.5 min-w-0 flex-1">{shown.map((entry) => (- <div key={entry.name} className="flex items-center justify-between text-[11px]">+ <div key={entry.name} className="flex items-center justify-between text-xs"><div className="flex items-center gap-1.5 min-w-0"><spanclassName="h-2 w-2 rounded-full shrink-0"diff --git a/packages/ui/src/dashboard/module-overview-grid.tsx b/packages/ui/src/dashboard/module-overview-grid.tsxindex 1f1061753..74f725c90 100644--- a/packages/ui/src/dashboard/module-overview-grid.tsx+++ b/packages/ui/src/dashboard/module-overview-grid.tsx@@ -114,7 +114,7 @@ export function ModuleOverviewGrid({ nodes, edges, repoId, linkPrefix, initialVi<buttontype="button"onClick={() => setExpanded((v) => !v)}- className="mt-2 w-full flex items-center justify-center gap-1 rounded-md border border-[var(--color-border-default)] py-1.5 text-[11px] text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)] hover:bg-[var(--color-bg-elevated)] transition-colors"+ className="mt-2 w-full flex items-center justify-center gap-1 rounded-md border border-[var(--color-border-default)] py-1.5 text-xs text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)] hover:bg-[var(--color-bg-elevated)] transition-colors">{expanded ? (<>diff --git a/packages/ui/src/dashboard/overview-grid.tsx b/packages/ui/src/dashboard/overview-grid.tsxnew file mode 100644index 000000000..2595c0e30--- /dev/null+++ b/packages/ui/src/dashboard/overview-grid.tsx@@ -0,0 +1,93 @@+import * as React from "react";+import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";++/**+ * The Overview's primary two-column arrangement: a wide main column (health,+ * contributors) beside a narrower triage/savings rail. Pure layout so the+ * arrangement is upgradable from the package.+ */+export function OverviewGrid({+ main,+ rail,+}: {+ main: React.ReactNode;+ rail: React.ReactNode;+}) {+ return (+ <div className="grid grid-cols-1 items-start gap-4 lg:grid-cols-3">+ <div className="space-y-4 lg:col-span-2">{main}</div>+ <div className="space-y-4">{rail}</div>+ </div>+ );+}++/** Two-up panel grid used by the Overview tab bodies. */+export function OverviewPanelPair({ children }: { children: React.ReactNode }) {+ return <div className="grid grid-cols-1 gap-4 md:grid-cols-2">{children}</div>;+}++/** Card chrome around the commit-activity sparkline, with its category legend. */+export function CommitActivityCard({+ sparkline,+}: {+ sparkline: React.ReactNode;+}) {+ return (+ <Card>+ <CardHeader className="pb-2">+ <CardTitle className="text-sm font-medium">Commit Activity</CardTitle>+ </CardHeader>+ <CardContent>+ {sparkline}+ <div className="mt-2 flex flex-wrap items-center gap-x-4 gap-y-1 text-[10px] text-[var(--color-text-tertiary)]">+ <span className="flex items-center gap-1">+ <span+ className="inline-block h-2 w-2 rounded-sm"+ style={{ background: "var(--color-info)" }}+ />{" "}+ Feature+ </span>+ <span className="flex items-center gap-1">+ <span+ className="inline-block h-2 w-2 rounded-sm"+ style={{ background: "var(--color-error)" }}+ />{" "}+ Fix+ </span>+ <span className="flex items-center gap-1">+ <span+ className="inline-block h-2 w-2 rounded-sm"+ style={{ background: "var(--color-accent-secondary)" }}+ />{" "}+ Refactor+ </span>+ <span className="flex items-center gap-1">+ <span+ className="inline-block h-2 w-2 rounded-sm"+ style={{ background: "var(--color-accent-fill)" }}+ />{" "}+ Dependency+ </span>+ </div>+ </CardContent>+ </Card>+ );+}++/** Generic titled card wrapper for the Structure tab panels (bus factor, ownership). */+export function TitledPanel({+ title,+ children,+}: {+ title: string;+ children: React.ReactNode;+}) {+ return (+ <Card>+ <CardHeader className="pb-2">+ <CardTitle className="text-sm font-medium">{title}</CardTitle>+ </CardHeader>+ <CardContent>{children}</CardContent>+ </Card>+ );+}diff --git a/packages/ui/src/dashboard/quick-actions.tsx b/packages/ui/src/dashboard/quick-actions.tsxindex 10add9104..bf320d92f 100644--- a/packages/ui/src/dashboard/quick-actions.tsx+++ b/packages/ui/src/dashboard/quick-actions.tsx@@ -200,13 +200,13 @@ export function QuickActions({})}</div><div className="flex flex-wrap gap-x-4 gap-y-0.5">- <span className="text-[11px] text-[var(--color-text-tertiary)]">+ <span className="text-xs text-[var(--color-text-tertiary)]">Last synced{" "}<span className="text-[var(--color-text-secondary)]">{lastSyncAt ? formatRelativeTime(lastSyncAt) : "never"}</span></span>- <span className="text-[11px] text-[var(--color-text-tertiary)]">+ <span className="text-xs text-[var(--color-text-tertiary)]">Last re-indexed{" "}<span className="text-[var(--color-text-secondary)]">{lastResyncAt ? formatRelativeTime(lastResyncAt) : "never"}diff --git a/packages/ui/src/dashboard/savings-mini.tsx b/packages/ui/src/dashboard/savings-mini.tsxindex 122ec0e13..5129d3b97 100644--- a/packages/ui/src/dashboard/savings-mini.tsx+++ b/packages/ui/src/dashboard/savings-mini.tsx@@ -12,41 +12,20 @@ export interface SavingsMiniData {pricing_model?: string;}-const LANG_COLORS: Record<string, string> = {- python: "var(--color-lang-python)",- typescript: "var(--color-lang-typescript)",- javascript: "var(--color-lang-typescript)",- go: "var(--color-lang-go)",- rust: "var(--color-lang-rust)",- java: "var(--color-lang-java)",- cpp: "var(--color-lang-cpp)",- c: "var(--color-lang-cpp)",- config: "var(--color-lang-config)",-};--function getLangColor(lang: string): string {- return LANG_COLORS[lang.toLowerCase()] ?? "var(--color-lang-other)";-}-interface SavingsMiniProps {/** Rollup from /distill-savings (or the overview-summary headline);* null/undefined when unavailable. */data?: SavingsMiniData | null;/** Repo id, for the "View costs →" link. */repoId: string;- /** Language → file-count map, rendered as a composition strip below savings. */- langDistribution?: Record<string, number>;- /** Optional "View in Graph →" target for the languages section. */- langHref?: string;}/*** Compact overview tile for agent token savings — the headline number, dollar* value priced at the detected agent model, and a distill-vs-MCP split, with a- * jump to the full Costs results page. A language-composition strip rides along- * the bottom of the same card.+ * jump to the full Costs results page.*/-export function SavingsMini({ data, repoId, langDistribution, langHref }: SavingsMiniProps) {+export function SavingsMini({ data, repoId }: SavingsMiniProps) {const distillSaved = data?.saved_tokens ?? 0;const mcpSaved = data?.mcp_tokens ?? 0;const total = distillSaved + mcpSaved;@@ -56,21 +35,12 @@ export function SavingsMini({ data, repoId, langDistribution, langHref }: Savingconst distillPct = total > 0 ? Math.round((distillSaved / total) * 100) : 0;const mcpPct = 100 - distillPct;- // Languages composition strip.- const langEntries = Object.entries(langDistribution ?? {})- .map(([name, value]) => ({ name, value }))- .sort((a, b) => b.value - a.value);- const langTotal = langEntries.reduce((s, e) => s + e.value, 0);- const langShown = langEntries.slice(0, 6);- const langOther = langEntries.slice(6).reduce((s, e) => s + e.value, 0);- if (langOther > 0) langShown.push({ name: "other", value: langOther });-return (<Card><CardHeader className="pb-2"><CardTitle className="text-sm flex items-center justify-between"><span className="flex items-center gap-2">- <Sparkles className="h-4 w-4 text-cyan-500" />+ <Sparkles className="h-4 w-4 text-[var(--color-accent-secondary)]" />Agent savings</span><a@@ -88,11 +58,11 @@ export function SavingsMini({ data, repoId, langDistribution, langHref }: Saving<span className="text-3xl font-semibold tabular-nums text-[var(--color-text-primary)]">{formatTokens(total)}</span>- <span className="text-base font-semibold tabular-nums text-green-500">+ <span className="text-base font-semibold tabular-nums text-[var(--color-success)]">{formatCost(data!.estimated_usd_saved ?? 0)}</span></div>- <p className="text-[11px] text-[var(--color-text-secondary)] -mt-1">+ <p className="text-xs text-[var(--color-text-secondary)] -mt-1">tokens saved for your agent{data!.pricing_model ? (<span className="text-[var(--color-text-tertiary)]">@@ -105,23 +75,27 @@ export function SavingsMini({ data, repoId, langDistribution, langHref }: Saving<div className="flex h-2 w-full overflow-hidden rounded-full bg-[var(--color-bg-inset)]">{distillSaved > 0 && (<div- className="h-full bg-cyan-500"- style={{ width: `${distillPct}%` }}+ className="h-full"+ style={{ width: `${distillPct}%`, background: "var(--color-accent-fill)" }}title={`Distill — ${formatTokens(distillSaved)}`}/>)}{mcpSaved > 0 && (<div- className="h-full bg-violet-500"- style={{ width: `${mcpPct}%` }}+ className="h-full"+ style={{ width: `${mcpPct}%`, background: "var(--color-accent-secondary)" }}title={`MCP tools — ${formatTokens(mcpSaved)}`}/>)}</div>- <div className="space-y-1 text-[11px]">+ <div className="space-y-1 text-xs"><div className="flex items-center justify-between gap-2"><span className="flex items-center gap-1.5 text-[var(--color-text-secondary)] whitespace-nowrap">- <span className="h-2 w-2 rounded-full bg-cyan-500 shrink-0" /> Distill+ <span+ className="h-2 w-2 rounded-full shrink-0"+ style={{ background: "var(--color-accent-fill)" }}+ />{" "}+ Distill</span><span className="tabular-nums text-[var(--color-text-tertiary)] shrink-0">{formatTokens(distillSaved)}@@ -129,7 +103,11 @@ export function SavingsMini({ data, repoId, langDistribution, langHref }: Saving</div><div className="flex items-center justify-between gap-2"><span className="flex items-center gap-1.5 text-[var(--color-text-secondary)] whitespace-nowrap">- <span className="h-2 w-2 rounded-full bg-violet-500 shrink-0" /> MCP tools+ <span+ className="h-2 w-2 rounded-full shrink-0"+ style={{ background: "var(--color-accent-secondary)" }}+ />{" "}+ MCP tools</span><span className="tabular-nums text-[var(--color-text-tertiary)] shrink-0">{formatTokens(mcpSaved)}@@ -145,64 +123,12 @@ export function SavingsMini({ data, repoId, langDistribution, langHref }: Saving</p><ahref={costsHref}- className="inline-block text-[11px] text-[var(--color-accent-primary)] hover:underline"+ className="inline-block text-xs text-[var(--color-accent-primary)] hover:underline">Open the Costs page →</a></div>)}-- {langTotal > 0 && (- <div className="mt-4 border-t border-[var(--color-border-secondary)] pt-3 space-y-2">- <div className="flex items-center justify-between">- <span className="text-[11px] font-medium uppercase tracking-wide text-[var(--color-text-tertiary)]">- Languages- </span>- {langHref && (- <a- href={langHref}- className="text-[10px] text-[var(--color-accent-primary)] hover:underline"- >- View in Graph →- </a>- )}- </div>- <div className="flex h-2 w-full overflow-hidden rounded-full bg-[var(--color-bg-inset)]">- {langShown.map((entry) => (- <div- key={entry.name}- className="h-full"- style={{- width: `${(entry.value / langTotal) * 100}%`,- backgroundColor: getLangColor(entry.name),- }}- title={`${entry.name} — ${Math.round((entry.value / langTotal) * 100)}%`}- />- ))}- </div>- <div className="grid grid-cols-2 gap-x-4 gap-y-1">- {langShown.map((entry) => (- <div- key={entry.name}- className="flex items-center justify-between text-[11px] min-w-0"- >- <span className="flex items-center gap-1.5 min-w-0">- <span- className="h-2 w-2 rounded-full shrink-0"- style={{ backgroundColor: getLangColor(entry.name) }}- />- <span className="text-[var(--color-text-secondary)] capitalize truncate">- {entry.name}- </span>- </span>- <span className="text-[var(--color-text-tertiary)] tabular-nums ml-2 shrink-0">- {Math.round((entry.value / langTotal) * 100)}%- </span>- </div>- ))}- </div>- </div>- )}</CardContent></Card>);diff --git a/packages/ui/src/dashboard/where-to-start.tsx b/packages/ui/src/dashboard/where-to-start.tsxdeleted file mode 100644index ba8585502..000000000--- a/packages/ui/src/dashboard/where-to-start.tsx+++ /dev/null@@ -1,66 +0,0 @@-import { Compass } from "lucide-react";-import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";-import { formatNumber, truncatePath } from "../lib/format";-import { fileEntityPath } from "../shared/entity/routes";--export interface WhereToStartTarget {- path: string;- pagerank: number;- doc_words: number;-}--interface WhereToStartCardProps {- /** Onboarding targets: high-centrality files with the least documentation. */- targets: WhereToStartTarget[];- repoId: string;- linkPrefix?: string;- previewCount?: number;-}--/**- * "Where do I start reading?" — the onboarding-targets list promoted from- * the old Overview Ownership tab. Rows link to the canonical file page.- */-export function WhereToStartCard({- targets,- repoId,- linkPrefix,- previewCount = 5,-}: WhereToStartCardProps) {- const prefix = linkPrefix ?? `/repos/${repoId}`;- if (targets.length === 0) return null;- const shown = targets.slice(0, previewCount);-- return (- <Card>- <CardHeader className="pb-2">- <CardTitle className="text-sm flex items-center gap-2">- <Compass className="h-4 w-4 text-[var(--color-accent-primary)]" />- Where to start- </CardTitle>- </CardHeader>- <CardContent className="pt-0">- <p className="text-[11px] text-[var(--color-text-tertiary)] mb-2">- Central files with the least documentation — high-leverage reading.- </p>- <ul className="space-y-1">- {shown.map((t) => (- <li key={t.path}>- <a- href={fileEntityPath(prefix, t.path)}- className="block -mx-2 px-2 py-1 rounded hover:bg-[var(--color-bg-elevated)] transition-colors"- >- <p className="text-[11px] font-mono text-[var(--color-text-primary)] truncate">- {truncatePath(t.path, 44)}- </p>- <p className="text-[10px] text-[var(--color-text-tertiary)]">- pagerank {t.pagerank.toFixed(4)} · {formatNumber(t.doc_words)} doc words- </p>- </a>- </li>- ))}- </ul>- </CardContent>- </Card>- );-}diff --git a/packages/web/src/components/dead-code/finding-row.tsx b/packages/ui/src/dead-code/finding-row.tsxsimilarity index 54%rename from packages/web/src/components/dead-code/finding-row.tsxrename to packages/ui/src/dead-code/finding-row.tsxindex 30e1c951c..810645496 100644--- a/packages/web/src/components/dead-code/finding-row.tsx+++ b/packages/ui/src/dead-code/finding-row.tsx@@ -1,18 +1,19 @@"use client";import { useState } from "react";-import { toast } from "sonner";import { GitBranch, Code2 } from "lucide-react";-import { Button } from "@repowise-dev/ui/ui/button";-import { Badge } from "@repowise-dev/ui/ui/badge";-import { ConfirmDialog } from "@repowise-dev/ui/ui/confirm-dialog";-import { RowActions } from "@repowise-dev/ui/shared/row-actions";-import { formatConfidence } from "@repowise-dev/ui/lib/format";-import { patchDeadCodeFinding } from "@/lib/api/dead-code";-import { cn } from "@/lib/utils/cn";-import type { DeadCodeFindingResponse } from "@/lib/api/types";+import { Button } from "../ui/button";+import { Badge } from "../ui/badge";+import { ConfirmDialog } from "../ui/confirm-dialog";+import { RowActions } from "../shared/row-actions";+import { formatConfidence } from "../lib/format";+import { cn } from "../lib/cn";+import type { DeadCodeFinding, DeadCodeStatus } from "@repowise-dev/types/dead-code";-const STATUS_LABELS: Record<string, { title: string; description: string; confirmLabel: string; destructive: boolean }> = {+const STATUS_LABELS: Record<+ string,+ { title: string; description: string; confirmLabel: string; destructive: boolean }+> = {resolved: {title: "Resolve finding?",description: "Mark this finding as resolved. You can undo from the toast.",@@ -27,66 +28,54 @@ const STATUS_LABELS: Record<string, { title: string; description: string; confir},false_positive: {title: "Mark as false positive?",- description: "This finding will be excluded from future analyses. You can undo from the toast.",+ description:+ "This finding will be excluded from future analyses. You can undo from the toast.",confirmLabel: "Mark FP",destructive: true,},};-interface FindingRowProps {- finding: DeadCodeFindingResponse;+const STATUS_COLORS: Record<string, string> = {+ open: "bg-[var(--color-error)]/10 text-[var(--color-error)] border-[var(--color-error)]/20",+ acknowledged:+ "bg-[var(--color-warning)]/10 text-[var(--color-warning)] border-[var(--color-warning)]/20",+ resolved:+ "bg-[var(--color-success)]/10 text-[var(--color-success)] border-[var(--color-success)]/20",+ false_positive:+ "bg-[var(--color-bg-elevated)] text-[var(--color-text-tertiary)] border-[var(--color-border-default)]",+};++export interface FindingRowProps {+ finding: DeadCodeFinding;+ /** Repo base path used to build the Graph / Symbol action links. */repoId: string;selected: boolean;onToggle: (id: string) => void;- onUpdate: (updated: DeadCodeFindingResponse) => void;+ /** Injected mutation — returns the updated finding (host owns the API + toasts). */+ onPatch: (id: string, patch: { status: DeadCodeStatus }) => Promise<DeadCodeFinding>;+ onUpdate: (updated: DeadCodeFinding) => void;}-const STATUS_COLORS: Record<string, string> = {- open: "bg-red-500/10 text-red-500 border-red-500/20",- acknowledged: "bg-yellow-500/10 text-yellow-500 border-yellow-500/20",- resolved: "bg-green-500/10 text-green-500 border-green-500/20",- false_positive: "bg-[var(--color-bg-elevated)] text-[var(--color-text-tertiary)] border-[var(--color-border-default)]",-};--export function FindingRow({ finding, repoId, selected, onToggle, onUpdate }: FindingRowProps) {+/**+ * Pure dead-code findings row: presentation + row-level status actions. The host+ * injects the patch mutation so this component carries no data/transport deps.+ */+export function FindingRow({ finding, repoId, selected, onToggle, onPatch, onUpdate }: FindingRowProps) {const [pending, setPending] = useState(false);const [confirmStatus, setConfirmStatus] = useState<string | null>(null);- const previousStatus = finding.status;-const applyPatch = async (status: string) => {setPending(true);try {- const updated = await patchDeadCodeFinding(finding.id, { status });+ const updated = await onPatch(finding.id, { status: status as DeadCodeStatus });onUpdate(updated);setConfirmStatus(null);- toast.success(`Finding ${status.replace(/_/g, " ")}`, {- action: {- label: "Undo",- onClick: async () => {- try {- const reverted = await patchDeadCodeFinding(finding.id, { status: previousStatus });- onUpdate(reverted);- } 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 finding: ${err.message}` : "Couldn't update finding",- );} finally {setPending(false);}};const requestPatch = (status: string) => setConfirmStatus(status);-const confirmConfig = confirmStatus ? STATUS_LABELS[confirmStatus] : null;return (@@ -106,9 +95,13 @@ export function FindingRow({ finding, repoId, selected, onToggle, onUpdate }: Fi/></td><td className="px-4 py-2.5 font-mono text-xs text-[var(--color-text-primary)] min-w-[200px] max-w-[480px]">- <span className="truncate block" title={finding.file_path}>{finding.file_path}</span>+ <span className="truncate block" title={finding.file_path}>+ {finding.file_path}+ </span>{finding.symbol_name && (- <span className="block truncate text-[var(--color-text-tertiary)]" title={finding.symbol_name}>{finding.symbol_name}</span>+ <span className="block truncate text-[var(--color-text-tertiary)]" title={finding.symbol_name}>+ {finding.symbol_name}+ </span>)}</td><td className="px-4 py-2.5 text-xs text-[var(--color-text-secondary)] tabular-nums">@@ -116,9 +109,9 @@ export function FindingRow({ finding, repoId, selected, onToggle, onUpdate }: FiclassName={cn("font-medium",finding.confidence >= 0.8- ? "text-red-500"+ ? "text-[var(--color-error)]": finding.confidence >= 0.6- ? "text-yellow-500"+ ? "text-[var(--color-warning)]": "text-[var(--color-text-secondary)]",)}>@@ -161,44 +154,50 @@ export function FindingRow({ finding, repoId, selected, onToggle, onUpdate }: Fi<div className="flex items-center gap-1 flex-wrap justify-end"><RowActionsactions={[- { icon: GitBranch, label: "Graph", href: `/repos/${repoId}/architecture?view=graph&node=${encodeURIComponent(finding.file_path)}` },- ...(finding.symbol_name ? [{ icon: Code2, label: "Symbol", href: `/repos/${repoId}/architecture?view=symbols` }] : []),+ {+ icon: GitBranch,+ label: "Graph",+ href: `/repos/${repoId}/architecture?view=graph&node=${encodeURIComponent(finding.file_path)}`,+ },+ ...(finding.symbol_name+ ? [{ icon: Code2, label: "Symbol", href: `/repos/${repoId}/architecture?view=symbols` }]+ : []),]}/>- {finding.status === "open" && (- <div className="flex items-center gap-1 flex-wrap justify-end">- <Button- size="sm"- variant="ghost"- disabled={pending}- onClick={() => requestPatch("resolved")}- className="h-6 px-2 text-xs text-green-500 hover:text-green-400"- aria-label={`Resolve ${finding.file_path}`}- >- Resolve- </Button>- <Button- size="sm"- variant="ghost"- disabled={pending}- onClick={() => requestPatch("acknowledged")}- className="h-6 px-2 text-xs"- aria-label={`Acknowledge ${finding.file_path}`}- >- Ack- </Button>- <Button- size="sm"- variant="ghost"- disabled={pending}- onClick={() => requestPatch("false_positive")}- className="h-6 px-2 text-xs text-[var(--color-text-tertiary)]"- aria-label={`Mark ${finding.file_path} as false positive`}- >- FP- </Button>- </div>- )}+ {finding.status === "open" && (+ <div className="flex items-center gap-1 flex-wrap justify-end">+ <Button+ size="sm"+ variant="ghost"+ disabled={pending}+ onClick={() => requestPatch("resolved")}+ className="h-6 px-2 text-xs text-[var(--color-success)] hover:text-[var(--color-success)]"+ aria-label={`Resolve ${finding.file_path}`}+ >+ Resolve+ </Button>+ <Button+ size="sm"+ variant="ghost"+ disabled={pending}+ onClick={() => requestPatch("acknowledged")}+ className="h-6 px-2 text-xs"+ aria-label={`Acknowledge ${finding.file_path}`}+ >+ Ack+ </Button>+ <Button+ size="sm"+ variant="ghost"+ disabled={pending}+ onClick={() => requestPatch("false_positive")}+ className="h-6 px-2 text-xs text-[var(--color-text-tertiary)]"+ aria-label={`Mark ${finding.file_path} as false positive`}+ >+ FP+ </Button>+ </div>+ )}</div></td>{confirmConfig && (diff --git a/packages/ui/src/dead-code/findings-breakdown-grid.tsx b/packages/ui/src/dead-code/findings-breakdown-grid.tsxindex c15d4dc93..332897197 100644--- a/packages/ui/src/dead-code/findings-breakdown-grid.tsx+++ b/packages/ui/src/dead-code/findings-breakdown-grid.tsx@@ -96,14 +96,24 @@ export function FindingsBreakdownGrid({ findings, className }: FindingsBreakdown{kinds.map((k) => {const c = counts[tier.id]?.[k] ?? 0;const intensity = max > 0 ? c / max : 0;+ // Heat scales the fill alpha; the hue comes from the token for+ // each tier (error → warning → muted) via color-mix.+ const tierToken =+ tier.id === "high"+ ? "var(--color-error)"+ : tier.id === "med"+ ? "var(--color-warning)"+ : "var(--color-text-tertiary)";+ const alphaPct =+ tier.id === "high"+ ? Math.round((0.12 + intensity * 0.55) * 100)+ : tier.id === "med"+ ? Math.round((0.1 + intensity * 0.5) * 100)+ : Math.round((0.08 + intensity * 0.4) * 100);const bg =c === 0? "transparent"- : tier.id === "high"- ? `rgba(244,63,94,${0.12 + intensity * 0.55})`- : tier.id === "med"- ? `rgba(245,158,11,${0.10 + intensity * 0.5})`- : `rgba(148,163,184,${0.08 + intensity * 0.4})`;+ : `color-mix(in srgb, ${tierToken} ${alphaPct}%, transparent)`;return (<tdkey={k}diff --git a/packages/web/src/components/dead-code/findings-table.tsx b/packages/ui/src/dead-code/findings-table.tsxsimilarity index 66%rename from packages/web/src/components/dead-code/findings-table.tsxrename to packages/ui/src/dead-code/findings-table.tsxindex 2985eb33b..3c7bc8af2 100644--- a/packages/web/src/components/dead-code/findings-table.tsx+++ b/packages/ui/src/dead-code/findings-table.tsx@@ -1,16 +1,13 @@"use client";-import { useState, useEffect } from "react";-import useSWR from "swr";-import { toast } from "sonner";-import { Tabs, TabsList, TabsTrigger, TabsContent } from "@repowise-dev/ui/ui/tabs";-import { Button } from "@repowise-dev/ui/ui/button";-import { Skeleton } from "@repowise-dev/ui/ui/skeleton";-import { ConfirmDialog } from "@repowise-dev/ui/ui/confirm-dialog";-import { EmptyState } from "@repowise-dev/ui/shared/empty-state";+import { useMemo, useState } from "react";+import { Tabs, TabsList, TabsTrigger, TabsContent } from "../ui/tabs";+import { Button } from "../ui/button";+import { Skeleton } from "../ui/skeleton";+import { ConfirmDialog } from "../ui/confirm-dialog";+import { EmptyState } from "../shared/empty-state";import { FindingRow } from "./finding-row";-import { listDeadCode, patchDeadCodeFinding } from "@/lib/api/dead-code";-import type { DeadCodeFindingResponse } from "@/lib/api/types";+import type { DeadCodeFinding, DeadCodeStatus } from "@repowise-dev/types/dead-code";type Kind = "unreachable_file" | "unused_export" | "zombie_package";@@ -20,47 +17,60 @@ const TABS: Array<{ value: Kind; label: string }> = [{ value: "zombie_package", label: "Zombie Packages" },];-interface FindingsTableProps {+export interface FindingsTableProps {+ /** Full open-findings slice; the table filters by kind / confidence / safety client-side. */+ findings: DeadCodeFinding[];+ /** Repo base path used to build row action links. */repoId: string;+ /** Injected mutation — host owns the API call, optimistic toast + undo. */+ onPatch: (id: string, patch: { status: DeadCodeStatus }) => Promise<DeadCodeFinding>;+ /** Injected bulk resolve — host owns the toast/partial-failure messaging. Returns the ids that actually resolved. */+ onBulkResolve?: (ids: string[]) => Promise<string[]>;+ isLoading?: boolean;}-export function FindingsTable({ repoId }: FindingsTableProps) {+/**+ * Canonical interactive dead-code table: kind tabs, a confidence slider (the+ * single confidence control for the spine), cleanup-ready filter, bulk resolve,+ * and per-row status actions. Pure presentation — the host injects the data+ * slice and the patch/bulk mutations, so this propagates via the package.+ */+export function FindingsTable({ findings, repoId, onPatch, onBulkResolve, isLoading }: FindingsTableProps) {const [activeTab, setActiveTab] = useState<Kind>("unreachable_file");const [minConfidence, setMinConfidence] = useState(0.4);const [safeOnly, setSafeOnly] = useState(false);const [selected, setSelected] = useState<Set<string>>(new Set());- const [items, setItems] = useState<Record<Kind, DeadCodeFindingResponse[]>>({- unreachable_file: [],- unused_export: [],- zombie_package: [],- });+ const [overrides, setOverrides] = useState<Record<string, DeadCodeFinding>>({});const [bulkPending, setBulkPending] = useState(false);const [bulkConfirmOpen, setBulkConfirmOpen] = useState(false);- const { data, isLoading } = useSWR(- `dead-code:${repoId}:${activeTab}:${minConfidence}:${safeOnly}`,- () =>- listDeadCode(repoId, {- kind: activeTab,- min_confidence: minConfidence,- safe_only: safeOnly || undefined,- status: "open",- limit: 200,- }),- { revalidateOnFocus: false },+ // Apply local optimistic overrides over the host-supplied slice so a resolved+ // row updates without a refetch.+ const merged = useMemo(+ () => findings.map((f) => overrides[f.id] ?? f),+ [findings, overrides],);- useEffect(() => {- if (!data) return;- setItems((prev) => ({ ...prev, [activeTab]: data }));- setSelected(new Set());- }, [data, activeTab]);-- const handleUpdate = (updated: DeadCodeFindingResponse) => {- setItems((prev) => ({- ...prev,- [activeTab]: prev[activeTab].map((f) => (f.id === updated.id ? updated : f)),- }));+ const byKind = useMemo(() => {+ const buckets: Record<Kind, DeadCodeFinding[]> = {+ unreachable_file: [],+ unused_export: [],+ zombie_package: [],+ };+ for (const f of merged) {+ if (f.status !== "open") continue;+ if (f.confidence < minConfidence) continue;+ if (safeOnly && !f.safe_to_delete) continue;+ const kind = f.kind as Kind;+ if (kind in buckets) buckets[kind].push(f);+ }+ return buckets;+ }, [merged, minConfidence, safeOnly]);++ const current = byKind[activeTab];++ const handleUpdate = (updated: DeadCodeFinding) => {+ setOverrides((prev) => ({ ...prev, [updated.id]: updated }));};const toggleSelect = (id: string) => {@@ -73,7 +83,6 @@ export function FindingsTable({ repoId }: FindingsTableProps) {};const toggleSelectAll = () => {- const current = items[activeTab];if (selected.size === current.length) {setSelected(new Set());} else {@@ -82,38 +91,30 @@ export function FindingsTable({ repoId }: FindingsTableProps) {};const resolveSelected = async () => {+ if (!onBulkResolve) return;const ids = Array.from(selected);setBulkPending(true);- let succeeded = 0;try {- for (const id of ids) {- try {- const updated = await patchDeadCodeFinding(id, { status: "resolved" });- handleUpdate(updated);- succeeded += 1;- } catch {- // continue; we'll report partial below+ const succeededIds = await onBulkResolve(ids);+ // Reflect only the rows that actually resolved — never a positional guess.+ const resolvedIds = new Set(succeededIds);+ setOverrides((prev) => {+ const next = { ...prev };+ for (const f of merged) {+ if (resolvedIds.has(f.id)) next[f.id] = { ...f, status: "resolved" as DeadCodeStatus };}- }+ return next;+ });setSelected(new Set());setBulkConfirmOpen(false);- 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");- }} finally {setBulkPending(false);}};- const current = items[activeTab];-return (<div className="space-y-4">- {/* Controls */}+ {/* Controls — the confidence slider is the only confidence axis. */}<div className="flex flex-wrap items-center gap-4"><div className="flex items-center gap-2"><label htmlFor="min-confidence" className="text-xs text-[var(--color-text-secondary)]">@@ -141,13 +142,13 @@ export function FindingsTable({ repoId }: FindingsTableProps) {Cleanup-ready only</label>- {selected.size > 0 && (+ {onBulkResolve && selected.size > 0 && (<Buttonsize="sm"variant="outline"disabled={bulkPending}onClick={() => setBulkConfirmOpen(true)}- className="text-green-500 border-green-500/30 hover:bg-green-500/10"+ className="text-[var(--color-success)] border-[var(--color-success)]/30 hover:bg-[var(--color-success)]/10">{bulkPending ? "Resolving…" : `Resolve ${selected.size} selected`}</Button>@@ -163,14 +164,22 @@ export function FindingsTable({ repoId }: FindingsTableProps) {onConfirm={resolveSelected}/>- <Tabs value={activeTab} onValueChange={(v) => setActiveTab(v as Kind)}>+ <Tabs+ value={activeTab}+ onValueChange={(v) => {+ setActiveTab(v as Kind);+ // Selection is per-kind; clearing on tab change keeps "Resolve N+ // selected" and the select-all checkbox scoped to the visible rows.+ setSelected(new Set());+ }}+ ><TabsList>{TABS.map((t) => (<TabsTrigger key={t.value} value={t.value}>{t.label}- {items[t.value].length > 0 && (+ {byKind[t.value].length > 0 && (<span className="ml-1.5 text-xs text-[var(--color-text-tertiary)]">- {items[t.value].length}+ {byKind[t.value].length}</span>)}</TabsTrigger>@@ -192,7 +201,7 @@ export function FindingsTable({ repoId }: FindingsTableProps) {/>) : (<div className="rounded-lg border border-[var(--color-border-default)] overflow-x-auto mt-2">- <table className="w-full min-w-[640px] text-sm">+ <table className="w-full text-sm"><caption className="sr-only">Dead code findings</caption><thead className="sticky top-0 z-10 bg-[var(--color-bg-elevated)]"><tr className="border-b border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]">@@ -236,6 +245,7 @@ export function FindingsTable({ repoId }: FindingsTableProps) {repoId={repoId}selected={selected.has(f.id)}onToggle={toggleSelect}+ onPatch={onPatch}onUpdate={handleUpdate}/>))}diff --git a/packages/ui/src/dead-code/index.ts b/packages/ui/src/dead-code/index.tsindex f7cf4418d..d43404fe3 100644--- a/packages/ui/src/dead-code/index.ts+++ b/packages/ui/src/dead-code/index.ts@@ -2,3 +2,5 @@ export * from "./summary-bar";export * from "./safe-to-delete-pile";export * from "./owner-leaderboard";export * from "./findings-breakdown-grid";+export * from "./findings-table";+export * from "./finding-row";diff --git a/packages/ui/src/dead-code/owner-leaderboard.tsx b/packages/ui/src/dead-code/owner-leaderboard.tsxindex c557a7fb0..2b6027dac 100644--- a/packages/ui/src/dead-code/owner-leaderboard.tsx+++ b/packages/ui/src/dead-code/owner-leaderboard.tsx@@ -87,7 +87,7 @@ export function OwnerLeaderboard({</div><div className="mt-1 h-1.5 w-full overflow-hidden rounded-full bg-[var(--color-bg-elevated)]"><div- className="h-full rounded-full bg-rose-400/60 transition-[width] duration-300"+ className="h-full rounded-full bg-[var(--color-error)]/60 transition-[width] duration-300"style={{ width: `${widthPct}%` }}/></div>diff --git a/packages/ui/src/dead-code/safe-to-delete-pile.tsx b/packages/ui/src/dead-code/safe-to-delete-pile.tsxindex 03e3ab220..bfd7489ad 100644--- a/packages/ui/src/dead-code/safe-to-delete-pile.tsx+++ b/packages/ui/src/dead-code/safe-to-delete-pile.tsx@@ -79,13 +79,13 @@ export function SafeToDeletePile({return (<divclassName={cn(- "rounded-xl border border-rose-500/30 bg-gradient-to-br from-rose-500/10 via-[var(--color-bg-elevated)] to-[var(--color-bg-elevated)]",- "p-5 shadow-sm",+ "rounded-xl border border-[var(--color-error)]/30 bg-gradient-to-br from-[var(--color-error)]/10 via-[var(--color-bg-elevated)] to-[var(--color-bg-elevated)]",+ "p-5",className,)}><div className="flex items-start gap-4">- <div className="rounded-lg bg-rose-500/15 p-2.5 text-rose-400 shrink-0">+ <div className="rounded-lg bg-[var(--color-error)]/15 p-2.5 text-[var(--color-error)] shrink-0"><Trash2 className="h-5 w-5" /></div><div className="flex-1 min-w-0">@@ -106,8 +106,8 @@ export function SafeToDeletePile({type="button"onClick={() => onPropose(findings.map((f) => f.id))}className={cn(- "inline-flex items-center gap-1.5 rounded-md border border-rose-500/40 bg-rose-500/10 px-3 py-1.5",- "text-xs font-medium text-rose-300 transition hover:bg-rose-500/20",+ "inline-flex items-center gap-1.5 rounded-md border border-[var(--color-error)]/40 bg-[var(--color-error)]/10 px-3 py-1.5",+ "text-xs font-medium text-[var(--color-error)] transition hover:bg-[var(--color-error)]/20",)}><Sparkles className="h-3.5 w-3.5" />@@ -132,7 +132,7 @@ export function SafeToDeletePile({)}><span- className="font-mono text-[11px] text-[var(--color-text-secondary)] truncate"+ className="font-mono text-xs text-[var(--color-text-secondary)] truncate"title={g.file_path}>{g.file_path}@@ -151,7 +151,7 @@ export function SafeToDeletePile({);})}{moreFiles > 0 && (- <li className="px-2 pt-0.5 text-[11px] text-[var(--color-text-tertiary)]">+ <li className="px-2 pt-0.5 text-xs text-[var(--color-text-tertiary)]">+{moreFiles.toLocaleString()} more file{moreFiles === 1 ? "" : "s"} —{" "}see findings table below.</li>diff --git a/packages/ui/src/dead-code/summary-bar.tsx b/packages/ui/src/dead-code/summary-bar.tsxindex 41eced424..9af0da52e 100644--- a/packages/ui/src/dead-code/summary-bar.tsx+++ b/packages/ui/src/dead-code/summary-bar.tsx@@ -1,4 +1,5 @@import { formatNumber } from "../lib/format";+import { MetricCard } from "../shared/metric-card";import type { DeadCodeSummary } from "@repowise-dev/types/dead-code";export interface SummaryBarProps {@@ -6,58 +7,47 @@ export interface SummaryBarProps {summary: DeadCodeSummary;}-export function SummaryBar({ summary }: SummaryBarProps) {+/** Compact list rendered inside a MetricCard value slot (By Kind / Confidence). */+function CountList({ entries }: { entries: [string, number][] }) {return (- <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">- <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-4">- <p className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-1">- Total Findings- </p>- <p className="text-2xl font-bold text-[var(--color-text-primary)] tabular-nums">- {formatNumber(summary.total_findings)}- </p>- </div>-- <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-4">- <p className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-1">- Candidate Lines- </p>- <p className="text-2xl font-bold text-amber-500 tabular-nums">- {formatNumber(summary.deletable_lines)}- </p>- </div>-- <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-4">- <p className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-2">- By Kind- </p>- <div className="space-y-1">- {Object.entries(summary.by_kind).map(([kind, count]) => (- <div key={kind} className="flex items-center justify-between text-xs">- <span className="text-[var(--color-text-secondary)] truncate">{kind.replace(/_/g, " ")}</span>- <span className="text-[var(--color-text-primary)] tabular-nums font-medium ml-2">- {formatNumber(count)}- </span>- </div>- ))}+ <div className="space-y-1 text-xs font-normal">+ {entries.map(([label, count]) => (+ <div key={label} className="flex items-center justify-between gap-2">+ <span className="truncate text-[var(--color-text-secondary)]">+ {label.replace(/_/g, " ")}+ </span>+ <span className="ml-2 font-medium tabular-nums text-[var(--color-text-primary)]">+ {formatNumber(count)}+ </span></div>- </div>+ ))}+ </div>+ );+}- <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-4">- <p className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-2">- Confidence- </p>- <div className="space-y-1">- {Object.entries(summary.confidence_summary).map(([level, count]) => (- <div key={level} className="flex items-center justify-between text-xs">- <span className="text-[var(--color-text-secondary)]">{level}</span>- <span className="text-[var(--color-text-primary)] tabular-nums font-medium">- {formatNumber(count)}- </span>- </div>- ))}- </div>- </div>+export function SummaryBar({ summary }: SummaryBarProps) {+ return (+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">+ <MetricCard+ label="Total Findings"+ value={formatNumber(summary.total_findings)}+ />+ <MetricCard+ label="Candidate Lines"+ value={+ <span className="text-[var(--color-warning)]">+ {formatNumber(summary.deletable_lines)}+ </span>+ }+ />+ <MetricCard+ label="By Kind"+ value={<CountList entries={Object.entries(summary.by_kind)} />}+ />+ <MetricCard+ label="Confidence"+ value={<CountList entries={Object.entries(summary.confidence_summary)} />}+ /></div>);}diff --git a/packages/ui/src/decisions/decision-evidence-drawer.tsx b/packages/ui/src/decisions/decision-evidence-drawer.tsxindex 8d42a6d3c..ee5aad21c 100644--- a/packages/ui/src/decisions/decision-evidence-drawer.tsx+++ b/packages/ui/src/decisions/decision-evidence-drawer.tsx@@ -136,7 +136,7 @@ function EvidenceRow({ row, isPrimary }: { row: DecisionEvidence; isPrimary?: bo</blockquote>{(row.evidence_file || row.evidence_commit) && (- <div className="mt-2 flex flex-wrap items-center gap-x-4 gap-y-1 text-[11px] text-[var(--color-text-tertiary)]">+ <div className="mt-2 flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-[var(--color-text-tertiary)]">{row.evidence_file && (<span className="inline-flex items-center gap-1 font-mono"><FileText className="h-3 w-3" aria-hidden />diff --git a/packages/ui/src/decisions/decision-graph-view.tsx b/packages/ui/src/decisions/decision-graph-view.tsxindex 473796e8e..30e2bbb3c 100644--- a/packages/ui/src/decisions/decision-graph-view.tsx+++ b/packages/ui/src/decisions/decision-graph-view.tsx@@ -197,7 +197,7 @@ const DecisionEdge = memo(function DecisionEdge(props: EdgeProps) {color: isConflict ? "white" : "var(--color-text-primary)",padding: "1px 6px",borderRadius: 4,- fontSize: 9,+ fontSize: 11,fontWeight: 600,pointerEvents: "none",border: `1px solid ${isConflict ? "var(--color-error)" : "var(--color-border-default)"}`,diff --git a/packages/ui/src/decisions/decision-health-widget.tsx b/packages/ui/src/decisions/decision-health-widget.tsxdeleted file mode 100644index 6650ad5c2..000000000--- a/packages/ui/src/decisions/decision-health-widget.tsx+++ /dev/null@@ -1,23 +0,0 @@-"use client";--import { StatCard } from "../shared/stat-card";-import type { DecisionHealth } from "@repowise-dev/types/decisions";--export interface DecisionHealthWidgetProps {- /** Resolved health summary; widget renders nothing while undefined. */- health: DecisionHealth | undefined;-}--export function DecisionHealthWidget({ health }: DecisionHealthWidgetProps) {- if (!health) return null;-- const { summary } = health;-- return (- <div className="grid grid-cols-3 gap-3">- <StatCard label="Active Decisions" value={summary.active} />- <StatCard label="Proposed" value={summary.proposed} />- <StatCard label="Stale" value={summary.stale} />- </div>- );-}diff --git a/packages/ui/src/decisions/decision-lineage.tsx b/packages/ui/src/decisions/decision-lineage.tsxindex 7e3879ce0..679a5bd0b 100644--- a/packages/ui/src/decisions/decision-lineage.tsx+++ b/packages/ui/src/decisions/decision-lineage.tsx@@ -85,7 +85,7 @@ export function DecisionLineage({</Link><Badgevariant="outline"- className={`h-4 shrink-0 text-[9px] ${STATUS_BADGE_VARIANT[entry.status] ?? ""}`}+ className={`h-4 shrink-0 text-[10px] ${STATUS_BADGE_VARIANT[entry.status] ?? ""}`}>{entry.status}</Badge>@@ -98,7 +98,7 @@ export function DecisionLineage({</div></div>{!isLast && (- <div className="ml-[5px] flex items-center gap-2 border-l border-[var(--color-border-default)] py-1.5 pl-[18px] text-[11px] text-[var(--color-text-tertiary)]">+ <div className="ml-[5px] flex items-center gap-2 border-l border-[var(--color-border-default)] py-1.5 pl-[18px] text-xs text-[var(--color-text-tertiary)]"><ArrowDown className="h-3 w-3" aria-hidden />{relationLabel && <span>{relationLabel}</span>}</div>diff --git a/packages/ui/src/decisions/decisions-table.tsx b/packages/ui/src/decisions/decisions-table.tsxindex 9f27a15bf..24945a9dc 100644--- a/packages/ui/src/decisions/decisions-table.tsx+++ b/packages/ui/src/decisions/decisions-table.tsx@@ -88,7 +88,7 @@ export function DecisionsTable({</Link>{d.evidence_preview?.source_quote && (<p- className="mt-0.5 truncate text-[11px] italic text-[var(--color-text-tertiary)]"+ className="mt-0.5 truncate text-xs italic text-[var(--color-text-tertiary)]"title={`${d.evidence_preview.source_quote}${d.evidence_preview.evidence_file? ` — ${d.evidence_preview.evidence_file}${diff --git a/packages/ui/src/decisions/index.ts b/packages/ui/src/decisions/index.tsindex 94bc1c066..c0d4878b1 100644--- a/packages/ui/src/decisions/index.ts+++ b/packages/ui/src/decisions/index.ts@@ -1,4 +1,3 @@-export * from "./decision-health-widget";export * from "./decisions-table";export * from "./module-link-editor";export * from "./verification-badge";diff --git a/packages/ui/src/decisions/module-link-editor.tsx b/packages/ui/src/decisions/module-link-editor.tsxindex 2c1a30ab4..1f134b53c 100644--- a/packages/ui/src/decisions/module-link-editor.tsx+++ b/packages/ui/src/decisions/module-link-editor.tsx@@ -96,7 +96,7 @@ export function ModuleLinkEditor({<h3 className="text-sm font-medium text-[var(--color-text-secondary)]">Governance scope</h3>- <p className="text-[11px] text-[var(--color-text-tertiary)]">+ <p className="text-xs text-[var(--color-text-tertiary)]">Link this decision to the modules and files it governs.</p></div>@@ -187,7 +187,7 @@ export function ModuleLinkEditor({{/* Footer actions */}<div className="flex items-center justify-between gap-2 border-t border-[var(--color-border-default)] pt-3">- <p className="text-[11px] text-[var(--color-text-tertiary)]">+ <p className="text-xs text-[var(--color-text-tertiary)]">{dirty ? "Unsaved changes" : "All linkage saved."}</p><div className="flex gap-2">@@ -238,7 +238,7 @@ function Field({ icon, label, chips, onRemove, disabled, children }: FieldProps){chips.map((c) => (<spankey={c}- className="inline-flex items-center gap-1 rounded-full border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2 py-0.5 font-mono text-[11px] text-[var(--color-text-primary)]"+ className="inline-flex items-center gap-1 rounded-full border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2 py-0.5 font-mono text-xs text-[var(--color-text-primary)]"><span className="max-w-[260px] truncate" title={c}>{c}diff --git a/packages/ui/src/dependencies/dependency-registry.tsx b/packages/ui/src/dependencies/dependency-registry.tsxindex 56668244a..eed405fc3 100644--- a/packages/ui/src/dependencies/dependency-registry.tsx+++ b/packages/ui/src/dependencies/dependency-registry.tsx@@ -119,7 +119,7 @@ export function DependencyRegistry({key={f}onClick={() => setDepFilter(f)}className={cn(- "rounded px-2 py-1 text-[11px] font-medium transition-colors",+ "rounded px-2 py-1 text-xs font-medium transition-colors",depFilter === f? "bg-[var(--color-accent-muted)] text-[var(--color-accent-primary)]": "text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)]",@@ -136,7 +136,7 @@ export function DependencyRegistry({value={ecosystem ?? ""}onChange={(e) => setEcosystem(e.target.value || null)}aria-label="Filter by ecosystem"- className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-2 py-1.5 text-[11px] text-[var(--color-text-primary)] outline-none"+ className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-2 py-1.5 text-xs text-[var(--color-text-primary)] outline-none"><option value="">All ecosystems</option>{data.ecosystems.map((eco) => (@@ -152,7 +152,7 @@ export function DependencyRegistry({value={manifest ?? ""}onChange={(e) => setManifest(e.target.value || null)}aria-label="Filter by manifest"- className="max-w-[260px] rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-2 py-1.5 text-[11px] text-[var(--color-text-primary)] outline-none"+ className="max-w-[260px] rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-2 py-1.5 text-xs text-[var(--color-text-primary)] outline-none"><option value="">All manifests</option>{data.manifests.map((m) => (@@ -196,16 +196,16 @@ export function DependencyRegistry({</p><div className="flex shrink-0 items-center gap-1">{e.is_dev_dep && (- <Badge variant="outline" className="text-[9px]">+ <Badge variant="outline" className="text-[10px]">dev</Badge>)}- <Badge variant="outline" className="text-[9px]">+ <Badge variant="outline" className="text-[10px]">{e.ecosystem}</Badge></div></div>- <div className="mt-1.5 flex items-center justify-between gap-2 text-[11px] text-[var(--color-text-tertiary)]">+ <div className="mt-1.5 flex items-center justify-between gap-2 text-xs text-[var(--color-text-tertiary)]"><span className="min-w-0 truncate font-mono" title={e.declared_in}>{renderManifestLink? renderManifestLink(e.declared_in, e.declared_in)diff --git a/packages/ui/src/docs/command-palette.tsx b/packages/ui/src/docs/command-palette.tsxindex 9ed32ca2c..bdb393a4b 100644--- a/packages/ui/src/docs/command-palette.tsx+++ b/packages/ui/src/docs/command-palette.tsx@@ -1,6 +1,6 @@"use client";-import { useEffect, useMemo, useRef, useState } from "react";+import { useEffect, useId, useMemo, useRef, useState } from "react";import { Search, CornerDownLeft } from "lucide-react";import { cn } from "../lib/cn";import { getPageTypeIcon, getPageTypeLabel } from "../lib/page-types";@@ -73,6 +73,10 @@ export function DocsCommandPalette({const [active, setActive] = useState(0);const inputRef = useRef<HTMLInputElement>(null);const debounced = useDebounce(query, 120);+ // Stable id base so the input's aria-activedescendant can point at the+ // active option row (rows are keyed by page id, which is unique per hit).+ const listboxId = useId();+ const optionId = (pageId: string) => `${listboxId}-opt-${pageId}`;// Global ⌘K / Ctrl-K toggle.useEffect(() => {@@ -203,6 +207,11 @@ export function DocsCommandPalette({onChange={(e) => setQuery(e.target.value)}onKeyDown={onInputKey}placeholder="Search pages by title, path, or content…"+ role="combobox"+ aria-expanded+ aria-controls={listboxId}+ aria-autocomplete="list"+ aria-activedescendant={hits[active] ? optionId(hits[active].page.id) : undefined}className="flex-1 bg-transparent text-sm text-[var(--color-text-primary)] placeholder:text-[var(--color-text-tertiary)] outline-none"/><kbd className="rounded border border-[var(--color-border-default)] px-1.5 py-0.5 text-[10px] text-[var(--color-text-tertiary)]">@@ -211,7 +220,12 @@ export function DocsCommandPalette({</div>{/* Results */}- <div className="max-h-[50vh] overflow-y-auto p-1.5">+ <div+ id={listboxId}+ role="listbox"+ aria-label="Search results"+ className="max-h-[50vh] overflow-y-auto p-1.5"+ >{debounced.trim().length < 2 ? (<p className="px-3 py-6 text-center text-xs text-[var(--color-text-tertiary)]">Type to search {pages.length} pages@@ -226,6 +240,9 @@ export function DocsCommandPalette({return (<buttonkey={hit.page.id}+ id={optionId(hit.page.id)}+ role="option"+ aria-selected={i === active}onMouseEnter={() => setActive(i)}onClick={() => choose(hit.page)}className={cn(@@ -246,12 +263,12 @@ export function DocsCommandPalette({</span></span>{hit.page.target_path && (- <span className="block truncate font-mono text-[11px] text-[var(--color-text-tertiary)]">+ <span className="block truncate font-mono text-xs text-[var(--color-text-tertiary)]">{hit.page.target_path}</span>)}{hit.snippet && (- <span className="mt-0.5 block truncate text-[11px] text-[var(--color-text-secondary)]">+ <span className="mt-0.5 block truncate text-xs text-[var(--color-text-secondary)]">{hit.snippet}</span>)}diff --git a/packages/ui/src/docs/docs-header.tsx b/packages/ui/src/docs/docs-header.tsxnew file mode 100644index 000000000..d5d079ede--- /dev/null+++ b/packages/ui/src/docs/docs-header.tsx@@ -0,0 +1,69 @@+"use client";++import { BookOpen, BarChart3 } from "lucide-react";+import { cn } from "../lib/cn";+import type { ReaderLinkComponent } from "./docs-reader";++export interface DocsHeaderTab {+ label: string;+ href: string;+ isActive: boolean;+ icon: "explorer" | "freshness";+}++const ICONS = {+ explorer: BookOpen,+ freshness: BarChart3,+} as const;++/**+ * Single compact chrome row for the documentation surface: title, the+ * Explorer / Doc-freshness view switch as a segmented control, and a+ * right-aligned slot for page-specific actions. Pure presentation — the host+ * resolves tab hrefs/active state and injects a router-aware ``LinkComponent``.+ */+export function DocsHeader({+ tabs,+ LinkComponent,+ children,+}: {+ tabs: DocsHeaderTab[];+ LinkComponent: ReaderLinkComponent;+ children?: React.ReactNode;+}) {+ const Link = LinkComponent;+ return (+ <div className="shrink-0 flex h-12 items-center gap-3 border-b border-[var(--color-border-default)] px-4 sm:px-6">+ <h1 className="text-sm font-semibold text-[var(--color-text-primary)]">+ Documentation+ </h1>++ <nav+ className="flex items-center rounded-lg bg-[var(--color-bg-elevated)] p-0.5"+ aria-label="Docs views"+ >+ {tabs.map((tab) => {+ const Icon = ICONS[tab.icon];+ return (+ <Link+ key={tab.href}+ href={tab.href}+ aria-current={tab.isActive ? "page" : undefined}+ className={cn(+ "flex items-center gap-1.5 rounded-md px-2.5 py-1 text-xs font-medium transition-colors",+ tab.isActive+ ? "bg-[var(--color-bg-surface)] text-[var(--color-text-primary)] shadow-sm"+ : "text-[var(--color-text-tertiary)] hover:text-[var(--color-text-secondary)]",+ )}+ >+ <Icon className="h-3.5 w-3.5" />+ {tab.label}+ </Link>+ );+ })}+ </nav>++ <div className="ml-auto flex items-center gap-2">{children}</div>+ </div>+ );+}diff --git a/packages/ui/src/docs/docs-page-actions.tsx b/packages/ui/src/docs/docs-page-actions.tsxnew file mode 100644index 000000000..ef6d4958b--- /dev/null+++ b/packages/ui/src/docs/docs-page-actions.tsx@@ -0,0 +1,184 @@+"use client";++import { useState } from "react";+import {+ ChevronDown,+ Download,+ FileText,+ FolderArchive,+ Loader2,+ PanelRight,+ PanelRightClose,+} from "lucide-react";+import { Button } from "../ui/button";+import { ConfidenceBadge } from "../wiki/confidence-badge";+import { READER_PERSONAS, type ReaderPersona } from "./reader-persona";+import { cn } from "../lib/cn";++/**+ * Per-page controls for the DocsHeader row — the compact freshness badge and+ * the reader-level segmented control. The reader control renders only when+ * filtering actually changes this page; on curated pages it disappears.+ */+export function DocsPageActions({+ confidence,+ freshnessStatus,+ persona,+ setPersona,+ personaHasEffect,+}: {+ confidence: number;+ freshnessStatus: string;+ persona: ReaderPersona;+ setPersona: (next: ReaderPersona) => void;+ personaHasEffect: boolean;+}) {+ return (+ <>+ <ConfidenceBadge score={confidence} status={freshnessStatus} />+ {personaHasEffect && (+ <div+ className="inline-flex items-center rounded-md border border-[var(--color-border-default)] p-0.5 shrink-0"+ role="group"+ aria-label="Reader level"+ >+ {READER_PERSONAS.map((p) => (+ <button+ key={p.value}+ onClick={() => setPersona(p.value)}+ title={p.hint}+ className={cn(+ "rounded px-1.5 py-0.5 text-[10px] font-medium transition-colors",+ persona === p.value+ ? "bg-[var(--color-accent-primary)] text-[var(--color-text-inverse)]"+ : "text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)]",+ )}+ >+ {p.label}+ </button>+ ))}+ </div>+ )}+ </>+ );+}++/** Insights-drawer toggle — header-resident; the drawer itself is lg-only. */+export function SidebarToggle({+ open,+ onToggle,+}: {+ open: boolean;+ onToggle: () => void;+}) {+ return (+ <button+ onClick={onToggle}+ className={cn(+ "hidden lg:inline-flex rounded-md p-1.5 transition-colors",+ open+ ? "text-[var(--color-accent)] hover:bg-[var(--color-bg-elevated)]"+ : "text-[var(--color-text-tertiary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-accent-primary)]",+ )}+ title={open ? "Hide insights" : "Show insights"}+ aria-pressed={open}+ >+ {open ? (+ <PanelRightClose className="h-3.5 w-3.5" />+ ) : (+ <PanelRight className="h-3.5 w-3.5" />+ )}+ </button>+ );+}++/**+ * Single Export menu. The host owns the actual download side-effects (file+ * writes / blob hrefs) — this shell only renders the menu and calls back.+ * There is no "Open full page" item: docs and wiki are one reader now.+ */+export function ExportMenu({+ isExporting,+ onExportPage,+ onExportAll,+ zipHref,+ hasPage,+}: {+ isExporting: boolean;+ onExportPage: () => void;+ onExportAll: () => void;+ zipHref: string;+ hasPage: boolean;+}) {+ const [open, setOpen] = useState(false);+ const itemClass =+ "flex w-full items-center gap-2 rounded px-2 py-1.5 text-xs text-[var(--color-text-secondary)] transition-colors hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]";++ return (+ <div className="relative">+ <Button+ variant="outline"+ size="sm"+ onClick={() => setOpen((o) => !o)}+ disabled={isExporting}+ aria-haspopup="menu"+ aria-expanded={open}+ >+ {isExporting ? (+ <Loader2 className="h-3.5 w-3.5 mr-1.5 animate-spin" />+ ) : (+ <Download className="h-3.5 w-3.5 mr-1.5" />+ )}+ Export+ <ChevronDown className="h-3 w-3 ml-1 opacity-60" />+ </Button>+ {open && (+ <>+ <div className="fixed inset-0 z-10" onClick={() => setOpen(false)} />+ <div+ role="menu"+ className="absolute right-0 top-full z-20 mt-1 w-52 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-1 shadow-md"+ >+ {hasPage && (+ <>+ <button+ role="menuitem"+ className={itemClass}+ onClick={() => {+ setOpen(false);+ onExportPage();+ }}+ >+ <Download className="h-3.5 w-3.5 shrink-0" />+ This page (Markdown)+ </button>+ <div className="my-1 border-t border-[var(--color-border-default)]" />+ </>+ )}+ <button+ role="menuitem"+ className={itemClass}+ onClick={() => {+ setOpen(false);+ onExportAll();+ }}+ >+ <FileText className="h-3.5 w-3.5 shrink-0" />+ All pages (Markdown)+ </button>+ <a+ role="menuitem"+ href={zipHref}+ download+ className={itemClass}+ onClick={() => setOpen(false)}+ >+ <FolderArchive className="h-3.5 w-3.5 shrink-0" />+ ZIP archive+ </a>+ </div>+ </>+ )}+ </div>+ );+}diff --git a/packages/ui/src/docs/docs-reader.tsx b/packages/ui/src/docs/docs-reader.tsxnew file mode 100644index 000000000..0b6223a20--- /dev/null+++ b/packages/ui/src/docs/docs-reader.tsx@@ -0,0 +1,513 @@+"use client";++import { useCallback, useEffect, useMemo, useRef } from "react";+import {+ FileText,+ Clock,+ Cpu,+ ArrowRight,+ ArrowLeft,+ Loader2,+ Layers,+ FileInput,+} from "lucide-react";+import type { DocPage } from "@repowise-dev/types/docs";+import { cn } from "../lib/cn";+import { formatRelativeTime, formatTokens } from "../lib/format";+import { getPageTypeLabel } from "../lib/page-types";+import { computeDocNav } from "./doc-nav";+import { filterMarkdownByPersona, type ReaderPersona } from "./reader-persona";+import { WikiMarkdown } from "../wiki/wiki-markdown";+import { TableOfContents } from "../wiki/table-of-contents";+import { BacklinksPanel } from "../wiki/backlinks-panel";+import {+ getBacklinks,+ getWikiLinks,+} from "../wiki/wiki-links-types";+import { Breadcrumb } from "../shared/breadcrumb";++/** Router-aware anchor — host injects Next.js Link / in-app interception. */+export type ReaderLinkComponent = React.ElementType<{+ href: string;+ className?: string;+ title?: string;+ children: React.ReactNode;+}>;++interface DocsReaderProps {+ page: DocPage | null;+ /** Full page list — powers hierarchical breadcrumbs and prev/next. */+ pages?: DocPage[];+ repoId: string;+ isLoading?: boolean;+ /** Select another page in-place (breadcrumb / prev-next / wiki links). */+ onSelectPage?: (page: DocPage) => void;+ /** Navigate by page id (resolved wiki links / backlinks fall through here). */+ onNavigatePageId?: (pageId: string) => void;+ persona: ReaderPersona;+ sidebarOpen: boolean;+ /** ``?page=`` href builder — host owns the route shape. */+ buildPageHref: (pageId: string) => string;+ /** Router-aware link for in-content + breadcrumb anchors. */+ LinkComponent: ReaderLinkComponent;+ /**+ * Data-bound rail sections (graph intelligence, git "at a glance", security)+ * that require host hooks. Rendered below the on-page contents + provenance.+ */+ intelligenceSlot?: React.ReactNode;+ /** Data-bound version history (host owns the SWR fetch). */+ versionHistorySlot?: React.ReactNode;+}++export function DocsReader({+ page,+ pages = [],+ repoId,+ isLoading,+ onSelectPage,+ onNavigatePageId,+ persona,+ sidebarOpen,+ buildPageHref,+ LinkComponent,+ intelligenceSlot,+ versionHistorySlot,+}: DocsReaderProps) {+ const scrollRef = useRef<HTMLDivElement>(null);++ const goToPageId = useCallback(+ (pageId: string) => {+ const target = pages.find((p) => p.id === pageId);+ if (target && onSelectPage) onSelectPage(target);+ else if (onNavigatePageId) onNavigatePageId(pageId);+ },+ [pages, onSelectPage, onNavigatePageId],+ );++ useEffect(() => {+ scrollRef.current?.scrollTo(0, 0);+ }, [page?.id]);++ if (isLoading) {+ return (+ <div className="flex items-center justify-center h-full">+ <Loader2 className="h-5 w-5 animate-spin text-[var(--color-accent-primary)]" />+ </div>+ );+ }++ if (!page) {+ return (+ <div className="flex flex-col items-center justify-center h-full gap-4 text-center px-8">+ <div className="rounded-full bg-[var(--color-bg-elevated)] border border-[var(--color-border-default)] p-4">+ <FileText className="h-8 w-8 text-[var(--color-text-tertiary)]" />+ </div>+ <div className="space-y-1">+ <h3 className="text-sm font-semibold text-[var(--color-text-primary)]">+ Select a page+ </h3>+ <p className="text-xs text-[var(--color-text-secondary)] max-w-sm">+ Choose a file or module from the tree to view its AI-generated documentation.+ </p>+ </div>+ </div>+ );+ }++ return (+ <DocsReaderBody+ page={page}+ pages={pages}+ repoId={repoId}+ sidebarOpen={sidebarOpen}+ scrollRef={scrollRef}+ goToPageId={goToPageId}+ persona={persona}+ buildPageHref={buildPageHref}+ LinkComponent={LinkComponent}+ intelligenceSlot={intelligenceSlot}+ versionHistorySlot={versionHistorySlot}+ />+ );+}++function DocsReaderBody({+ page,+ pages,+ repoId,+ sidebarOpen,+ scrollRef,+ goToPageId,+ persona,+ buildPageHref,+ LinkComponent,+ intelligenceSlot,+ versionHistorySlot,+}: {+ page: DocPage;+ pages: DocPage[];+ repoId: string;+ sidebarOpen: boolean;+ scrollRef: React.RefObject<HTMLDivElement | null>;+ goToPageId: (pageId: string) => void;+ persona: ReaderPersona;+ buildPageHref: (pageId: string) => string;+ LinkComponent: ReaderLinkComponent;+ intelligenceSlot?: React.ReactNode;+ versionHistorySlot?: React.ReactNode;+}) {+ const nav = useMemo(() => computeDocNav(page, pages), [page, pages]);+ const wikiLinks = useMemo(() => getWikiLinks(page.metadata), [page.metadata]);++ const visibleContent = useMemo(+ () => filterMarkdownByPersona(page.content, persona),+ [page.content, persona],+ );++ const moduleSeg = useMemo(+ () =>+ [...nav.breadcrumbs]+ .slice(0, -1)+ .reverse()+ .find((s) => s.pageId && s.pageId !== page.id),+ [nav.breadcrumbs, page.id],+ );++ const relatedLinks = useMemo(() => {+ const byId = new Map(pages.map((p) => [p.id, p]));+ const seen = new Set<string>();+ const out: { id: string; title: string }[] = [];+ for (const link of wikiLinks) {+ const target = link.target_page_id;+ if (target === page.id || seen.has(target)) continue;+ const hit = byId.get(target);+ if (!hit) continue;+ seen.add(target);+ out.push({ id: hit.id, title: hit.title });+ }+ return out;+ }, [wikiLinks, pages, page.id]);++ const layerName =+ typeof page.metadata?.layer_name === "string" ? page.metadata.layer_name : "";+ const layerId =+ typeof page.metadata?.layer_id === "string" ? page.metadata.layer_id : "";+ const layerPage = useMemo(+ () =>+ layerId+ ? pages.find(+ (p) => p.page_type === "layer_page" && p.target_path === layerId,+ ) ??+ (layerName+ ? pages.find(+ (p) =>+ p.page_type === "layer_page" &&+ p.target_path === `layer:${layerName}`,+ )+ : undefined)+ : layerName+ ? pages.find(+ (p) =>+ p.page_type === "layer_page" &&+ p.target_path === `layer:${layerName}`,+ )+ : undefined,+ [pages, layerId, layerName],+ );++ const sources = useMemo(() => {+ const raw = page.metadata?.sources;+ if (!Array.isArray(raw)) return [];+ const byPath = new Map(pages.map((p) => [p.target_path, p]));+ return (raw as Array<{ path?: string; kind?: string }>)+ .map((s) => {+ const path = typeof s?.path === "string" ? s.path : "";+ return { path, kind: s?.kind ?? "", pageId: byPath.get(path)?.id };+ })+ .filter((s) => s.path);+ }, [page.metadata, pages]);++ // Resolved wiki link: a real href (middle-click opens in a new tab) with+ // plain clicks intercepted for in-app nav.+ const WikiInlineLink = useMemo(() => {+ function Comp({+ href,+ className,+ title,+ children,+ }: {+ href: string;+ className?: string;+ title?: string;+ children: React.ReactNode;+ }) {+ return (+ <a+ href={href}+ className={className}+ title={title}+ onClick={(e) => {+ if (e.metaKey || e.ctrlKey || e.shiftKey || e.button !== 0) return;+ try {+ const u = new URL(href, window.location.origin);+ const pid = u.searchParams.get("page");+ if (pid) {+ e.preventDefault();+ goToPageId(pid);+ }+ } catch {+ /* fall through to default navigation */+ }+ }}+ >+ {children}+ </a>+ );+ }+ return Comp;+ }, [goToPageId]);++ return (+ <div className="flex h-full">+ <div className="flex flex-col flex-1 min-w-0">+ <div ref={scrollRef} className="flex-1 overflow-y-auto">+ <div className="px-4 sm:px-6 py-8 max-w-[768px] mx-auto">+ {/* Hierarchical breadcrumb */}+ <div className="mb-3 overflow-hidden">+ <Breadcrumb+ segments={nav.breadcrumbs.map((seg) => ({+ label: seg.label,+ ...(seg.pageId && seg.pageId !== page.id+ ? { href: buildPageHref(seg.pageId) }+ : {}),+ }))}+ LinkComponent={WikiInlineLink}+ />+ </div>++ {/* Title */}+ <h1 className="font-serif text-[2rem] leading-tight font-semibold tracking-tight text-[var(--color-text-primary)] mb-2 break-words">+ {page.title}+ </h1>++ {/* One calm metadata line: type + module + layer + freshness ++ version + model — every metadata fact stated once, here. */}+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1.5 text-[10px] text-[var(--color-text-tertiary)] mb-6">+ <span className="rounded-full bg-[var(--color-bg-elevated)] px-2 py-0.5 uppercase tracking-wider">+ {getPageTypeLabel(page.page_type)}+ </span>+ {moduleSeg && (+ <button+ onClick={() => goToPageId(moduleSeg.pageId!)}+ className="rounded-full border border-[var(--color-border-default)] px-2 py-0.5 text-[var(--color-text-secondary)] transition-colors hover:border-[var(--color-border-accent)] hover:text-[var(--color-accent-primary)]"+ >+ in {moduleSeg.label}+ </button>+ )}+ {layerName &&+ (layerPage ? (+ <button+ onClick={() => goToPageId(layerPage.id)}+ className="inline-flex items-center gap-1 rounded-full border border-[var(--color-border-default)] px-2 py-0.5 text-[var(--color-text-secondary)] transition-colors hover:border-[var(--color-border-accent)] hover:text-[var(--color-accent-primary)]"+ >+ <Layers className="h-2.5 w-2.5" />+ {layerName}+ </button>+ ) : (+ <span className="inline-flex items-center gap-1 rounded-full bg-[var(--color-bg-elevated)] px-2 py-0.5">+ <Layers className="h-2.5 w-2.5" />+ {layerName}+ </span>+ ))}+ <span className="flex items-center gap-1">+ <Clock className="h-3 w-3" />+ {formatRelativeTime(page.updated_at)}+ </span>+ <span>v{page.version}</span>+ <span className="font-mono">+ {formatTokens(page.input_tokens)} in · {formatTokens(page.output_tokens)} out+ </span>+ {page.model_name && (+ <span className="flex items-center gap-1 font-mono">+ <Cpu className="h-3 w-3" />+ {page.model_name}+ </span>+ )}+ </div>++ {/* Low-confidence flag */}+ {page.confidence > 0 && page.confidence < 0.5 && (+ <div className="mb-4 flex items-start gap-1.5 rounded-md border border-[var(--color-warning)]/40 bg-[var(--color-warning)]/10 px-3 py-2">+ <span className="text-xs text-[var(--color-text-primary)]">+ This page was generated with low confidence — verify against the source before relying on it.+ </span>+ </div>+ )}++ {/* Human notes (read-only callout; editing lives in the rail) */}+ {page.human_notes && (+ <div className="mb-4 rounded-lg border border-[var(--color-border-accent)] bg-[var(--color-accent-blue)]/5 px-4 py-3">+ <p className="text-sm text-[var(--color-text-secondary)] whitespace-pre-wrap leading-relaxed">+ {page.human_notes}+ </p>+ </div>+ )}++ {/* Markdown content */}+ <article className="prose prose-invert max-w-none leading-relaxed overflow-hidden">+ <WikiMarkdown+ content={visibleContent}+ wikiLinks={wikiLinks}+ buildHref={(pid) => buildPageHref(pid)}+ LinkComponent={WikiInlineLink}+ />+ </article>++ {/* Sibling prev / next */}+ {(nav.prev || nav.next) && (+ <nav className="mt-8 flex items-stretch gap-3 border-t border-[var(--color-border-default)] pt-4">+ {nav.prev ? (+ <button+ onClick={() => goToPageId(nav.prev!.pageId)}+ className="group flex flex-1 items-center gap-2 rounded-lg border border-[var(--color-border-default)] px-3 py-2 text-left transition-colors hover:border-[var(--color-border-accent)] hover:bg-[var(--color-bg-elevated)]"+ >+ <ArrowLeft className="h-3.5 w-3.5 shrink-0 text-[var(--color-text-tertiary)] group-hover:text-[var(--color-accent-primary)]" />+ <span className="min-w-0">+ <span className="block text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">+ Previous+ </span>+ <span className="block truncate text-xs text-[var(--color-text-secondary)]">+ {nav.prev.title}+ </span>+ </span>+ </button>+ ) : (+ <span className="flex-1" />+ )}+ {nav.next && (+ <button+ onClick={() => goToPageId(nav.next!.pageId)}+ className="group flex flex-1 items-center justify-end gap-2 rounded-lg border border-[var(--color-border-default)] px-3 py-2 text-right transition-colors hover:border-[var(--color-border-accent)] hover:bg-[var(--color-bg-elevated)]"+ >+ <span className="min-w-0">+ <span className="block text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">+ Next+ </span>+ <span className="block truncate text-xs text-[var(--color-text-secondary)]">+ {nav.next.title}+ </span>+ </span>+ <ArrowRight className="h-3.5 w-3.5 shrink-0 text-[var(--color-text-tertiary)] group-hover:text-[var(--color-accent-primary)]" />+ </button>+ )}+ </nav>+ )}++ {/* Version history (host-supplied data wrapper) */}+ {versionHistorySlot && <div className="mt-8">{versionHistorySlot}</div>}++ {/* Metadata warnings */}+ {Array.isArray(page.metadata?.hallucination_warnings) &&+ (page.metadata.hallucination_warnings as string[]).length > 0 && (+ <div className="mt-4 rounded-lg border border-[var(--color-warning)]/40 bg-[var(--color-warning)]/10 px-4 py-3">+ <p className="text-xs font-medium text-[var(--color-warning)] mb-1.5">+ Possible inaccuracies detected+ </p>+ <ul className="space-y-0.5">+ {(page.metadata.hallucination_warnings as string[]).map((w, i) => (+ <li key={i} className="text-xs text-[var(--color-text-secondary)] font-mono">+ {String(w)}+ </li>+ ))}+ </ul>+ </div>+ )}+ </div>+ </div>+ </div>++ {/* Right intelligence rail — on-page contents, provenance, related,+ backlinks, then host-supplied data-bound intelligence sections. */}+ {sidebarOpen && (+ <div className="hidden lg:block border-l border-[var(--color-border-default)] bg-[var(--color-bg-surface)] shrink-0 w-[260px] overflow-auto">+ <div className="space-y-6 p-4">+ <TableOfContents content={page.content} />+ {sources.length > 0 && (+ <div>+ <div className="flex items-center gap-1.5 mb-2">+ <FileInput className="h-3 w-3 text-[var(--color-text-tertiary)]" />+ <span className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider">+ Built from+ </span>+ </div>+ <ul className="space-y-1">+ {sources.slice(0, 5).map((s) => (+ <li key={s.path} className="text-xs">+ {s.pageId ? (+ <button+ onClick={() => goToPageId(s.pageId!)}+ className="truncate text-left font-mono text-[var(--color-text-secondary)] hover:text-[var(--color-accent-primary)] transition-colors w-full"+ title={`${s.path} (${s.kind})`}+ >+ {s.path.split("/").pop()}+ </button>+ ) : (+ <span+ className="block truncate font-mono text-[var(--color-text-tertiary)]"+ title={`${s.path} (${s.kind})`}+ >+ {s.path.split("/").pop()}+ </span>+ )}+ </li>+ ))}+ </ul>+ {sources.length > 5 && (+ <p className="mt-1 text-[10px] text-[var(--color-text-tertiary)]">+ + {sources.length - 5} more+ </p>+ )}+ </div>+ )}+ {relatedLinks.length > 0 && (+ <div>+ <p className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-2">+ Related+ </p>+ <ul className="space-y-1.5">+ {relatedLinks.slice(0, 5).map((r) => (+ <li key={r.id} className="text-xs">+ <button+ onClick={() => goToPageId(r.id)}+ className="truncate text-left text-[var(--color-text-secondary)] hover:text-[var(--color-accent-primary)] transition-colors w-full"+ title={r.title}+ >+ {r.title}+ </button>+ </li>+ ))}+ </ul>+ {relatedLinks.length > 5 && (+ <p className="mt-1 text-[10px] text-[var(--color-text-tertiary)]">+ + {relatedLinks.length - 5} more+ </p>+ )}+ </div>+ )}+ <BacklinksPanel+ backlinks={getBacklinks(page.metadata)}+ repoId={repoId}+ buildHref={(_rid, pid) => buildPageHref(pid)}+ renderLink={({ href, className, title, children }) => (+ <LinkComponent href={href} className={className} title={title}>+ {children}+ </LinkComponent>+ )}+ />+ {intelligenceSlot}+ </div>+ </div>+ )}+ </div>+ );+}diff --git a/packages/ui/src/docs/docs-tree.tsx b/packages/ui/src/docs/docs-tree.tsxindex 66b421a50..5afd2412c 100644--- a/packages/ui/src/docs/docs-tree.tsx+++ b/packages/ui/src/docs/docs-tree.tsx@@ -634,6 +634,7 @@ function TreeItem({toggleDir,onSelectPage,forceExpand = false,+ showFreshness = false,}: {node: TreeNode;depth: number;@@ -643,6 +644,8 @@ function TreeItem({onSelectPage: (page: DocPage) => void;/** Open every dir while a search is active so matches are never hidden. */forceExpand?: boolean;+ /** Per-row freshness dots are opt-in — off by default to keep rows quiet. */+ showFreshness?: boolean;}) {const isExpanded = forceExpand || expandedDirs.has(node.path);const isSelected = node.page && node.page.id === selectedPageId;@@ -658,7 +661,7 @@ function TreeItem({}}{...(node.page && node.page.title !== node.name ? { title: node.page.title } : {})}className={cn(- "flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-xs transition-colors hover:bg-[var(--color-bg-elevated)]",+ "flex w-full items-center gap-1.5 rounded-md px-2 py-1.5 text-left text-xs transition-colors hover:bg-[var(--color-bg-elevated)]",isSelected? "bg-[var(--color-accent-muted)] text-[var(--color-accent-primary)]": "text-[var(--color-text-secondary)]",@@ -702,12 +705,12 @@ function TreeItem({(node.path === ONBOARDING_DIR_KEY || node.path.startsWith("@section:")) &&"text-[var(--color-text-primary)]",node.path.startsWith("@section:") &&- "text-[11px] uppercase tracking-wider",+ "text-xs uppercase tracking-wider",)}>{node.name}</span>- {node.page && (+ {showFreshness && node.page && (<FreshnessDot status={node.page.freshness_status as FreshnessStatus} />)}</button>@@ -724,6 +727,7 @@ function TreeItem({toggleDir={toggleDir}onSelectPage={onSelectPage}forceExpand={forceExpand}+ showFreshness={showFreshness}/>))}</div>@@ -738,7 +742,7 @@ function TreeItem({onClick={() => node.page && onSelectPage(node.page)}{...(node.page && node.page.title !== node.name ? { title: node.page.title } : {})}className={cn(- "flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-xs transition-colors hover:bg-[var(--color-bg-elevated)]",+ "flex w-full items-center gap-1.5 rounded-md px-2 py-1.5 text-left text-xs transition-colors hover:bg-[var(--color-bg-elevated)]",isSelected? "bg-[var(--color-accent-muted)] text-[var(--color-accent-primary)]": "text-[var(--color-text-secondary)]",@@ -753,7 +757,7 @@ function TreeItem({)}/><span className="truncate">{node.name}</span>- {node.page && (+ {showFreshness && node.page && (<FreshnessDot status={node.page.freshness_status as FreshnessStatus} />)}</button>@@ -817,6 +821,9 @@ export function DocsTree({ pages, selectedPageId, onSelectPage, className }: Doc// Filters are a power-user affordance — start hidden so the panel opens// calm; the funnel button shows a count when any filter is active.const [showFilters, setShowFilters] = useState(false);+ // Per-row freshness dots are opt-in noise — off by default. Turning this on+ // (or filtering by status) is how a reader audits staleness across the tree.+ const [showFreshness, setShowFreshness] = useState(false);const tree = useMemo(() => (viewMode === "domain" ? buildDomainTree(pages) : buildTree(pages)),@@ -857,7 +864,7 @@ export function DocsTree({ pages, selectedPageId, onSelectPage, className }: Dockey={mode}onClick={() => setViewMode(mode)}className={cn(- "flex flex-1 items-center justify-center gap-1.5 rounded px-2 py-1 text-[11px] font-medium transition-colors",+ "flex flex-1 items-center justify-center gap-1.5 rounded px-2 py-1 text-xs font-medium transition-colors",viewMode === mode? "bg-[var(--color-bg-surface)] text-[var(--color-text-primary)] shadow-sm": "text-[var(--color-text-tertiary)] hover:text-[var(--color-text-secondary)]",@@ -892,7 +899,7 @@ export function DocsTree({ pages, selectedPageId, onSelectPage, className }: Doc><Filter className="h-3.5 w-3.5" />{activeFilterCount > 0 && (- <span className="absolute -top-1 -right-1 flex h-3.5 w-3.5 items-center justify-center rounded-full bg-[var(--color-accent-fill)] text-[9px] font-semibold text-[var(--color-text-on-accent)]">+ <span className="absolute -top-1 -right-1 flex h-3.5 w-3.5 items-center justify-center rounded-full bg-[var(--color-accent-fill)] text-[10px] font-semibold text-[var(--color-text-on-accent)]">{activeFilterCount}</span>)}@@ -937,6 +944,15 @@ export function DocsTree({ pages, selectedPageId, onSelectPage, className }: Doc</button>))}</div>+ <label className="flex items-center gap-1.5 text-[10px] text-[var(--color-text-tertiary)] cursor-pointer select-none">+ <input+ type="checkbox"+ checked={showFreshness}+ onChange={(e) => setShowFreshness(e.target.checked)}+ className="h-3 w-3 accent-[var(--color-accent-primary)]"+ />+ Show freshness dots on every row+ </label></div>)}@@ -971,7 +987,7 @@ export function DocsTree({ pages, selectedPageId, onSelectPage, className }: Doc<p>No matching pages</p></div>) : (- <div className="space-y-0.5">+ <div className="space-y-1">{filteredTree.map((node) => (<TreeItemkey={node.path}@@ -982,6 +998,7 @@ export function DocsTree({ pages, selectedPageId, onSelectPage, className }: DoctoggleDir={toggleDir}onSelectPage={onSelectPage}forceExpand={search.trim().length > 0}+ showFreshness={showFreshness || freshnessFilter !== "all"}/>))}</div>diff --git a/packages/ui/src/docs/index.ts b/packages/ui/src/docs/index.tsindex b4a9a5c56..2300b31ed 100644--- a/packages/ui/src/docs/index.ts+++ b/packages/ui/src/docs/index.ts@@ -2,3 +2,6 @@ export * from "./docs-tree";export * from "./doc-nav";export * from "./command-palette";export * from "./reader-persona";+export * from "./docs-reader";+export * from "./docs-header";+export * from "./docs-page-actions";diff --git a/packages/ui/src/files/file-doc-tab.tsx b/packages/ui/src/files/file-doc-tab.tsxindex 89774e497..9f1af0e42 100644--- a/packages/ui/src/files/file-doc-tab.tsx+++ b/packages/ui/src/files/file-doc-tab.tsx@@ -41,7 +41,7 @@ export function FileDocTab({ wikiPage, docSlot, wikiHref }: FileDocTabProps) {</Badge>{wikiPage.updated_at && (<span- className="text-[11px] text-[var(--color-text-tertiary)]"+ className="text-xs text-[var(--color-text-tertiary)]"title={new Date(wikiPage.updated_at).toLocaleString()}>updated {formatRelativeTime(wikiPage.updated_at)}@@ -50,7 +50,7 @@ export function FileDocTab({ wikiPage, docSlot, wikiHref }: FileDocTabProps) {{wikiHref && (<ahref={wikiHref}- className="ml-auto text-[11px] text-[var(--color-accent-primary)] hover:underline"+ className="ml-auto text-xs text-[var(--color-accent-primary)] hover:underline">Open in Docs →</a>diff --git a/packages/ui/src/files/file-graph-tab.tsx b/packages/ui/src/files/file-graph-tab.tsxindex 9c8df8a93..44760185e 100644--- a/packages/ui/src/files/file-graph-tab.tsx+++ b/packages/ui/src/files/file-graph-tab.tsx@@ -1,6 +1,7 @@import { Network } from "lucide-react";import { EmptyState } from "../shared/empty-state";import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";+import { StatGrid, StatTile } from "../shared/stat-grid";import { truncatePath } from "../lib/format";import type { FileDetailGraph, FileGraphNeighbor } from "@repowise-dev/types/files";@@ -39,7 +40,7 @@ function NeighborList({{neighbors.length === 0 ? (<p className="text-xs text-[var(--color-text-tertiary)]">None in the indexed graph.</p>) : (- <ul className="space-y-1">+ <ul className="space-y-2">{neighbors.map((n) => {const isSymbol = n.node_type === "symbol" || n.node_id.includes("::");const href = isSymbol ? symbolHref(n.node_id) : fileHref(n.node_id);@@ -47,9 +48,9 @@ function NeighborList({<li key={`${n.node_id}-${n.edge_type}`}><ahref={href}- className="flex items-center gap-2 -mx-2 px-2 py-0.5 rounded hover:bg-[var(--color-bg-elevated)] transition-colors"+ className="flex items-center gap-2 -mx-2 px-2 py-1 rounded hover:bg-[var(--color-bg-elevated)] transition-colors">- <span className="text-[11px] font-mono text-[var(--color-text-primary)] truncate flex-1 min-w-0">+ <span className="font-mono text-xs text-[var(--color-text-primary)] truncate flex-1 min-w-0" title={n.node_id}>{truncatePath(n.node_id, 48)}</span><span className="text-[10px] text-[var(--color-text-tertiary)] shrink-0">@@ -88,17 +89,17 @@ export function FileGraphTab({ graph, filePath, linkPrefix, fileHref, symbolHrefreturn (<div className="space-y-4">- <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">- <Stat+ <StatGrid columns={4}>+ <StatTilelabel="PageRank"value={`${Math.round(graph.pagerank_percentile)}th pct`}hint={graph.pagerank.toFixed(6)}/>- <Stat label="Dependents (in)" value={String(graph.in_degree)} />- <Stat label="Dependencies (out)" value={String(graph.out_degree)} />- <Stat label="Community" value={graph.community_label ?? `#${graph.community_id}`} />- </div>- <div className="flex flex-wrap gap-2 text-[11px]">+ <StatTile label="Dependents (in)" value={String(graph.in_degree)} />+ <StatTile label="Dependencies (out)" value={String(graph.out_degree)} />+ <StatTile label="Community" value={graph.community_label ?? `#${graph.community_id}`} />+ </StatGrid>+ <div className="flex flex-wrap gap-3 text-xs"><ahref={`${linkPrefix}/architecture?view=graph&node=${encodeURIComponent(filePath)}`}className="text-[var(--color-accent-primary)] hover:underline"@@ -129,16 +130,3 @@ export function FileGraphTab({ graph, filePath, linkPrefix, fileHref, symbolHref</div>);}--function Stat({ label, value, hint }: { label: string; value: string; hint?: string }) {- return (- <div className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-2.5">- <p className="text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)] mb-0.5">- {label}- </p>- <p className="text-sm font-semibold text-[var(--color-text-primary)]" title={hint}>- {value}- </p>- </div>- );-}diff --git a/packages/ui/src/files/file-history-tab.tsx b/packages/ui/src/files/file-history-tab.tsxindex a4228e79a..2b0a91221 100644--- a/packages/ui/src/files/file-history-tab.tsx+++ b/packages/ui/src/files/file-history-tab.tsx@@ -1,6 +1,9 @@import { GitBranch, Bot } from "lucide-react";import { EmptyState } from "../shared/empty-state";import { CommitCategorySparkline } from "../git/commit-category-sparkline";+import { AgentTierBar } from "../git/agent-tier-bar";+import { OwnershipDonut } from "../git/ownership-donut";+import { StatGrid, StatTile } from "../shared/stat-grid";import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";import { formatRelativeTime, truncatePath } from "../lib/format";import type { FileDetailGit } from "@repowise-dev/types/files";@@ -12,12 +15,6 @@ interface FileHistoryTabProps {partnerHref: (path: string) => string;}-const TIER_LABELS: Record<string, string> = {- "1": "near-autonomous",- "2": "human-driven",- "3": "assisted",-};-export function FileHistoryTab({ git, linkPrefix, partnerHref }: FileHistoryTabProps) {if (!git) {return (@@ -35,12 +32,12 @@ export function FileHistoryTab({ git, linkPrefix, partnerHref }: FileHistoryTabPreturn (<div className="space-y-4">- <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">- <Stat label="Commits (total)" value={git.commit_count_total ?? 0} />- <Stat label="Commits (90d)" value={git.commit_count_90d} />- <Stat label="Contributors" value={git.contributor_count} />- <Stat label="Bus factor" value={git.bus_factor} />- </div>+ <StatGrid columns={4}>+ <StatTile label="Commits (total)" value={git.commit_count_total ?? 0} />+ <StatTile label="Commits (90d)" value={git.commit_count_90d} />+ <StatTile label="Contributors" value={git.contributor_count} />+ <StatTile label="Bus factor" value={git.bus_factor} />+ </StatGrid><div className="grid grid-cols-1 gap-4 lg:grid-cols-2"><Card>@@ -60,7 +57,7 @@ export function FileHistoryTab({ git, linkPrefix, partnerHref }: FileHistoryTabPhref={`${linkPrefix}/commits?commit=${c.sha}`}className="flex items-center gap-2 -mx-2 px-2 py-1 rounded hover:bg-[var(--color-bg-elevated)] transition-colors">- <span className="text-[11px] font-mono text-[var(--color-text-tertiary)] shrink-0">+ <span className="text-xs font-mono text-[var(--color-text-tertiary)] shrink-0">{c.sha.slice(0, 8)}</span><span className="text-xs text-[var(--color-text-primary)] truncate flex-1">@@ -110,16 +107,7 @@ export function FileHistoryTab({ git, linkPrefix, partnerHref }: FileHistoryTabP{agentPct != null && ` · ${agentPct}% of indexed history`}</p>{Object.keys(git.agent.tier_counts).length > 0 && (- <div className="flex flex-wrap gap-1.5">- {Object.entries(git.agent.tier_counts).map(([tier, count]) => (- <span- key={tier}- className="rounded border border-[var(--color-border-default)] px-1.5 py-0.5 text-[10px] text-[var(--color-text-secondary)]"- >- {TIER_LABELS[tier] ?? `tier ${tier}`}: {count}- </span>- ))}- </div>+ <AgentTierBar tierCounts={git.agent.tier_counts} />)}</div>)}@@ -137,21 +125,12 @@ export function FileHistoryTab({ git, linkPrefix, partnerHref }: FileHistoryTabP{git.top_authors.length === 0 ? (<p className="text-xs text-[var(--color-text-tertiary)]">No author data.</p>) : (- <ul className="space-y-1">- {git.top_authors.slice(0, 6).map((a) => (- <li key={a.name} className="flex items-center justify-between gap-2">- <a- href={`${linkPrefix}/owners/${encodeURIComponent(a.name)}`}- className="text-xs text-[var(--color-text-primary)] hover:text-[var(--color-accent-primary)] hover:underline truncate"- >- {a.name}- </a>- <span className="text-[10px] tabular-nums text-[var(--color-text-tertiary)] shrink-0">- {a.commit_count} commits- </span>- </li>- ))}- </ul>+ <OwnershipDonut+ slices={git.top_authors.map((a) => ({+ name: a.name,+ value: a.commit_count,+ }))}+ />)}</CardContent></Card>@@ -166,17 +145,17 @@ export function FileHistoryTab({ git, linkPrefix, partnerHref }: FileHistoryTabPNo co-change partners detected.</p>) : (- <ul className="space-y-1">+ <ul className="space-y-2">{git.co_change_partners.slice(0, 8).map((p) => (<li key={p.file_path}><ahref={partnerHref(p.file_path)}- className="flex items-center justify-between gap-2 -mx-2 px-2 py-0.5 rounded hover:bg-[var(--color-bg-elevated)] transition-colors"+ className="flex items-center justify-between gap-2 -mx-2 px-2 py-1 rounded hover:bg-[var(--color-bg-elevated)] transition-colors">- <span className="text-[11px] font-mono text-[var(--color-text-primary)] truncate">+ <span className="font-mono text-xs text-[var(--color-text-primary)] truncate" title={p.file_path}>{truncatePath(p.file_path, 44)}</span>- <span className="text-[10px] tabular-nums text-[var(--color-text-tertiary)] shrink-0">+ <span className="text-xs tabular-nums text-[var(--color-text-tertiary)] shrink-0">×{p.co_change_count}</span></a>@@ -190,16 +169,3 @@ export function FileHistoryTab({ git, linkPrefix, partnerHref }: FileHistoryTabP</div>);}--function Stat({ label, value }: { label: string; value: number }) {- return (- <div className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-2.5">- <p className="text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)] mb-0.5">- {label}- </p>- <p className="text-base font-semibold tabular-nums text-[var(--color-text-primary)]">- {value}- </p>- </div>- );-}diff --git a/packages/ui/src/files/file-overview-tab.tsx b/packages/ui/src/files/file-overview-tab.tsxnew file mode 100644index 000000000..b0305eb05--- /dev/null+++ b/packages/ui/src/files/file-overview-tab.tsx@@ -0,0 +1,132 @@+import { ArrowRight, Code2, Network } from "lucide-react";+import type { FileDetailResponse } from "@repowise-dev/types/files";+import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";+import { Badge } from "../ui/badge";+import { StatGrid, StatTile } from "../shared/stat-grid";+import { scoreTextColor } from "../health/tokens";+import { truncatePath } from "../lib/format";++interface FileOverviewTabProps {+ data: FileDetailResponse;+ /** Build a symbol-page href. */+ symbolHref: (symbolId: string) => string;+ /** Build a file-page href. */+ fileHref: (path: string) => string;+}++/**+ * The default file tab: a compact health glance, key symbols, and an inline+ * dependency snapshot so undocumented files are never empty (the old default+ * landed on an empty "No documentation yet" Doc tab).+ */+export function FileOverviewTab({ data, symbolHref, fileHref }: FileOverviewTabProps) {+ const score = data.health.metric?.score;+ const deadLines = data.dead_code.reduce((s, f) => s + f.lines, 0);+ const keySymbols = [...data.symbols]+ .sort((a, b) => b.complexity_estimate - a.complexity_estimate)+ .slice(0, 8);++ return (+ <div className="space-y-4">+ {/* ── Health glance ── */}+ <StatGrid columns={4}>+ <StatTile+ label="Health"+ value={+ <span className={score != null ? scoreTextColor(score) : undefined}>+ {score != null ? `${score.toFixed(1)}/10` : "—"}+ </span>+ }+ />+ <StatTile+ label="Symbols"+ value={data.graph?.symbol_count ?? data.symbols.length}+ />+ <StatTile+ label="Dependencies"+ value={data.graph ? `${data.graph.in_degree} in · ${data.graph.out_degree} out` : "—"}+ />+ <StatTile+ label="Dead code"+ value={data.dead_code.length > 0 ? `${data.dead_code.length} (${deadLines} ln)` : "0"}+ />+ </StatGrid>++ {/* ── Key symbols ── */}+ {keySymbols.length > 0 && (+ <Card>+ <CardHeader className="pb-2">+ <CardTitle className="flex items-center gap-1.5 text-sm font-medium">+ <Code2 className="h-4 w-4 text-[var(--color-text-secondary)]" /> Key symbols+ </CardTitle>+ </CardHeader>+ <CardContent className="flex flex-wrap gap-1.5">+ {keySymbols.map((s) => (+ <a+ key={s.symbol_id}+ href={symbolHref(s.symbol_id)}+ className="inline-flex items-center gap-1 rounded border border-[var(--color-border-default)] px-2 py-0.5 font-mono text-xs text-[var(--color-text-secondary)] transition-colors hover:border-[var(--color-accent-primary)] hover:text-[var(--color-accent-primary)]"+ >+ {s.name}+ <span className="text-[10px] text-[var(--color-text-tertiary)]">{s.kind}</span>+ </a>+ ))}+ </CardContent>+ </Card>+ )}++ {/* ── Inline dependency snapshot ── */}+ {data.graph && (data.graph.dependents.length > 0 || data.graph.dependencies.length > 0) && (+ <Card>+ <CardHeader className="pb-2">+ <CardTitle className="flex items-center gap-1.5 text-sm font-medium">+ <Network className="h-4 w-4 text-[var(--color-text-secondary)]" /> Dependency snapshot+ </CardTitle>+ </CardHeader>+ <CardContent className="grid grid-cols-[1fr_auto_1fr] items-start gap-3">+ <div className="space-y-1">+ <p className="text-[10px] font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">+ Dependents ({data.graph.in_degree})+ </p>+ {data.graph.dependents.slice(0, 5).map((n) => (+ <a+ key={`in-${n.node_id}`}+ href={fileHref(n.node_id)}+ className="block truncate font-mono text-xs text-[var(--color-text-secondary)] hover:text-[var(--color-accent-primary)]"+ title={n.node_id}+ >+ {truncatePath(n.node_id, 30)}+ </a>+ ))}+ </div>+ <ArrowRight className="mt-5 h-4 w-4 text-[var(--color-text-tertiary)]" />+ <div className="space-y-1">+ <p className="text-[10px] font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">+ Dependencies ({data.graph.out_degree})+ </p>+ {data.graph.dependencies.slice(0, 5).map((n) => {+ const isSymbol = n.node_type === "symbol" || n.node_id.includes("::");+ return (+ <a+ key={`out-${n.node_id}`}+ href={isSymbol ? symbolHref(n.node_id) : fileHref(n.node_id)}+ className="block truncate font-mono text-xs text-[var(--color-text-secondary)] hover:text-[var(--color-accent-primary)]"+ title={n.node_id}+ >+ {truncatePath(n.node_id, 30)}+ </a>+ );+ })}+ </div>+ </CardContent>+ </Card>+ )}++ {data.graph?.is_entry_point && (+ <Badge variant="outline" className="text-[10px] text-[var(--color-info)] border-[var(--color-info)]/30">+ Entry point+ </Badge>+ )}+ </div>+ );+}diff --git a/packages/ui/src/files/file-page-tabs.ts b/packages/ui/src/files/file-page-tabs.tsindex 3fdea0103..b16f77b65 100644--- a/packages/ui/src/files/file-page-tabs.ts+++ b/packages/ui/src/files/file-page-tabs.ts@@ -1,4 +1,13 @@/** Tab ids for the file entity page. Lives outside the client component so- * server components can validate `?tab=` values without importing client code. */-export const FILE_PAGE_TABS = ["doc", "health", "history", "coverage", "graph"] as const;+ * server components can validate `?tab=` values without importing client code.+ * Order is the rendered tab order: Overview first so undocumented files are+ * never empty; Coverage last (often empty). */+export const FILE_PAGE_TABS = [+ "overview",+ "doc",+ "health",+ "history",+ "graph",+ "coverage",+] as const;export type FilePageTab = (typeof FILE_PAGE_TABS)[number];diff --git a/packages/ui/src/files/file-page.tsx b/packages/ui/src/files/file-page.tsxindex 182cbe71a..46c743c4a 100644--- a/packages/ui/src/files/file-page.tsx+++ b/packages/ui/src/files/file-page.tsx@@ -1,11 +1,14 @@"use client";import type { ReactNode } from "react";-import { Flame, DoorOpen, Trash2 } from "lucide-react";+import { Flame, DoorOpen, Trash2, Users } from "lucide-react";import { Badge } from "../ui/badge";import { Tabs, TabsContent, TabsList, TabsTrigger } from "../ui/tabs";import { scoreBadgeClass } from "../health/tokens";import { fileEntityPath, symbolEntityPath } from "../shared/entity/routes";+import { EntityHeader } from "../shared/entity";+import type { BreadcrumbSegment } from "../shared/breadcrumb";+import { FileOverviewTab } from "./file-overview-tab";import { FileDocTab } from "./file-doc-tab";import { FileHealthTab, type FindingStatus } from "./file-health-tab";import { FileHistoryTab } from "./file-history-tab";@@ -18,6 +21,12 @@ export interface FilePageProps {data: FileDetailResponse;repoId: string;linkPrefix?: string;+ breadcrumb?: BreadcrumbSegment[];+ LinkComponent?: React.ElementType<{+ href: string;+ className?: string;+ children: React.ReactNode;+ }>;/** Server-rendered wiki content for the Doc tab. */docSlot?: ReactNode;/** Shiki HTML with per-line data-covered attributes (Coverage tab). */@@ -30,15 +39,17 @@ export interface FilePageProps {}/**- * The canonical "everything about this file" page. Header (path, owner,- * health, signal chips, governing decisions) + Doc / Health / History /- * Coverage / Graph tabs. Purely presentational — data and callbacks come- * from the host; routing is plain hrefs built off `linkPrefix`.+ * The canonical "everything about this file" page. A standardized entity+ * header (eyebrow, breadcrumb, identity, summary, primary health signal,+ * owner pill, governing decisions) over Overview / Doc / Health / History /+ * Graph / Coverage tabs. Overview leads so undocumented files are never empty.*/export function FilePage({data,repoId,linkPrefix,+ breadcrumb,+ LinkComponent,docSlot,coverageCodeHtml,wikiHref,@@ -55,79 +66,91 @@ export function FilePage({const symbolHref = (s: string) => symbolEntityPath(prefix, s);const defaultTab: FilePageTab =- initialTab && FILE_PAGE_TABS.includes(initialTab) ? initialTab : "doc";+ initialTab && FILE_PAGE_TABS.includes(initialTab) ? initialTab : "overview";return (<div className="space-y-4">- {/* ── Header ── */}- <div className="space-y-2">- <h1- className="font-mono text-base sm:text-lg text-[var(--color-text-primary)] break-all"- title={data.file_path}- >- {data.file_path}- </h1>- <div className="flex flex-wrap items-center gap-2">- {score != null && (+ <EntityHeader+ eyebrow="FILE"+ breadcrumb={breadcrumb ?? []}+ identity={+ <span className="font-mono break-all" title={data.file_path}>+ {data.file_path}+ </span>+ }+ summary={fileSummary(data)}+ primarySignal={+ score != null ? (<spanclassName={`inline-flex items-baseline rounded px-2 py-0.5 text-sm font-bold tabular-nums ${scoreBadgeClass(score)}`}>{score.toFixed(1)}<span className="ml-0.5 text-[10px] font-normal opacity-70">/10</span></span>- )}- {language && (- <Badge variant="outline" className="text-[10px] h-5 capitalize">- {language}- </Badge>- )}- {data.graph?.is_entry_point && (- <Badge variant="outline" className="text-[10px] h-5 text-[var(--color-info)] border-[var(--color-info)]/30">- <DoorOpen className="h-2.5 w-2.5" /> entry point- </Badge>- )}- {data.git?.is_hotspot && (- <Badge variant="outline" className="text-[10px] h-5 text-[var(--color-error)] border-[var(--color-error)]/30">- <Flame className="h-2.5 w-2.5" /> hotspot- </Badge>- )}- {data.dead_code.length > 0 && (- <Badge variant="outline" className="text-[10px] h-5 text-[var(--color-warning)] border-[var(--color-warning)]/30">- <Trash2 className="h-2.5 w-2.5" /> {data.dead_code.length} dead ({deadLines} lines)- </Badge>- )}- {owner && (+ ) : undefined+ }+ metaBadges={+ <>+ {language && (+ <Badge variant="outline" className="h-5 text-[10px] capitalize">+ {language}+ </Badge>+ )}+ {data.graph?.is_entry_point && (+ <Badge variant="outline" className="h-5 text-[10px] text-[var(--color-info)] border-[var(--color-info)]/30">+ <DoorOpen className="h-2.5 w-2.5" /> entry point+ </Badge>+ )}+ {data.git?.is_hotspot && (+ <Badge variant="outline" className="h-5 text-[10px] text-[var(--color-error)] border-[var(--color-error)]/30">+ <Flame className="h-2.5 w-2.5" /> hotspot+ </Badge>+ )}+ {data.dead_code.length > 0 && (+ <Badge variant="outline" className="h-5 text-[10px] text-[var(--color-warning)] border-[var(--color-warning)]/30">+ <Trash2 className="h-2.5 w-2.5" /> {data.dead_code.length} dead ({deadLines} lines)+ </Badge>+ )}+ </>+ }+ people={+ owner ? (<ahref={`${prefix}/owners/${encodeURIComponent(owner)}`}- className="text-[11px] text-[var(--color-text-secondary)] hover:text-[var(--color-accent-primary)] hover:underline"+ className="inline-flex items-center gap-1 text-xs text-[var(--color-text-secondary)] hover:text-[var(--color-accent-primary)] hover:underline">+ <Users className="h-3.5 w-3.5 text-[var(--color-text-tertiary)]" />owned by <span className="font-medium">{owner}</span>{data.git?.primary_owner_commit_pct != null &&` (${Math.round(data.git.primary_owner_commit_pct * 100)}%)`}</a>- )}- </div>- {data.governing_decisions.length > 0 && (- <div className="flex flex-wrap items-center gap-1.5">- <span className="text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">- Governed by- </span>- {data.governing_decisions.map((d) => (- <a- key={d.id}- href={`${prefix}/decisions/${d.id}`}- className="rounded border border-[var(--color-border-default)] px-1.5 py-0.5 text-[11px] text-[var(--color-text-secondary)] hover:text-[var(--color-accent-primary)] hover:border-[var(--color-accent-primary)] transition-colors"- >- {d.title}- </a>- ))}- </div>- )}- </div>+ ) : undefined+ }+ decisions={+ data.governing_decisions.length > 0 ? (+ <div className="flex flex-wrap items-center gap-1.5">+ <span className="text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">+ Governed by+ </span>+ {data.governing_decisions.map((d) => (+ <a+ key={d.id}+ href={`${prefix}/decisions/${d.id}`}+ className="rounded border border-[var(--color-border-default)] px-1.5 py-0.5 text-xs text-[var(--color-text-secondary)] transition-colors hover:border-[var(--color-accent-primary)] hover:text-[var(--color-accent-primary)]"+ >+ {d.title}+ </a>+ ))}+ </div>+ ) : undefined+ }+ {...(LinkComponent ? { LinkComponent } : {})}+ />{/* ── Tabs ── */}<Tabs defaultValue={defaultTab} onValueChange={(v) => onTabChange?.(v as FilePageTab)}><TabsList className="flex-wrap">+ <TabsTrigger value="overview">Overview</TabsTrigger><TabsTrigger value="doc">Doc</TabsTrigger><TabsTrigger value="health">Health@@ -138,9 +161,12 @@ export function FilePage({)}</TabsTrigger><TabsTrigger value="history">History</TabsTrigger>- <TabsTrigger value="coverage">Coverage</TabsTrigger><TabsTrigger value="graph">Graph</TabsTrigger>+ <TabsTrigger value="coverage">Coverage</TabsTrigger></TabsList>+ <TabsContent value="overview" className="mt-4">+ <FileOverviewTab data={data} symbolHref={symbolHref} fileHref={fileHref} />+ </TabsContent><TabsContent value="doc" className="mt-4"><FileDocTab wikiPage={data.wiki_page} docSlot={docSlot} wikiHref={wikiHref} /></TabsContent>@@ -156,9 +182,6 @@ export function FilePage({<TabsContent value="history" className="mt-4"><FileHistoryTab git={data.git} linkPrefix={prefix} partnerHref={fileHref} /></TabsContent>- <TabsContent value="coverage" className="mt-4">- <FileCoverageTab coverage={data.coverage} coverageCodeHtml={coverageCodeHtml} />- </TabsContent><TabsContent value="graph" className="mt-4"><FileGraphTabgraph={data.graph}@@ -168,7 +191,23 @@ export function FilePage({symbolHref={symbolHref}/></TabsContent>+ <TabsContent value="coverage" className="mt-4">+ <FileCoverageTab coverage={data.coverage} coverageCodeHtml={coverageCodeHtml} />+ </TabsContent></Tabs></div>);}++/** Synthesised "what is this" one-liner for a file — wiki summary or fallback. */+function fileSummary(data: FileDetailResponse): string {+ const wiki = data.wiki_page?.summary?.trim();+ if (wiki) return wiki;+ const lang = data.graph?.language;+ const symbols = data.graph?.symbol_count ?? data.symbols.length;+ const name = data.file_path.split("/").pop() ?? data.file_path;+ const langPart = lang ? `${lang} ` : "";+ return `Undocumented ${langPart}file ${name}${+ symbols ? ` — ${symbols} symbol${symbols === 1 ? "" : "s"}` : ""+ }.`;+}diff --git a/packages/ui/src/files/index.ts b/packages/ui/src/files/index.tsindex 1cbb9aa57..d251b1761 100644--- a/packages/ui/src/files/index.ts+++ b/packages/ui/src/files/index.ts@@ -1,5 +1,6 @@export * from "./file-page";export * from "./file-page-tabs";+export * from "./file-overview-tab";export * from "./file-doc-tab";export * from "./file-health-tab";export * from "./file-history-tab";diff --git a/packages/ui/src/git/agent-tier-bar.tsx b/packages/ui/src/git/agent-tier-bar.tsxnew file mode 100644index 000000000..16838d747--- /dev/null+++ b/packages/ui/src/git/agent-tier-bar.tsx@@ -0,0 +1,72 @@+"use client";++import { cn } from "../lib/cn";++/**+ * Canonical autonomy-tier labels. The same numeric tiers surface on file+ * history, owner profiles, and commit detail — this is the single source so+ * the wording can't drift across those three surfaces.+ */+export const AGENT_TIER_LABELS: Record<string, string> = {+ "1": "autonomous",+ "2": "human-driven",+ "3": "assisted",+};++const TIER_TONE: Record<string, string> = {+ "1": "bg-[var(--color-accent-primary)]",+ "2": "bg-[var(--color-info)]",+ "3": "bg-[var(--color-accent-secondary)]",+};++const TIER_ORDER = ["1", "2", "3"];++export interface AgentTierBarProps {+ /** Map of autonomy tier ("1"|"2"|"3") → commit count. */+ tierCounts: Record<string, number>;+ className?: string;+}++/**+ * One stacked bar showing the mix of agent-autonomy tiers, replacing the+ * three different text-chip treatments that previously rendered the same+ * `tier_counts` data on file history, owner profiles, and commit detail.+ */+export function AgentTierBar({ tierCounts, className }: AgentTierBarProps) {+ const entries = TIER_ORDER.map((tier) => ({+ tier,+ count: tierCounts[tier] ?? 0,+ })).filter((e) => e.count > 0);++ const total = entries.reduce((s, e) => s + e.count, 0);+ if (total === 0) return null;++ return (+ <div className={cn("space-y-2", className)}>+ <div className="flex h-2 w-full overflow-hidden rounded-full bg-[var(--color-bg-inset)]">+ {entries.map((e) => (+ <div+ key={e.tier}+ className={cn("h-full", TIER_TONE[e.tier] ?? "bg-[var(--color-accent-primary)]")}+ style={{ width: `${(e.count / total) * 100}%` }}+ title={`${AGENT_TIER_LABELS[e.tier] ?? `tier ${e.tier}`}: ${e.count}`}+ />+ ))}+ </div>+ <div className="flex flex-wrap gap-x-3 gap-y-1 text-xs text-[var(--color-text-tertiary)]">+ {entries.map((e) => (+ <span key={e.tier} className="inline-flex items-center gap-1.5">+ <span+ className={cn(+ "h-2 w-2 rounded-full",+ TIER_TONE[e.tier] ?? "bg-[var(--color-accent-primary)]",+ )}+ />+ {AGENT_TIER_LABELS[e.tier] ?? `tier ${e.tier}`}+ <span className="tabular-nums text-[var(--color-text-secondary)]">{e.count}</span>+ </span>+ ))}+ </div>+ </div>+ );+}diff --git a/packages/ui/src/git/bus-factor-panel.tsx b/packages/ui/src/git/bus-factor-panel.tsxindex b7b75fe70..3197ba631 100644--- a/packages/ui/src/git/bus-factor-panel.tsx+++ b/packages/ui/src/git/bus-factor-panel.tsx@@ -78,13 +78,13 @@ export function BusFactorPanel({ hotspots, riskPreviewCount = 5 }: BusFactorPane</ResponsiveContainer><div className="flex items-center gap-4 mt-2 text-[10px] text-[var(--color-text-tertiary)]"><span className="flex items-center gap-1">- <span className="inline-block h-2 w-2 rounded-sm bg-green-500" /> Safe (≥3): {high}+ <span className="inline-block h-2 w-2 rounded-sm bg-[var(--color-success)]" /> Safe (≥3): {high}</span><span className="flex items-center gap-1">- <span className="inline-block h-2 w-2 rounded-sm bg-yellow-500" /> Warning (2): {medium}+ <span className="inline-block h-2 w-2 rounded-sm bg-[var(--color-warning)]" /> Warning (2): {medium}</span><span className="flex items-center gap-1">- <span className="inline-block h-2 w-2 rounded-sm bg-red-500" /> Risk (≤1): {low}+ <span className="inline-block h-2 w-2 rounded-sm bg-[var(--color-error)]" /> Risk (≤1): {low}</span></div></div>diff --git a/packages/ui/src/git/change-history-card.tsx b/packages/ui/src/git/change-history-card.tsxindex aa81fdee9..a06fb5262 100644--- a/packages/ui/src/git/change-history-card.tsx+++ b/packages/ui/src/git/change-history-card.tsx@@ -60,13 +60,13 @@ export function ChangeHistoryCard({{priorDefectCount != null && (<div className="flex items-center gap-1.5 text-xs"><Bug- className={`h-3 w-3 ${hasDefects ? "text-red-400" : "text-[var(--color-text-tertiary)]"}`}+ className={`h-3 w-3 ${hasDefects ? "text-[var(--color-error)]" : "text-[var(--color-text-tertiary)]"}`}/><span className="flex-1 text-[var(--color-text-tertiary)]">Bug-fix history</span><span- className={`tabular-nums ${hasDefects ? "text-red-400" : "text-[var(--color-text-secondary)]"}`}+ className={`tabular-nums ${hasDefects ? "text-[var(--color-error)]" : "text-[var(--color-text-secondary)]"}`}title="Bug-fix commits that touched this file in the trailing defect window.">{priorDefectCount} {priorDefectCount === 1 ? "fix" : "fixes"}diff --git a/packages/ui/src/git/churn-bar.tsx b/packages/ui/src/git/churn-bar.tsxindex 66ee9168a..011204792 100644--- a/packages/ui/src/git/churn-bar.tsx+++ b/packages/ui/src/git/churn-bar.tsx@@ -8,10 +8,10 @@ interface ChurnBarProps {export function ChurnBar({ percentile, className }: ChurnBarProps) {const color =percentile >= 75- ? "bg-red-500"+ ? "bg-[var(--color-error)]": percentile >= 50- ? "bg-yellow-500"- : "bg-green-500";+ ? "bg-[var(--color-warning)]"+ : "bg-[var(--color-success)]";return (<div className={cn("h-1.5 w-full rounded-full bg-[var(--color-bg-elevated)]", className)}>diff --git a/packages/ui/src/git/churn-vs-bus-factor-scatter.tsx b/packages/ui/src/git/churn-vs-bus-factor-scatter.tsxindex 7d2358b15..9d3a51134 100644--- a/packages/ui/src/git/churn-vs-bus-factor-scatter.tsx+++ b/packages/ui/src/git/churn-vs-bus-factor-scatter.tsx@@ -109,7 +109,7 @@ export function ChurnVsBusFactorScatter({return (<div className={cn("w-full space-y-2", className)}>- <div className="flex items-center justify-between text-[11px] text-[var(--color-text-tertiary)]">+ <div className="flex items-center justify-between text-xs text-[var(--color-text-tertiary)]"><span>{points.length} files plotted</span>@@ -117,8 +117,8 @@ export function ChurnVsBusFactorScatter({className={cn("inline-flex items-center gap-1 rounded px-1.5 py-0.5 tabular-nums",dangerCount > 0- ? "bg-red-500/15 text-red-400"- : "bg-green-500/15 text-green-400",+ ? "bg-[var(--color-error)]/15 text-[var(--color-error)]"+ : "bg-[var(--color-success)]/15 text-[var(--color-success)]",)}><span className="font-medium">{dangerCount}</span>@@ -138,7 +138,7 @@ export function ChurnVsBusFactorScatter({y={padding.top}width={innerW * 0.5}height={innerH * 0.5}- fill="rgba(244, 63, 94, 0.06)"+ fill="color-mix(in srgb, var(--color-error) 6%, transparent)"/>{/* Axes */}@@ -214,8 +214,8 @@ export function ChurnVsBusFactorScatter({const cx = padding.left + (p._x / 100) * innerW;const cy = padding.top + innerH - (p._y / 100) * innerH;const fill = p._danger- ? "rgba(244,63,94,0.7)"- : "rgba(245,158,11,0.45)";+ ? "color-mix(in srgb, var(--color-error) 70%, transparent)"+ : "color-mix(in srgb, var(--color-warning) 45%, transparent)";return (<g key={p.file_path}><circle@@ -223,7 +223,11 @@ export function ChurnVsBusFactorScatter({cy={cy}r={p._r}fill={fill}- stroke={p._danger ? "rgba(244,63,94,0.9)" : "rgba(0,0,0,0.2)"}+ stroke={+ p._danger+ ? "color-mix(in srgb, var(--color-error) 90%, transparent)"+ : "var(--color-border-default)"+ }strokeWidth={p._danger ? 1 : 0.5}onClick={onSelect ? () => onSelect(p.file_path) : undefined}style={{ cursor: onSelect ? "pointer" : "default" }}@@ -244,7 +248,7 @@ export function ChurnVsBusFactorScatter({same quadrant. */}</svg>{dangerPoints.length > 0 && (- <ul className="space-y-0.5 text-[11px]">+ <ul className="space-y-0.5 text-xs">{dangerPoints.map((p) => (<likey={`legend-${p.file_path}`}diff --git a/packages/ui/src/git/contributors-strip.tsx b/packages/ui/src/git/contributors-strip.tsxindex 40052bb50..73e3204bf 100644--- a/packages/ui/src/git/contributors-strip.tsx+++ b/packages/ui/src/git/contributors-strip.tsx@@ -59,7 +59,6 @@ export function ContributorsStrip({const shownPct = top.reduce((s, o) => s + (o.pct ?? 0), 0);const otherPct = Math.max(0, 100 - shownPct);const count = contributorCount ?? owners.length;- const lead = top[0];const hasProvenance =!!provenance && provenance.agentCommits > 0 && provenance.totalCommits > 0;@@ -73,13 +72,13 @@ export function ContributorsStrip({<span className="flex items-center gap-2"><Users className="h-4 w-4 text-[var(--color-accent-secondary)]" />Contributors- <span className="text-[11px] font-normal text-[var(--color-text-tertiary)] tabular-nums">+ <span className="text-xs font-normal text-[var(--color-text-tertiary)] tabular-nums">{count}</span></span><ahref={ownersHref}- className="inline-flex items-center gap-1 text-[11px] font-normal text-[var(--color-accent-primary)] hover:underline"+ className="inline-flex items-center gap-1 text-xs font-normal text-[var(--color-accent-primary)] hover:underline">View owners <ArrowRight className="h-3 w-3" /></a>@@ -104,7 +103,7 @@ export function ContributorsStrip({{top.slice(0, 4).map((o, i) => (<spankey={o.email ?? o.name}- className="flex items-center gap-1.5 text-[11px] text-[var(--color-text-secondary)] min-w-0"+ className="flex items-center gap-1.5 text-xs text-[var(--color-text-secondary)] min-w-0"><spanclassName="h-2 w-2 rounded-full shrink-0"@@ -117,29 +116,22 @@ export function ContributorsStrip({</span>))}{owners.length > 4 && (- <span className="text-[11px] text-[var(--color-text-tertiary)]">+ <span className="text-xs text-[var(--color-text-tertiary)]">+{owners.length - 4} more</span>)}</div>- {lead && (- <p className="text-[11px] text-[var(--color-text-tertiary)]">- {firstName(lead.name)} owns {Math.round(lead.pct)}% of files- {count > 1 ? ` across ${count} contributors` : ""}.- </p>- )}-{/* Agent provenance — only when there's something to report */}{hasProvenance && (<div className="mt-1 border-t border-[var(--color-border-default)] pt-2.5 space-y-2"><div className="flex items-center justify-between gap-2">- <span className="flex items-center gap-1.5 text-[11px] font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">+ <span className="flex items-center gap-1.5 text-xs font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]"><Bot className="h-3 w-3" />Authorship</span><ahref={commitsHref}- className="text-[11px] tabular-nums text-[var(--color-text-secondary)] hover:text-[var(--color-accent-primary)] transition-colors"+ className="text-xs tabular-nums text-[var(--color-text-secondary)] hover:text-[var(--color-accent-primary)] transition-colors"><span className="font-semibold text-[var(--color-accent-primary)]">{Math.round(provenance!.agentPct)}%@@ -159,7 +151,7 @@ export function ContributorsStrip({title={`Agents — ${Math.round(provenance!.agentPct)}%`}/></div>- <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[11px] text-[var(--color-text-secondary)]">+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-[var(--color-text-secondary)]"><span className="flex items-center gap-1.5"><span className="h-2 w-2 rounded-full bg-[var(--color-text-tertiary)]" />Humandiff --git a/packages/ui/src/git/hotspot-table.tsx b/packages/ui/src/git/hotspot-table.tsxindex 72779e33d..281ebbe30 100644--- a/packages/ui/src/git/hotspot-table.tsx+++ b/packages/ui/src/git/hotspot-table.tsx@@ -280,9 +280,9 @@ export function HotspotTable({{h.commit_count_90d}</span>{accelerating ? (- <TrendingUp className="h-3 w-3 text-red-500" />+ <TrendingUp className="h-3 w-3 text-[var(--color-error)]" />) : (- <TrendingDown className="h-3 w-3 text-green-500" />+ <TrendingDown className="h-3 w-3 text-[var(--color-success)]" />)}</span></td>@@ -298,7 +298,7 @@ export function HotspotTable({<span className="inline-flex items-center justify-end gap-1">{trendScore != null ? (<>- <Flame className={cn("h-3 w-3 shrink-0", trendScore >= 5 ? "text-red-500" : trendScore >= 2 ? "text-orange-400" : "text-[var(--color-text-tertiary)]")} />+ <Flame className={cn("h-3 w-3 shrink-0", trendScore >= 5 ? "text-[var(--color-error)]" : trendScore >= 2 ? "text-[var(--color-warning)]" : "text-[var(--color-text-tertiary)]")} /><span className="text-[var(--color-text-secondary)]">{trendScore.toFixed(2)}</span>@@ -312,19 +312,19 @@ export function HotspotTable({<spanclassName={`inline-flex items-center justify-center rounded px-1.5 py-0.5 text-xs font-medium tabular-nums ${h.bus_factor <= 1- ? "bg-red-500/15 text-red-400"+ ? "bg-[var(--color-error)]/15 text-[var(--color-error)]": h.bus_factor === 2- ? "bg-yellow-500/15 text-yellow-400"- : "bg-green-500/15 text-green-400"+ ? "bg-[var(--color-warning)]/15 text-[var(--color-warning)]"+ : "bg-[var(--color-success)]/15 text-[var(--color-success)]"}`}>{h.bus_factor}</span></td><td className="px-3 py-2.5 text-xs tabular-nums hidden lg:table-cell">- <span className="text-green-400">+{formatLOC(h.lines_added_90d)}</span>+ <span className="text-[var(--color-success)]">+{formatLOC(h.lines_added_90d)}</span>{" "}- <span className="text-red-400">-{formatLOC(h.lines_deleted_90d)}</span>+ <span className="text-[var(--color-error)]">-{formatLOC(h.lines_deleted_90d)}</span></td><td className="px-3 py-2.5 text-xs text-[var(--color-text-secondary)] hidden md:table-cell">{h.primary_owner ?? "—"}diff --git a/packages/ui/src/git/hotspot-trend-strip.tsx b/packages/ui/src/git/hotspot-trend-strip.tsxindex e65637980..0d2124a4d 100644--- a/packages/ui/src/git/hotspot-trend-strip.tsx+++ b/packages/ui/src/git/hotspot-trend-strip.tsx@@ -83,7 +83,7 @@ export function HotspotTrendStrip({><TrendBadge trend={trend} /><span- className="flex-1 truncate font-mono text-[11px] text-[var(--color-text-primary)]"+ className="flex-1 truncate font-mono text-xs text-[var(--color-text-primary)]"title={h.file_path}>{h.file_path}@@ -92,7 +92,7 @@ export function HotspotTrendStrip({{Math.round(h.churn_percentile)}th %ile</span>{h.bus_factor <= 1 && (- <span className="shrink-0 rounded-full border border-red-500/40 bg-red-500/10 px-1.5 py-0.5 text-[10px] font-medium text-red-300">+ <span className="shrink-0 rounded-full border border-[var(--color-error)]/40 bg-[var(--color-error)]/10 px-1.5 py-0.5 text-[10px] font-medium text-[var(--color-error)]">bus×1</span>)}@@ -107,14 +107,14 @@ export function HotspotTrendStrip({function TrendBadge({ trend }: { trend: Trend }) {if (trend === "heating") {return (- <span className="inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-rose-500/15 text-rose-400">+ <span className="inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-[var(--color-error)]/15 text-[var(--color-error)]"><TrendingUp className="h-3 w-3" /></span>);}if (trend === "cooling") {return (- <span className="inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-emerald-500/15 text-emerald-400">+ <span className="inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-[var(--color-success)]/15 text-[var(--color-success)]"><TrendingDown className="h-3 w-3" /></span>);diff --git a/packages/ui/src/git/index.ts b/packages/ui/src/git/index.tsindex fab91a44d..050eb7140 100644--- a/packages/ui/src/git/index.ts+++ b/packages/ui/src/git/index.ts@@ -1,3 +1,4 @@+export * from "./agent-tier-bar";export * from "./bus-factor-panel";export * from "./change-history-card";export * from "./churn-bar";@@ -9,6 +10,7 @@ export * from "./contributor-bar";export * from "./contributors-strip";export * from "./contributor-network";export * from "./hotspot-table";+export * from "./ownership-donut";export * from "./ownership-table";export * from "./ownership-treemap";export * from "./risk-distribution-chart";diff --git a/packages/ui/src/git/ownership-donut.tsx b/packages/ui/src/git/ownership-donut.tsxnew file mode 100644index 000000000..37878e137--- /dev/null+++ b/packages/ui/src/git/ownership-donut.tsx@@ -0,0 +1,119 @@+"use client";++import { PieChart, Pie, Cell, Tooltip, ResponsiveContainer } from "recharts";+import { EmptyState } from "../shared/empty-state";++export interface OwnershipDonutSlice {+ name: string;+ value: number;+}++interface OwnershipDonutProps {+ /** Contributors (or any ownership shares) — largest first is not required. */+ slices: OwnershipDonutSlice[];+ /** Max slices before the remainder collapses into an "Others" wedge. */+ maxSlices?: number;+}++const SLICE_COLORS = [+ "var(--color-accent-primary)",+ "var(--color-info)",+ "var(--color-accent-secondary)",+ "var(--color-success)",+ "var(--color-warning)",+ "var(--color-accent-fill)",+];+const OTHERS_COLOR = "var(--color-text-tertiary)";++/**+ * Ownership concentration as a donut — shows at a glance whether a file is+ * owned by one person (bus-factor risk) or shared. Replaces the plain+ * "Top authors" count list.+ */+export function OwnershipDonut({ slices, maxSlices = 5 }: OwnershipDonutProps) {+ const sorted = [...slices].filter((s) => s.value > 0).sort((a, b) => b.value - a.value);+ const total = sorted.reduce((s, d) => s + d.value, 0);++ if (total === 0) {+ return (+ <EmptyState title="No author data" description="Author attribution appears after the next git sync." />+ );+ }++ const head = sorted.slice(0, maxSlices);+ const restTotal = sorted.slice(maxSlices).reduce((s, d) => s + d.value, 0);+ const data = restTotal > 0 ? [...head, { name: "Others", value: restTotal }] : head;+ const top = sorted[0]!;++ return (+ <div className="flex items-center gap-4">+ <div className="relative flex shrink-0 items-center justify-center">+ <ResponsiveContainer width={140} height={140}>+ <PieChart>+ <Pie+ data={data}+ cx="50%"+ cy="50%"+ innerRadius={40}+ outerRadius={62}+ paddingAngle={2}+ dataKey="value"+ startAngle={90}+ endAngle={-270}+ >+ {data.map((entry, i) => (+ <Cell+ key={entry.name}+ fill={+ entry.name === "Others"+ ? OTHERS_COLOR+ : SLICE_COLORS[i % SLICE_COLORS.length] ?? OTHERS_COLOR+ }+ strokeWidth={0}+ />+ ))}+ </Pie>+ <Tooltip+ contentStyle={{+ background: "var(--color-bg-overlay)",+ border: "1px solid var(--color-border-default)",+ borderRadius: "6px",+ fontSize: "12px",+ color: "var(--color-text-primary)",+ }}+ formatter={(value, name) => {+ const n = typeof value === "number" ? value : 0;+ return [`${n} commits (${Math.round((n / total) * 100)}%)`, name];+ }}+ />+ </PieChart>+ </ResponsiveContainer>+ <div className="pointer-events-none absolute flex flex-col items-center">+ <span className="text-lg font-bold tabular-nums text-[var(--color-text-primary)]">+ {Math.round((top.value / total) * 100)}%+ </span>+ <span className="text-[10px] text-[var(--color-text-tertiary)]">top owner</span>+ </div>+ </div>+ <ul className="min-w-0 flex-1 space-y-1 text-xs">+ {data.map((entry, i) => (+ <li key={entry.name} className="flex items-center gap-2">+ <span+ className="h-2 w-2 shrink-0 rounded-full"+ style={{+ backgroundColor:+ entry.name === "Others"+ ? OTHERS_COLOR+ : SLICE_COLORS[i % SLICE_COLORS.length] ?? OTHERS_COLOR,+ }}+ />+ <span className="truncate text-[var(--color-text-primary)]">{entry.name}</span>+ <span className="ml-auto shrink-0 tabular-nums text-[var(--color-text-tertiary)]">+ {Math.round((entry.value / total) * 100)}%+ </span>+ </li>+ ))}+ </ul>+ </div>+ );+}diff --git a/packages/ui/src/git/ownership-treemap.tsx b/packages/ui/src/git/ownership-treemap.tsxindex 84127bc42..0a786957c 100644--- a/packages/ui/src/git/ownership-treemap.tsx+++ b/packages/ui/src/git/ownership-treemap.tsx@@ -213,17 +213,17 @@ export function OwnershipTreemap({ entries, busFactorByModule, onSelect }: Owner<pclassName={tooltip.busFactor <= 1- ? "text-red-400 font-medium mt-0.5"+ ? "text-[var(--color-error)] font-medium mt-0.5": tooltip.busFactor === 2- ? "text-amber-300 font-medium mt-0.5"- : "text-emerald-300 mt-0.5"+ ? "text-[var(--color-warning)] font-medium mt-0.5"+ : "text-[var(--color-success)] mt-0.5"}>Bus factor: {tooltip.busFactor}</p>)}{tooltip.isSilo && (- <p className="text-yellow-400 font-medium mt-0.5">Silo risk</p>+ <p className="text-[var(--color-warning)] font-medium mt-0.5">Silo risk</p>)}</div>)}diff --git a/packages/ui/src/graph/centrality-leaderboard.tsx b/packages/ui/src/graph/centrality-leaderboard.tsxindex e4de11ba9..330370729 100644--- a/packages/ui/src/graph/centrality-leaderboard.tsx+++ b/packages/ui/src/graph/centrality-leaderboard.tsx@@ -60,7 +60,7 @@ export function CentralityLeaderboard({<div className="flex items-center justify-between gap-2 border-b border-[var(--color-border-default)] px-2 py-2">{!collapsed && (<div className="flex items-center gap-1.5 min-w-0">- <Crown className="h-3.5 w-3.5 text-yellow-500 shrink-0" />+ <Crown className="h-3.5 w-3.5 text-[var(--color-warning)] shrink-0" /><span className="text-xs font-medium text-[var(--color-text-primary)] truncate">Centrality</span>@@ -116,7 +116,7 @@ export function CentralityLeaderboard({{i + 1}</span><div className="min-w-0 flex-1">- <p className="text-[11px] font-mono text-[var(--color-text-primary)] truncate">+ <p className="text-xs font-mono text-[var(--color-text-primary)] truncate">{n.label ?? n.node_id}</p><div className="mt-0.5 h-1 rounded-full bg-[var(--color-bg-inset)] overflow-hidden">@@ -134,7 +134,7 @@ export function CentralityLeaderboard({);})}{ranked.length === 0 && (- <li className="px-3 py-4 text-[11px] text-[var(--color-text-tertiary)] text-center">+ <li className="px-3 py-4 text-xs text-[var(--color-text-tertiary)] text-center">No graph metrics yet.</li>)}diff --git a/packages/ui/src/graph/graph-canvas-shell.tsx b/packages/ui/src/graph/graph-canvas-shell.tsxnew file mode 100644index 000000000..9e7d67eac--- /dev/null+++ b/packages/ui/src/graph/graph-canvas-shell.tsx@@ -0,0 +1,66 @@+"use client";++import * as React from "react";+import { cn } from "../lib/cn";++export interface GraphCanvasShellProps {+ /** Optional one-line title rendered above the canvas (no second header band). */+ title?: string;+ /** Optional one-line description under the title. */+ description?: string;+ /** Right-aligned slot in the title row (e.g. a hint or a single action). */+ titleActions?: React.ReactNode;+ /** A full-width banner slot above the canvas (e.g. truncation notice). */+ banner?: React.ReactNode;+ /** The canvas itself (Sigma / ReactFlow host). Fills the remaining height. */+ children: React.ReactNode;+ /** Overlays drawn on top of the canvas (panels, doc rails, modals). */+ overlay?: React.ReactNode;+ className?: string;+}++/**+ * The single airy canvas container for every graph surface (Communities,+ * Explore, the Knowledge Graph layers route, and Coupling). Replaces the+ * per-view `rounded-lg border` frame and the double-header pattern: it owns at+ * most ONE thin title row and lets the diagram breathe with no box outline or+ * background fill behind it.+ */+export function GraphCanvasShell({+ title,+ description,+ titleActions,+ banner,+ children,+ overlay,+ className,+}: GraphCanvasShellProps) {+ return (+ <div className={cn("flex h-full flex-col", className)}>+ {(title || description || titleActions) && (+ <div className="flex shrink-0 flex-wrap items-start justify-between gap-2 px-4 pt-3 sm:px-6">+ <div className="min-w-0">+ {title && (+ <h2 className="text-sm font-semibold text-[var(--color-text-primary)]">+ {title}+ </h2>+ )}+ {description && (+ <p className="mt-0.5 text-xs text-[var(--color-text-secondary)]">+ {description}+ </p>+ )}+ </div>+ {titleActions && (+ <div className="flex shrink-0 items-center gap-2">{titleActions}</div>+ )}+ </div>+ )}+ {banner && <div className="shrink-0 px-4 pt-3 sm:px-6">{banner}</div>}+ <div className="relative min-h-0 flex-1 overflow-hidden">+ {children}+ {overlay}+ </div>+ </div>+ );+}diff --git a/packages/ui/src/graph/graph-community-panel.tsx b/packages/ui/src/graph/graph-community-panel.tsxindex f57b6c3bb..bb051c17c 100644--- a/packages/ui/src/graph/graph-community-panel.tsx+++ b/packages/ui/src/graph/graph-community-panel.tsx@@ -58,7 +58,7 @@ export function GraphCommunityPanel({<div className="px-4 py-2 border-b border-[var(--color-border-default)]"><buttononClick={onExpandOnCanvas}- className="flex w-full items-center justify-center gap-1.5 rounded-md border border-[var(--color-border-default)] px-2 py-1.5 text-[11px] text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)] transition-colors"+ className="flex w-full items-center justify-center gap-1.5 rounded-md border border-[var(--color-border-default)] px-2 py-1.5 text-xs text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)] transition-colors"><Sparkles className="h-3 w-3" />Expand on canvas@@ -79,7 +79,7 @@ export function GraphCommunityPanel({<div className="p-4 space-y-4">{/* Members */}<div>- <p className="text-[11px] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-2">+ <p className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-2">Members ({community.member_count})</p><div className="space-y-1">@@ -96,13 +96,13 @@ export function GraphCommunityPanel({{memberHref ? (<ahref={memberHref(m.path)}- className="block text-[11px] font-mono text-[var(--color-text-primary)] truncate hover:text-[var(--color-accent-primary)] hover:underline"+ className="block text-xs font-mono text-[var(--color-text-primary)] truncate hover:text-[var(--color-accent-primary)] hover:underline"title={m.path}>{truncatePath(m.path)}</a>) : (- <p className="text-[11px] font-mono text-[var(--color-text-primary)] truncate" title={m.path}>+ <p className="text-xs font-mono text-[var(--color-text-primary)] truncate" title={m.path}>{truncatePath(m.path)}</p>)}@@ -133,7 +133,7 @@ export function GraphCommunityPanel({{/* Neighboring Communities */}{community.neighboring_communities.length > 0 && (<div>- <p className="text-[11px] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-2">+ <p className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-2">Neighboring Communities</p><div className="space-y-1">@@ -144,11 +144,11 @@ export function GraphCommunityPanel({><div className="flex items-center gap-1.5 min-w-0"><ArrowRight className="h-3 w-3 shrink-0 text-[var(--color-text-tertiary)]" />- <span className="text-[11px] text-[var(--color-text-primary)] truncate">+ <span className="text-xs text-[var(--color-text-primary)] truncate">{n.label}</span></div>- <Badge variant="outline" className="text-[9px] shrink-0 h-4">+ <Badge variant="outline" className="text-[10px] shrink-0 h-4">{n.cross_edge_count} edges</Badge></div>diff --git a/packages/ui/src/graph/graph-context-drawer.tsx b/packages/ui/src/graph/graph-context-drawer.tsxindex 153a77a6d..1696edbe3 100644--- a/packages/ui/src/graph/graph-context-drawer.tsx+++ b/packages/ui/src/graph/graph-context-drawer.tsx@@ -164,7 +164,7 @@ export function GraphContextDrawer({key={tab.id}value={tab.id}disabled={tab.disabled}- className="rounded-md px-2 py-1 text-[11px] font-medium data-[state=active]:bg-[var(--color-bg-inset)] data-[state=active]:text-[var(--color-text-primary)]"+ className="rounded-md px-2 py-1 text-xs font-medium data-[state=active]:bg-[var(--color-bg-inset)] data-[state=active]:text-[var(--color-text-primary)]">{tab.label}</TabsTrigger>@@ -208,7 +208,7 @@ export interface GraphDrawerActionsProps {export function GraphDrawerActions({ actions }: GraphDrawerActionsProps) {if (actions.length === 0) {return (- <p className="text-[11px] text-[var(--color-text-tertiary)]">+ <p className="text-xs text-[var(--color-text-tertiary)]">No actions available for this node.</p>);@@ -224,7 +224,7 @@ export function GraphDrawerActions({ actions }: GraphDrawerActionsProps) {{a.label}</span>{a.description && (- <span className="block text-[11px] text-[var(--color-text-tertiary)]">+ <span className="block text-xs text-[var(--color-text-tertiary)]">{a.description}</span>)}diff --git a/packages/ui/src/graph/graph-flow.tsx b/packages/ui/src/graph/graph-flow.tsxindex 0edf8a873..6dd903d4b 100644--- a/packages/ui/src/graph/graph-flow.tsx+++ b/packages/ui/src/graph/graph-flow.tsx@@ -40,7 +40,7 @@ import { useGraphContextMenu } from "./use-graph-context-menu";import { useGraphSearch } from "./use-graph-search";import { useCommunityFilter } from "./use-community-filter";import { useGraphKeyboardShortcuts } from "./use-graph-keyboard-shortcuts";-import { GraphToolbar, type ColorMode, type ViewMode, type LayoutMode, type GraphTheme } from "./graph-toolbar";+import { GraphToolbar, type ColorMode, type ViewMode, type LayoutMode, type GraphTheme, type Scope } from "./graph-toolbar";import { GraphLegend } from "./graph-legend";import { GraphContextMenu } from "./graph-context-menu";import { GraphInspectionPanel } from "./graph-inspection-panel";@@ -137,6 +137,10 @@ export interface GraphFlowProps {* hosting page dismiss any competing right-rail panel (doc panel etc.)* so the right side is a single sidebar. */onCommunityPanelOpen?: (communityId: number) => void;+ /** Restricts the toolbar's scope cluster. Explore passes `["modules","full"]`+ * so the constellation scope (now the Knowledge Graph view's Communities+ * lens) is not reachable from here. Defaults to all scopes. */+ availableScopes?: Scope[];}export function GraphFlow(props: GraphFlowProps) {@@ -170,6 +174,7 @@ export function GraphFlow(props: GraphFlowProps) {renderPathFinder,renderCommunityPanel,onCommunityPanelOpen,+ availableScopes,} = props;const sigmaRef = useRef<SigmaCanvasHandle>(null);@@ -1079,7 +1084,7 @@ export function GraphFlow(props: GraphFlowProps) {<div className="flex items-center gap-1 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]/90 backdrop-blur-sm px-2.5 py-1.5 shadow-lg shadow-black/20"><buttononClick={() => handleBreadcrumbClick(-1)}- className="flex items-center gap-1 text-[11px] text-[var(--color-text-tertiary)] hover:text-[var(--color-accent-graph)] transition-colors"+ className="flex items-center gap-1 text-xs text-[var(--color-text-tertiary)] hover:text-[var(--color-accent-graph)] transition-colors"><Home className="w-3 h-3" /><span>Root</span>@@ -1093,7 +1098,7 @@ export function GraphFlow(props: GraphFlowProps) {<ChevronRight className="w-3 h-3 text-[var(--color-text-tertiary)]" /><buttononClick={() => !isLast && handleBreadcrumbClick(i)}- className={`text-[11px] font-mono transition-colors ${+ className={`text-xs font-mono transition-colors ${isLast? "text-[var(--color-text-primary)] font-medium cursor-default": "text-[var(--color-text-tertiary)] hover:text-[var(--color-accent-graph)]"@@ -1148,6 +1153,7 @@ export function GraphFlow(props: GraphFlowProps) {graphTheme={graphTheme}onGraphThemeChange={handleGraphThemeChange}onToggleHelp={handleToggleShortcutHelp}+ availableScopes={availableScopes}/></div>@@ -1169,7 +1175,7 @@ export function GraphFlow(props: GraphFlowProps) {<div className="absolute top-14 right-3 z-10 w-[min(16rem,calc(100vw-1.5rem))]"><div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]/95 backdrop-blur-sm shadow-lg shadow-black/20 p-3"><div className="flex items-center justify-between mb-2">- <span className="text-[11px] font-medium text-[var(--color-text-primary)]">+ <span className="text-xs font-medium text-[var(--color-text-primary)]">Execution Flows</span><span className="text-[10px] text-[var(--color-text-tertiary)]">@@ -1181,7 +1187,7 @@ export function GraphFlow(props: GraphFlowProps) {<buttonkey={flow.entry_point}onClick={() => setActiveFlowIdx(activeFlowIdx === idx ? null : idx)}- className={`w-full text-left px-2 py-1.5 rounded-md text-[11px] transition-colors ${+ className={`w-full text-left px-2 py-1.5 rounded-md text-xs transition-colors ${activeFlowIdx === idx? "bg-[var(--color-accent-primary)]/15 text-[var(--color-accent-primary)]": "text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-overlay)] hover:text-[var(--color-text-primary)]"diff --git a/packages/ui/src/graph/graph-inspection-panel.tsx b/packages/ui/src/graph/graph-inspection-panel.tsxindex 6f6de463a..a3ce8db35 100644--- a/packages/ui/src/graph/graph-inspection-panel.tsx+++ b/packages/ui/src/graph/graph-inspection-panel.tsx@@ -191,7 +191,7 @@ export const GraphInspectionPanel = memo(function GraphInspectionPanel({{/* Neighbors */}{neighbors.length > 0 && (<div className="border-t border-[var(--color-border-default)] pt-3">- <p className="text-[11px] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-2">+ <p className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-2">{isMod ? "Connected Modules" : "Neighbors"} ({neighbors.length})</p><div className="space-y-0.5 max-h-48 overflow-y-auto">@@ -206,11 +206,11 @@ export const GraphInspectionPanel = memo(function GraphInspectionPanel({style={{ background: communityFamily(n.communityId).hub }}/><div className="min-w-0 flex-1">- <p className="text-[11px] font-mono text-[var(--color-text-secondary)] group-hover:text-[var(--color-text-primary)] truncate">+ <p className="text-xs font-mono text-[var(--color-text-secondary)] group-hover:text-[var(--color-text-primary)] truncate">{n.label}</p></div>- <span className="text-[9px] text-[var(--color-text-tertiary)] shrink-0">+ <span className="text-[10px] text-[var(--color-text-tertiary)] shrink-0">{n.direction === "importer" ? "imports this" : "imported"}</span></button>@@ -228,13 +228,13 @@ export const GraphInspectionPanel = memo(function GraphInspectionPanel({Ego Graph</span>{egoDepth != null && egoDepth > 0 && egoVisibleCount != null && (- <span className="text-[9px] text-[var(--color-text-tertiary)] tabular-nums">+ <span className="text-[10px] text-[var(--color-text-tertiary)] tabular-nums">{egoVisibleCount} nodes</span>)}</div><div className="flex items-center gap-2">- <span className="text-[9px] text-[var(--color-text-tertiary)] w-4 text-right tabular-nums">+ <span className="text-[10px] text-[var(--color-text-tertiary)] w-4 text-right tabular-nums">{egoDepth ?? 0}</span><input@@ -246,9 +246,9 @@ export const GraphInspectionPanel = memo(function GraphInspectionPanel({className="flex-1 h-1 accent-[var(--color-accent-graph)] cursor-pointer"aria-label="Ego graph depth"/>- <span className="text-[9px] text-[var(--color-text-tertiary)]">5</span>+ <span className="text-[10px] text-[var(--color-text-tertiary)]">5</span></div>- <p className="text-[9px] text-[var(--color-text-tertiary)] mt-1">+ <p className="text-[10px] text-[var(--color-text-tertiary)] mt-1">{(egoDepth ?? 0) === 0? "Slide to filter by hop distance": `Showing nodes within ${egoDepth} hop${egoDepth === 1 ? "" : "s"}`}@@ -391,16 +391,16 @@ function FileMetadata({</span>)}{data.isTest && (- <span className="inline-flex items-center gap-1 rounded-md bg-purple-500/10 text-purple-400 px-1.5 py-0.5 text-[10px] font-medium">+ <span className="inline-flex items-center gap-1 rounded-md bg-[var(--color-accent-secondary)]/10 text-[var(--color-accent-secondary)] px-1.5 py-0.5 text-[10px] font-medium"><FlaskConical className="w-2.5 h-2.5" /> Test</span>)}{data.hasDoc ? (- <span className="inline-flex items-center gap-1 rounded-md bg-green-500/10 text-green-400 px-1.5 py-0.5 text-[10px] font-medium">+ <span className="inline-flex items-center gap-1 rounded-md bg-[var(--color-success)]/10 text-[var(--color-success)] px-1.5 py-0.5 text-[10px] font-medium"><BookOpen className="w-2.5 h-2.5" /> Documented</span>) : (- <span className="inline-flex items-center gap-1 rounded-md bg-slate-500/10 text-slate-400 px-1.5 py-0.5 text-[10px] font-medium">+ <span className="inline-flex items-center gap-1 rounded-md bg-[var(--color-bg-inset)] text-[var(--color-text-tertiary)] px-1.5 py-0.5 text-[10px] font-medium"><BookOpen className="w-2.5 h-2.5" /> No docs</span>)}diff --git a/packages/ui/src/graph/graph-legend.tsx b/packages/ui/src/graph/graph-legend.tsxindex d24e30824..c4b81e8a1 100644--- a/packages/ui/src/graph/graph-legend.tsx+++ b/packages/ui/src/graph/graph-legend.tsx@@ -65,7 +65,7 @@ export const GraphLegend = memo(function GraphLegend({const entries = allEntries.slice(0, 12);const overflow = allEntries.length - entries.length;return (- <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)]/80 backdrop-blur-sm text-xs shadow-lg shadow-black/20 min-w-[160px] max-w-[220px]">+ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)]/80 backdrop-blur-sm text-xs shadow-sm min-w-[160px] max-w-[220px]"><buttononClick={() => setExpanded((s) => !s)}className="flex items-center justify-between w-full px-2.5 py-2 text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] transition-colors"@@ -81,8 +81,8 @@ export const GraphLegend = memo(function GraphLegend({</button>{expanded && (<div className="px-2.5 pb-2.5 space-y-1 border-t border-[var(--color-border-default)] pt-2">- <p className="text-[9px] text-[var(--color-text-tertiary)] uppercase tracking-wider font-medium">- Knowledge Graph+ <p className="text-[10px] text-[var(--color-text-tertiary)] uppercase tracking-wider font-medium">+ Communities</p>{entries.length === 0 && (<p className="text-[10px] text-[var(--color-text-tertiary)]">@@ -102,7 +102,7 @@ export const GraphLegend = memo(function GraphLegend({style={{ background: color }}/><span className="truncate flex-1">{e.label}</span>- <span className="tabular-nums text-[9px] shrink-0">{e.memberCount}</span>+ <span className="tabular-nums text-[10px] shrink-0">{e.memberCount}</span></button>);})}@@ -112,7 +112,7 @@ export const GraphLegend = memo(function GraphLegend({listed</p>)}- <p className="text-[9px] text-[var(--color-text-tertiary)] pt-1.5 border-t border-[var(--color-border-default)]">+ <p className="text-[10px] text-[var(--color-text-tertiary)] pt-1.5 border-t border-[var(--color-border-default)]">Inner ring = entry surface</p></div>@@ -122,7 +122,7 @@ export const GraphLegend = memo(function GraphLegend({}return (- <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)]/80 backdrop-blur-sm text-xs shadow-lg shadow-black/20 min-w-[120px] max-w-[150px]">+ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)]/80 backdrop-blur-sm text-xs shadow-sm min-w-[120px] max-w-[150px]"><buttononClick={() => setExpanded((s) => !s)}className="flex items-center justify-between w-full px-2.5 py-2 text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] transition-colors"@@ -139,7 +139,7 @@ export const GraphLegend = memo(function GraphLegend({{expanded && (<div className="px-2.5 pb-2.5 space-y-1.5 border-t border-[var(--color-border-default)] pt-2">- <p className="text-[9px] text-[var(--color-text-tertiary)] uppercase tracking-wider font-medium">+ <p className="text-[10px] text-[var(--color-text-tertiary)] uppercase tracking-wider font-medium">{colorMode === "language" ? "Language" : colorMode === "community" ? "Community" : "Risk"}</p>@@ -166,7 +166,7 @@ export const GraphLegend = memo(function GraphLegend({{onToggleAllCommunities && entries && (<buttononClick={() => onToggleAllCommunities(!allSelected)}- className="text-[9px] text-[var(--color-accent-graph)] hover:underline mb-0.5"+ className="text-[10px] text-[var(--color-accent-graph)] hover:underline mb-0.5">{allSelected ? "Deselect All" : "Select All"}</button>@@ -242,7 +242,7 @@ export const GraphLegend = memo(function GraphLegend({{onEdgeTypeToggle && visibleEdgeTypes && (<>- <p className="text-[9px] text-[var(--color-text-tertiary)] uppercase tracking-wider font-medium pt-1.5 border-t border-[var(--color-border-default)] mt-1.5">+ <p className="text-[10px] text-[var(--color-text-tertiary)] uppercase tracking-wider font-medium pt-1.5 border-t border-[var(--color-border-default)] mt-1.5">Edges</p>{([@@ -274,7 +274,7 @@ export const GraphLegend = memo(function GraphLegend({)}{viewMode !== "module" && viewMode !== "full" && (- <p className="text-[9px] text-[var(--color-text-tertiary)] pt-1 border-t border-[var(--color-border-default)]">+ <p className="text-[10px] text-[var(--color-text-tertiary)] pt-1 border-t border-[var(--color-border-default)]">{viewMode === "dead" && "Showing unreachable files"}{viewMode === "hotfiles" && "Most-committed files (30d)"}{viewMode === "unified" && "Unified: community + risk signals"}diff --git a/packages/ui/src/graph/graph-toolbar.tsx b/packages/ui/src/graph/graph-toolbar.tsxindex d208d4551..0c501a9cd 100644--- a/packages/ui/src/graph/graph-toolbar.tsx+++ b/packages/ui/src/graph/graph-toolbar.tsx@@ -93,11 +93,15 @@ interface GraphToolbarProps {onGraphThemeChange: (theme: GraphTheme) => void;/** Opens the keyboard-shortcut help overlay (also bound to `?`). */onToggleHelp?: () => void;+ /** Which scopes the scope cluster offers. Defaults to all three; the Explore+ * surface omits the constellation scope (it lives in the Knowledge Graph+ * view) so there is no cross-view jump back through the toolbar. */+ availableScopes?: Scope[] | undefined;}// Scope = which subset of nodes are drawn. Mutually exclusive.const SCOPES: { id: Scope; icon: typeof Boxes; label: string; hint: string }[] = [- { id: "architecture", icon: GitFork, label: "Knowledge Graph", hint: "Detected communities" },+ { id: "architecture", icon: GitFork, label: "Communities", hint: "Detected communities" },{ id: "modules", icon: Boxes, label: "Modules", hint: "Folder / package rollup" },{ id: "full", icon: LayoutGrid, label: "Full", hint: "All files and symbols" },];@@ -149,7 +153,11 @@ export const GraphToolbar = memo(function GraphToolbar({graphTheme,onGraphThemeChange,onToggleHelp,+ availableScopes,}: GraphToolbarProps) {+ const scopes = availableScopes+ ? SCOPES.filter((s) => availableScopes.includes(s.id))+ : SCOPES;// Below sm the full control cluster is too much chrome over the canvas —// collapse it behind a single toggle, keeping search always reachable.const [mobileOpen, setMobileOpen] = useState(false);@@ -180,7 +188,7 @@ export const GraphToolbar = memo(function GraphToolbar({{/* Mobile: single toggle for the control cluster */}<buttononClick={() => setMobileOpen((s) => !s)}- className={`flex items-center gap-1.5 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]/90 backdrop-blur-sm px-2 py-1.5 text-[10px] font-medium shadow-lg shadow-black/20 sm:hidden ${+ className={`flex items-center gap-1.5 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]/90 backdrop-blur-sm px-2 py-1.5 text-[10px] font-medium shadow-sm sm:hidden ${mobileOpen? "text-[var(--color-accent-primary)]": "text-[var(--color-text-secondary)]"@@ -192,9 +200,11 @@ export const GraphToolbar = memo(function GraphToolbar({Controls</button>- {/* Scope (mutually exclusive) */}- <div className={`${clusterVisibility} gap-0.5 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]/90 backdrop-blur-sm p-1 shadow-lg shadow-black/20`}>- {SCOPES.map((m) => {+ {/* Scope (mutually exclusive). Hidden when only one scope is offered —+ the surface is locked (e.g. the Communities lens). */}+ {scopes.length > 1 && (+ <div className={`${clusterVisibility} gap-0.5 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]/90 backdrop-blur-sm p-1 shadow-sm`}>+ {scopes.map((m) => {const Icon = m.icon;const isActive = activeScope === m.id;return (@@ -216,10 +226,11 @@ export const GraphToolbar = memo(function GraphToolbar({);})}</div>+ )}{/* Overlays (additive signal chips) — not applicable in the constellation */}{!isConstellation && (- <div className={`${clusterVisibility} gap-0.5 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]/90 backdrop-blur-sm p-1 shadow-lg shadow-black/20`}>+ <div className={`${clusterVisibility} gap-0.5 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]/90 backdrop-blur-sm p-1 shadow-sm`}>{OVERLAYS.map((o) => {const Icon = o.icon;const isActive = activeOverlays.has(o.id);@@ -244,8 +255,10 @@ export const GraphToolbar = memo(function GraphToolbar({</div>)}- <div className={`${clusterVisibility} gap-1.5 items-center`}>- <div className="flex gap-0.5 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]/90 backdrop-blur-sm p-1 shadow-lg shadow-black/20">+ {/* Layout · color · actions collapse into one floating group so the+ canvas isn't fenced in by a row of separate shadowed pills. */}+ <div className={`${clusterVisibility} items-center gap-1 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]/90 backdrop-blur-sm p-1 shadow-sm`}>+ <div className="flex gap-0.5">{isConstellation ? (// Constellation is locked to the radial layout; show a single// active indicator instead of the Force/Hierarchical toggle.@@ -253,7 +266,7 @@ export const GraphToolbar = memo(function GraphToolbar({key={RADIAL_LAYOUT.id}disabledclassName="flex items-center gap-1 px-2 py-1 rounded-md text-[10px] font-medium bg-[var(--color-accent-graph)]/15 text-[var(--color-accent-graph)] cursor-default"- title={`${RADIAL_LAYOUT.label} (fixed for Knowledge Graph)`}+ title={`${RADIAL_LAYOUT.label} (fixed for Communities)`}aria-label={RADIAL_LAYOUT.label}aria-pressed>@@ -283,7 +296,7 @@ export const GraphToolbar = memo(function GraphToolbar({)}</div>- <div className="flex gap-0.5 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]/90 backdrop-blur-sm p-1 shadow-lg shadow-black/20">+ <div className="flex gap-0.5 border-l border-[var(--color-border-default)] pl-1">{COLOR_MODES.map((m) => {const Icon = m.icon;const isActive = colorMode === m.id;@@ -306,7 +319,7 @@ export const GraphToolbar = memo(function GraphToolbar({})}</div>- <div className="flex gap-0.5 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]/90 backdrop-blur-sm p-1 shadow-lg shadow-black/20">+ <div className="flex gap-0.5 border-l border-[var(--color-border-default)] pl-1"><Buttonsize="sm"variant="ghost"@@ -385,7 +398,7 @@ export const GraphToolbar = memo(function GraphToolbar({</div><div className="relative">- <div className="flex items-center gap-1 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]/90 backdrop-blur-sm px-2 py-1 shadow-lg shadow-black/20">+ <div className="flex items-center gap-1 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]/90 backdrop-blur-sm px-2 py-1 shadow-sm"><Search className="w-3 h-3 text-[var(--color-text-tertiary)] shrink-0" /><inputtype="text"@@ -394,10 +407,10 @@ export const GraphToolbar = memo(function GraphToolbar({onKeyDown={onSearchKeyDown}placeholder="Search nodes…"aria-label="Search graph nodes"- className="bg-transparent text-[11px] text-[var(--color-text-primary)] placeholder:text-[var(--color-text-tertiary)] outline-none w-28 lg:w-40"+ className="bg-transparent text-xs text-[var(--color-text-primary)] placeholder:text-[var(--color-text-tertiary)] outline-none w-28 lg:w-40"/>{searchQuery && searchMatchCount != null && searchTotalCount != null && (- <span className="text-[9px] text-[var(--color-text-tertiary)] tabular-nums whitespace-nowrap">+ <span className="text-[10px] text-[var(--color-text-tertiary)] tabular-nums whitespace-nowrap">{searchMatchCount} / {searchTotalCount}</span>)}diff --git a/packages/ui/src/graph/graph-tooltip.tsx b/packages/ui/src/graph/graph-tooltip.tsxindex 6a5df4d30..7054ec293 100644--- a/packages/ui/src/graph/graph-tooltip.tsx+++ b/packages/ui/src/graph/graph-tooltip.tsx@@ -81,7 +81,7 @@ export function GraphTooltip({)}</div><div className="min-w-0 flex-1">- <p className="font-mono font-semibold text-[var(--color-text-primary)] text-[11px] leading-tight break-all">+ <p className="font-mono font-semibold text-[var(--color-text-primary)] text-xs leading-tight break-all">{nodeId.split("/").pop()}</p><p className="text-[10px] text-[var(--color-text-tertiary)] mt-0.5 truncate">@@ -229,7 +229,7 @@ export function GraphTooltip({<div className="flex items-center gap-2 p-3 pt-0"><buttononClick={onViewDocs}- className="flex-1 flex items-center justify-center gap-1.5 rounded-lg bg-[var(--color-bg-inset)] hover:bg-[var(--color-bg-surface)] border border-[var(--color-border-default)] px-2.5 py-1.5 text-[11px] font-medium text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] transition-colors"+ className="flex-1 flex items-center justify-center gap-1.5 rounded-lg bg-[var(--color-bg-inset)] hover:bg-[var(--color-bg-surface)] border border-[var(--color-border-default)] px-2.5 py-1.5 text-xs font-medium text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] transition-colors"><BookOpen className="w-3 h-3" />View Docs@@ -237,7 +237,7 @@ export function GraphTooltip({{isFile && onViewSymbol && (<buttononClick={onViewSymbol}- className="flex-1 flex items-center justify-center gap-1.5 rounded-lg bg-[var(--color-bg-inset)] hover:bg-[var(--color-bg-surface)] border border-[var(--color-border-default)] px-2.5 py-1.5 text-[11px] font-medium text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] transition-colors"+ className="flex-1 flex items-center justify-center gap-1.5 rounded-lg bg-[var(--color-bg-inset)] hover:bg-[var(--color-bg-surface)] border border-[var(--color-border-default)] px-2.5 py-1.5 text-xs font-medium text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] transition-colors"><Code2 className="w-3 h-3" />View Symbol@@ -246,7 +246,7 @@ export function GraphTooltip({{onExplore && (<buttononClick={onExplore}- className="flex-1 flex items-center justify-center gap-1.5 rounded-lg bg-[var(--color-accent-graph)]/10 hover:bg-[var(--color-accent-graph)]/20 border border-[var(--color-accent-graph)]/30 px-2.5 py-1.5 text-[11px] font-medium text-[var(--color-accent-graph)] transition-colors"+ className="flex-1 flex items-center justify-center gap-1.5 rounded-lg bg-[var(--color-accent-graph)]/10 hover:bg-[var(--color-accent-graph)]/20 border border-[var(--color-accent-graph)]/30 px-2.5 py-1.5 text-xs font-medium text-[var(--color-accent-graph)] transition-colors"><ArrowRight className="w-3 h-3" />Explorediff --git a/packages/ui/src/graph/graph-truncation-banner.tsx b/packages/ui/src/graph/graph-truncation-banner.tsxindex 7ca9d6831..392255a27 100644--- a/packages/ui/src/graph/graph-truncation-banner.tsx+++ b/packages/ui/src/graph/graph-truncation-banner.tsx@@ -66,7 +66,7 @@ export function GraphTruncationBanner({size="sm"variant="ghost"onClick={onSwitchToArchitecture}- className="h-7 px-2 text-[11px] font-medium text-[var(--color-warning)] hover:bg-[var(--color-warning)]/15 hover:text-[var(--color-warning)]"+ className="h-7 px-2 text-xs font-medium text-[var(--color-warning)] hover:bg-[var(--color-warning)]/15 hover:text-[var(--color-warning)]">Switch to Architecture</Button>@@ -76,7 +76,7 @@ export function GraphTruncationBanner({size="sm"variant="ghost"onClick={() => onLoadMore(nextLimit)}- className="h-7 px-2 text-[11px] font-medium text-[var(--color-warning)] hover:bg-[var(--color-warning)]/15 hover:text-[var(--color-warning)]"+ className="h-7 px-2 text-xs font-medium text-[var(--color-warning)] hover:bg-[var(--color-warning)]/15 hover:text-[var(--color-warning)]">Load {formatNumber(Math.min(LOAD_MORE_STEP, nextLimit - limit))} more</Button>diff --git a/packages/ui/src/graph/index.ts b/packages/ui/src/graph/index.tsindex ef7c24717..0e5586722 100644--- a/packages/ui/src/graph/index.ts+++ b/packages/ui/src/graph/index.ts@@ -9,6 +9,7 @@ export * from "./centrality-leaderboard";export * from "./node-badges";export * from "./graph-context-drawer";export * from "./graph-truncation-banner";+export * from "./graph-canvas-shell";export * from "./graph-flow";export * from "./context";export * from "./elk-layout";diff --git a/packages/ui/src/graph/node-badges.tsx b/packages/ui/src/graph/node-badges.tsxindex 829a4eff3..99df57fb8 100644--- a/packages/ui/src/graph/node-badges.tsx+++ b/packages/ui/src/graph/node-badges.tsx@@ -76,7 +76,7 @@ export function NodeBadges({ signals, only, size = "xs", className }: NodeBadgesif (active.length === 0) return null;const sizeClass =- size === "sm" ? "text-[11px] px-2 py-0.5" : "text-[10px] px-1.5 py-0.5";+ size === "sm" ? "text-xs px-2 py-0.5" : "text-[10px] px-1.5 py-0.5";const iconSize = size === "sm" ? "w-3 h-3" : "w-2.5 h-2.5";return (diff --git a/packages/ui/src/graph/path-finder-panel.tsx b/packages/ui/src/graph/path-finder-panel.tsxindex 697c463b7..e1dce34ab 100644--- a/packages/ui/src/graph/path-finder-panel.tsx+++ b/packages/ui/src/graph/path-finder-panel.tsx@@ -98,7 +98,7 @@ function NodeAutocomplete({{showDropdown && displayResults.length > 0 && (<div className="absolute top-full left-0 mt-1 w-full max-h-52 overflow-auto z-50 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)] shadow-xl shadow-black/30 py-1">{results.length === 0 && topNodes.length > 0 && (- <div className="px-3 py-1 text-[9px] text-[var(--color-text-tertiary)] uppercase tracking-wider">+ <div className="px-3 py-1 text-[10px] text-[var(--color-text-tertiary)] uppercase tracking-wider">Top files by importance</div>)}diff --git a/packages/ui/src/graph/sigma/sigma-controls.tsx b/packages/ui/src/graph/sigma/sigma-controls.tsxindex 2966ba79c..78030574f 100644--- a/packages/ui/src/graph/sigma/sigma-controls.tsx+++ b/packages/ui/src/graph/sigma/sigma-controls.tsx@@ -88,7 +88,7 @@ export function SigmaControls({</Button>)}{isLayoutRunning && (- <div className="text-[9px] text-center text-[var(--color-accent-graph)] animate-pulse whitespace-nowrap">+ <div className="text-[10px] text-center text-[var(--color-accent-graph)] animate-pulse whitespace-nowrap">Layout optimizing...</div>)}diff --git a/packages/ui/src/health/ai-prompt-modal.tsx b/packages/ui/src/health/ai-prompt-modal.tsxindex 19527c0a6..0bf7bb614 100644--- a/packages/ui/src/health/ai-prompt-modal.tsx+++ b/packages/ui/src/health/ai-prompt-modal.tsx@@ -114,7 +114,7 @@ export function AiPromptModal({<div className="space-y-3"><div>- <p className="text-[11px] uppercase tracking-wider text-[var(--color-text-tertiary)] mb-1.5">+ <p className="text-xs uppercase tracking-wider text-[var(--color-text-tertiary)] mb-1.5">Target agent</p><div className="grid grid-cols-3 gap-2">@@ -139,7 +139,7 @@ export function AiPromptModal({{f.label}</span></div>- <p className="mt-0.5 text-[11px] text-[var(--color-text-tertiary)] leading-snug">+ <p className="mt-0.5 text-xs text-[var(--color-text-tertiary)] leading-snug">{f.hint}</p></button>@@ -154,7 +154,7 @@ export function AiPromptModal({</pre></div>- <div className="flex flex-wrap items-center justify-between gap-2 text-[11px] text-[var(--color-text-tertiary)]">+ <div className="flex flex-wrap items-center justify-between gap-2 text-xs text-[var(--color-text-tertiary)]"><span>{prompt.length.toLocaleString()} chars · approx{" "}{Math.round(prompt.length / 4).toLocaleString()} tokensdiff --git a/packages/ui/src/health/biomarker-details.tsx b/packages/ui/src/health/biomarker-details.tsxindex 91ad76b2e..6011503d7 100644--- a/packages/ui/src/health/biomarker-details.tsx+++ b/packages/ui/src/health/biomarker-details.tsx@@ -35,7 +35,7 @@ function joinStats(...parts: Array<string | null | undefined>): string | null {function StatLine({ children }: { children: React.ReactNode }) {return (- <div className="text-[11px] text-[var(--color-text-tertiary)] tabular-nums">+ <div className="text-xs text-[var(--color-text-tertiary)] tabular-nums">{children}</div>);@@ -118,7 +118,7 @@ export function BiomarkerDetails({const corrPct = pct(num(details.correlation));const coChanges = num(details.co_change_count);return (- <div className="text-[11px] text-[var(--color-text-tertiary)]">+ <div className="text-xs text-[var(--color-text-tertiary)]"><PartnerLinkpath={partner}onPartnerSelect={onPartnerSelect}@@ -151,7 +151,7 @@ export function BiomarkerDetails({);if (!partner && !stats) return null;return (- <div className="text-[11px] text-[var(--color-text-tertiary)]">+ <div className="text-xs text-[var(--color-text-tertiary)]">{stats ? <span className="tabular-nums">{stats}</span> : null}{partner ? (<div>@@ -172,7 +172,7 @@ export function BiomarkerDetails({? (details.assertion_lines as unknown[]).map(num).filter((v) => v != null): [];return (- <div className="text-[11px] text-[var(--color-text-tertiary)]">+ <div className="text-xs text-[var(--color-text-tertiary)]">{lines.length === 2 ? (<span className="tabular-nums">lines {lines[0]}–{lines[1]}</span>) : null}diff --git a/packages/ui/src/health/biomarker-list.tsx b/packages/ui/src/health/biomarker-list.tsxindex fae46b6c1..798929501 100644--- a/packages/ui/src/health/biomarker-list.tsx+++ b/packages/ui/src/health/biomarker-list.tsx@@ -137,7 +137,7 @@ function BiomarkerGroup({<span className="text-xs text-[var(--color-text-tertiary)]">{CATEGORY_LABEL[info.category]}</span>- <span className="ml-auto inline-flex items-center gap-1.5 text-[11px] tabular-nums">+ <span className="ml-auto inline-flex items-center gap-1.5 text-xs tabular-nums">{(Object.keys(sevCounts) as Severity[]).map((s) =>sevCounts[s] > 0 ? (<spandiff --git a/packages/ui/src/health/churn-complexity-quadrant.tsx b/packages/ui/src/health/churn-complexity-quadrant.tsxindex d1e3c8c3c..d73f149fe 100644--- a/packages/ui/src/health/churn-complexity-quadrant.tsx+++ b/packages/ui/src/health/churn-complexity-quadrant.tsx@@ -161,7 +161,7 @@ export function ChurnComplexityQuadrant({})}</svg>{hovered ? (- <div className="pointer-events-none absolute bottom-2 left-2 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2 py-1 text-[11px] shadow-md">+ <div className="pointer-events-none absolute bottom-2 left-2 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2 py-1 text-xs shadow-md"><span className="font-mono text-[var(--color-text-primary)]">{hovered.file_path}</span><span className="ml-2 text-[var(--color-text-tertiary)]">{hovered.commit_count_90d} commits · CCN {hovered.max_ccn} · {hovered.score.toFixed(1)}diff --git a/packages/ui/src/health/code-health-controls.tsx b/packages/ui/src/health/code-health-controls.tsxnew file mode 100644index 000000000..40a5d0597--- /dev/null+++ b/packages/ui/src/health/code-health-controls.tsx@@ -0,0 +1,152 @@+"use client";++import * as React from "react";+import { cn } from "../lib/cn";+import { scoreBadgeClass } from "./tokens";+import type { CodeHealthMapFile } from "./code-health-map";++/** Labelled <select> used across the Triage queue filters. */+export function FilterSelect({+ label,+ value,+ onChange,+ options,+}: {+ label: string;+ value: string;+ onChange: (v: string) => void;+ options: { value: string; label: string }[];+}) {+ return (+ <label className="inline-flex items-center gap-1.5 text-xs text-[var(--color-text-tertiary)]">+ <span className="uppercase tracking-wider">{label}</span>+ <select+ value={value}+ onChange={(e) => onChange(e.target.value)}+ className="text-xs px-2 py-1 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] text-[var(--color-text-primary)]"+ >+ {options.map((o) => (+ <option key={o.value} value={o.value}>+ {o.label}+ </option>+ ))}+ </select>+ </label>+ );+}++/** Toggleable filter chip (Hotspots / Untested / Failing). */+export function FilterChip({+ active,+ onClick,+ children,+}: {+ active: boolean;+ onClick: () => void;+ children: React.ReactNode;+}) {+ return (+ <button+ type="button"+ onClick={onClick}+ className={cn(+ "text-xs rounded-md px-2 py-1 border transition-colors",+ active+ ? "bg-[var(--color-accent-muted)] text-[var(--color-accent-primary)] border-[var(--color-accent-primary)]/50"+ : "border-[var(--color-border-default)] text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] hover:border-[var(--color-border-strong)]",+ )}+ >+ {children}+ </button>+ );+}++/** Two-state segmented toggle (Queue / All files). */+export function ViewToggle<T extends string>({+ value,+ options,+ onChange,+}: {+ value: T;+ options: { value: T; label: string }[];+ onChange: (v: T) => void;+}) {+ return (+ <div className="flex rounded-md border border-[var(--color-border-default)] overflow-hidden text-xs">+ {options.map((opt) => (+ <button+ key={opt.value}+ type="button"+ onClick={() => onChange(opt.value)}+ className={cn(+ "px-3 py-1.5 font-medium transition-colors",+ value === opt.value+ ? "bg-[var(--color-accent-primary)] text-[var(--color-text-inverse)]"+ : "bg-transparent text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)]",+ )}+ >+ {opt.label}+ </button>+ ))}+ </div>+ );+}++/** The inspected file (last bubble hovered in the map) shown in the rail. */+export function FileSpotlight({+ file,+ onOpen,+}: {+ file: CodeHealthMapFile | null;+ onOpen: (path: string) => void;+}) {+ if (!file) {+ return (+ <div className="rounded-lg border border-dashed border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3 text-xs text-[var(--color-text-tertiary)]">+ Hover a bubble to inspect a file; click it to open the full breakdown.+ </div>+ );+ }+ const name = file.file_path.split("/").pop() ?? file.file_path;+ return (+ <div className="space-y-2 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3">+ <div className="flex items-center gap-2">+ <span+ className={cn(+ "inline-flex items-center justify-center rounded px-1.5 py-0.5 text-xs font-semibold",+ scoreBadgeClass(file.score),+ )}+ >+ {file.score.toFixed(1)}+ </span>+ <span+ className="truncate text-sm font-medium text-[var(--color-text-primary)]"+ title={file.file_path}+ >+ {name}+ </span>+ </div>+ <div+ className="truncate font-mono text-xs text-[var(--color-text-tertiary)]"+ title={file.file_path}+ >+ {file.file_path}+ </div>+ <div className="flex flex-wrap gap-x-3 gap-y-1 text-xs text-[var(--color-text-secondary)]">+ <span>{file.nloc.toLocaleString()} NLOC</span>+ {file.line_coverage_pct != null ? (+ <span>{Math.round(file.line_coverage_pct)}% coverage</span>+ ) : null}+ <span>{file.has_test_file ? "has tests" : "untested"}</span>+ {file.module ? <span className="truncate">{file.module}</span> : null}+ </div>+ <button+ type="button"+ onClick={() => onOpen(file.file_path)}+ className="w-full rounded-md border border-[var(--color-border-default)] px-2 py-1.5 text-xs font-medium text-[var(--color-text-secondary)] transition-colors hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]"+ >+ Open details+ </button>+ </div>+ );+}diff --git a/packages/ui/src/health/code-health-map.tsx b/packages/ui/src/health/code-health-map.tsxnew file mode 100644index 000000000..d68396611--- /dev/null+++ b/packages/ui/src/health/code-health-map.tsx@@ -0,0 +1,626 @@+"use client";++import { useEffect, useMemo, useRef, useState } from "react";+import * as d3 from "d3-hierarchy";+import { scoreBand, type ScoreBand } from "./tokens";+import { useCommunityFamilies } from "../shared/use-theme-tokens";++export interface CodeHealthMapFile {+ file_path: string;+ score: number;+ nloc: number;+ module: string | null;+ line_coverage_pct: number | null;+ has_test_file: boolean;+ /** 0–100 churn percentile — drives the churn overlay. */+ churn_percentile?: number | null;+ /** Reclaimable lines on this file — drives the dead-code overlay. */+ dead_code_lines?: number | null;+ /** Open security findings on this file — drives the security overlay. */+ security_findings?: number | null;+}++/**+ * Lens applied to the same field — recolors every file node without re-laying+ * the galaxies. One diagram, switchable overlay (the page spine).+ */+export type CodeHealthOverlay =+ | "health"+ | "coverage"+ | "churn"+ | "dead-code"+ | "security";++export interface CodeHealthMapProps {+ files: CodeHealthMapFile[];+ /** Highlight ring on this file. */+ selectedPath?: string | null;+ /** Filename substring — non-matching nodes dim out. */+ search?: string;+ /** File click → open the drawer. */+ onSelectFile?: (path: string) => void;+ /** Hover feeds the details rail. */+ onHoverFile?: (file: CodeHealthMapFile | null) => void;+ /** Canvas min height in px. */+ minHeight?: number;+ /** Which lens recolors the field. Defaults to `health`. */+ overlay?: CodeHealthOverlay;+ /** When provided, an on-canvas lens switcher is rendered. */+ onOverlayChange?: (overlay: CodeHealthOverlay) => void;+ /**+ * The active overlay's per-file signal is still loading. When true the legend+ * shows a "loading…" note instead of its bands, so an all-neutral field reads+ * as "fetching data" rather than "no data".+ */+ overlayLoading?: boolean;+}++/* Band → SVG fill var(). Same ramp as every score pill on the surface:+ * worst files burn clay/red, healthy ones go green. */+const BAND_FILL: Record<ScoreBand, string> = {+ critical: "var(--color-error)",+ poor: "var(--color-warning)",+ fair: "var(--color-caution)",+ good: "var(--color-success)",+};++const BAND_LABEL: { band: ScoreBand; label: string }[] = [+ { band: "critical", label: "Alert" },+ { band: "poor", label: "Warning" },+ { band: "fair", label: "Fair" },+ { band: "good", label: "Healthy" },+];++/** Neutral fill for nodes a non-health overlay has no signal for. */+const NEUTRAL_FILL = "var(--color-text-tertiary)";++interface LegendRow {+ fill: string;+ label: string;+}++/** Lens metadata: how to fill a node and what the on-canvas key reads. */+interface OverlaySpec {+ label: string;+ /** Caption shown under the legend key. */+ caption: string;+ fill: (f: CodeHealthMapFile) => string;+ legend: LegendRow[];+}++/** Coverage band: green = well covered, red = uncovered, grey = no data. */+function coverageFill(pct: number | null | undefined): string {+ if (pct == null) return NEUTRAL_FILL;+ if (pct >= 80) return "var(--color-success)";+ if (pct >= 50) return "var(--color-caution)";+ if (pct >= 20) return "var(--color-warning)";+ return "var(--color-error)";+}++/** Churn band: red = top-decile churn, green = quiet. */+function churnFill(pctile: number | null | undefined): string {+ if (pctile == null) return NEUTRAL_FILL;+ if (pctile >= 90) return "var(--color-error)";+ if (pctile >= 70) return "var(--color-warning)";+ if (pctile >= 40) return "var(--color-caution)";+ return "var(--color-success)";+}++const OVERLAY_SPECS: Record<CodeHealthOverlay, OverlaySpec> = {+ health: {+ label: "Health",+ caption: "galaxy = module · size = lines of code",+ fill: (f) => BAND_FILL[scoreBand(f.score)],+ legend: BAND_LABEL.map((b) => ({ fill: BAND_FILL[b.band], label: b.label })),+ },+ coverage: {+ label: "Coverage",+ caption: "color = line coverage · grey = no coverage data",+ fill: (f) => coverageFill(f.line_coverage_pct),+ legend: [+ { fill: "var(--color-success)", label: "≥80%" },+ { fill: "var(--color-caution)", label: "50–80%" },+ { fill: "var(--color-warning)", label: "20–50%" },+ { fill: "var(--color-error)", label: "<20%" },+ { fill: NEUTRAL_FILL, label: "no data" },+ ],+ },+ churn: {+ label: "Churn",+ caption: "color = 90-day churn percentile",+ fill: (f) => churnFill(f.churn_percentile),+ legend: [+ { fill: "var(--color-error)", label: "Top 10%" },+ { fill: "var(--color-warning)", label: "Top 30%" },+ { fill: "var(--color-caution)", label: "Top 60%" },+ { fill: "var(--color-success)", label: "Quiet" },+ { fill: NEUTRAL_FILL, label: "no data" },+ ],+ },+ "dead-code": {+ label: "Dead code",+ caption: "red = reclaimable lines · grey = clean",+ fill: (f) => ((f.dead_code_lines ?? 0) > 0 ? "var(--color-error)" : NEUTRAL_FILL),+ legend: [+ { fill: "var(--color-error)", label: "Has dead code" },+ { fill: NEUTRAL_FILL, label: "Clean" },+ ],+ },+ security: {+ label: "Security",+ caption: "red = open findings · grey = clean",+ fill: (f) => ((f.security_findings ?? 0) > 0 ? "var(--color-error)" : NEUTRAL_FILL),+ legend: [+ { fill: "var(--color-error)", label: "Has findings" },+ { fill: NEUTRAL_FILL, label: "Clean" },+ ],+ },+};++/**+ * Lenses offered in the on-canvas switcher. Only the three backed by per-file+ * map data are exposed; dead-code and security have no per-file signal in the+ * map payload and live on their own tabs, so their `OVERLAY_SPECS` entries stay+ * defined (the type is extensible) but are not presented here.+ */+const OVERLAY_ORDER: CodeHealthOverlay[] = ["health", "coverage", "churn"];++const GOLDEN_ANGLE = Math.PI * (3 - Math.sqrt(5)); // ~2.39996 rad++/** One module = one galaxy: its files plus size aggregates. */+export interface GalaxyAgg {+ module: string;+ files: CodeHealthMapFile[]; // NLOC-desc+ totalNloc: number;+ maxNloc: number;+}++/**+ * Group flat file rows into per-module galaxies, dropping zero-NLOC files+ * (they can't be sized). Files come back sorted biggest-first. Pure + exported+ * for unit testing.+ */+export function groupByModule(files: CodeHealthMapFile[]): GalaxyAgg[] {+ const byModule = new Map<string, CodeHealthMapFile[]>();+ for (const f of files) {+ if (f.nloc <= 0) continue;+ const key = f.module ?? "(ungrouped)";+ const arr = byModule.get(key);+ if (arr) arr.push(f);+ else byModule.set(key, [f]);+ }+ const out: GalaxyAgg[] = [];+ for (const [module, group] of byModule) {+ group.sort((a, b) => b.nloc - a.nloc);+ out.push({+ module,+ files: group,+ totalNloc: group.reduce((s, f) => s + f.nloc, 0),+ maxNloc: group[0]?.nloc ?? 1,+ });+ }+ // Biggest galaxies first → stable z-order (small ones paint on top).+ out.sort((a, b) => b.totalNloc - a.totalNloc);+ return out;+}++interface FileNode {+ file: CodeHealthMapFile;+ x: number;+ y: number;+ r: number;+}++interface Galaxy {+ module: string;+ cx: number;+ cy: number;+ R: number;+ fileCount: number;+ colorId: number;+ nodes: FileNode[];+}++/** Stable, well-spread hash so a module maps to a consistent palette family. */+function moduleColorId(module: string): number {+ let h = 0;+ for (let i = 0; i < module.length; i++) h = (h * 31 + module.charCodeAt(i)) | 0;+ return Math.abs(h);+}++/** Deterministic pseudo-random in [0,1) — for the static starfield. */+function rand(i: number): number {+ const x = Math.sin(i * 127.1) * 43758.5453;+ return x - Math.floor(x);+}++/** Label a galaxy once its on-screen footprint clears this radius (px). */+const LABEL_MIN_SCREEN_R = 40;+/** Spokes drawn from each hub to its N biggest files (overview / focused). */+const SPOKES_OVERVIEW = 8;+const SPOKES_FOCUSED = 36;++export function CodeHealthMap({+ files,+ selectedPath,+ search,+ onSelectFile,+ onHoverFile,+ minHeight = 640,+ overlay = "health",+ onOverlayChange,+ overlayLoading = false,+}: CodeHealthMapProps) {+ const overlaySpec = OVERLAY_SPECS[overlay] ?? OVERLAY_SPECS.health;+ const containerRef = useRef<HTMLDivElement>(null);+ const [dims, setDims] = useState({ width: 0, height: 0 });+ const [focusModule, setFocusModule] = useState<string | null>(null);+ const [hovered, setHovered] = useState<CodeHealthMapFile | null>(null);+ const famFor = useCommunityFamilies();++ useEffect(() => {+ if (!containerRef.current) return;+ const observer = new ResizeObserver((es) => {+ const first = es[0];+ if (!first) return;+ const { width, height } = first.contentRect;+ setDims({ width, height: Math.max(height, minHeight) });+ });+ observer.observe(containerRef.current);+ return () => observer.disconnect();+ }, [minHeight]);++ // Esc always exits a focused galaxy — a guaranteed zoom-out.+ useEffect(() => {+ const onKey = (e: KeyboardEvent) => {+ if (e.key === "Escape") setFocusModule(null);+ };+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, []);++ const S = Math.max(0, Math.min(dims.width, dims.height));++ // Galaxy placement (d3-pack) + hub-and-spoke file layout (phyllotaxis).+ const { galaxies, byModule } = useMemo(() => {+ if (S === 0 || files.length === 0) {+ return { galaxies: [] as Galaxy[], byModule: new Map<string, Galaxy>() };+ }+ const aggs = groupByModule(files);+ const root = d3+ .hierarchy<{ value?: number; agg?: GalaxyAgg; children?: unknown[] }>(+ { children: aggs.map((a) => ({ value: a.totalNloc, agg: a })) },+ (d) => d.children as { value?: number; agg?: GalaxyAgg }[] | undefined,+ )+ .sum((d) => d.value ?? 0);+ d3.pack<{ value?: number; agg?: GalaxyAgg }>().size([S, S]).padding(S * 0.012)(+ root as d3.HierarchyNode<{ value?: number; agg?: GalaxyAgg }>,+ );+ const galaxies: Galaxy[] = [];+ for (const leaf of root.leaves() as d3.HierarchyCircularNode<{ agg?: GalaxyAgg }>[]) {+ const agg = leaf.data.agg;+ if (!agg) continue;+ const R = leaf.r;+ const cx = leaf.x;+ const cy = leaf.y;+ const n = agg.files.length;+ const spread = R * 0.84;+ const maxNodeR = Math.max(2, R * 0.16);+ const nodes: FileNode[] = agg.files.map((file, i) => {+ const rr = spread * Math.sqrt((i + 0.55) / n);+ const ang = i * GOLDEN_ANGLE;+ const nodeR = Math.max(+ 1.2,+ Math.min(maxNodeR, maxNodeR * Math.sqrt(file.nloc / agg.maxNloc)),+ );+ return { file, x: cx + rr * Math.cos(ang), y: cy + rr * Math.sin(ang), r: nodeR };+ });+ galaxies.push({ module: agg.module, cx, cy, R, fileCount: n, colorId: moduleColorId(agg.module), nodes });+ }+ const byModule = new Map(galaxies.map((g) => [g.module, g]));+ return { galaxies, byModule };+ }, [files, S]);++ // Starfield — static layer, regenerated only on resize.+ const stars = useMemo(() => {+ const { width, height } = dims;+ if (width === 0) return [] as { x: number; y: number; r: number }[];+ const count = Math.min(160, Math.floor((width * height) / 9000));+ return Array.from({ length: count }, (_, i) => ({+ x: rand(i) * width,+ y: rand(i + 1000) * height,+ r: 0.4 + rand(i + 2000) * 1.3,+ }));+ }, [dims]);++ const focusGalaxy = focusModule ? byModule.get(focusModule) ?? null : null;++ const offX = (dims.width - S) / 2;+ const offY = (dims.height - S) / 2;+ const k = focusGalaxy ? (S * 0.9) / (2 * focusGalaxy.R) : 1;+ const camX = focusGalaxy ? focusGalaxy.cx : S / 2;+ const camY = focusGalaxy ? focusGalaxy.cy : S / 2;+ const tx = dims.width / 2 - k * (camX + offX);+ const ty = dims.height / 2 - k * (camY + offY);+ const toScreen = (x: number, y: number) => ({ x: k * (x + offX) + tx, y: k * (y + offY) + ty });++ const q = (search ?? "").trim().toLowerCase();++ if (S === 0) {+ return <div ref={containerRef} className="w-full rounded-xl bg-[var(--color-bg-canvas)]" style={{ minHeight }} />;+ }++ if (files.length === 0) {+ return (+ <div+ ref={containerRef}+ className="flex w-full items-center justify-center rounded-xl border border-dashed border-[var(--color-border-default)] bg-[var(--color-bg-canvas)] text-sm text-[var(--color-text-tertiary)]"+ style={{ minHeight }}+ >+ No files to map yet — run <code className="mx-1 font-mono">repowise init</code> to populate health.+ </div>+ );+ }++ const labelled = galaxies.filter((g) => focusGalaxy === g || g.R * k >= LABEL_MIN_SCREEN_R);+ const spokeCap = focusGalaxy ? SPOKES_FOCUSED : SPOKES_OVERVIEW;++ return (+ <div+ ref={containerRef}+ className="relative w-full overflow-hidden rounded-xl border border-[var(--color-border-default)]"+ style={{ minHeight }}+ >+ <svg+ width={dims.width}+ height={dims.height}+ role="img"+ aria-label={`Code universe: modules as galaxies, files radiating from each hub, sized by lines of code and colored by ${overlaySpec.label.toLowerCase()}`}+ className="block"+ >+ <defs>+ <radialGradient id="ch-mist" cx="50%" cy="42%" r="75%">+ <stop offset="0%" stopColor="var(--color-bg-surface)" />+ <stop offset="100%" stopColor="var(--color-bg-canvas)" />+ </radialGradient>+ <filter id="ch-nebula" x="-30%" y="-30%" width="160%" height="160%">+ <feGaussianBlur stdDeviation="7" />+ </filter>+ </defs>++ {/* Misty backdrop + starfield (static, clicking it exits a galaxy). */}+ <rect+ x={0}+ y={0}+ width={dims.width}+ height={dims.height}+ fill="url(#ch-mist)"+ onClick={() => setFocusModule(null)}+ />+ <g className="pointer-events-none">+ {stars.map((s, i) => (+ <circle key={`star-${i}`} cx={s.x} cy={s.y} r={s.r} fill="var(--color-canvas-dot)" />+ ))}+ </g>++ <g style={{ transition: "transform 460ms cubic-bezier(0.4,0,0.2,1)" }} transform={`translate(${tx},${ty}) scale(${k})`}>+ {/* Nebula blobs (back layer) */}+ {galaxies.map((g) => {+ const fam = famFor(g.colorId);+ const faded = focusGalaxy != null && focusGalaxy !== g;+ return (+ <circle+ key={`blob-${g.module}`}+ cx={g.cx + offX}+ cy={g.cy + offY}+ r={g.R * 0.96}+ fill={fam.hub}+ fillOpacity={faded ? 0.05 : 0.16}+ filter="url(#ch-nebula)"+ className="cursor-zoom-in"+ onClick={(e) => {+ e.stopPropagation();+ setFocusModule((m) => (m === g.module ? null : g.module));+ }}+ />+ );+ })}++ {/* Spokes — hub to its biggest files */}+ {galaxies.map((g) => {+ const fam = famFor(g.colorId);+ const faded = focusGalaxy != null && focusGalaxy !== g;+ if (faded) return null;+ return (+ <g key={`spokes-${g.module}`} stroke={fam.hub} strokeOpacity={0.28}>+ {g.nodes.slice(0, spokeCap).map((nd) => (+ <line+ key={nd.file.file_path}+ x1={g.cx + offX}+ y1={g.cy + offY}+ x2={nd.x + offX}+ y2={nd.y + offY}+ strokeWidth={0.6}+ vectorEffect="non-scaling-stroke"+ />+ ))}+ </g>+ );+ })}++ {/* File nodes */}+ {galaxies.map((g) => {+ const faded = focusGalaxy != null && focusGalaxy !== g;+ return (+ <g key={`nodes-${g.module}`}>+ {g.nodes.map((nd) => {+ const f = nd.file;+ const dim = q.length > 0 && !f.file_path.toLowerCase().includes(q);+ const isSel = selectedPath === f.file_path;+ const isHover = hovered?.file_path === f.file_path;+ return (+ <circle+ key={f.file_path}+ cx={nd.x + offX}+ cy={nd.y + offY}+ r={isHover ? nd.r + 1.5 : nd.r}+ fill={overlaySpec.fill(f)}+ fillOpacity={faded ? 0.18 : dim ? 0.12 : isHover || isSel ? 1 : 0.9}+ stroke={isSel ? "var(--color-text-primary)" : "var(--color-bg-canvas)"}+ strokeWidth={isSel ? 2 : 0.5}+ vectorEffect="non-scaling-stroke"+ className={onSelectFile ? "cursor-pointer" : undefined}+ onMouseEnter={() => {+ setHovered(f);+ onHoverFile?.(f);+ }}+ onMouseLeave={() => setHovered((h) => (h === f ? null : h))}+ onClick={(e) => {+ e.stopPropagation();+ onSelectFile?.(f.file_path);+ }}+ >+ <title>{`${f.file_path}\nscore ${f.score.toFixed(1)} · ${f.nloc.toLocaleString()} NLOC`}</title>+ </circle>+ );+ })}+ </g>+ );+ })}++ {/* Hub markers */}+ {galaxies.map((g) => {+ const fam = famFor(g.colorId);+ const faded = focusGalaxy != null && focusGalaxy !== g;+ return (+ <circle+ key={`hub-${g.module}`}+ cx={g.cx + offX}+ cy={g.cy + offY}+ r={Math.max(2.5, g.R * 0.035)}+ fill={fam.hub}+ fillOpacity={faded ? 0.3 : 0.95}+ stroke="var(--color-bg-canvas)"+ strokeWidth={1}+ vectorEffect="non-scaling-stroke"+ className="pointer-events-none"+ />+ );+ })}+ </g>+ </svg>++ {/* Editorial galaxy labels — real-px HTML overlay, crisp at any zoom */}+ <div className="pointer-events-none absolute inset-0">+ {labelled.map((g) => {+ const fam = famFor(g.colorId);+ // toScreen already folds in offX/offY — pass the raw pack coords so+ // the label lands on the hub (don't double-add the offset).+ const p = toScreen(g.cx, g.cy);+ if (p.x < -40 || p.x > dims.width + 40 || p.y < 0 || p.y > dims.height) return null;+ const big = focusGalaxy === g;+ return (+ <span+ key={`lbl-${g.module}`}+ className={`absolute -translate-x-1/2 -translate-y-1/2 inline-flex items-center gap-1.5 whitespace-nowrap rounded bg-[var(--color-bg-glass)] px-1.5 py-0.5 font-serif uppercase tracking-wide text-[var(--color-text-primary)] shadow-sm ring-1 ring-[var(--color-border-default)] backdrop-blur-sm ${+ big ? "text-sm font-semibold" : "text-[12px] font-medium"+ }`}+ style={{ left: p.x, top: p.y }}+ >+ {/* Galaxy color as a dot — the text itself stays high-contrast so+ purple/plum module hues remain legible in dark mode. */}+ <span className="h-1.5 w-1.5 shrink-0 rounded-full" style={{ backgroundColor: fam.hub }} aria-hidden />+ {g.module}+ </span>+ );+ })}+ </div>++ {/* Lens switcher (on-canvas) — recolors the same field. */}+ {onOverlayChange ? (+ <div className="absolute left-3 top-3 flex flex-wrap gap-1 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-glass)] p-1 text-xs shadow-sm backdrop-blur-sm">+ {OVERLAY_ORDER.map((mode) => (+ <button+ key={mode}+ type="button"+ onClick={() => onOverlayChange(mode)}+ aria-pressed={overlay === mode}+ className={+ overlay === mode+ ? "rounded px-2 py-1 font-medium bg-[var(--color-accent-primary)] text-[var(--color-text-inverse)]"+ : "rounded px-2 py-1 text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]"+ }+ >+ {OVERLAY_SPECS[mode].label}+ </button>+ ))}+ </div>+ ) : null}++ {/* Legend (on-canvas) — follows the active lens. */}+ <div+ className={`absolute left-3 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-glass)] px-3 py-2 text-xs shadow-sm backdrop-blur-sm ${+ onOverlayChange ? "top-14" : "top-3"+ }`}+ >+ <div className="mb-1.5 font-medium text-[var(--color-text-secondary)]">+ {overlaySpec.label}+ </div>+ {overlayLoading ? (+ <div className="flex items-center gap-1.5 text-[var(--color-text-tertiary)]">+ <span className="h-2.5 w-2.5 animate-pulse rounded-full bg-[var(--color-text-tertiary)]" />+ loading {overlaySpec.label.toLowerCase()}…+ </div>+ ) : (+ <div className="flex flex-col gap-1">+ {overlaySpec.legend.map((row) => (+ <span+ key={row.label}+ className="flex items-center gap-1.5 text-[var(--color-text-tertiary)]"+ >+ <span className="h-2.5 w-2.5 rounded-full" style={{ backgroundColor: row.fill }} />+ {row.label}+ </span>+ ))}+ </div>+ )}+ <div className="mt-2 border-t border-[var(--color-border-default)] pt-1.5 text-[var(--color-text-tertiary)]">+ {overlaySpec.caption}+ <br />+ click a galaxy to zoom+ </div>+ </div>++ {/* Zoom-out breadcrumb — only shown while a galaxy is focused */}+ {focusGalaxy ? (+ <div className="absolute right-3 top-3 flex items-center gap-1.5 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-glass)] px-2.5 py-1.5 text-xs shadow-sm backdrop-blur-sm">+ <span className="max-w-[180px] truncate font-medium text-[var(--color-text-primary)]">{focusGalaxy.module}</span>+ <button+ type="button"+ onClick={() => setFocusModule(null)}+ className="ml-1 rounded border border-[var(--color-border-default)] px-1.5 py-0.5 text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]"+ >+ ← Overview+ </button>+ </div>+ ) : null}++ {/* Hover tooltip */}+ {hovered ? <HoverCard file={hovered} /> : null}+ </div>+ );+}++function HoverCard({ file }: { file: CodeHealthMapFile }) {+ const cov = file.line_coverage_pct;+ return (+ <div className="pointer-events-none absolute bottom-3 left-3 max-w-[75%] rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2.5 py-1.5 text-xs shadow-md">+ <div className="truncate font-mono text-[var(--color-text-primary)]">{file.file_path}</div>+ <div className="text-[var(--color-text-tertiary)]">+ score {file.score.toFixed(1)} · {file.nloc.toLocaleString()} NLOC+ {cov != null ? ` · ${Math.round(cov)}% cov` : ""}+ {file.has_test_file ? "" : " · untested"}+ </div>+ </div>+ );+}diff --git a/packages/ui/src/health/defect-accuracy-card.tsx b/packages/ui/src/health/defect-accuracy-card.tsxindex 2831b6fbd..edf439415 100644--- a/packages/ui/src/health/defect-accuracy-card.tsx+++ b/packages/ui/src/health/defect-accuracy-card.tsx@@ -169,7 +169,7 @@ export function DefectAccuracyCard({) : (<Minus className="h-3 w-3 shrink-0 text-[var(--color-text-tertiary)]" aria-label="no recent fix" />)}- <span className="truncate font-mono text-[11px] text-[var(--color-text-secondary)]">+ <span className="truncate font-mono text-xs text-[var(--color-text-secondary)]">{f.file_path}</span></span>diff --git a/packages/ui/src/health/file-path-picker.tsx b/packages/ui/src/health/file-path-picker.tsxnew file mode 100644index 000000000..eeb1651a3--- /dev/null+++ b/packages/ui/src/health/file-path-picker.tsx@@ -0,0 +1,179 @@+"use client";++import * as React from "react";+import { X } from "lucide-react";++export interface FilePathPickerProps {+ selected: string[];+ onAdd: (paths: string[]) => void;+ onRemove: (path: string) => void;+ /**+ * Typeahead source — resolves a query to candidate paths. Web injects the+ * graph node search; the picker stays free of data dependencies.+ */+ onSearch: (query: string) => Promise<string[]>;+}++/**+ * Chips + typeahead input over the repo's file index. Pasting a multi-line /+ * comma-separated list adds every path at once. Presentational: the search+ * source is injected so this propagates via package bump.+ */+export function FilePathPicker({ selected, onAdd, onRemove, onSearch }: FilePathPickerProps) {+ const [query, setQuery] = React.useState("");+ const [suggestions, setSuggestions] = React.useState<string[]>([]);+ const [openList, setOpenList] = React.useState(false);+ const [activeIndex, setActiveIndex] = React.useState(-1);+ const containerRef = React.useRef<HTMLDivElement>(null);++ // Debounced typeahead over the injected search source.+ React.useEffect(() => {+ if (!query.trim()) {+ setSuggestions([]);+ setOpenList(false);+ return;+ }+ let cancelled = false;+ const t = window.setTimeout(async () => {+ try {+ const results = await onSearch(query.trim());+ if (cancelled) return;+ const paths = results.filter((p) => !selected.includes(p));+ setSuggestions(paths);+ setOpenList(paths.length > 0);+ setActiveIndex(-1);+ } catch {+ if (!cancelled) setSuggestions([]);+ }+ }, 200);+ return () => {+ cancelled = true;+ window.clearTimeout(t);+ };+ }, [query, selected, onSearch]);++ // Close the list when clicking outside.+ React.useEffect(() => {+ const handler = (e: MouseEvent) => {+ if (containerRef.current && !containerRef.current.contains(e.target as Node)) {+ setOpenList(false);+ }+ };+ document.addEventListener("mousedown", handler);+ return () => document.removeEventListener("mousedown", handler);+ }, []);++ const commit = (path: string) => {+ onAdd([path]);+ setQuery("");+ setSuggestions([]);+ setOpenList(false);+ };++ const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {+ if (e.key === "ArrowDown" && suggestions.length > 0) {+ e.preventDefault();+ setOpenList(true);+ setActiveIndex((i) => (i + 1) % suggestions.length);+ } else if (e.key === "ArrowUp" && suggestions.length > 0) {+ e.preventDefault();+ setActiveIndex((i) => (i <= 0 ? suggestions.length - 1 : i - 1));+ } else if (e.key === "Enter") {+ e.preventDefault();+ if (openList && activeIndex >= 0 && suggestions[activeIndex]) {+ commit(suggestions[activeIndex]);+ } else if (query.trim()) {+ commit(query.trim());+ }+ } else if (e.key === "Escape") {+ setOpenList(false);+ } else if (e.key === "Backspace" && !query && selected.length > 0) {+ onRemove(selected[selected.length - 1]!);+ }+ };++ const handlePaste = (e: React.ClipboardEvent<HTMLInputElement>) => {+ const text = e.clipboardData.getData("text");+ if (/[\n,]/.test(text)) {+ e.preventDefault();+ onAdd(text.split(/[\n,]+/));+ setQuery("");+ }+ };++ return (+ <div ref={containerRef} className="relative">+ <div+ className="flex flex-wrap items-center gap-1.5 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2 py-1.5 focus-within:ring-1 focus-within:ring-[var(--color-accent-primary)]"+ onClick={() => containerRef.current?.querySelector("input")?.focus()}+ >+ {selected.map((p) => (+ <span+ key={p}+ className="inline-flex items-center gap-1 rounded border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-1.5 py-0.5 text-xs font-mono text-[var(--color-text-primary)]"+ title={p}+ >+ <span className="truncate max-w-[280px]">{p}</span>+ <button+ type="button"+ onClick={(e) => {+ e.stopPropagation();+ onRemove(p);+ }}+ aria-label={`Remove ${p}`}+ className="text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)]"+ >+ <X className="h-3 w-3" />+ </button>+ </span>+ ))}+ <input+ value={query}+ onChange={(e) => setQuery(e.target.value)}+ onKeyDown={handleKeyDown}+ onPaste={handlePaste}+ onFocus={() => suggestions.length > 0 && setOpenList(true)}+ placeholder={+ selected.length === 0+ ? "src/auth/login.py — type to search, paste a list, Enter to add"+ : "Add another…"+ }+ aria-label="Changed file paths"+ role="combobox"+ aria-expanded={openList}+ aria-controls="impact-file-suggestions"+ aria-autocomplete="list"+ className="min-w-[180px] flex-1 bg-transparent px-1 py-0.5 text-xs font-mono text-[var(--color-text-primary)] placeholder:text-[var(--color-text-tertiary)] focus:outline-none"+ />+ </div>+ {openList && suggestions.length > 0 ? (+ <ul+ id="impact-file-suggestions"+ role="listbox"+ className="absolute z-20 mt-1 w-full max-h-56 overflow-y-auto rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)] py-1 shadow-lg"+ >+ {suggestions.map((s, i) => (+ <li key={s} role="option" aria-selected={i === activeIndex}>+ <button+ type="button"+ onMouseDown={(e) => {+ e.preventDefault();+ commit(s);+ }}+ onMouseEnter={() => setActiveIndex(i)}+ className={`block w-full truncate px-3 py-1.5 text-left text-xs font-mono ${+ i === activeIndex+ ? "bg-[var(--color-bg-elevated)] text-[var(--color-text-primary)]"+ : "text-[var(--color-text-secondary)]"+ }`}+ title={s}+ >+ {s}+ </button>+ </li>+ ))}+ </ul>+ ) : null}+ </div>+ );+}diff --git a/packages/ui/src/health/health-distribution-bar.tsx b/packages/ui/src/health/health-distribution-bar.tsxindex 59920b0fa..b451aa2f9 100644--- a/packages/ui/src/health/health-distribution-bar.tsx+++ b/packages/ui/src/health/health-distribution-bar.tsx@@ -65,7 +65,7 @@ export function HealthDistributionBar({})}</div>{showCounts && (- <div className="flex flex-wrap gap-x-3 gap-y-0.5 text-[11px] text-[var(--color-text-tertiary)]">+ <div className="flex flex-wrap gap-x-3 gap-y-0.5 text-xs text-[var(--color-text-tertiary)]">{ORDER.map((b) => (<span key={b} className="inline-flex items-center gap-1 tabular-nums"><span className={`inline-block h-1.5 w-1.5 rounded-full ${BAND_DOT[b]}`} />diff --git a/packages/ui/src/health/hidden-coupling-list.tsx b/packages/ui/src/health/hidden-coupling-list.tsxindex f9951309b..c7b2df546 100644--- a/packages/ui/src/health/hidden-coupling-list.tsx+++ b/packages/ui/src/health/hidden-coupling-list.tsx@@ -1,6 +1,7 @@"use client";-import { ArrowLeftRight } from "lucide-react";+import { useState } from "react";+import { ArrowLeftRight, ChevronDown, ChevronRight } from "lucide-react";import type { BiomarkerDetailsRecord } from "./biomarker-details";import { SEVERITY_CHIP, SEVERITY_LABEL, type Severity } from "./tokens";@@ -18,6 +19,10 @@ export interface HiddenCouplingListProps {limit?: number;onSelect?: ((path: string) => void) | undefined;hrefFor?: ((path: string) => string) | undefined;+ /** Start collapsed, showing only `collapsedCount` pairs behind a toggle. */+ collapsible?: boolean;+ /** Pairs shown while collapsed. */+ collapsedCount?: number;}interface CouplingPair {@@ -89,24 +94,49 @@ export function HiddenCouplingList({limit = 15,onSelect,hrefFor,+ collapsible = false,+ collapsedCount = 4,}: HiddenCouplingListProps) {- const rows = aggregate(findings).slice(0, limit);- if (rows.length === 0) return null;+ const all = aggregate(findings).slice(0, limit);+ const [open, setOpen] = useState(!collapsible);+ if (all.length === 0) return null;+ const rows = open ? all : all.slice(0, collapsedCount);+ const headerInner = (+ <>+ {collapsible ? (+ open ? (+ <ChevronDown className="h-4 w-4 text-[var(--color-text-tertiary)]" aria-hidden="true" />+ ) : (+ <ChevronRight className="h-4 w-4 text-[var(--color-text-tertiary)]" aria-hidden="true" />+ )+ ) : null}+ <ArrowLeftRight className="h-4 w-4 text-[var(--color-accent-secondary)]" aria-hidden="true" />+ <h2 className="text-sm font-medium text-[var(--color-text-primary)]">Hidden coupling pairs</h2>+ <span className="text-xs text-[var(--color-text-tertiary)]">+ Files that co-change without an import edge+ </span>+ <span className="ml-auto text-xs text-[var(--color-text-tertiary)]">+ {all.length} pair{all.length === 1 ? "" : "s"}+ </span>+ </>+ );return (<section className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)]">- <header className="flex items-center gap-2 px-4 py-3 border-b border-[var(--color-border-default)]">- <ArrowLeftRight className="h-4 w-4 text-violet-500" aria-hidden="true" />- <h2 className="text-sm font-medium text-[var(--color-text-primary)]">- Hidden coupling pairs- </h2>- <span className="text-xs text-[var(--color-text-tertiary)]">- Files that co-change without an import edge- </span>- <span className="ml-auto text-xs text-[var(--color-text-tertiary)]">- {rows.length} pair{rows.length === 1 ? "" : "s"}- </span>- </header>+ {collapsible ? (+ <button+ type="button"+ onClick={() => setOpen((v) => !v)}+ aria-expanded={open}+ className="flex w-full items-center gap-2 px-4 py-3 border-b border-[var(--color-border-default)] text-left hover:bg-[var(--color-bg-elevated)] transition-colors"+ >+ {headerInner}+ </button>+ ) : (+ <header className="flex items-center gap-2 px-4 py-3 border-b border-[var(--color-border-default)]">+ {headerInner}+ </header>+ )}<ul className="divide-y divide-[var(--color-border-default)]">{rows.map((row) => (<li key={row.key} className="p-3 space-y-1.5">@@ -123,7 +153,7 @@ export function HiddenCouplingList({<span>· {row.co_change_count} co-commits</span></span></div>- <div className="grid grid-cols-1 gap-1 text-[11px] font-mono">+ <div className="grid grid-cols-1 gap-1 text-xs font-mono"><PairLink path={row.a} onSelect={onSelect} hrefFor={hrefFor} /><span className="text-[var(--color-text-tertiary)] inline-flex items-center gap-1"><ArrowLeftRight className="h-3 w-3" aria-hidden="true" />@@ -133,6 +163,15 @@ export function HiddenCouplingList({</li>))}</ul>+ {collapsible && all.length > collapsedCount ? (+ <button+ type="button"+ onClick={() => setOpen((v) => !v)}+ className="w-full border-t border-[var(--color-border-default)] px-4 py-2 text-xs font-medium text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)] transition-colors"+ >+ {open ? "Show less" : `Show all ${all.length}`}+ </button>+ ) : null}</section>);}diff --git a/packages/ui/src/health/hot-functions-panel.tsx b/packages/ui/src/health/hot-functions-panel.tsxindex b2e6a7511..c951bb7df 100644--- a/packages/ui/src/health/hot-functions-panel.tsx+++ b/packages/ui/src/health/hot-functions-panel.tsx@@ -1,6 +1,7 @@"use client";-import { ArrowUpRight, Flame } from "lucide-react";+import { useState } from "react";+import { ArrowUpRight, ChevronDown, ChevronRight, Flame } from "lucide-react";import { biomarkerLabel } from "./biomarker-glossary";import type { BiomarkerDetailsRecord } from "./biomarker-details";import { SEVERITY_CHIP, SEVERITY_LABEL, type Severity } from "./tokens";@@ -27,6 +28,10 @@ export interface HotFunctionsPanelProps {onSelect?: ((f: HotFunctionFinding) => void) | undefined;/** Href for the function name → canonical symbol page. */symbolHrefFor?: ((f: HotFunctionFinding) => string | undefined) | undefined;+ /** Start collapsed, showing only `collapsedCount` rows behind a toggle. */+ collapsible?: boolean;+ /** Rows shown while collapsed. */+ collapsedCount?: number;}const HOT_FUNCTION_BIOMARKERS = new Set([@@ -88,24 +93,49 @@ export function HotFunctionsPanel({limit = 15,onSelect,symbolHrefFor,+ collapsible = false,+ collapsedCount = 4,}: HotFunctionsPanelProps) {- const rows = aggregate(findings).slice(0, limit);- if (rows.length === 0) return null;+ const all = aggregate(findings).slice(0, limit);+ const [open, setOpen] = useState(!collapsible);+ if (all.length === 0) return null;+ const rows = open ? all : all.slice(0, collapsedCount);+ const headerInner = (+ <>+ {collapsible ? (+ open ? (+ <ChevronDown className="h-4 w-4 text-[var(--color-text-tertiary)]" aria-hidden="true" />+ ) : (+ <ChevronRight className="h-4 w-4 text-[var(--color-text-tertiary)]" aria-hidden="true" />+ )+ ) : null}+ <Flame className="h-4 w-4 text-[var(--color-warning)]" aria-hidden="true" />+ <h2 className="text-sm font-medium text-[var(--color-text-primary)]">Hot functions</h2>+ <span className="text-xs text-[var(--color-text-tertiary)]">+ Top functions where churn, age, and complexity collide+ </span>+ <span className="ml-auto text-xs text-[var(--color-text-tertiary)]">+ {all.length} function{all.length === 1 ? "" : "s"}+ </span>+ </>+ );return (<section className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)]">- <header className="flex items-center gap-2 px-4 py-3 border-b border-[var(--color-border-default)]">- <Flame className="h-4 w-4 text-[var(--color-warning)]" aria-hidden="true" />- <h2 className="text-sm font-medium text-[var(--color-text-primary)]">- Hot functions- </h2>- <span className="text-xs text-[var(--color-text-tertiary)]">- Top functions where churn, age, and complexity collide- </span>- <span className="ml-auto text-xs text-[var(--color-text-tertiary)]">- {rows.length} function{rows.length === 1 ? "" : "s"}- </span>- </header>+ {collapsible ? (+ <button+ type="button"+ onClick={() => setOpen((v) => !v)}+ aria-expanded={open}+ className="flex w-full items-center gap-2 px-4 py-3 border-b border-[var(--color-border-default)] text-left hover:bg-[var(--color-bg-elevated)] transition-colors"+ >+ {headerInner}+ </button>+ ) : (+ <header className="flex items-center gap-2 px-4 py-3 border-b border-[var(--color-border-default)]">+ {headerInner}+ </header>+ )}<ul className="divide-y divide-[var(--color-border-default)]">{rows.map((row) => {const interactive = !!onSelect;@@ -140,7 +170,7 @@ export function HotFunctionsPanel({</span>);})()}- <span className="text-[11px] font-mono text-[var(--color-text-tertiary)] truncate">+ <span className="text-xs font-mono text-[var(--color-text-tertiary)] truncate">{row.file_path}</span><span className="ml-auto inline-flex items-center gap-2">@@ -166,6 +196,15 @@ export function HotFunctionsPanel({);})}</ul>+ {collapsible && all.length > collapsedCount ? (+ <button+ type="button"+ onClick={() => setOpen((v) => !v)}+ className="w-full border-t border-[var(--color-border-default)] px-4 py-2 text-xs font-medium text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)] transition-colors"+ >+ {open ? "Show less" : `Show all ${all.length}`}+ </button>+ ) : null}</section>);}diff --git a/packages/ui/src/health/impact-effort-quadrant.tsx b/packages/ui/src/health/impact-effort-quadrant.tsxindex 12704e4c9..aa72e2a12 100644--- a/packages/ui/src/health/impact-effort-quadrant.tsx+++ b/packages/ui/src/health/impact-effort-quadrant.tsx@@ -44,13 +44,19 @@ export function ImpactEffortQuadrant({const plotW = W - padL - padR;const plotH = H - padT - padB;const maxImpact = Math.max(...data.map((d) => d.total_impact), 1);+ const minImpact = Math.min(...data.map((d) => d.total_impact));+ // When every impact is identical (or zero) the (max−impact)/max ratio would+ // collapse every dot onto the top edge and degenerate the midline. Center the+ // dots vertically instead so the plot stays readable.+ const flatImpact = maxImpact === minImpact || maxImpact === 0;const xScale = (pct: number) => padL + (pct / 100) * plotW;- const yScale = (impact: number) => padT + ((maxImpact - impact) / maxImpact) * plotH;+ const yScale = (impact: number) =>+ flatImpact ? padT + plotH / 2 : padT + ((maxImpact - impact) / maxImpact) * plotH;// Quadrant midpoints — between M (38) and L (62), and at half impact.const midX = xScale(50);- const midY = yScale(maxImpact / 2);+ const midY = flatImpact ? padT + plotH / 2 : yScale(maxImpact / 2);// Jitter helper so dots within the same effort bucket don't perfectly stack.const jitter = (s: string) => {@@ -131,7 +137,7 @@ export function ImpactEffortQuadrant({})}</svg>{hovered ? (- <div className="pointer-events-none absolute bottom-2 left-2 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2 py-1 text-[11px] shadow-md">+ <div className="pointer-events-none absolute bottom-2 left-2 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2 py-1 text-xs shadow-md"><span className="font-mono text-[var(--color-text-primary)]">{hovered.file_path}</span><span className="ml-2 text-[var(--color-text-tertiary)]">−{hovered.total_impact.toFixed(2)} · {hovered.effort_bucket} · {hovered.score.toFixed(1)}diff --git a/packages/ui/src/health/index.ts b/packages/ui/src/health/index.tsindex 276eacb2d..d0f746e90 100644--- a/packages/ui/src/health/index.ts+++ b/packages/ui/src/health/index.ts@@ -19,10 +19,14 @@ export * from "./sparkline";export * from "./health-tabs";export * from "./page-chrome";export * from "./trend-chart";+export * from "./trend-slope-chart";export * from "./file-trend-chart";export * from "./file-signals-panel";export * from "./risk-coverage-scatter";export * from "./impact-effort-quadrant";+export * from "./code-health-map";+export * from "./code-health-controls";+export * from "./file-path-picker";export * from "./churn-complexity-quadrant";export * from "./health-file-drawer";export * from "./ai-prompt-builder";diff --git a/packages/ui/src/health/kpi-cards.tsx b/packages/ui/src/health/kpi-cards.tsxindex 0ce7ea5f2..cf5fe5eb8 100644--- a/packages/ui/src/health/kpi-cards.tsx+++ b/packages/ui/src/health/kpi-cards.tsx@@ -137,7 +137,7 @@ function Card({</div>{children}{delta != null ? (- <p className={`mt-1 text-[11px] tabular-nums ${deltaColor(delta)}`}>+ <p className={`mt-1 text-xs tabular-nums ${deltaColor(delta)}`}>{formatDelta(delta)} vs. prior</p>) : null}diff --git a/packages/ui/src/health/page-chrome.tsx b/packages/ui/src/health/page-chrome.tsxindex 41209d6cc..af5ce65e6 100644--- a/packages/ui/src/health/page-chrome.tsx+++ b/packages/ui/src/health/page-chrome.tsx@@ -59,7 +59,7 @@ export function HealthPageChrome({<p className="text-sm text-[var(--color-text-secondary)]">{subtitle}</p>) : null}{meta ? (- <p className="mt-1 text-[11px] text-[var(--color-text-tertiary)]">+ <p className="mt-1 text-xs text-[var(--color-text-tertiary)]">Indexed {formatIndexedAt(meta.last_indexed_at)}{meta.head_commit ? (<>diff --git a/packages/ui/src/health/refactoring-card.tsx b/packages/ui/src/health/refactoring-card.tsxindex 4d001ee97..e5fa064fb 100644--- a/packages/ui/src/health/refactoring-card.tsx+++ b/packages/ui/src/health/refactoring-card.tsx@@ -144,7 +144,7 @@ export function RefactoringCard({{target.primary_suggestion}</p>) : null}- <div className="flex items-center gap-3 pt-1 text-[11px] text-[var(--color-text-tertiary)] flex-wrap">+ <div className="flex items-center gap-3 pt-1 text-xs text-[var(--color-text-tertiary)] flex-wrap"><span>Score {target.score.toFixed(1)}/10</span><span>· {target.nloc} NLOC</span><span>· {effortLabel[target.effort_bucket]} effort</span>@@ -194,11 +194,11 @@ export function RefactoringCard({{f.function_name ? (<span className="text-xs font-mono text-[var(--color-text-tertiary)]">{f.function_name}</span>) : null}- <span className="ml-auto text-[11px] tabular-nums text-[var(--color-error)]">+ <span className="ml-auto text-xs tabular-nums text-[var(--color-error)]">−{f.health_impact.toFixed(2)}</span></div>- <p className="text-[11px] text-[var(--color-text-tertiary)] line-clamp-2">{f.reason}</p>+ <p className="text-xs text-[var(--color-text-tertiary)] line-clamp-2">{f.reason}</p>{onStatusChange ? (<div className="flex flex-wrap gap-1 pt-1"><StatusButton current={f.status} value="acknowledged" onClick={() => onStatusChange(f.id, "acknowledged")} label="Acknowledge" />diff --git a/packages/ui/src/health/risk-coverage-scatter.tsx b/packages/ui/src/health/risk-coverage-scatter.tsxindex ea4e5a07d..72045e50c 100644--- a/packages/ui/src/health/risk-coverage-scatter.tsx+++ b/packages/ui/src/health/risk-coverage-scatter.tsx@@ -150,7 +150,7 @@ export function RiskCoverageScatter({})}</svg>{hovered ? (- <div className="pointer-events-none absolute bottom-2 left-2 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2 py-1 text-[11px] shadow-md">+ <div className="pointer-events-none absolute bottom-2 left-2 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2 py-1 text-xs shadow-md"><span className="font-mono text-[var(--color-text-primary)]">{hovered.file_path}</span><span className="ml-2 text-[var(--color-text-tertiary)]">{hovered.health_score.toFixed(1)} · {hovered.line_coverage_pct?.toFixed(0)}% · {hovered.nloc} NLOCdiff --git a/packages/ui/src/health/score-breakdown.tsx b/packages/ui/src/health/score-breakdown.tsxindex bf1259dfd..726ebfb0e 100644--- a/packages/ui/src/health/score-breakdown.tsx+++ b/packages/ui/src/health/score-breakdown.tsx@@ -93,10 +93,10 @@ export function ScoreBreakdown({{c.findings.slice(0, 6).map((f) => (<likey={f.id}- className="flex flex-wrap items-baseline gap-x-2 text-[11px]"+ className="flex flex-wrap items-baseline gap-x-2 text-xs"><span- className={`inline-block rounded px-1.5 py-px text-[9px] uppercase font-semibold ${SEVERITY_CHIP[f.severity]}`}+ className={`inline-block rounded px-1.5 py-px text-[10px] uppercase font-semibold ${SEVERITY_CHIP[f.severity]}`}>{SEVERITY_LABEL[f.severity]}</span>@@ -114,7 +114,7 @@ export function ScoreBreakdown({</li>))}{c.findings.length > 6 ? (- <li className="text-[11px] text-[var(--color-text-tertiary)]">+ <li className="text-xs text-[var(--color-text-tertiary)]">+ {c.findings.length - 6} more</li>) : null}diff --git a/packages/ui/src/health/severity-distribution.tsx b/packages/ui/src/health/severity-distribution.tsxindex 0c54bc41d..d4ae9afd5 100644--- a/packages/ui/src/health/severity-distribution.tsx+++ b/packages/ui/src/health/severity-distribution.tsx@@ -49,7 +49,7 @@ export function SeverityDistribution({})}</div>{showCounts && (- <div className="flex flex-wrap gap-x-3 gap-y-0.5 text-[11px] text-[var(--color-text-tertiary)]">+ <div className="flex flex-wrap gap-x-3 gap-y-0.5 text-xs text-[var(--color-text-tertiary)]">{ORDER.map((s) => (<span key={s} className="inline-flex items-center gap-1 tabular-nums"><span className={`inline-block h-1.5 w-1.5 rounded-full ${SEVERITY_BAR[s]}`} />diff --git a/packages/ui/src/health/trend-chart.tsx b/packages/ui/src/health/trend-chart.tsxindex be0304684..9685cc83b 100644--- a/packages/ui/src/health/trend-chart.tsx+++ b/packages/ui/src/health/trend-chart.tsx@@ -52,7 +52,7 @@ export function TrendChart({ history, height = 220 }: TrendChartProps) {<h3 className="text-sm font-semibold text-[var(--color-text-primary)]">KPI trend</h3>- <div className="flex items-center gap-3 text-[11px] text-[var(--color-text-tertiary)]">+ <div className="flex items-center gap-3 text-xs text-[var(--color-text-tertiary)]"><Legend dot="bg-[var(--color-success)]" label="Average" /><Legend dot="bg-[var(--color-warning)]" label="Hotspot" /><Legend dot="bg-[var(--color-error)]" label="Worst" />diff --git a/packages/ui/src/health/trend-slope-chart.tsx b/packages/ui/src/health/trend-slope-chart.tsxnew file mode 100644index 000000000..b683e3b26--- /dev/null+++ b/packages/ui/src/health/trend-slope-chart.tsx@@ -0,0 +1,121 @@+"use client";++import { useMemo, useState } from "react";+import { scoreBand } from "./tokens";++export interface TrendSlopePoint {+ file_path: string;+ before: number;+ after: number;+ delta: number;+}++export interface TrendSlopeChartProps {+ points: TrendSlopePoint[];+ height?: number;+ /** Cap the number of slopes drawn (largest |delta| first). */+ max?: number;+}++const BAND_STROKE: Record<string, string> = {+ critical: "var(--color-error)",+ poor: "var(--color-warning)",+ fair: "var(--color-caution)",+ good: "var(--color-success)",+};++/**+ * Slope chart for "largest score changes" — each file is a line from its+ * before-score to its after-score across two snapshot columns. Declines drop,+ * improvements rise; colour follows the after-score health band. Replaces the+ * Before/After/Δ table (movement is read positionally, not parsed row by row).+ */+export function TrendSlopeChart({ points, height = 320, max = 18 }: TrendSlopeChartProps) {+ const [hovered, setHovered] = useState<TrendSlopePoint | null>(null);++ const data = useMemo(+ () =>+ [...points]+ .sort((a, b) => Math.abs(b.delta) - Math.abs(a.delta))+ .slice(0, max),+ [points, max],+ );++ if (data.length === 0) {+ return (+ <div className="rounded-lg border border-dashed border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-6 text-sm text-[var(--color-text-tertiary)]">+ No per-file score changes to plot yet.+ </div>+ );+ }++ const W = 640;+ const H = height;+ const padT = 16;+ const padB = 28;+ const xBefore = 140;+ const xAfter = W - 140;+ const plotH = H - padT - padB;++ // Fixed 0–10 health domain so the slope angle is meaningful across renders.+ const yScale = (score: number) => padT + ((10 - Math.max(0, Math.min(10, score))) / 10) * plotH;++ return (+ <div className="relative rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3">+ <svg viewBox={`0 0 ${W} ${H}`} width="100%" height={H} role="img" aria-label="Score change slope chart">+ {/* Axis columns */}+ <line x1={xBefore} y1={padT} x2={xBefore} y2={H - padB} stroke="currentColor" strokeOpacity={0.15} />+ <line x1={xAfter} y1={padT} x2={xAfter} y2={H - padB} stroke="currentColor" strokeOpacity={0.15} />+ <text x={xBefore} y={H - 8} fontSize={11} textAnchor="middle" fill="currentColor" opacity={0.6}>+ Before+ </text>+ <text x={xAfter} y={H - 8} fontSize={11} textAnchor="middle" fill="currentColor" opacity={0.6}>+ After+ </text>++ {data.map((p) => {+ const y1 = yScale(p.before);+ const y2 = yScale(p.after);+ const stroke = BAND_STROKE[scoreBand(p.after)] ?? "var(--color-caution)";+ const isHovered = hovered?.file_path === p.file_path;+ const name = p.file_path.split("/").pop() ?? p.file_path;+ return (+ <g+ key={p.file_path}+ onMouseEnter={() => setHovered(p)}+ onMouseLeave={() => setHovered(null)}+ className="cursor-default"+ >+ <line+ x1={xBefore}+ y1={y1}+ x2={xAfter}+ y2={y2}+ stroke={stroke}+ strokeWidth={isHovered ? 2.5 : 1.5}+ strokeOpacity={hovered && !isHovered ? 0.25 : 0.8}+ />+ <circle cx={xBefore} cy={y1} r={isHovered ? 4 : 3} fill={stroke} fillOpacity={0.9} />+ <circle cx={xAfter} cy={y2} r={isHovered ? 4 : 3} fill={stroke} fillOpacity={0.9} />+ <text x={xBefore - 8} y={y1 + 3} fontSize={10} textAnchor="end" fill="currentColor" opacity={isHovered ? 0.9 : 0.55}>+ {p.before.toFixed(1)}+ </text>+ <text x={xAfter + 8} y={y2 + 3} fontSize={10} textAnchor="start" fill="currentColor" opacity={isHovered ? 0.9 : 0.55}>+ {name}+ </text>+ </g>+ );+ })}+ </svg>+ {hovered ? (+ <div className="pointer-events-none absolute left-2 top-2 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2 py-1 text-xs shadow-md">+ <span className="font-mono text-[var(--color-text-primary)]">{hovered.file_path}</span>+ <span className="ml-2 tabular-nums text-[var(--color-text-tertiary)]">+ {hovered.before.toFixed(1)} → {hovered.after.toFixed(1)} ({hovered.delta >= 0 ? "+" : ""}+ {hovered.delta.toFixed(1)})+ </span>+ </div>+ ) : null}+ </div>+ );+}diff --git a/packages/ui/src/lib/format.ts b/packages/ui/src/lib/format.tsindex dfe0ecc25..2c8d63eb0 100644--- a/packages/ui/src/lib/format.ts+++ b/packages/ui/src/lib/format.ts@@ -47,6 +47,18 @@ export function formatRelativeTime(date: string | Date): string {return `${Math.floor(months / 12)}y ago`;}+/** Relative time that tolerates null/invalid input, returning `fallback`+ * (default "—"). The single null-safe wrapper used by the owner surfaces. */+export function formatRelativeTimeOrNull(+ iso: string | null | undefined,+ fallback = "—",+): string {+ if (!iso) return fallback;+ const d = new Date(iso);+ if (Number.isNaN(d.getTime()) || d.getTime() > Date.now()) return fallback;+ return formatRelativeTime(d);+}+/** Format a datetime to an absolute string: "Mar 19, 2026" */export function formatDate(date: string | Date): string {const d = typeof date === "string" ? new Date(date) : date;diff --git a/packages/ui/src/modules/index.ts b/packages/ui/src/modules/index.tsindex 08f28205e..fec8a3805 100644--- a/packages/ui/src/modules/index.ts+++ b/packages/ui/src/modules/index.ts@@ -1,3 +1,5 @@export * from "./module-health-card";export * from "./module-health-list";export * from "./module-health-detail";+export * from "./module-helpers";+export * from "./module-detail-shell";diff --git a/packages/ui/src/modules/module-detail-shell.tsx b/packages/ui/src/modules/module-detail-shell.tsxnew file mode 100644index 000000000..3fd12c2a1--- /dev/null+++ b/packages/ui/src/modules/module-detail-shell.tsx@@ -0,0 +1,39 @@+"use client";++import * as React from "react";+import { ArrowLeft } from "lucide-react";++export interface ModuleDetailShellProps {+ /** Href for the "← All modules" back link. */+ backHref: string;+ LinkComponent?: React.ElementType<{+ href: string;+ className?: string;+ children: React.ReactNode;+ }>;+ children?: React.ReactNode;+}++/**+ * The ui-owned chrome for the module detail route: the `← All modules` back+ * link plus the centred wide shell. Lives in ui so the hosted app picks up+ * the layout on a package bump; the web route only injects the href + Link.+ */+export function ModuleDetailShell({+ backHref,+ LinkComponent = "a",+ children,+}: ModuleDetailShellProps) {+ const Link = LinkComponent;+ return (+ <div className="mx-auto w-full max-w-[1600px] space-y-4 p-4 sm:p-6">+ <Link+ href={backHref}+ className="inline-flex items-center gap-1 text-xs text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]"+ >+ <ArrowLeft className="h-3 w-3" /> All modules+ </Link>+ {children}+ </div>+ );+}diff --git a/packages/ui/src/modules/module-health-card.tsx b/packages/ui/src/modules/module-health-card.tsxindex 573becd4a..a4d7a451a 100644--- a/packages/ui/src/modules/module-health-card.tsx+++ b/packages/ui/src/modules/module-health-card.tsx@@ -5,6 +5,7 @@ import type { ModuleHealthSummary } from "@repowise-dev/types/modules";import { Card, CardContent } from "../ui/card";import { Badge } from "../ui/badge";import { cn } from "../lib/cn";+import { HealthChip, MetricTile } from "./module-helpers";interface ModuleHealthCardProps {module: ModuleHealthSummary;@@ -12,18 +13,11 @@ interface ModuleHealthCardProps {compact?: boolean | undefined;}-function scoreClass(score: number): string {- if (score >= 70) return "text-emerald-300 bg-emerald-500/10 border-emerald-500/40";- if (score >= 40) return "text-amber-300 bg-amber-500/10 border-amber-500/40";- return "text-red-300 bg-red-500/10 border-red-500/40";-}-/*** Single module health card — at-a-glance summary of churn, owners, dead* code, docs and decisions for one module. Sized for a 3-column grid.*/export function ModuleHealthCard({ module, onClick, compact }: ModuleHealthCardProps) {- const score = Math.round(module.health_score);return (<CardonClick={() => onClick?.(module)}@@ -39,32 +33,23 @@ export function ModuleHealthCard({ module, onClick, compact }: ModuleHealthCardP<Folder className="h-4 w-4 text-[var(--color-text-tertiary)]" /><span className="truncate">{module.module_path}</span></div>- <p className="mt-0.5 text-[10px] text-[var(--color-text-tertiary)]">+ <p className="mt-0.5 text-xs text-[var(--color-text-tertiary)]">{module.file_count} files · {module.symbol_count} symbols</p></div>- <div- className={cn(- "rounded-md border px-2 py-1 text-center",- scoreClass(module.health_score),- )}- title="Composite health score — see module health doc"- >- <div className="text-lg font-bold leading-none tabular-nums">{score}</div>- <div className="text-[9px] uppercase tracking-wider opacity-70">health</div>- </div>+ <HealthChip score={module.health_score} size="sm" /></div><div className="mt-3 grid grid-cols-3 gap-2 text-xs">- <Metric icon={<Flame className="h-3 w-3 text-orange-400" />} label="Hotspots" value={module.hotspot_count} />- <Metric icon={<Trash2 className="h-3 w-3 text-rose-400" />} label="Dead lines" value={module.dead_code_lines} />- <Metric icon={<BookOpen className="h-3 w-3 text-sky-400" />} label="Doc" value={`${Math.round(module.doc_coverage_pct)}%`} />- <Metric icon={<Users className="h-3 w-3 text-violet-400" />} label="Bus med" value={module.median_bus_factor.toFixed(1)} />- <Metric icon={<ShieldAlert className="h-3 w-3 text-red-400" />} label="Bus min" value={module.min_bus_factor} />- <Metric icon={<Lightbulb className="h-3 w-3 text-yellow-400" />} label="Decisions" value={module.decision_count} />+ <MetricTile size="sm" icon={<Flame className="h-3 w-3 text-[var(--color-warning)]" />} label="Hotspots" value={module.hotspot_count} />+ <MetricTile size="sm" icon={<Trash2 className="h-3 w-3 text-[var(--color-error)]" />} label="Dead lines" value={module.dead_code_lines} />+ <MetricTile size="sm" icon={<BookOpen className="h-3 w-3 text-[var(--color-info)]" />} label="Doc" value={`${Math.round(module.doc_coverage_pct)}%`} />+ <MetricTile size="sm" icon={<Users className="h-3 w-3 text-[var(--color-accent-primary)]" />} label="Bus med" value={module.median_bus_factor.toFixed(1)} />+ <MetricTile size="sm" icon={<ShieldAlert className="h-3 w-3 text-[var(--color-error)]" />} label="Bus min" value={module.min_bus_factor} />+ <MetricTile size="sm" icon={<Lightbulb className="h-3 w-3 text-[var(--color-caution)]" />} label="Decisions" value={module.decision_count} /></div>- <div className="mt-3 flex items-center justify-between text-[11px]">+ <div className="mt-3 flex items-center justify-between text-xs"><span className="truncate text-[var(--color-text-secondary)]">{module.primary_owner ?? "—"}{module.primary_owner && (@@ -88,23 +73,3 @@ export function ModuleHealthCard({ module, onClick, compact }: ModuleHealthCardP</Card>);}--function Metric({- icon,- label,- value,-}: {- icon: React.ReactNode;- label: string;- value: string | number;-}) {- return (- <div>- <div className="flex items-center gap-0.5 text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">- {icon}- {label}- </div>- <div className="tabular-nums font-semibold text-[var(--color-text-primary)]">{value}</div>- </div>- );-}diff --git a/packages/ui/src/modules/module-health-detail.tsx b/packages/ui/src/modules/module-health-detail.tsxindex 682d99537..a1df6a71b 100644--- a/packages/ui/src/modules/module-health-detail.tsx+++ b/packages/ui/src/modules/module-health-detail.tsx@@ -1,7 +1,6 @@"use client";import {- Folder,Flame,Trash2,BookOpen,@@ -19,109 +18,101 @@ import { Badge } from "../ui/badge";import { cn } from "../lib/cn";import { truncatePath } from "../lib/format";import { OwnerAvatar } from "../owners/owner-avatar";--function scoreCls(score: number): string {- if (score >= 70) return "text-emerald-300 bg-emerald-500/10 border-emerald-500/40";- if (score >= 40) return "text-amber-300 bg-amber-500/10 border-amber-500/40";- return "text-red-300 bg-red-500/10 border-red-500/40";-}+import { EntityHeader } from "../shared/entity";+import type { BreadcrumbSegment } from "../shared/breadcrumb";+import { HealthChip, MetricTile, ModuleIdentity } from "./module-helpers";export interface ModuleHealthDetailViewProps {module: ModuleHealthDetailModel;+ /** Breadcrumb back to repo › modules. Built by the web route. */+ breadcrumb?: BreadcrumbSegment[];+ LinkComponent?: React.ElementType<{+ href: string;+ className?: string;+ children: React.ReactNode;+ }>;onSelectOwner?: (owner: ModuleHealthOwner) => void;onSelectFile?: (filePath: string) => void;onSelectDecision?: (decisionId: string) => void;}/**- * Single-module deep view: composite health score, owner mix, hotspots,- * decisions, and headline metrics. Mirrors {@link OwnerProfileView} in- * tone — fast to scan, all numbers linked.+ * Single-module deep view: a standardized entity header (eyebrow, breadcrumb,+ * identity, one-line summary, primary health signal) over the owner mix,+ * hotspots, decisions, and headline metric tiles.*/export function ModuleHealthDetailView({module,+ breadcrumb,+ LinkComponent,onSelectOwner,onSelectFile,onSelectDecision,}: ModuleHealthDetailViewProps) {- const score = Math.round(module.health_score);+ const summary = moduleSummary(module);return (<div className="space-y-6">- {/* ── Header ── */}- <Card>- <CardContent className="p-5">- <div className="flex flex-wrap items-start gap-5">- <div- className={cn(- "flex flex-col items-center justify-center rounded-lg border px-4 py-3 text-center min-w-[88px]",- scoreCls(module.health_score),- )}- >- <span className="text-3xl font-bold tabular-nums">{score}</span>- <span className="text-[10px] uppercase tracking-wider opacity-70">- health- </span>- </div>- <div className="flex-1 min-w-0">- <h1 className="flex items-center gap-2 text-2xl font-bold text-[var(--color-text-primary)]">- <Folder className="h-5 w-5 text-[var(--color-text-tertiary)]" />- {module.module_path}- </h1>- <p className="mt-1 text-xs text-[var(--color-text-tertiary)]">- {module.file_count} files · {module.symbol_count} symbols ·{" "}- {module.contributor_count} contributors- </p>- <div className="mt-2 flex flex-wrap items-center gap-2">- {module.is_silo && <Badge variant="outdated">silo</Badge>}- {module.min_bus_factor <= 1 && (- <Badge variant="outdated">bus ≤ 1</Badge>- )}- {module.decision_count > 0 && (- <Badge variant="accent">- {module.decision_count} decisions- </Badge>- )}- </div>- </div>- </div>+ <EntityHeader+ eyebrow="MODULE"+ breadcrumb={breadcrumb ?? []}+ identity={+ <ModuleIdentity+ modulePath={module.module_path}+ fileCount={module.file_count}+ symbolCount={module.symbol_count}+ contributorCount={module.contributor_count}+ />+ }+ summary={summary}+ primarySignal={<HealthChip score={module.health_score} size="lg" />}+ metaBadges={+ <>+ {module.is_silo && <Badge variant="outdated">silo</Badge>}+ {module.min_bus_factor <= 1 && <Badge variant="outdated">bus ≤ 1</Badge>}+ {module.decision_count > 0 && (+ <Badge variant="accent">{module.decision_count} decisions</Badge>+ )}+ </>+ }+ {...(LinkComponent ? { LinkComponent } : {})}+ />- <div className="mt-5 grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-6">- <Headline- label="Hotspots"- value={module.hotspot_count}- icon={<Flame className="h-3.5 w-3.5 text-orange-400" />}- tone={module.hotspot_count > 0 ? "warn" : undefined}- />- <Headline- label="Dead lines"- value={module.dead_code_lines}- icon={<Trash2 className="h-3.5 w-3.5 text-rose-400" />}- tone={module.dead_code_lines > 0 ? "warn" : undefined}- />- <Headline- label="Doc coverage"- value={`${Math.round(module.doc_coverage_pct)}%`}- icon={<BookOpen className="h-3.5 w-3.5 text-sky-400" />}- />- <Headline- label="Bus med"- value={module.median_bus_factor.toFixed(1)}- icon={<Users className="h-3.5 w-3.5 text-violet-400" />}- />- <Headline- label="Bus min"- value={module.min_bus_factor}- icon={<ShieldAlert className="h-3.5 w-3.5 text-red-400" />}- tone={module.min_bus_factor <= 1 ? "danger" : undefined}- />- <Headline- label="Avg churn"- value={`${Math.round(module.avg_churn_percentile)}`}- />- </div>- </CardContent>- </Card>+ {/* ── Headline metric tiles ── */}+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-6">+ <MetricTile+ label="Hotspots"+ value={module.hotspot_count}+ icon={<Flame className="h-3.5 w-3.5 text-[var(--color-warning)]" />}+ {...(module.hotspot_count > 0 ? { tone: "warn" as const } : {})}+ />+ <MetricTile+ label="Dead lines"+ value={module.dead_code_lines}+ icon={<Trash2 className="h-3.5 w-3.5 text-[var(--color-error)]" />}+ {...(module.dead_code_lines > 0 ? { tone: "warn" as const } : {})}+ />+ <MetricTile+ label="Doc coverage"+ value={`${Math.round(module.doc_coverage_pct)}%`}+ icon={<BookOpen className="h-3.5 w-3.5 text-[var(--color-info)]" />}+ />+ <MetricTile+ label="Bus med"+ value={module.median_bus_factor.toFixed(1)}+ icon={<Users className="h-3.5 w-3.5 text-[var(--color-accent-primary)]" />}+ />+ <MetricTile+ label="Bus min"+ value={module.min_bus_factor}+ icon={<ShieldAlert className="h-3.5 w-3.5 text-[var(--color-error)]" />}+ {...(module.min_bus_factor <= 1 ? { tone: "danger" as const } : {})}+ />+ <MetricTile+ label="Avg churn"+ value={`${Math.round(module.avg_churn_percentile)}`}+ />+ </div>{/* ── Body ── */}<div className="grid gap-4 lg:grid-cols-3">@@ -134,7 +125,7 @@ export function ModuleHealthDetailView({People who primarily own files in this module.</p></CardHeader>- <CardContent className="pt-0 space-y-1.5">+ <CardContent className="pt-0 space-y-2">{module.owners.length === 0 && (<p className="py-4 text-center text-xs text-[var(--color-text-tertiary)]">No ownership signal.@@ -161,7 +152,9 @@ export function ModuleHealthDetailView({<divclassName={cn("h-full",- pct > 80 ? "bg-amber-500" : "bg-[var(--color-accent-primary)]",+ pct > 80+ ? "bg-[var(--color-warning)]"+ : "bg-[var(--color-accent-primary)]",)}style={{ width: `${pct}%` }}/>@@ -179,7 +172,7 @@ export function ModuleHealthDetailView({<Card><CardHeader className="pb-2"><CardTitle className="text-sm flex items-center gap-1.5">- <FileWarning className="h-4 w-4 text-orange-400" /> Top hotspots+ <FileWarning className="h-4 w-4 text-[var(--color-warning)]" /> Top hotspots</CardTitle></CardHeader><CardContent className="pt-0 space-y-1">@@ -192,7 +185,7 @@ export function ModuleHealthDetailView({<buttonkey={p}onClick={() => onSelectFile?.(p)}- className="block w-full truncate rounded px-2 py-1 text-left font-mono text-[11px] text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]"+ className="block w-full truncate rounded px-2 py-1 text-left font-mono text-xs text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]"title={p}>{truncatePath(p, 40)}@@ -206,7 +199,7 @@ export function ModuleHealthDetailView({<Card><CardHeader className="pb-2"><CardTitle className="text-sm flex items-center gap-1.5">- <Lightbulb className="h-4 w-4 text-yellow-400" /> Governing decisions+ <Lightbulb className="h-4 w-4 text-[var(--color-caution)]" /> Governing decisions</CardTitle></CardHeader><CardContent className="pt-0 space-y-1">@@ -218,7 +211,7 @@ export function ModuleHealthDetailView({key={id}onClick={() => onSelectDecision?.(id)}title={typeof d === "string" ? undefined : `${d.title} (${d.status})`}- className="block w-full truncate rounded px-2 py-1 text-left text-[11px] text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]"+ className="block w-full truncate rounded px-2 py-1 text-left text-xs text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]">{label}</button>@@ -233,30 +226,23 @@ export function ModuleHealthDetailView({);}-function Headline({- label,- value,- icon,- tone,-}: {- label: string;- value: string | number;- icon?: React.ReactNode | undefined;- tone?: "warn" | "danger" | undefined;-}) {- const color =- tone === "danger"- ? "text-red-400"- : tone === "warn"- ? "text-orange-300"- : "text-[var(--color-text-primary)]";- return (- <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-3 py-2">- <div className="flex items-center gap-1 text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">- {icon}- {label}- </div>- <div className={`mt-1 text-xl font-bold tabular-nums ${color}`}>{value}</div>- </div>- );+/**+ * Synthesised one-line "what is this" for a module — the missing summary.+ * Leads with the dominant health signal (the reason the score is what it is)+ * so the reader instantly knows where to look.+ */+function moduleSummary(m: ModuleHealthDetailModel): string {+ const lead = m.module_path.split("/").pop() || m.module_path;+ const parts: string[] = [];+ if (m.hotspot_count > 0) {+ parts.push(`${m.hotspot_count} hotspot${m.hotspot_count === 1 ? "" : "s"}`);+ }+ if (m.min_bus_factor <= 1) parts.push("bus-factor risk");+ if (m.dead_code_lines > 0) parts.push(`${m.dead_code_lines} dead lines`);+ if (parts.length === 0) {+ parts.push(`${Math.round(m.doc_coverage_pct)}% documented`);+ }+ return `The ${lead} module — ${m.file_count} files owned by ${+ m.primary_owner ?? "no clear owner"+ }. Leading signals: ${parts.join(", ")}.`;}diff --git a/packages/ui/src/modules/module-helpers.tsx b/packages/ui/src/modules/module-helpers.tsxnew file mode 100644index 000000000..e2cf841a5--- /dev/null+++ b/packages/ui/src/modules/module-helpers.tsx@@ -0,0 +1,131 @@+import * as React from "react";+import { Folder } from "lucide-react";+import { cn } from "../lib/cn";++/**+ * Single source of truth for module-health colour + chrome shared by the+ * module card and the module detail header. Module scores are on a 0–100+ * scale (unlike the 0–10 file-health pills in `health/tokens`), so these+ * helpers live alongside the module components rather than reusing the+ * file-score ramp.+ */++/** Colour classes for a 0–100 module health score. */+export function scoreColor(score: number): string {+ if (score >= 70)+ return "text-[var(--color-success)] bg-[var(--color-success)]/10 border-[var(--color-success)]/40";+ if (score >= 40)+ return "text-[var(--color-caution)] bg-[var(--color-caution)]/10 border-[var(--color-caution)]/40";+ return "text-[var(--color-error)] bg-[var(--color-error)]/10 border-[var(--color-error)]/40";+}++export interface HealthChipProps {+ /** Raw 0–100 health score. */+ score: number;+ /** `lg` for the detail header, `sm` for the card. */+ size?: "sm" | "lg";+ className?: string;+}++/** The composite-health score chip — one rendering for card + detail. */+export function HealthChip({ score, size = "sm", className }: HealthChipProps) {+ const rounded = Math.round(score);+ return (+ <div+ className={cn(+ "flex flex-col items-center justify-center rounded-md border text-center",+ size === "lg" ? "min-w-[88px] px-4 py-3" : "px-2 py-1",+ scoreColor(score),+ className,+ )}+ title="Composite health score"+ >+ <span+ className={cn(+ "font-bold leading-none tabular-nums",+ size === "lg" ? "text-3xl" : "text-lg",+ )}+ >+ {rounded}+ </span>+ <span+ className={cn(+ "uppercase tracking-wider opacity-70",+ size === "lg" ? "mt-1 text-xs" : "text-[10px]",+ )}+ >+ health+ </span>+ </div>+ );+}++export interface MetricTileProps {+ label: string;+ value: string | number;+ icon?: React.ReactNode;+ tone?: "warn" | "danger";+ /** `lg` for the detail header tiles, `sm` for the compact card grid. */+ size?: "sm" | "lg";+}++/** The shared module metric tile — replaces the card `Metric` + detail `Headline`. */+export function MetricTile({ label, value, icon, tone, size = "lg" }: MetricTileProps) {+ const color =+ tone === "danger"+ ? "text-[var(--color-error)]"+ : tone === "warn"+ ? "text-[var(--color-warning)]"+ : "text-[var(--color-text-primary)]";++ if (size === "sm") {+ return (+ <div>+ <div className="flex items-center gap-0.5 text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">+ {icon}+ {label}+ </div>+ <div className={cn("font-semibold tabular-nums", color)}>{value}</div>+ </div>+ );+ }++ return (+ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-3 py-2">+ <div className="flex items-center gap-1 text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">+ {icon}+ {label}+ </div>+ <div className={cn("mt-1 text-xl font-bold tabular-nums", color)}>{value}</div>+ </div>+ );+}++export interface ModuleIdentityProps {+ modulePath: string;+ fileCount: number;+ symbolCount: number;+ contributorCount?: number;+}++/** The shared "📁 path · N files · N symbols" identity line. */+export function ModuleIdentity({+ modulePath,+ fileCount,+ symbolCount,+ contributorCount,+}: ModuleIdentityProps) {+ return (+ <div className="min-w-0">+ {/* Heading semantics live on EntityHeader's <h1>; this is the styled identity. */}+ <div className="flex items-center gap-2 text-2xl font-bold text-[var(--color-text-primary)]">+ <Folder className="h-5 w-5 text-[var(--color-text-tertiary)] shrink-0" />+ <span className="truncate font-mono">{modulePath}</span>+ </div>+ <p className="mt-1 text-xs text-[var(--color-text-tertiary)]">+ {fileCount} files · {symbolCount} symbols+ {contributorCount != null && ` · ${contributorCount} contributors`}+ </p>+ </div>+ );+}diff --git a/packages/ui/src/onboarding/first-five-files.tsx b/packages/ui/src/onboarding/first-five-files.tsxindex 228ca6a50..4cfa90028 100644--- a/packages/ui/src/onboarding/first-five-files.tsx+++ b/packages/ui/src/onboarding/first-five-files.tsx@@ -91,8 +91,8 @@ export function FirstFiveFiles({return (<li key={f.file_path}><Wrapper>- <span className="text-[11px] tabular-nums text-[var(--color-text-tertiary)]">{i + 1}</span>- <p className="font-mono text-[11px] text-[var(--color-text-primary)] truncate min-w-0 flex-1">+ <span className="text-xs tabular-nums text-[var(--color-text-tertiary)]">{i + 1}</span>+ <p className="font-mono text-xs text-[var(--color-text-primary)] truncate min-w-0 flex-1">{f.file_path}</p>{f.is_entry_point && <Badge variant="accent" className="h-4 text-[10px] shrink-0">entry</Badge>}diff --git a/packages/ui/src/owners/owner-card.tsx b/packages/ui/src/owners/owner-card.tsxindex 8c0cf7671..7c26dcb87 100644--- a/packages/ui/src/owners/owner-card.tsx+++ b/packages/ui/src/owners/owner-card.tsx@@ -5,6 +5,7 @@ import type { OwnerListEntry } from "@repowise-dev/types/owners";import { Card } from "../ui/card";import { Badge } from "../ui/badge";import { cn } from "../lib/cn";+import { formatRelativeTimeOrNull } from "../lib/format";import { OwnerAvatar } from "./owner-avatar";interface OwnerCardProps {@@ -13,17 +14,6 @@ interface OwnerCardProps {highlight?: boolean;}-function timeAgo(iso: string | null): string {- if (!iso) return "—";- const ms = Date.now() - new Date(iso).getTime();- if (Number.isNaN(ms) || ms < 0) return "—";- const d = Math.floor(ms / 86_400_000);- if (d < 1) return "today";- if (d < 30) return `${d}d ago`;- if (d < 365) return `${Math.floor(d / 30)}mo ago`;- return `${Math.floor(d / 365)}y ago`;-}-/*** Single-row owner card used in the directory list. Highlights silos and* bus-factor risk so engineering leaders can spot concentrated risk fast.@@ -52,7 +42,7 @@ export function OwnerCard({ owner, onSelect, highlight }: OwnerCardProps) {)}</div>{owner.email && (- <div className="truncate text-[11px] text-[var(--color-text-tertiary)]">+ <div className="truncate text-xs text-[var(--color-text-tertiary)]">{owner.email}</div>)}@@ -61,28 +51,28 @@ export function OwnerCard({ owner, onSelect, highlight }: OwnerCardProps) {<Statlabel="Hotspots"value={owner.hotspots_owned}- icon={<Flame className="h-3 w-3 text-orange-400" />}+ icon={<Flame className="h-3 w-3 text-[var(--color-warning)]" />}tone={owner.hotspots_owned > 0 ? "warn" : undefined}/><Statlabel="Bus≤1"value={owner.bus_factor_risk_files}- icon={<ShieldAlert className="h-3 w-3 text-red-400" />}+ icon={<ShieldAlert className="h-3 w-3 text-[var(--color-error)]" />}tone={owner.bus_factor_risk_files > 0 ? "danger" : undefined}/><Statlabel="Dead lines"value={owner.dead_code_lines_owned}- icon={<Trash2 className="h-3 w-3 text-rose-400" />}+ icon={<Trash2 className="h-3 w-3 text-[var(--color-text-tertiary)]" />}tone={owner.dead_code_lines_owned > 0 ? "muted" : undefined}/></div>- <div className="mt-3 flex items-center justify-between text-[11px] text-[var(--color-text-tertiary)]">+ <div className="mt-3 flex items-center justify-between text-xs text-[var(--color-text-tertiary)]"><span className="flex items-center gap-1"><GitCommit className="h-3 w-3" />{owner.commit_count_90d} commits / 90d</span>- <span>last touched {timeAgo(owner.last_commit_at)}</span>+ <span>last touched {formatRelativeTimeOrNull(owner.last_commit_at)}</span></div></div></div>@@ -103,11 +93,11 @@ function Stat({}) {const toneCls =tone === "danger"- ? "text-red-400"+ ? "text-[var(--color-error)]": tone === "warn"- ? "text-orange-300"+ ? "text-[var(--color-warning)]": tone === "muted"- ? "text-rose-300/70"+ ? "text-[var(--color-text-tertiary)]": "text-[var(--color-text-primary)]";return (<div>diff --git a/packages/ui/src/owners/owner-directory.tsx b/packages/ui/src/owners/owner-directory.tsxindex 1cd354fce..a607189f6 100644--- a/packages/ui/src/owners/owner-directory.tsx+++ b/packages/ui/src/owners/owner-directory.tsx@@ -140,7 +140,7 @@ function Headline({tone?: "warn" | "danger";}) {const color =- tone === "danger" ? "text-red-400" : tone === "warn" ? "text-orange-300" : "text-[var(--color-text-primary)]";+ tone === "danger" ? "text-[var(--color-error)]" : tone === "warn" ? "text-[var(--color-warning)]" : "text-[var(--color-text-primary)]";return (<div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-3"><div className="text-[10px] font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">diff --git a/packages/ui/src/owners/owner-profile.tsx b/packages/ui/src/owners/owner-profile.tsxindex 6d26d0cb9..ac85663f6 100644--- a/packages/ui/src/owners/owner-profile.tsx+++ b/packages/ui/src/owners/owner-profile.tsx@@ -26,7 +26,8 @@ import {type ResponsiveColumn,} from "../shared/responsive-table";import { cn } from "../lib/cn";-import { truncatePath } from "../lib/format";+import { truncatePath, formatRelativeTimeOrNull } from "../lib/format";+import { AgentTierBar } from "../git/agent-tier-bar";import { OwnerAvatar } from "./owner-avatar";const dateFormatter = new Intl.DateTimeFormat(undefined, {@@ -47,15 +48,7 @@ function fmtCompact(n: number): string {return n.toLocaleString();}-function timeAgo(iso: string | null): string {- if (!iso) return "never";- const d = Math.floor((Date.now() - new Date(iso).getTime()) / 86_400_000);- if (Number.isNaN(d) || d < 0) return "never";- if (d < 1) return "today";- if (d < 30) return `${d}d ago`;- if (d < 365) return `${Math.floor(d / 30)}mo ago`;- return `${Math.floor(d / 365)}y ago`;-}+const timeAgo = (iso: string | null) => formatRelativeTimeOrNull(iso, "never");export interface OwnerProfileViewProps {owner: OwnerProfile;@@ -159,28 +152,28 @@ export function OwnerProfileView({{/* ---------- Risk strip ---------- */}<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4"><RiskTile- icon={<Users className="h-4 w-4 text-amber-400" />}+ icon={<Users className="h-4 w-4 text-[var(--color-warning)]" />}label="Silo modules"value={owner.silo_modules}help="modules where this person owns >80% of files"tone={owner.silo_modules > 0 ? "warn" : "ok"}/><RiskTile- icon={<ShieldAlert className="h-4 w-4 text-red-400" />}+ icon={<ShieldAlert className="h-4 w-4 text-[var(--color-error)]" />}label="Bus-factor risk"value={owner.bus_factor_risk_files}help="files with bus_factor ≤ 1 that they own"tone={owner.bus_factor_risk_files > 0 ? "danger" : "ok"}/><RiskTile- icon={<Flame className="h-4 w-4 text-orange-400" />}+ icon={<Flame className="h-4 w-4 text-[var(--color-warning)]" />}label="Hotspots owned"value={owner.hotspots_owned}help="high-churn files where they are primary owner"tone={owner.hotspots_owned > 0 ? "warn" : "ok"}/><RiskTile- icon={<Trash2 className="h-4 w-4 text-rose-400" />}+ icon={<Trash2 className="h-4 w-4 text-[var(--color-text-tertiary)]" />}label="Dead-code burden"value={`${owner.dead_code_files_owned} files · ${fmtCompact(owner.dead_code_lines_owned)} lines`}help="dead code findings whose primary owner is this person"@@ -334,19 +327,8 @@ export function OwnerProfileView({</span></div>{Object.keys(owner.agent_collab.tier_counts).length > 0 && (- <div className="flex flex-wrap gap-1.5 pt-1">- {Object.entries(owner.agent_collab.tier_counts)- .sort(([a], [b]) => a.localeCompare(b))- .map(([tier, n]) => (- <Badge key={tier} variant="outline" className="text-[10px]">- {tier === "1"- ? "autonomous"- : tier === "2"- ? "agent"- : "assisted"}- : {n}- </Badge>- ))}+ <div className="pt-1">+ <AgentTierBar tierCounts={owner.agent_collab.tier_counts} /></div>)}</CardContent>@@ -416,9 +398,9 @@ function Headline({}) {const color =tone === "add"- ? "text-emerald-300"+ ? "text-[var(--color-success)]": tone === "del"- ? "text-rose-300"+ ? "text-[var(--color-error)]": "text-[var(--color-text-primary)]";return (<div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-3 py-2">@@ -446,15 +428,15 @@ function RiskTile({}) {const border =tone === "danger"- ? "border-red-500/40 bg-red-500/5"+ ? "border-[var(--color-error)]/40 bg-[var(--color-error)]/5": tone === "warn"- ? "border-amber-500/40 bg-amber-500/5"+ ? "border-[var(--color-warning)]/40 bg-[var(--color-warning)]/5": tone === "muted"- ? "border-rose-500/30 bg-rose-500/5"+ ? "border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]": "border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]";return (<div className={cn("rounded-lg border p-3", border)}>- <div className="flex items-center gap-1.5 text-[11px] uppercase tracking-wider text-[var(--color-text-tertiary)]">+ <div className="flex items-center gap-1.5 text-xs uppercase tracking-wider text-[var(--color-text-tertiary)]">{icon}{label}</div>@@ -514,7 +496,7 @@ const FILE_COLUMNS: ResponsiveColumn<OwnerFileEntry>[] = [priority: 1,cellClassName: "max-w-[320px]",render: (f) => (- <span className="flex items-center gap-1.5 truncate font-mono text-[11px] text-[var(--color-text-primary)]">+ <span className="flex items-center gap-1.5 truncate font-mono text-xs text-[var(--color-text-primary)]">{f.is_hotspot && <Flame className="h-3 w-3 shrink-0 text-[var(--color-warning)]" />}{truncatePath(f.file_path, 48)}</span>@@ -597,19 +579,23 @@ function ChurnPill({ value }: { value: number }) {function BusBadge({ bf }: { bf: number }) {const color =- bf <= 1 ? "text-red-400" : bf === 2 ? "text-amber-300" : "text-emerald-300";+ bf <= 1+ ? "text-[var(--color-error)]"+ : bf === 2+ ? "text-[var(--color-warning)]"+ : "text-[var(--color-success)]";return <span className={cn("font-semibold", color)}>{bf}</span>;}function categoryColor(category: string): string {const map: Record<string, string> = {- feat: "bg-emerald-400",- fix: "bg-rose-400",- refactor: "bg-sky-400",- docs: "bg-indigo-400",- test: "bg-violet-400",- chore: "bg-zinc-400",- perf: "bg-amber-400",+ feat: "bg-[var(--color-success)]",+ fix: "bg-[var(--color-error)]",+ refactor: "bg-[var(--color-accent-secondary)]",+ docs: "bg-[var(--color-info)]",+ test: "bg-[var(--color-accent-primary)]",+ chore: "bg-[var(--color-text-tertiary)]",+ perf: "bg-[var(--color-warning)]",};return map[category] ?? "bg-[var(--color-accent-primary)]";}diff --git a/packages/ui/src/security/findings-table.tsx b/packages/ui/src/security/findings-table.tsxindex 4f1cd91af..7a9b06b93 100644--- a/packages/ui/src/security/findings-table.tsx+++ b/packages/ui/src/security/findings-table.tsx@@ -90,7 +90,7 @@ export function SecurityFindingsTable({ findings, onSelect }: SecurityFindingsTa</div><div className="rounded-lg border border-[var(--color-border-default)] overflow-x-auto">- <table className="w-full min-w-[720px] text-sm">+ <table className="w-full min-w-[560px] text-sm"><thead className="sticky top-0 z-10 bg-[var(--color-bg-elevated)]"><tr className="border-b border-[var(--color-border-default)]"><th className="px-3 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider w-20">@@ -129,12 +129,12 @@ export function SecurityFindingsTable({ findings, onSelect }: SecurityFindingsTa<span className="block truncate" title={f.file_path}>{f.file_path}</span></td><td className="px-3 py-2 text-xs text-[var(--color-text-secondary)]">{f.kind}</td>- <td className="px-3 py-2 font-mono text-[11px] text-[var(--color-text-tertiary)] max-w-[320px]">+ <td className="px-3 py-2 font-mono text-xs text-[var(--color-text-tertiary)] max-w-[320px]"><span className="block truncate" title={f.snippet ?? ""}>{f.snippet ?? "—"}</span></td>- <td className="px-3 py-2 text-[11px] text-[var(--color-text-tertiary)] tabular-nums">+ <td className="px-3 py-2 text-xs text-[var(--color-text-tertiary)] tabular-nums">{new Date(f.detected_at).toLocaleDateString()}</td></tr>diff --git a/packages/ui/src/security/index.ts b/packages/ui/src/security/index.tsindex 62ddfd244..8fd321c79 100644--- a/packages/ui/src/security/index.ts+++ b/packages/ui/src/security/index.ts@@ -1,3 +1,3 @@-export * from "./severity-distribution";export * from "./findings-table";export * from "./findings-by-directory";+export * from "./severity-directory-matrix";diff --git a/packages/ui/src/security/severity-directory-matrix.tsx b/packages/ui/src/security/severity-directory-matrix.tsxnew file mode 100644index 000000000..235bd3c85--- /dev/null+++ b/packages/ui/src/security/severity-directory-matrix.tsx@@ -0,0 +1,130 @@+"use client";++import * as React from "react";+import { cn } from "../lib/cn";+import type { SecurityFinding } from "./findings-table";++export interface SeverityDirectoryMatrixProps {+ findings: SecurityFinding[];+ /** Path-segment depth to group at (default 2). */+ depth?: number;+ /** Cap the number of directory rows (highest total first). */+ maxRows?: number;+ className?: string;+}++const SEVERITY_ORDER = ["high", "med", "low"] as const;+const SEVERITY_LABEL: Record<string, string> = {+ high: "High",+ med: "Medium",+ low: "Low",+};+const SEVERITY_TOKEN: Record<string, string> = {+ high: "var(--color-error)",+ med: "var(--color-warning)",+ low: "var(--color-text-tertiary)",+};++/**+ * Severity × directory heat matrix — where the security findings concentrate,+ * so reviewers know which area to triage first. Mirrors the dead-code+ * confidence × kind grid idiom; intensity rides on a token via color-mix.+ */+export function SeverityDirectoryMatrix({+ findings,+ depth = 2,+ maxRows = 14,+ className,+}: SeverityDirectoryMatrixProps) {+ const { rows, max } = React.useMemo(() => {+ const byDir = new Map<string, { dir: string; counts: Record<string, number>; total: number }>();+ let max = 0;+ for (const f of findings) {+ const segments = f.file_path.split("/").slice(0, depth);+ const dir = segments.length === 0 ? "(root)" : segments.join("/");+ const sev = SEVERITY_ORDER.includes(f.severity as (typeof SEVERITY_ORDER)[number])+ ? f.severity+ : "low";+ const cur = byDir.get(dir) ?? { dir, counts: {}, total: 0 };+ cur.counts[sev] = (cur.counts[sev] ?? 0) + 1;+ cur.total += 1;+ if (cur.counts[sev] > max) max = cur.counts[sev];+ byDir.set(dir, cur);+ }+ const ordered = Array.from(byDir.values())+ .sort((a, b) => b.total - a.total)+ .slice(0, maxRows);+ return { rows: ordered, max };+ }, [findings, depth, maxRows]);++ if (rows.length === 0) {+ return (+ <div+ className={cn(+ "rounded-md border border-dashed border-[var(--color-border-default)] p-4 text-center text-xs text-[var(--color-text-tertiary)]",+ className,+ )}+ >+ No findings yet.+ </div>+ );+ }++ return (+ <div+ className={cn(+ "overflow-hidden rounded-md border border-[var(--color-border-default)]",+ className,+ )}+ >+ <table className="w-full border-collapse text-xs">+ <thead>+ <tr className="bg-[var(--color-bg-elevated)]">+ <th className="px-3 py-2 text-left font-medium text-[var(--color-text-tertiary)]">+ Directory+ </th>+ {SEVERITY_ORDER.map((s) => (+ <th+ key={s}+ className="px-2 py-2 text-right font-medium text-[var(--color-text-tertiary)]"+ >+ {SEVERITY_LABEL[s]}+ </th>+ ))}+ </tr>+ </thead>+ <tbody>+ {rows.map((r) => (+ <tr key={r.dir} className="border-t border-[var(--color-border-default)]">+ <td+ className="max-w-[260px] truncate px-3 py-2 font-mono text-[var(--color-text-secondary)]"+ title={r.dir}+ >+ {r.dir}+ </td>+ {SEVERITY_ORDER.map((s) => {+ const c = r.counts[s] ?? 0;+ const intensity = max > 0 ? c / max : 0;+ const alphaPct = Math.round((0.1 + intensity * 0.55) * 100);+ const bg =+ c === 0+ ? "transparent"+ : `color-mix(in srgb, ${SEVERITY_TOKEN[s]} ${alphaPct}%, transparent)`;+ return (+ <td+ key={s}+ className="px-2 py-2 text-right tabular-nums"+ style={{ backgroundColor: bg }}+ title={`${c} ${SEVERITY_LABEL[s]} in ${r.dir}`}+ >+ {c || ""}+ </td>+ );+ })}+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ );+}diff --git a/packages/ui/src/security/severity-distribution.tsx b/packages/ui/src/security/severity-distribution.tsxdeleted file mode 100644index 5eef1d1e3..000000000--- a/packages/ui/src/security/severity-distribution.tsx+++ /dev/null@@ -1,84 +0,0 @@-"use client";--import { ShieldAlert } from "lucide-react";-import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";--const SEVERITY_ORDER = ["high", "med", "low"] as const;-const SEVERITY_LABELS: Record<string, string> = {- high: "High / critical",- med: "Medium",- low: "Low",-};-const SEVERITY_COLORS: Record<string, string> = {- high: "var(--color-error)",- med: "var(--color-warning)",- low: "var(--color-success)",-};--export interface SeverityDistributionProps {- /** Map of severity → count. */- counts: Record<string, number>;-}--export function SeverityDistribution({ counts }: SeverityDistributionProps) {- const total = Object.values(counts).reduce((s, n) => s + n, 0);-- return (- <Card>- <CardHeader className="pb-2">- <CardTitle className="text-sm flex items-center gap-2">- <ShieldAlert className="h-4 w-4 text-red-400" />- Severity distribution- </CardTitle>- </CardHeader>- <CardContent className="pt-0 space-y-3">- {total === 0 ? (- <p className="text-xs text-[var(--color-text-secondary)] py-4 text-center">- No security findings.- </p>- ) : (- <>- <div className="flex h-2 w-full overflow-hidden rounded-full bg-[var(--color-bg-inset)]">- {SEVERITY_ORDER.map((sev) => {- const c = counts[sev] ?? 0;- if (c === 0) return null;- return (- <div- key={sev}- style={{- width: `${(c / total) * 100}%`,- backgroundColor: SEVERITY_COLORS[sev],- }}- title={`${SEVERITY_LABELS[sev]}: ${c}`}- />- );- })}- </div>- <div className="grid grid-cols-3 gap-2 text-xs">- {SEVERITY_ORDER.map((sev) => {- const c = counts[sev] ?? 0;- return (- <div- key={sev}- className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-3 py-2"- >- <div className="flex items-center gap-1.5 mb-1">- <span- className="h-2 w-2 rounded-full"- style={{ backgroundColor: SEVERITY_COLORS[sev] }}- />- <span className="text-[var(--color-text-secondary)]">{SEVERITY_LABELS[sev]}</span>- </div>- <p className="text-lg font-semibold text-[var(--color-text-primary)] tabular-nums">- {c}- </p>- </div>- );- })}- </div>- </>- )}- </CardContent>- </Card>- );-}diff --git a/packages/ui/src/shared/adaptive-panel.tsx b/packages/ui/src/shared/adaptive-panel.tsxindex 255bbce9e..0d03ad3d3 100644--- a/packages/ui/src/shared/adaptive-panel.tsx+++ b/packages/ui/src/shared/adaptive-panel.tsx@@ -136,7 +136,7 @@ export function AdaptivePanel({</DialogPrimitive.Close></header>)}- <div className="flex min-h-0 flex-1 flex-col overflow-y-auto">{children}</div>+ <div className="flex min-h-0 flex-1 flex-col overflow-y-auto overflow-x-hidden">{children}</div></DialogPrimitive.Content></DialogPrimitive.Portal></DialogPrimitive.Root>diff --git a/packages/ui/src/shared/collapsible-section.tsx b/packages/ui/src/shared/collapsible-section.tsxnew file mode 100644index 000000000..c68ccd2d2--- /dev/null+++ b/packages/ui/src/shared/collapsible-section.tsx@@ -0,0 +1,47 @@+"use client";++import * as React from "react";+import { cn } from "../lib/cn";++export interface CollapsibleSectionProps {+ title: React.ReactNode;+ /** Right-aligned hint shown on the toggle (e.g. a count). */+ hint?: React.ReactNode;+ defaultOpen?: boolean;+ children?: React.ReactNode;+ className?: string;+}++/**+ * The progressive-disclosure idiom used across Code Health: a borderless+ * toggle button that reveals a demoted table/queue beneath. One home so the+ * disclosure chrome restyles everywhere on a package bump.+ */+export function CollapsibleSection({+ title,+ hint,+ defaultOpen = false,+ children,+ className,+}: CollapsibleSectionProps) {+ const [open, setOpen] = React.useState(defaultOpen);+ return (+ <section className={cn("space-y-3", className)}>+ <button+ type="button"+ onClick={() => setOpen((v) => !v)}+ aria-expanded={open}+ className="flex w-full items-center gap-2 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-3 py-2 text-sm font-medium text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"+ >+ <span className="text-[var(--color-text-tertiary)]">{open ? "▾" : "▸"}</span>+ {title}+ {hint != null && (+ <span className="ml-auto text-xs font-normal text-[var(--color-text-tertiary)]">+ {hint}+ </span>+ )}+ </button>+ {open ? <div className="space-y-3">{children}</div> : null}+ </section>+ );+}diff --git a/packages/ui/src/shared/entity/entity-header.tsx b/packages/ui/src/shared/entity/entity-header.tsxnew file mode 100644index 000000000..380904a5c--- /dev/null+++ b/packages/ui/src/shared/entity/entity-header.tsx@@ -0,0 +1,100 @@+import * as React from "react";+import { cn } from "../../lib/cn";+import { Breadcrumb, type BreadcrumbSegment } from "../breadcrumb";++export type EntityEyebrow = "FILE" | "SYMBOL" | "MODULE";++export interface EntityHeaderProps {+ eyebrow: EntityEyebrow;+ breadcrumb: BreadcrumbSegment[];+ /** Mono filename / kind-aware identity line. */+ identity: React.ReactNode;+ /**+ * Heading tag for the identity line. Defaults to `h1` (these are top-level+ * detail-page headers); pass `h2` for a header nested under an existing `h1`.+ */+ identityAs?: "h1" | "h2";+ /** One-line "what is this" — wiki summary or signature fallback. */+ summary?: string;+ /** The single most important fact (health gauge / hotspot), aligned right. */+ primarySignal?: React.ReactNode;+ /** De-piled secondary badges row. */+ metaBadges?: React.ReactNode;+ /** Top exported symbols as chips. */+ keySymbols?: React.ReactNode;+ /** Owner avatar + bus-factor pill. */+ people?: React.ReactNode;+ /** Open in Docs / Show in graph / View symbols. */+ actions?: React.ReactNode;+ /** Governing decision records, grouped beneath. */+ decisions?: React.ReactNode;+ LinkComponent?: React.ElementType<{+ href: string;+ className?: string;+ children: React.ReactNode;+ }>;+ className?: string;+}++/**+ * The shared detail-page header: eyebrow → breadcrumb → identity + primary+ * signal → summary → meta badges → key symbols → people → actions → decisions.+ * Calm and airy; reused by file/symbol/module detail pages.+ */+export function EntityHeader({+ eyebrow,+ breadcrumb,+ identity,+ identityAs: IdentityTag = "h1",+ summary,+ primarySignal,+ metaBadges,+ keySymbols,+ people,+ actions,+ decisions,+ LinkComponent,+ className,+}: EntityHeaderProps) {+ return (+ <header className={cn("space-y-3", className)}>+ <p className="text-xs font-semibold uppercase tracking-wider text-[var(--color-text-tertiary)]">+ {eyebrow}+ </p>++ {breadcrumb.length > 0 && (+ <Breadcrumb+ segments={breadcrumb}+ {...(LinkComponent ? { LinkComponent } : {})}+ />+ )}++ <div className="flex flex-wrap items-start justify-between gap-3">+ <IdentityTag className="min-w-0 text-lg font-semibold text-[var(--color-text-primary)]">+ {identity}+ </IdentityTag>+ {primarySignal && <div className="shrink-0">{primarySignal}</div>}+ </div>++ {summary && (+ <p className="text-sm text-[var(--color-text-secondary)]">{summary}</p>+ )}++ {metaBadges && (+ <div className="flex flex-wrap items-center gap-2">{metaBadges}</div>+ )}++ {keySymbols && (+ <div className="flex flex-wrap items-center gap-1.5">{keySymbols}</div>+ )}++ {people && <div className="flex items-center gap-2">{people}</div>}++ {actions && (+ <div className="flex flex-wrap items-center gap-2">{actions}</div>+ )}++ {decisions && <div className="space-y-2">{decisions}</div>}+ </header>+ );+}diff --git a/packages/ui/src/shared/entity/entity-hover-card.tsx b/packages/ui/src/shared/entity/entity-hover-card.tsxindex 8e8e3a1c4..dbee767cd 100644--- a/packages/ui/src/shared/entity/entity-hover-card.tsx+++ b/packages/ui/src/shared/entity/entity-hover-card.tsx@@ -48,7 +48,7 @@ function HoverCardBody({ entity, meta }: { entity: EntityRef; meta?: EntityMeta{ENTITY_KIND_LABEL[entity.kind]}</span></div>- <p className="font-mono text-[11px] leading-snug text-[var(--color-text-primary)] break-all">+ <p className="font-mono text-xs leading-snug text-[var(--color-text-primary)] break-all">{entity.id}</p>{meta && meta.kind === entity.kind && <MetaSection meta={meta} />}@@ -86,7 +86,7 @@ function FileMeta({ data }: { data?: import("./types").FileEntityMeta | undefinereturn (<div className="space-y-1">{data.summary && (- <p className="text-[11px] leading-snug text-[var(--color-text-secondary)] line-clamp-3">+ <p className="text-xs leading-snug text-[var(--color-text-secondary)] line-clamp-3">{data.summary}</p>)}@@ -192,7 +192,7 @@ function CommitMeta({ data }: { data?: import("./types").CommitEntityMeta | unde<Row label="Author" value={data.author ?? null} /><Row label="Date" value={data.date ?? null} />{data.message && (- <p className="text-[11px] text-[var(--color-text-secondary)] line-clamp-2">+ <p className="text-xs text-[var(--color-text-secondary)] line-clamp-2">{data.message}</p>)}diff --git a/packages/ui/src/shared/entity/index.ts b/packages/ui/src/shared/entity/index.tsindex 9c2f4add6..f1b030155 100644--- a/packages/ui/src/shared/entity/index.ts+++ b/packages/ui/src/shared/entity/index.ts@@ -1,4 +1,9 @@export { EntityLink } from "./entity-link";+export {+ EntityHeader,+ type EntityHeaderProps,+ type EntityEyebrow,+} from "./entity-header";export { EntityHoverCard } from "./entity-hover-card";export {resolveEntityHref,diff --git a/packages/ui/src/shared/file-card/file-card.tsx b/packages/ui/src/shared/file-card/file-card.tsxindex 3638fbede..f2eadefb5 100644--- a/packages/ui/src/shared/file-card/file-card.tsx+++ b/packages/ui/src/shared/file-card/file-card.tsx@@ -52,7 +52,7 @@ function LinkButton({ href, icon: Icon, label }: { href: string; icon: React.Comreturn (<ahref={href}- className="inline-flex items-center gap-1 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2 py-1 text-[11px] text-[var(--color-text-secondary)] hover:border-[var(--color-accent-primary)] hover:text-[var(--color-text-primary)] transition-colors"+ className="inline-flex items-center gap-1 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2 py-1 text-xs text-[var(--color-text-secondary)] hover:border-[var(--color-accent-primary)] hover:text-[var(--color-text-primary)] transition-colors"><Icon className="h-3 w-3" /><span>{label}</span>@@ -83,7 +83,7 @@ export function FileCard({ data, links, hideHeader = false, className }: FileCar</Badge>)}{busFactor !== undefined && busFactor <= 1 && (- <Badge variant="outline" className="gap-1 text-red-400 border-red-400/30">+ <Badge variant="outline" className="gap-1 text-[var(--color-error)] border-[var(--color-error)]/30"><Users className="h-3 w-3" /> bus×{busFactor}</Badge>)}@@ -110,8 +110,8 @@ export function FileCard({ data, links, hideHeader = false, className }: FileCarlabel="Lines"value={<>- <span className="text-green-400">+{formatLOC(git.lines_added_90d ?? 0)}</span>{" "}- <span className="text-red-400">-{formatLOC(git.lines_deleted_90d ?? 0)}</span>+ <span className="text-[var(--color-success)]">+{formatLOC(git.lines_added_90d ?? 0)}</span>{" "}+ <span className="text-[var(--color-error)]">-{formatLOC(git.lines_deleted_90d ?? 0)}</span></>}/>@@ -125,9 +125,9 @@ export function FileCard({ data, links, hideHeader = false, className }: FileCarvalue={git.temporal_hotspot_score.toFixed(2)}accent={git.temporal_hotspot_score >= 5- ? "text-red-400"+ ? "text-[var(--color-error)]": git.temporal_hotspot_score >= 2- ? "text-orange-400"+ ? "text-[var(--color-warning)]": "text-[var(--color-text-secondary)]"}/>@@ -141,7 +141,7 @@ export function FileCard({ data, links, hideHeader = false, className }: FileCar<><Statlabel="Status"- value={<span className="text-green-400">Indexed</span>}+ value={<span className="text-[var(--color-success)]">Indexed</span>}/>{docs.freshness_pct !== undefined && (<Stat label="Freshness" value={`${Math.round(docs.freshness_pct)}%`} />@@ -152,14 +152,14 @@ export function FileCard({ data, links, hideHeader = false, className }: FileCar{docs.doc_url && (<ahref={docs.doc_url}- className="inline-flex items-center gap-1 mt-1 text-[var(--color-accent-primary)] hover:underline text-[11px]"+ className="inline-flex items-center gap-1 mt-1 text-[var(--color-accent-primary)] hover:underline text-xs">Open doc <ExternalLink className="h-3 w-3" /></a>)}</>) : (- <p className="text-[var(--color-text-tertiary)] italic text-[11px]">+ <p className="text-[var(--color-text-tertiary)] italic text-xs">No doc generated for this file yet.</p>)}@@ -170,13 +170,13 @@ export function FileCard({ data, links, hideHeader = false, className }: FileCar<Section title={`Symbols (${symbols.total})`} icon={Code2}>{symbols.top && symbols.top.length > 0 ? (symbols.top.slice(0, 5).map((s) => (- <div key={s.id} className="flex items-baseline justify-between gap-2 text-[11px]">+ <div key={s.id} className="flex items-baseline justify-between gap-2 text-xs"><span className="font-mono text-[var(--color-text-primary)] truncate">{s.name}</span>{s.kind && <span className="text-[var(--color-text-tertiary)] shrink-0">{s.kind}</span>}</div>))) : (- <p className="text-[var(--color-text-tertiary)] italic text-[11px]">No symbols indexed.</p>+ <p className="text-[var(--color-text-tertiary)] italic text-xs">No symbols indexed.</p>)}</Section>)}@@ -185,12 +185,12 @@ export function FileCard({ data, links, hideHeader = false, className }: FileCar<Section title={`Decisions (${decisions.count})`} icon={BookOpen}>{decisions.titles && decisions.titles.length > 0 ? (decisions.titles.slice(0, 4).map((t, i) => (- <p key={i} className="text-[11px] text-[var(--color-text-primary)] truncate">+ <p key={i} className="text-xs text-[var(--color-text-primary)] truncate">· {t}</p>))) : (- <p className="text-[11px] text-[var(--color-text-tertiary)]">+ <p className="text-xs text-[var(--color-text-tertiary)]">{decisions.count} decision{decisions.count === 1 ? "" : "s"} reference this file.</p>)}@@ -199,12 +199,12 @@ export function FileCard({ data, links, hideHeader = false, className }: FileCar{deadCode && deadCode.findings_count > 0 && (<Section title="Dead code" icon={Trash2}>- <Stat label="Findings" value={deadCode.findings_count} accent="text-red-400" />+ <Stat label="Findings" value={deadCode.findings_count} accent="text-[var(--color-error)]" />{deadCode.reclaimable_lines !== undefined && (<Statlabel="Lines reclaimable"value={formatLOC(deadCode.reclaimable_lines)}- accent="text-red-400"+ accent="text-[var(--color-error)]"/>)}</Section>@@ -212,12 +212,12 @@ export function FileCard({ data, links, hideHeader = false, className }: FileCar{security && security.findings_count > 0 && (<Section title="Security" icon={ShieldAlert}>- <Stat label="Findings" value={security.findings_count} accent="text-red-400" />+ <Stat label="Findings" value={security.findings_count} accent="text-[var(--color-error)]" />{security.critical_count !== undefined && security.critical_count > 0 && (<Statlabel="Critical"value={security.critical_count}- accent="text-red-400"+ accent="text-[var(--color-error)]"/>)}</Section>diff --git a/packages/ui/src/shared/file-card/index.ts b/packages/ui/src/shared/file-card/index.tsindex 71b3d496b..9fa9291d0 100644--- a/packages/ui/src/shared/file-card/index.ts+++ b/packages/ui/src/shared/file-card/index.ts@@ -2,4 +2,5 @@ export { FileCard } from "./file-card";export type { FileCardProps } from "./file-card";export { FileCardDialog } from "./file-card-dialog";export type { FileCardDialogProps } from "./file-card-dialog";-export type { FileCardData, FileCardLinks } from "./types";+export type { FileCardData, FileCardLinks, HotspotLike } from "./types";+export { hotspotToFileCard } from "./types";diff --git a/packages/ui/src/shared/file-card/types.ts b/packages/ui/src/shared/file-card/types.tsindex 6a2cd18aa..93b7857d7 100644--- a/packages/ui/src/shared/file-card/types.ts+++ b/packages/ui/src/shared/file-card/types.ts@@ -54,6 +54,38 @@ export interface FileCardData {};}+/** Structural subset of a hotspot row needed to build a FileCardData. */+export interface HotspotLike {+ file_path: string;+ churn_percentile?: number;+ commit_count_90d?: number;+ lines_added_90d?: number;+ lines_deleted_90d?: number;+ bus_factor?: number;+ primary_owner?: string | null;+ is_hotspot?: boolean;+ temporal_hotspot_score?: number | null;+}++/**+ * Map a hotspot row to the universal file-card shape (git section only).+ * Undefined fields are dropped so the result satisfies+ * `exactOptionalPropertyTypes`.+ */+export function hotspotToFileCard(h: HotspotLike): FileCardData {+ const git: NonNullable<FileCardData["git"]> = {};+ if (h.churn_percentile !== undefined) git.churn_percentile = h.churn_percentile;+ if (h.commit_count_90d !== undefined) git.commit_count_90d = h.commit_count_90d;+ if (h.lines_added_90d !== undefined) git.lines_added_90d = h.lines_added_90d;+ if (h.lines_deleted_90d !== undefined) git.lines_deleted_90d = h.lines_deleted_90d;+ if (h.bus_factor !== undefined) git.bus_factor = h.bus_factor;+ if (h.primary_owner !== undefined) git.primary_owner = h.primary_owner;+ if (h.is_hotspot !== undefined) git.is_hotspot = h.is_hotspot;+ if (h.temporal_hotspot_score !== undefined)+ git.temporal_hotspot_score = h.temporal_hotspot_score;+ return { file_path: h.file_path, git };+}+export interface FileCardLinks {graph?: string;docs?: string;diff --git a/packages/ui/src/shared/index.ts b/packages/ui/src/shared/index.tsindex 607f3977f..b5cde672d 100644--- a/packages/ui/src/shared/index.ts+++ b/packages/ui/src/shared/index.ts@@ -17,6 +17,19 @@ export * from "./empty-state";export { InfoTip, type InfoTipProps } from "./info-tip";export { OwlLoader, type OwlLoaderProps } from "./owl-loader";export * from "./stat-card";+export { PageShell, type PageShellProps } from "./page-shell";+export { ViewTabs, type ViewTab, type ViewTabsProps } from "./view-tabs";+export { MetricCard, type MetricCardProps } from "./metric-card";+export {+ CollapsibleSection,+ type CollapsibleSectionProps,+} from "./collapsible-section";+export {+ StatGrid,+ StatTile,+ type StatGridProps,+ type StatTileProps,+} from "./stat-grid";export * from "./results-footer";export { RowActions, type RowAction } from "./row-actions";export * from "./entity";diff --git a/packages/ui/src/shared/metric-card.tsx b/packages/ui/src/shared/metric-card.tsxnew file mode 100644index 000000000..20b844e5b--- /dev/null+++ b/packages/ui/src/shared/metric-card.tsx@@ -0,0 +1,101 @@+import * as React from "react";+import { cn } from "../lib/cn";+import { Card, CardContent } from "../ui/card";++export interface MetricCardProps {+ label: string;+ value: React.ReactNode;+ /**+ * Signed change indicator. `positive` is a good-vs-bad flag (drives+ * success/error colouring), not up-vs-down. Set `neutral` to render the+ * change uncolored for metrics where growth carries no value judgement.+ */+ delta?: { value: string; positive: boolean; neutral?: boolean };+ /** Optional inline sparkline node, rendered beneath the value. */+ sparkline?: React.ReactNode;+ /** Optional distribution bar node, rendered beneath the value. */+ distBar?: React.ReactNode;+ icon?: React.ReactNode;+ /** Wraps the tile in a link. */+ href?: string;+ LinkComponent?: React.ElementType<{+ href: string;+ className?: string;+ children: React.ReactNode;+ }>;+ className?: string;+}++/**+ * The canonical stat tile: label + value with optional delta, sparkline, and+ * distribution-bar slots. Built on `Card`; the future single replacement for+ * the near-identical summary-card variants across views.+ */+export function MetricCard({+ label,+ value,+ delta,+ sparkline,+ distBar,+ icon,+ href,+ LinkComponent = "a",+ className,+}: MetricCardProps) {+ const card = (+ <Card+ className={cn(+ "h-full transition-colors hover:border-[var(--color-border-hover)]",+ href && "cursor-pointer",+ className,+ )}+ >+ <CardContent className="p-4">+ <div className="flex items-start justify-between gap-2">+ <div className="min-w-0 space-y-1">+ <p className="text-xs font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">+ {label}+ </p>+ <div className="flex items-baseline gap-2">+ <div className="text-2xl font-bold tabular-nums text-[var(--color-text-primary)]">+ {value}+ </div>+ {delta && (+ <span+ className={cn(+ "text-xs font-medium tabular-nums",+ delta.neutral+ ? "text-[var(--color-text-tertiary)]"+ : delta.positive+ ? "text-[var(--color-success)]"+ : "text-[var(--color-error)]",+ )}+ >+ {(delta.neutral ? "" : delta.positive ? "↑ " : "↓ ") + delta.value}+ </span>+ )}+ </div>+ </div>+ {icon && (+ <div className="shrink-0 rounded-md bg-[var(--color-bg-elevated)] p-2 text-[var(--color-text-secondary)]">+ {icon}+ </div>+ )}+ </div>+ {sparkline && <div className="mt-3">{sparkline}</div>}+ {distBar && <div className="mt-3">{distBar}</div>}+ </CardContent>+ </Card>+ );++ if (href) {+ const Link = LinkComponent;+ return (+ <Link href={href} className="block h-full no-underline">+ {card}+ </Link>+ );+ }++ return card;+}diff --git a/packages/ui/src/shared/page-shell.tsx b/packages/ui/src/shared/page-shell.tsxnew file mode 100644index 000000000..4085cbe62--- /dev/null+++ b/packages/ui/src/shared/page-shell.tsx@@ -0,0 +1,53 @@+import * as React from "react";+import { cn } from "../lib/cn";++export interface PageShellProps {+ title: string;+ icon?: React.ReactNode;+ description?: string;+ /** Right-aligned action slot in the header band. */+ actions?: React.ReactNode;+ /** `default` ~1280px for reading surfaces; `wide` ~1600px for canvases. */+ maxWidth?: "default" | "wide";+ className?: string;+ children?: React.ReactNode;+}++/**+ * The single page frame: outer padding, centred max width, vertical rhythm,+ * and one header band (title + optional icon + one-line description + actions).+ * Replaces the hand-rolled per-page headers.+ */+export function PageShell({+ title,+ icon,+ description,+ actions,+ maxWidth = "default",+ className,+ children,+}: PageShellProps) {+ return (+ <div+ className={cn(+ "mx-auto w-full p-[var(--page-pad)] space-y-[var(--section-gap)]",+ maxWidth === "wide" ? "max-w-[1600px]" : "max-w-[1280px]",+ className,+ )}+ >+ <header className="flex flex-wrap items-start justify-between gap-4">+ <div className="min-w-0 space-y-1">+ <h1 className="flex items-center gap-2 text-xl font-semibold text-[var(--color-text-primary)]">+ {icon}+ {title}+ </h1>+ {description && (+ <p className="text-sm text-[var(--color-text-secondary)]">{description}</p>+ )}+ </div>+ {actions && <div className="flex shrink-0 items-center gap-2">{actions}</div>}+ </header>+ {children}+ </div>+ );+}diff --git a/packages/ui/src/shared/stat-grid.tsx b/packages/ui/src/shared/stat-grid.tsxnew file mode 100644index 000000000..20a9f523b--- /dev/null+++ b/packages/ui/src/shared/stat-grid.tsx@@ -0,0 +1,53 @@+import * as React from "react";+import { cn } from "../lib/cn";++export interface StatGridProps {+ /** Column count at the widest breakpoint. Defaults to a responsive 4-up. */+ columns?: 2 | 3 | 4;+ className?: string;+ children?: React.ReactNode;+}++const COLUMN_CLASS: Record<NonNullable<StatGridProps["columns"]>, string> = {+ 2: "grid-cols-1 sm:grid-cols-2",+ 3: "grid-cols-1 sm:grid-cols-2 lg:grid-cols-3",+ 4: "grid-cols-1 sm:grid-cols-2 lg:grid-cols-4",+};++/** Responsive grid wrapper for `StatTile`s. */+export function StatGrid({ columns = 4, className, children }: StatGridProps) {+ return (+ <div className={cn("grid gap-3", COLUMN_CLASS[columns], className)}>+ {children}+ </div>+ );+}++export interface StatTileProps {+ label: string;+ value: React.ReactNode;+ hint?: string;+ className?: string;+}++/** Compact label/value/hint cell — the consolidated inline-stat helper. */+export function StatTile({ label, value, hint, className }: StatTileProps) {+ return (+ <div+ className={cn(+ "rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3",+ className,+ )}+ >+ <p className="text-xs font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">+ {label}+ </p>+ <p className="mt-1 text-lg font-semibold tabular-nums text-[var(--color-text-primary)]">+ {value}+ </p>+ {hint && (+ <p className="mt-0.5 text-xs text-[var(--color-text-secondary)]">{hint}</p>+ )}+ </div>+ );+}diff --git a/packages/ui/src/shared/view-tabs.tsx b/packages/ui/src/shared/view-tabs.tsxnew file mode 100644index 000000000..8de70c21c--- /dev/null+++ b/packages/ui/src/shared/view-tabs.tsx@@ -0,0 +1,108 @@+"use client";++import * as React from "react";+import { cn } from "../lib/cn";++export interface ViewTab {+ id: string;+ label: string;+ badge?: number;+}++export interface ViewTabsProps {+ tabs: ViewTab[];+ value: string;+ onValueChange: (id: string) => void;+ /** The active panel, rendered below the tab row. */+ children?: React.ReactNode;+ className?: string;+}++/**+ * The single borderless-underline tab row. Pure presentation: callers own URL+ * sync via `value`/`onValueChange`. Replaces the segmented primitive usage and+ * bespoke `border-b` switchers.+ */+export function ViewTabs({+ tabs,+ value,+ onValueChange,+ children,+ className,+}: ViewTabsProps) {+ // Stable id base so each tab can be aria-labelled to the shared panel and+ // the panel can point back at the active tab.+ const baseId = React.useId();+ const tabId = (id: string) => `${baseId}-tab-${id}`;+ const panelId = `${baseId}-panel`;+ const tabRefs = React.useRef<Record<string, HTMLButtonElement | null>>({});++ // Keep the active tab in view even though the scrollbar is hidden — it can+ // otherwise scroll off-screen with no way to reveal it.+ React.useEffect(() => {+ tabRefs.current[value]?.scrollIntoView({ inline: "nearest", block: "nearest" });+ }, [value]);++ // Left/right arrow keys move selection (and focus) between tabs; Home/End+ // jump to the ends. Roving tabIndex keeps a single tab-stop for the row.+ const onKeyDown = (e: React.KeyboardEvent) => {+ const i = tabs.findIndex((t) => t.id === value);+ if (i < 0) return;+ let next = i;+ if (e.key === "ArrowRight") next = (i + 1) % tabs.length;+ else if (e.key === "ArrowLeft") next = (i - 1 + tabs.length) % tabs.length;+ else if (e.key === "Home") next = 0;+ else if (e.key === "End") next = tabs.length - 1;+ else return;+ e.preventDefault();+ const nextTab = tabs[next];+ if (!nextTab) return;+ onValueChange(nextTab.id);+ tabRefs.current[nextTab.id]?.focus();+ };++ return (+ <div className={cn("space-y-4", className)}>+ <div+ role="tablist"+ onKeyDown={onKeyDown}+ className="flex items-center gap-4 overflow-x-auto border-b border-[var(--color-border-default)] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"+ >+ {tabs.map((tab) => {+ const active = tab.id === value;+ return (+ <button+ key={tab.id}+ ref={(el) => {+ tabRefs.current[tab.id] = el;+ }}+ id={tabId(tab.id)}+ type="button"+ role="tab"+ aria-selected={active}+ aria-controls={panelId}+ tabIndex={active ? 0 : -1}+ onClick={() => onValueChange(tab.id)}+ className={cn(+ "inline-flex items-center gap-1.5 whitespace-nowrap border-b-2 border-transparent px-1 pb-2 -mb-px text-sm font-medium ring-offset-[var(--color-bg-root)] transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)] focus-visible:ring-offset-2",+ active+ ? "border-[var(--color-accent-primary)] text-[var(--color-text-primary)]"+ : "text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]",+ )}+ >+ {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)]">+ {tab.badge}+ </span>+ )}+ </button>+ );+ })}+ </div>+ <div id={panelId} role="tabpanel" aria-labelledby={tabId(value)} tabIndex={0}>+ {children}+ </div>+ </div>+ );+}diff --git a/packages/ui/src/symbols/hot-symbols-board.tsx b/packages/ui/src/symbols/hot-symbols-board.tsxdeleted file mode 100644index 276d9ba17..000000000--- a/packages/ui/src/symbols/hot-symbols-board.tsx+++ /dev/null@@ -1,121 +0,0 @@-"use client";--import { useState } from "react";-import { ArrowRight, ChevronDown, ChevronRight, Flame } from "lucide-react";-import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";-import { Badge } from "../ui/badge";-import { cn } from "../lib/cn";-import type { CodeSymbol } from "@repowise-dev/types/symbols";--export interface HotSymbol {- symbol: CodeSymbol;- /** Composite hotness score (higher = hotter). */- score: number;- pagerank?: number;-}--export interface HotSymbolsBoardProps {- items: HotSymbol[];- /** Cap items rendered (default 8). */- limit?: number;- onSelect?: (sym: CodeSymbol) => void;- className?: string;- /**- * When true (default) the board starts collapsed — header only, content- * hidden behind an expand toggle. The table below it is the primary- * surface; this board is a secondary preview, so keeping it folded by- * default avoids stealing top-of-page real estate.- */- defaultCollapsed?: boolean;-}--export function HotSymbolsBoard({- items,- limit = 8,- onSelect,- className,- defaultCollapsed = true,-}: HotSymbolsBoardProps) {- const [open, setOpen] = useState(!defaultCollapsed);- const top = items.slice(0, limit);- if (top.length === 0) {- return null;- }- const max = top[0]?.score ?? 1;-- return (- <Card className={className}>- <CardHeader className="pb-2">- <button- type="button"- onClick={() => setOpen((v) => !v)}- aria-expanded={open}- className="w-full text-left -my-1 -mx-1 rounded px-1 py-1 hover:bg-[var(--color-bg-elevated)] transition-colors"- >- <CardTitle className="text-sm flex items-center gap-2">- {open ? (- <ChevronDown className="h-3.5 w-3.5 text-[var(--color-text-tertiary)]" />- ) : (- <ChevronRight className="h-3.5 w-3.5 text-[var(--color-text-tertiary)]" />- )}- <Flame className="h-4 w-4 text-orange-500" />- Hot symbols- <span className="text-[10px] font-normal text-[var(--color-text-tertiary)] uppercase tracking-wider">- churn × centrality × complexity- </span>- <span className="ml-auto text-[10px] font-normal text-[var(--color-text-tertiary)] tabular-nums">- {top.length}- </span>- </CardTitle>- </button>- </CardHeader>- {open && (- <CardContent className="pt-0">- <div className="grid grid-cols-1 md:grid-cols-2 gap-2">- {top.map(({ symbol, score }) => {- const intensity = max > 0 ? score / max : 0;- return (- <button- key={symbol.id}- onClick={onSelect ? () => onSelect(symbol) : undefined}- disabled={!onSelect}- className={cn(- "group rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-3 py-2 text-left transition-colors",- onSelect && "hover:border-[var(--color-accent-primary)] cursor-pointer",- )}- title={`${symbol.file_path}:${symbol.start_line}`}- >- <div className="flex items-center justify-between gap-2 mb-1">- <span className="font-mono text-xs text-[var(--color-text-primary)] truncate">- {symbol.name}- </span>- <ArrowRight className="h-3 w-3 text-[var(--color-text-tertiary)] shrink-0 opacity-0 group-hover:opacity-100 transition-opacity" />- </div>- <div className="flex flex-wrap items-center gap-1 mb-1.5">- <Badge variant="outline" className="text-[10px] h-4">- {symbol.kind}- </Badge>- {symbol.complexity_estimate > 10 && (- <Badge variant="stale" className="text-[10px] h-4">- cx {symbol.complexity_estimate}- </Badge>- )}- </div>- <p className="text-[10px] font-mono text-[var(--color-text-tertiary)] truncate">- {symbol.file_path}:{symbol.start_line}- </p>- <div className="mt-1.5 h-1 rounded-full bg-[var(--color-bg-inset)] overflow-hidden">- <div- className="h-full rounded-full bg-orange-500"- style={{ width: `${Math.round(intensity * 100)}%` }}- />- </div>- </button>- );- })}- </div>- </CardContent>- )}- </Card>- );-}diff --git a/packages/ui/src/symbols/index.ts b/packages/ui/src/symbols/index.tsindex e17469f33..20eeb6617 100644--- a/packages/ui/src/symbols/index.ts+++ b/packages/ui/src/symbols/index.ts@@ -1,7 +1,7 @@export * from "./symbol-page";+export * from "./symbol-index-header";export * from "./symbol-table";export * from "./symbol-drawer";-export * from "./symbol-graph-panel";-export * from "./symbol-git-panel";-export * from "./hot-symbols-board";+export * from "./symbol-detail-body";+export * from "./symbol-call-graph";export * from "./top-symbols-row";diff --git a/packages/ui/src/symbols/symbol-call-graph.tsx b/packages/ui/src/symbols/symbol-call-graph.tsxnew file mode 100644index 000000000..dc60394e9--- /dev/null+++ b/packages/ui/src/symbols/symbol-call-graph.tsx@@ -0,0 +1,116 @@+"use client";++import { ArrowRight } from "lucide-react";+import type { SymbolBodyCall } from "@repowise-dev/types/symbols";+import { truncatePath } from "../lib/format";+import { cn } from "../lib/cn";++interface SymbolCallGraphProps {+ centerName: string;+ callers: SymbolBodyCall[];+ callees: SymbolBodyCall[];+ symbolHref?: (id: string) => string;+ /** Cap per column so the mini-graph stays compact. */+ limit?: number;+}++function CallNode({+ entry,+ symbolHref,+}: {+ entry: SymbolBodyCall;+ symbolHref?: (id: string) => string;+}) {+ const inner = (+ <div className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-2 py-1.5 transition-colors hover:border-[var(--color-border-hover)]">+ <div className="flex items-center gap-1.5">+ <span+ className={cn(+ "h-1.5 w-1.5 shrink-0 rounded-full",+ (entry.confidence ?? 1) >= 0.9+ ? "bg-[var(--color-success)]"+ : (entry.confidence ?? 1) >= 0.7+ ? "bg-[var(--color-caution)]"+ : "bg-[var(--color-text-tertiary)]",+ )}+ />+ <span className="truncate font-mono text-xs text-[var(--color-text-primary)]">+ {entry.name}+ </span>+ </div>+ <div className="truncate pl-3 text-[10px] text-[var(--color-text-tertiary)]" title={entry.file}>+ {truncatePath(entry.file, 28)}+ </div>+ </div>+ );+ if (!symbolHref) return inner;+ return (+ <a href={symbolHref(entry.symbol_id)} className="block no-underline">+ {inner}+ </a>+ );+}++/**+ * A compact centered call-graph: callers feed into the centered symbol, which+ * feeds the callees. Replaces the two flat caller/callee lists with the graph+ * shape the data actually describes. Empty columns read as "no edges".+ */+export function SymbolCallGraph({+ centerName,+ callers,+ callees,+ symbolHref,+ limit = 6,+}: SymbolCallGraphProps) {+ const callersShown = callers.slice(0, limit);+ const calleesShown = callees.slice(0, limit);++ return (+ <div className="grid grid-cols-[1fr_auto_1fr] items-center gap-3">+ <div className="space-y-1.5">+ <p className="text-[10px] font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">+ Called by ({callers.length})+ </p>+ {callersShown.length === 0 ? (+ <p className="text-xs italic text-[var(--color-text-tertiary)]">None</p>+ ) : (+ callersShown.map((c) => (+ <CallNode key={`${c.symbol_id}-${c.edge_type}`} entry={c} {...(symbolHref ? { symbolHref } : {})} />+ ))+ )}+ {callers.length > limit && (+ <p className="text-[10px] text-[var(--color-text-tertiary)]">+ +{callers.length - limit} more+ </p>+ )}+ </div>++ <div className="flex flex-col items-center gap-1">+ <ArrowRight className="h-4 w-4 text-[var(--color-text-tertiary)]" />+ <div className="max-w-[140px] truncate rounded-md border border-[var(--color-accent-primary)] bg-[var(--color-accent-primary)]/10 px-3 py-2 text-center font-mono text-xs font-semibold text-[var(--color-text-primary)]">+ {centerName}+ </div>+ <ArrowRight className="h-4 w-4 text-[var(--color-text-tertiary)]" />+ </div>++ <div className="space-y-1.5">+ <p className="text-[10px] font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">+ Calls ({callees.length})+ </p>+ {calleesShown.length === 0 ? (+ <p className="text-xs italic text-[var(--color-text-tertiary)]">None</p>+ ) : (+ calleesShown.map((c) => (+ <CallNode key={`${c.symbol_id}-${c.edge_type}`} entry={c} {...(symbolHref ? { symbolHref } : {})} />+ ))+ )}+ {callees.length > limit && (+ <p className="text-[10px] text-[var(--color-text-tertiary)]">+ +{callees.length - limit} more+ </p>+ )}+ </div>+ </div>+ );+}diff --git a/packages/ui/src/symbols/symbol-detail-body.tsx b/packages/ui/src/symbols/symbol-detail-body.tsxnew file mode 100644index 000000000..a41674e3e--- /dev/null+++ b/packages/ui/src/symbols/symbol-detail-body.tsx@@ -0,0 +1,394 @@+"use client";++import {+ AlertTriangle,+ Flame,+ GitBranch,+ Lightbulb,+ Network,+ Radius,+ Skull,+ Users,+} from "lucide-react";+import type { SymbolDetailData } from "@repowise-dev/types/symbols";+import { Badge } from "../ui/badge";+import { Button } from "../ui/button";+import { StatGrid, StatTile } from "../shared/stat-grid";+import { scoreBadgeClass } from "../health/tokens";+import { truncatePath } from "../lib/format";+import { cn } from "../lib/cn";+import { SymbolCallGraph } from "./symbol-call-graph";++export interface SymbolDetailBodyProps {+ data: SymbolDetailData;+ /** Build an href to a sibling symbol page (route surface). Omit in the modal. */+ symbolHref?: (symbolId: string) => string;+ /** Build an href to the parent file page. */+ fileHref?: (filePath: string) => string;+ /** Blast-radius CTA — wired by the host. */+ onOpenBlastRadius?: () => void;+ /** Loading flag for the optional graph/git feeds (modal streams them in). */+ metricsLoading?: boolean;+ className?: string;+}++function ageDays(t: number | null | undefined): number | null {+ if (!t) return null;+ return Math.max(0, Math.round((Date.now() / 1000 - t) / 86400));+}++/**+ * The single symbol-detail body rendered by BOTH the drawer (modal) and the+ * routed page. Purely presentational — no routing, no data fetching. Every+ * intelligence block (graph metrics, entry-point score, call graph, heritage,+ * git/owner context, co-changes, dead code, governing decisions) is data-driven:+ * it renders only when its feed is present and degrades silently when absent.+ *+ * The two surfaces differ in what they CAN supply, not in what the body can+ * render. The drawer's web wrapper streams file-level git intelligence+ * (git/co-changes/dead-code/entry-point/recent-owner/churn) from dedicated+ * endpoints, so those blocks light up there. The routed endpoint+ * (`SymbolDetailResponse`) omits file-level git intelligence by design — it+ * carries symbol, graph (callers/callees), function-blame, governing decisions,+ * and file_context — so the body simply hides the git/co-change/dead-code blocks+ * on the route rather than fabricating them. Governing decisions render here for+ * both surfaces so each fact appears exactly once.+ */+export function SymbolDetailBody({+ data,+ symbolHref,+ fileHref,+ onOpenBlastRadius,+ metricsLoading,+ className,+}: SymbolDetailBodyProps) {+ const { identity: id } = data;+ const graph = data.graph;+ const git = data.git;+ const age = ageDays(data.blame_median_author_time);+ const fileTo = fileHref ? fileHref(id.file_path) : undefined;+ const coChanges = (data.co_changes ?? []).slice(0, 6);+ const deadCode = data.dead_code ?? [];+ const heritage = data.heritage;+ const heritageParents = heritage?.parents ?? [];+ const heritageChildren = heritage?.children ?? [];+ const governingDecisions = data.governing_decisions ?? [];++ return (+ <div className={cn("space-y-4", className)}>+ {/* ── Signature + docstring ── */}+ {data.signature && (+ <pre className="overflow-x-auto rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-3 text-xs font-mono text-[var(--color-text-primary)]">+ {data.signature}+ </pre>+ )}+ {data.docstring && (+ <p className="whitespace-pre-wrap text-sm leading-relaxed text-[var(--color-text-secondary)]">+ {data.docstring}+ </p>+ )}+ {id.parent_name && (+ <p className="text-xs text-[var(--color-text-tertiary)]">+ Parent:{" "}+ <span className="font-mono text-[var(--color-text-secondary)]">+ {id.parent_name}+ </span>+ </p>+ )}++ {/* ── Signals (callers/callees counts intentionally omitted — see call graph) ── */}+ <StatGrid columns={4}>+ <StatTile+ label="Importance"+ value={data.importance_score != null ? data.importance_score.toFixed(3) : "—"}+ />+ <StatTile+ label="Complexity"+ value={data.complexity_estimate != null ? String(data.complexity_estimate) : "—"}+ />+ <StatTile+ label="Modifications"+ value={data.blame_mod_count != null ? String(data.blame_mod_count) : "—"}+ {...(data.blame_recent_mod_count != null+ ? { hint: `${data.blame_recent_mod_count} recent` }+ : {})}+ />+ <StatTile label="Median age" value={age != null ? `${age}d` : "—"} />+ </StatGrid>++ {/* ── Graph metrics ── */}+ {graph &&+ (graph.pagerank_percentile != null ||+ graph.betweenness_percentile != null ||+ graph.community_label != null ||+ (graph.entry_point_score != null && graph.entry_point_score > 0)) && (+ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3">+ <p className="mb-2 text-[10px] font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">+ Graph metrics+ </p>+ <div className="grid grid-cols-2 gap-x-4 gap-y-1.5 text-xs sm:grid-cols-4">+ {graph.pagerank_percentile != null && (+ <Metric label="PageRank" value={`Top ${100 - graph.pagerank_percentile}%`} />+ )}+ {graph.betweenness_percentile != null && (+ <Metric label="Betweenness" value={`Top ${100 - graph.betweenness_percentile}%`} />+ )}+ <Metric label="Degree" value={`${graph.in_degree} in · ${graph.out_degree} out`} />+ {graph.community_label && (+ <Metric label="Community" value={graph.community_label} />+ )}+ </div>+ {graph.entry_point_score != null && graph.entry_point_score > 0 && (+ <div className="mt-2.5 flex items-center justify-between gap-2 text-xs">+ <span className="text-[var(--color-text-tertiary)]">Entry point</span>+ <div className="flex items-center gap-1.5">+ <div className="h-1.5 w-12 overflow-hidden rounded-full bg-[var(--color-bg-elevated)]">+ <div+ className="h-full rounded-full bg-[var(--color-accent-primary)]"+ style={{ width: `${Math.round(graph.entry_point_score * 100)}%` }}+ />+ </div>+ <span className="font-mono tabular-nums text-[var(--color-text-secondary)]">+ {(graph.entry_point_score * 100).toFixed(0)}%+ </span>+ </div>+ </div>+ )}+ </div>+ )}++ {/* ── Call graph (replaces caller/callee lists) ── */}+ {graph && (+ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3">+ {metricsLoading ? (+ <p className="text-xs text-[var(--color-text-tertiary)]">Loading call graph…</p>+ ) : (+ <SymbolCallGraph+ centerName={id.name}+ callers={graph.callers}+ callees={graph.callees}+ {...(symbolHref ? { symbolHref } : {})}+ />+ )}+ </div>+ )}++ {/* ── Heritage (extends / implements / extended-by) ── */}+ {(heritageParents.length > 0 || heritageChildren.length > 0) && (+ <div className="space-y-2 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3">+ <p className="flex items-center gap-1 text-[10px] font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">+ <Network className="h-3 w-3" /> Heritage+ </p>+ {heritageParents.length > 0 && (+ <div className="space-y-1">+ <p className="text-[10px] text-[var(--color-text-tertiary)]">Extends / implements</p>+ {heritageParents.map((r) => (+ <p+ key={`${r.kind}:${r.parent_id ?? r.parent_name}:${r.line}`}+ className="truncate pl-2 font-mono text-xs text-[var(--color-text-primary)]"+ title={r.parent_id ?? r.parent_name}+ >+ {r.parent_name}+ <span className="ml-1 text-[var(--color-text-tertiary)]">({r.kind})</span>+ </p>+ ))}+ </div>+ )}+ {heritageChildren.length > 0 && (+ <div className="space-y-1">+ <p className="text-[10px] text-[var(--color-text-tertiary)]">Extended / implemented by</p>+ {heritageChildren.map((r) => (+ <p+ key={`${r.kind}:${r.child_id ?? r.child_name}:${r.line}`}+ className="truncate pl-2 font-mono text-xs text-[var(--color-text-primary)]"+ title={r.child_id ?? r.child_name}+ >+ {r.child_name}+ <span className="ml-1 text-[var(--color-text-tertiary)]">({r.kind})</span>+ </p>+ ))}+ </div>+ )}+ </div>+ )}++ {/* ── Blame owner ── */}+ {data.blame_owner_name && (+ <p className="flex items-center gap-1.5 text-xs text-[var(--color-text-secondary)]">+ <Users className="h-3.5 w-3.5 text-[var(--color-text-tertiary)]" />+ Blame owner <span className="font-medium">{data.blame_owner_name}</span>+ {data.blame_owner_line_pct != null &&+ ` (${Math.round(data.blame_owner_line_pct * 100)}% of lines)`}+ </p>+ )}++ {/* ── File git context ── */}+ {git && (+ <div className="space-y-1.5 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3 text-xs">+ <p className="text-[10px] font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">+ File context+ </p>+ <div className="flex flex-wrap items-center gap-2 text-[var(--color-text-tertiary)]">+ {git.primary_owner_name && (+ <span className="text-[var(--color-text-secondary)]">+ {git.primary_owner_name}+ {git.primary_owner_commit_pct != null &&+ ` (${Math.round(git.primary_owner_commit_pct * 100)}%)`}+ </span>+ )}+ {git.bus_factor != null && (+ <span+ className={cn(+ "inline-flex items-center rounded px-1.5 py-0.5 tabular-nums",+ git.bus_factor <= 1+ ? "bg-[var(--color-error)]/15 text-[var(--color-error)]"+ : git.bus_factor === 2+ ? "bg-[var(--color-caution)]/15 text-[var(--color-caution)]"+ : "bg-[var(--color-success)]/15 text-[var(--color-success)]",+ )}+ >+ bus {git.bus_factor}+ </span>+ )}+ {git.contributor_count != null && <span>{git.contributor_count} contributors</span>}+ {git.commit_count_90d != null && <span>{git.commit_count_90d} commits / 90d</span>}+ {git.churn_percentile != null && (+ <span>churn top {100 - Math.round(git.churn_percentile)}%</span>+ )}+ {git.is_hotspot && (+ <span className="inline-flex items-center gap-0.5 rounded bg-[var(--color-error)]/15 px-1.5 py-0.5 text-[var(--color-error)]">+ <Flame className="h-3 w-3" /> hotspot+ </span>+ )}+ </div>+ {git.recent_owner_name && git.recent_owner_name !== git.primary_owner_name && (+ <p className="text-[var(--color-text-tertiary)]">+ Recent owner (90d):{" "}+ <span className="text-[var(--color-text-secondary)]">{git.recent_owner_name}</span>+ </p>+ )}+ </div>+ )}++ {/* ── Co-changes ── */}+ {coChanges.length > 0 && (+ <div className="space-y-1.5">+ <p className="flex items-center gap-1 text-[10px] font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">+ <GitBranch className="h-3 w-3" /> Co-changes+ </p>+ <ul className="space-y-1">+ {coChanges.map((p) => (+ <li+ key={p.file_path}+ className="flex items-center justify-between gap-2 font-mono text-xs"+ >+ <span className="truncate text-[var(--color-text-secondary)]" title={p.file_path}>+ {truncatePath(p.file_path, 40)}+ </span>+ <span className="tabular-nums text-[var(--color-text-tertiary)]">+ {p.co_change_count}×+ </span>+ </li>+ ))}+ </ul>+ </div>+ )}++ {/* ── Dead code in scope ── */}+ {deadCode.length > 0 && (+ <div className="space-y-1.5">+ <p className="flex items-center gap-1 text-[10px] font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">+ <Skull className="h-3 w-3" /> Dead code in scope+ </p>+ <ul className="space-y-1">+ {deadCode.map((f) => (+ <li key={f.id} className="flex items-start gap-2 text-xs">+ <AlertTriangle+ className={cn(+ "mt-0.5 h-3 w-3 shrink-0",+ f.safe_to_delete ? "text-[var(--color-error)]" : "text-[var(--color-caution)]",+ )}+ />+ <span className="text-[var(--color-text-secondary)]">+ <span className="font-medium">{f.kind}</span>{" "}+ <span className="text-[var(--color-text-tertiary)]">+ — {f.reason} ({f.lines} lines)+ </span>+ </span>+ </li>+ ))}+ </ul>+ </div>+ )}++ {/* ── Governing decisions (rendered here so BOTH surfaces show them once) ── */}+ {governingDecisions.length > 0 && (+ <div className="space-y-1.5">+ <p className="flex items-center gap-1 text-[10px] font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">+ <Lightbulb className="h-3 w-3" /> Governing decisions+ </p>+ <ul className="space-y-1">+ {governingDecisions.slice(0, 5).map((d) => (+ <li+ key={d.id}+ className="flex items-center justify-between gap-2 text-xs text-[var(--color-text-secondary)]"+ >+ <span className="truncate" title={d.title}>+ {d.title}+ </span>+ <span className="shrink-0 text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">+ {d.status}+ </span>+ </li>+ ))}+ </ul>+ </div>+ )}++ {/* ── Parent file ── */}+ {fileTo && (+ <div className="flex flex-wrap items-center gap-3 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3">+ <span className="text-[10px] font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">+ Parent file+ </span>+ <a+ href={fileTo}+ className="truncate font-mono text-xs text-[var(--color-accent-primary)] hover:underline"+ >+ {data.identity.file_path}+ </a>+ {data.file_context?.health_score != null && (+ <span+ className={`inline-flex items-baseline rounded px-1.5 py-0.5 text-xs font-bold tabular-nums ${scoreBadgeClass(data.file_context.health_score)}`}+ >+ {data.file_context.health_score.toFixed(1)}+ <span className="ml-0.5 text-[10px] font-normal opacity-70">/10</span>+ </span>+ )}+ {(data.file_context?.language || id.language) && (+ <Badge variant="outline" className="h-5 text-[10px] capitalize">+ {data.file_context?.language || id.language}+ </Badge>+ )}+ </div>+ )}++ {/* ── Blast radius CTA ── */}+ {onOpenBlastRadius && (+ <Button variant="outline" size="sm" onClick={onOpenBlastRadius}>+ <Radius className="mr-1.5 h-3.5 w-3.5" />+ View blast radius for {truncatePath(id.file_path, 28)}+ </Button>+ )}+ </div>+ );+}++function Metric({ label, value }: { label: string; value: string }) {+ return (+ <div className="flex items-center justify-between gap-2">+ <span className="text-[var(--color-text-tertiary)]">{label}</span>+ <span className="font-mono text-[var(--color-text-secondary)]">{value}</span>+ </div>+ );+}diff --git a/packages/ui/src/symbols/symbol-drawer.tsx b/packages/ui/src/symbols/symbol-drawer.tsxindex 059361fb8..abf678813 100644--- a/packages/ui/src/symbols/symbol-drawer.tsx+++ b/packages/ui/src/symbols/symbol-drawer.tsx@@ -1,6 +1,6 @@"use client";-import type { ReactNode } from "react";+import { Flame } from "lucide-react";import {Dialog,DialogContent,@@ -11,90 +11,83 @@ import {import { Badge } from "../ui/badge";import { ScrollArea } from "../ui/scroll-area";import { Separator } from "../ui/separator";-import type { CodeSymbol } from "@repowise-dev/types/symbols";+import type { SymbolDetailData } from "@repowise-dev/types/symbols";+import { SymbolDetailBody } from "./symbol-detail-body";interface SymbolDrawerProps {- symbol: CodeSymbol | null;+ /** Normalized symbol body data — null hides the modal. */+ data: SymbolDetailData | null;onClose: () => void;- /**- * Right-column graph intelligence slot. Wrappers pass a data-coupled- * `<SymbolGraphPanelWrapper>` here; pass `null` to hide the column.- */- graphPanel?: ReactNode;- /**- * Additional right-column slot for file-level git context (owner, bus- * factor, co-changes, overlapping dead code). Rendered below the graph- * panel when both are present.- */- gitPanel?: ReactNode;+ /** The optional graph/git feeds are streamed in by the wrapper. */+ metricsLoading?: boolean;+ /** Build an href to a sibling symbol page. */+ symbolHref?: (symbolId: string) => string;+ /** Build an href to the parent file page. */+ fileHref?: (filePath: string) => string;+ onOpenBlastRadius?: () => void;}-export function SymbolDrawer({ symbol, onClose, graphPanel, gitPanel }: SymbolDrawerProps) {+/**+ * The modal symbol surface. Renders the SAME `SymbolDetailBody` as the routed+ * `SymbolPage`, so the drawer and the page expose identical capabilities+ * (graph metrics, call graph, git context, co-changes, dead code, blast radius).+ */+export function SymbolDrawer({+ data,+ onClose,+ metricsLoading,+ symbolHref,+ fileHref,+ onOpenBlastRadius,+}: SymbolDrawerProps) {return (- <Dialog open={symbol !== null} onOpenChange={(open) => !open && onClose()}>+ <Dialog open={data !== null} onOpenChange={(open) => !open && onClose()}><DialogContent className="max-w-[95vw] w-[1000px] max-h-[88vh] overflow-hidden p-0">- {symbol && (+ {data && (<><div className="px-6 pt-6 pb-3"><DialogHeader>- <DialogTitle className="font-mono text-base">{symbol.name}</DialogTitle>- <DialogDescription className="font-mono text-xs text-[var(--color-text-tertiary)] break-all">- {symbol.file_path}:{symbol.start_line}+ <DialogTitle className="font-mono text-base">+ {data.identity.name}+ </DialogTitle>+ <DialogDescription className="break-all font-mono text-xs text-[var(--color-text-tertiary)]">+ {data.identity.file_path}:{data.identity.start_line}</DialogDescription></DialogHeader>- <div className="flex flex-wrap gap-1.5 mt-2">- <Badge variant="accent">{symbol.kind}</Badge>- <Badge variant="outline">{symbol.language}</Badge>- {symbol.visibility && symbol.visibility !== "public" && (- <Badge variant="default">{symbol.visibility}</Badge>+ <div className="mt-2 flex flex-wrap items-center gap-1.5">+ <Badge variant="accent">{data.identity.kind}</Badge>+ {data.identity.language && (+ <Badge variant="outline">{data.identity.language}</Badge>)}- {symbol.is_async && <Badge variant="default">async</Badge>}- {symbol.complexity_estimate > 10 && (- <Badge variant="stale">complexity {symbol.complexity_estimate}</Badge>+ {data.identity.visibility &&+ data.identity.visibility !== "public" && (+ <Badge variant="default">{data.identity.visibility}</Badge>+ )}+ {data.identity.is_async && <Badge variant="default">async</Badge>}+ {data.identity.file_is_hotspot && (+ <Badge+ variant="outline"+ className="text-[var(--color-error)] border-[var(--color-error)]/30"+ >+ <Flame className="h-2.5 w-2.5" /> hot file+ </Badge>)}</div></div><Separator />- <div className="flex min-h-0 flex-1 overflow-hidden" style={{ maxHeight: "calc(85vh - 120px)" }}>- <ScrollArea className="flex-1 min-w-0">- <div className="px-6 py-4 space-y-3">- <div className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]">- <pre className="p-4 text-xs font-mono text-[var(--color-text-primary)] whitespace-pre-wrap break-all">- <code>{symbol.signature || symbol.name}</code>- </pre>- </div>-- {symbol.docstring && (- <div className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3">- <p className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-1.5">- Docstring- </p>- <p className="text-sm text-[var(--color-text-secondary)] whitespace-pre-wrap">- {symbol.docstring}- </p>- </div>- )}-- {symbol.parent_name && (- <p className="text-xs text-[var(--color-text-tertiary)]">- Parent: <span className="font-mono text-[var(--color-text-secondary)]">{symbol.parent_name}</span>- </p>- )}- </div>- </ScrollArea>-- {(graphPanel || gitPanel) && (- <div className="hidden md:flex flex-col border-l border-[var(--color-border-default)] bg-[var(--color-bg-surface)] w-[340px] shrink-0 overflow-hidden">- <ScrollArea className="flex-1 min-h-0">- {graphPanel}- {graphPanel && gitPanel && <Separator />}- {gitPanel}- </ScrollArea>- </div>- )}- </div>+ <ScrollArea className="max-h-[calc(85vh-120px)]">+ <div className="px-6 py-4">+ <SymbolDetailBody+ data={data}+ {...(metricsLoading != null ? { metricsLoading } : {})}+ {...(symbolHref ? { symbolHref } : {})}+ {...(fileHref ? { fileHref } : {})}+ {...(onOpenBlastRadius ? { onOpenBlastRadius } : {})}+ />+ </div>+ </ScrollArea></>)}</DialogContent>diff --git a/packages/ui/src/symbols/symbol-git-panel.tsx b/packages/ui/src/symbols/symbol-git-panel.tsxdeleted file mode 100644index 1fa7dc35e..000000000--- a/packages/ui/src/symbols/symbol-git-panel.tsx+++ /dev/null@@ -1,252 +0,0 @@-"use client";--import {- AlertTriangle,- Flame,- GitBranch,- Lightbulb,- Radius,- Skull,- Users,-} from "lucide-react";-import { Button } from "../ui/button";-import { truncatePath } from "../lib/format";-import { cn } from "../lib/cn";--export interface SymbolGitPanelOwner {- name: string;- email?: string;- commit_count?: number;- pct?: number;-}--export interface SymbolGitPanelCoChange {- file_path: string;- co_change_count: number;-}--export interface SymbolGitPanelDeadFinding {- id: string;- kind: string;- reason: string;- confidence: number;- lines: number;- safe_to_delete: boolean;-}--export interface SymbolGitPanelProps {- filePath: string;- loading?: boolean;- /** Git metadata bundle — null when the file has no git history. */- git?: {- primary_owner_name: string | null;- primary_owner_commit_pct: number | null;- recent_owner_name?: string | null;- recent_owner_commit_pct?: number | null;- bus_factor: number;- contributor_count: number;- commit_count_90d: number;- is_hotspot: boolean;- churn_percentile: number;- top_authors?: SymbolGitPanelOwner[];- } | null;- coChanges?: SymbolGitPanelCoChange[];- /** Dead-code findings whose line range overlaps the symbol. */- deadCode?: SymbolGitPanelDeadFinding[];- /** Decision records governing this file / module. Optional. */- governingDecisions?: Array<{ id: string; title: string; status: string }>;- /** Optional callback for the "View blast radius" CTA. */- onOpenBlastRadius?: () => void;- /** Click handler when an owner name is selected. */- onSelectOwner?: (name: string, email?: string | null) => void;- /** Click handler for governing decision rows. */- onSelectDecision?: (id: string) => void;-}--/**- * Side-panel that overlays file-level git intelligence onto a symbol.- * Lives in shared `packages/ui/` so the hosted frontend can re-use it- * without re-implementing the layout. All data fetching stays in the- * web-side wrapper; this component is purely presentational.- */-export function SymbolGitPanel({- filePath,- loading,- git,- coChanges,- deadCode,- governingDecisions,- onOpenBlastRadius,- onSelectOwner,- onSelectDecision,-}: SymbolGitPanelProps) {- const hasDead = (deadCode?.length ?? 0) > 0;- const visibleCoChanges = (coChanges ?? []).slice(0, 6);- const moreCoChanges = (coChanges?.length ?? 0) - visibleCoChanges.length;-- return (- <div className="px-4 py-3 space-y-4 text-xs">- <p className="text-[10px] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider">- File context- </p>-- {loading && (- <div className="space-y-2">- <div className="h-3 w-24 rounded bg-[var(--color-bg-elevated)] animate-pulse" />- <div className="h-3 w-32 rounded bg-[var(--color-bg-elevated)] animate-pulse" />- </div>- )}-- {!loading && !git && (- <p className="text-[var(--color-text-tertiary)]">No git history for this file.</p>- )}-- {git && (- <div className="space-y-2">- <div className="flex items-center gap-2">- <Users className="h-3.5 w-3.5 text-[var(--color-text-tertiary)]" />- {git.primary_owner_name ? (- <button- onClick={() => onSelectOwner?.(git.primary_owner_name!, null)}- disabled={!onSelectOwner}- className={cn(- "text-[var(--color-text-secondary)] text-left",- onSelectOwner && "hover:underline hover:text-[var(--color-accent-primary)]",- )}- >- {git.primary_owner_name}- {git.primary_owner_commit_pct != null && (- <span className="ml-1 text-[var(--color-text-tertiary)] tabular-nums">- ({Math.round(git.primary_owner_commit_pct * 100)}%)- </span>- )}- </button>- ) : (- <span className="text-[var(--color-text-secondary)]">—</span>- )}- </div>- {git.recent_owner_name && git.recent_owner_name !== git.primary_owner_name && (- <p className="text-[var(--color-text-tertiary)] pl-5">- Recent owner (90d): {git.recent_owner_name}- </p>- )}- <div className="flex flex-wrap items-center gap-2 text-[var(--color-text-tertiary)]">- <span- className={cn(- "inline-flex items-center rounded px-1.5 py-0.5 tabular-nums",- git.bus_factor <= 1- ? "bg-red-500/15 text-red-400"- : git.bus_factor === 2- ? "bg-yellow-500/15 text-yellow-400"- : "bg-green-500/15 text-green-400",- )}- title="Bus factor"- >- bus {git.bus_factor}- </span>- <span>{git.contributor_count} contributors</span>- <span>{git.commit_count_90d} commits / 90d</span>- {git.is_hotspot && (- <span className="inline-flex items-center gap-0.5 rounded bg-red-500/15 px-1.5 py-0.5 text-red-400">- <Flame className="h-3 w-3" />- hotspot- </span>- )}- </div>- </div>- )}-- {visibleCoChanges.length > 0 && (- <div className="space-y-1.5">- <p className="text-[10px] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider flex items-center gap-1">- <GitBranch className="h-3 w-3" />- Co-changes- </p>- <ul className="space-y-1">- {visibleCoChanges.map((p) => (- <li- key={p.file_path}- className="flex items-center justify-between gap-2 font-mono text-[11px]"- >- <span className="truncate text-[var(--color-text-secondary)]" title={p.file_path}>- {truncatePath(p.file_path, 36)}- </span>- <span className="tabular-nums text-[var(--color-text-tertiary)]">- {p.co_change_count}×- </span>- </li>- ))}- </ul>- {moreCoChanges > 0 && (- <p className="text-[10px] text-[var(--color-text-tertiary)]">- +{moreCoChanges} more- </p>- )}- </div>- )}-- {hasDead && (- <div className="space-y-1.5">- <p className="text-[10px] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider flex items-center gap-1">- <Skull className="h-3 w-3" />- Dead code in scope- </p>- <ul className="space-y-1">- {deadCode!.map((f) => (- <li key={f.id} className="flex items-start gap-2 text-[11px]">- <AlertTriangle- className={cn(- "h-3 w-3 mt-0.5 shrink-0",- f.safe_to_delete ? "text-red-400" : "text-yellow-400",- )}- />- <span className="text-[var(--color-text-secondary)]">- <span className="font-medium">{f.kind}</span>{" "}- <span className="text-[var(--color-text-tertiary)]">- — {f.reason} ({f.lines} lines)- </span>- </span>- </li>- ))}- </ul>- </div>- )}-- {governingDecisions && governingDecisions.length > 0 && (- <div className="space-y-1.5">- <p className="text-[10px] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider flex items-center gap-1">- <Lightbulb className="h-3 w-3" />- Governing decisions- </p>- <ul className="space-y-1">- {governingDecisions.slice(0, 5).map((d) => (- <li key={d.id}>- <button- onClick={() => onSelectDecision?.(d.id)}- className="flex w-full items-center justify-between gap-2 rounded px-1 py-0.5 text-left text-[11px] text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]"- >- <span className="truncate">{d.title}</span>- <span className="text-[10px] text-[var(--color-text-tertiary)] uppercase">- {d.status}- </span>- </button>- </li>- ))}- </ul>- </div>- )}-- {onOpenBlastRadius && (- <Button- variant="outline"- size="sm"- className="w-full"- onClick={onOpenBlastRadius}- >- <Radius className="h-3.5 w-3.5 mr-1.5" />- View blast radius for {truncatePath(filePath, 24)}- </Button>- )}- </div>- );-}diff --git a/packages/ui/src/symbols/symbol-graph-panel.tsx b/packages/ui/src/symbols/symbol-graph-panel.tsxdeleted file mode 100644index 6b06704fb..000000000--- a/packages/ui/src/symbols/symbol-graph-panel.tsx+++ /dev/null@@ -1,222 +0,0 @@-"use client";--import { Badge } from "../ui/badge";-import { Skeleton } from "../ui/skeleton";-import { ScrollArea } from "../ui/scroll-area";-import { Separator } from "../ui/separator";-import { truncatePath } from "../lib/format";-import { cn } from "../lib/cn";-import type {- CallerCalleeEntry,- CallersCallees,- GraphMetrics,-} from "@repowise-dev/types/graph";--interface SymbolGraphPanelProps {- metrics: GraphMetrics | undefined;- metricsLoading: boolean;- callData: CallersCallees | undefined;- callsLoading: boolean;- heritageData?: CallersCallees | undefined;-}--function PercentileBadge({ value, label }: { value: number; label: string }) {- const color =- value >= 75- ? "text-green-400 bg-green-400/10 border-green-400/20"- : value >= 50- ? "text-yellow-400 bg-yellow-400/10 border-yellow-400/20"- : "text-[var(--color-text-tertiary)] bg-[var(--color-bg-elevated)] border-[var(--color-border-default)]";-- return (- <div className="flex items-center justify-between gap-2">- <span className="text-[11px] text-[var(--color-text-tertiary)]">{label}</span>- <span className={cn("text-[11px] font-mono px-1.5 py-0.5 rounded border", color)}>- Top {100 - value}%- </span>- </div>- );-}--function CallerCalleeList({- items,- label,-}: {- items: CallerCalleeEntry[];- label: string;-}) {- if (items.length === 0) {- return (- <div>- <p className="text-[11px] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-1.5">- {label} (0)- </p>- <p className="text-[11px] text-[var(--color-text-tertiary)] italic">None found</p>- </div>- );- }-- return (- <div>- <p className="text-[11px] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-1.5">- {label} ({items.length})- </p>- <div className="space-y-1">- {items.slice(0, 15).map((item) => (- <div- key={item.symbol_id}- className="flex items-start gap-1.5 py-1 px-1.5 rounded hover:bg-[var(--color-bg-elevated)] transition-colors"- >- <span- className={cn(- "mt-1.5 w-1.5 h-1.5 rounded-full shrink-0",- item.confidence >= 0.9- ? "bg-green-400"- : item.confidence >= 0.7- ? "bg-yellow-400"- : "bg-[var(--color-text-tertiary)]",- )}- />- <div className="min-w-0 flex-1">- <p className="text-[11px] font-mono text-[var(--color-text-primary)] truncate" title={item.symbol_id}>- {item.name}- </p>- <p className="text-[10px] text-[var(--color-text-tertiary)] truncate" title={item.file}>- {truncatePath(item.file)}- </p>- </div>- {item.edge_type !== "calls" && (- <Badge variant="outline" className="text-[9px] shrink-0 h-4">- {item.edge_type}- </Badge>- )}- </div>- ))}- {items.length > 15 && (- <p className="text-[10px] text-[var(--color-text-tertiary)] px-1.5">- +{items.length - 15} more- </p>- )}- </div>- </div>- );-}--export function SymbolGraphPanel({- metrics,- metricsLoading,- callData,- callsLoading,- heritageData,-}: SymbolGraphPanelProps) {- const hasHeritage =- heritageData && (heritageData.caller_count > 0 || heritageData.callee_count > 0);-- return (- <ScrollArea className="h-full">- <div className="space-y-4 px-3 py-3">- <div>- <p className="text-[11px] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-2">- Graph Metrics- </p>- {metricsLoading ? (- <div className="space-y-2">- <Skeleton className="h-4 w-full" />- <Skeleton className="h-4 w-full" />- <Skeleton className="h-4 w-3/4" />- </div>- ) : metrics ? (- <div className="space-y-1.5">- <PercentileBadge value={metrics.pagerank_percentile} label="PageRank" />- <PercentileBadge value={metrics.betweenness_percentile} label="Betweenness" />- <div className="flex items-center justify-between gap-2">- <span className="text-[11px] text-[var(--color-text-tertiary)]">Degree</span>- <span className="text-[11px] font-mono text-[var(--color-text-secondary)]">- {metrics.in_degree} in · {metrics.out_degree} out- </span>- </div>- {metrics.community_label && (- <div className="flex items-center justify-between gap-2">- <span className="text-[11px] text-[var(--color-text-tertiary)]">Community</span>- <Badge variant="outline" className="text-[10px] h-5">- {metrics.community_label}- </Badge>- </div>- )}- {metrics.entry_point_score != null && metrics.entry_point_score > 0 && (- <div className="flex items-center justify-between gap-2">- <span className="text-[11px] text-[var(--color-text-tertiary)]">Entry Point</span>- <div className="flex items-center gap-1.5">- <div className="w-12 h-1.5 rounded-full bg-[var(--color-bg-elevated)] overflow-hidden">- <div- className="h-full rounded-full bg-[var(--color-accent)]"- style={{ width: `${Math.round(metrics.entry_point_score * 100)}%` }}- />- </div>- <span className="text-[10px] font-mono text-[var(--color-text-secondary)]">- {(metrics.entry_point_score * 100).toFixed(0)}%- </span>- </div>- </div>- )}- </div>- ) : (- <p className="text-[11px] text-[var(--color-text-tertiary)] italic">- Not indexed in graph- </p>- )}- </div>-- <Separator />-- <div>- {callsLoading ? (- <div className="space-y-2">- <Skeleton className="h-4 w-24" />- <Skeleton className="h-8 w-full" />- <Skeleton className="h-8 w-full" />- </div>- ) : callData ? (- <div className="space-y-3">- <CallerCalleeList items={callData.callers} label="Called by" />- <CallerCalleeList items={callData.callees} label="Calls" />- </div>- ) : null}- </div>-- {hasHeritage && heritageData && (- <>- <Separator />- <div>- <p className="text-[11px] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-1.5">- Heritage- </p>- {heritageData.callers.length > 0 && (- <div className="mb-2">- <p className="text-[10px] text-[var(--color-text-tertiary)] mb-1">Extended/Implemented by:</p>- {heritageData.callers.map((c) => (- <p key={c.symbol_id} className="text-[11px] font-mono text-[var(--color-text-primary)] truncate pl-2">- {c.name}- <span className="text-[var(--color-text-tertiary)] ml-1">({c.edge_type})</span>- </p>- ))}- </div>- )}- {heritageData.callees.length > 0 && (- <div>- <p className="text-[10px] text-[var(--color-text-tertiary)] mb-1">Extends/Implements:</p>- {heritageData.callees.map((c) => (- <p key={c.symbol_id} className="text-[11px] font-mono text-[var(--color-text-primary)] truncate pl-2">- {c.name}- <span className="text-[var(--color-text-tertiary)] ml-1">({c.edge_type})</span>- </p>- ))}- </div>- )}- </div>- </>- )}- </div>- </ScrollArea>- );-}diff --git a/packages/ui/src/symbols/symbol-index-header.tsx b/packages/ui/src/symbols/symbol-index-header.tsxnew file mode 100644index 000000000..c6275648c--- /dev/null+++ b/packages/ui/src/symbols/symbol-index-header.tsx@@ -0,0 +1,22 @@+import { Code2 } from "lucide-react";++/**+ * The Symbol Index page header. Lifted out of the web architecture route so+ * the title + descriptive copy live with the symbol surface and propagate on+ * a package bump (the index header previously couldn't drift-free track the+ * drawer surface it sits above).+ */+export function SymbolIndexHeader() {+ return (+ <div>+ <h1 className="mb-1 flex items-center gap-2 text-xl font-semibold text-[var(--color-text-primary)]">+ <Code2 className="h-5 w-5 text-[var(--color-accent-primary)]" />+ Symbol Index+ </h1>+ <p className="text-sm text-[var(--color-text-secondary)]">+ Searchable index of all functions, classes, and exports — sorted by+ importance, with hotspot, entry-point, and complexity signals inline.+ </p>+ </div>+ );+}diff --git a/packages/ui/src/symbols/symbol-page.tsx b/packages/ui/src/symbols/symbol-page.tsxindex 54dbedd81..1c192fb13 100644--- a/packages/ui/src/symbols/symbol-page.tsx+++ b/packages/ui/src/symbols/symbol-page.tsx@@ -1,259 +1,173 @@-import { ArrowDownLeft, ArrowUpRight, Flame } from "lucide-react";+import { Flame } from "lucide-react";import { Badge } from "../ui/badge";-import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";-import { scoreBadgeClass } from "../health/tokens";import { fileEntityPath, symbolEntityPath } from "../shared/entity/routes";-import { truncatePath } from "../lib/format";-import type { SymbolCallEntry, SymbolDetailResponse } from "@repowise-dev/types/symbols";+import { EntityHeader } from "../shared/entity";+import type { BreadcrumbSegment } from "../shared/breadcrumb";+import type {+ SymbolDetailData,+ SymbolDetailResponse,+} from "@repowise-dev/types/symbols";+import { SymbolDetailBody } from "./symbol-detail-body";export interface SymbolPageProps {data: SymbolDetailResponse;repoId: string;linkPrefix?: string;+ breadcrumb?: BreadcrumbSegment[];+ LinkComponent?: React.ElementType<{+ href: string;+ className?: string;+ children: React.ReactNode;+ }>;+ onOpenBlastRadius?: () => void;}-function ageDays(medianAuthorTime: number | null | undefined): number | null {- if (!medianAuthorTime) return null;- return Math.max(0, Math.round((Date.now() / 1000 - medianAuthorTime) / 86400));-}--function CallList({- title,- icon,- entries,- symbolHref,-}: {- title: string;- icon: React.ReactNode;- entries: SymbolCallEntry[];- symbolHref: (id: string) => string;-}) {- return (- <Card>- <CardHeader className="pb-2">- <CardTitle className="text-sm font-medium flex items-center gap-2">- {icon}- {title}- <span className="text-[10px] font-normal text-[var(--color-text-tertiary)] tabular-nums">- {entries.length}- </span>- </CardTitle>- </CardHeader>- <CardContent>- {entries.length === 0 ? (- <p className="text-xs text-[var(--color-text-tertiary)]">None in the indexed graph.</p>- ) : (- <ul className="space-y-1">- {entries.map((e) => (- <li key={`${e.symbol_id}-${e.edge_type}`}>- <a- href={symbolHref(e.symbol_id)}- className="flex items-center gap-2 -mx-2 px-2 py-0.5 rounded hover:bg-[var(--color-bg-elevated)] transition-colors"- >- <span className="text-[11px] font-mono text-[var(--color-text-primary)] truncate">- {e.name}- </span>- <span className="text-[10px] text-[var(--color-text-tertiary)] truncate flex-1 min-w-0">- {truncatePath(e.file, 36)}- </span>- <span className="text-[10px] text-[var(--color-text-tertiary)] shrink-0">- {e.edge_type}- </span>- </a>- </li>- ))}- </ul>- )}- </CardContent>- </Card>- );+/**+ * Pure mapping of the route's `SymbolDetailResponse` onto the unified+ * `SymbolDetailData`. The drawer surface normalizes its `CodeSymbol` + graph+ * APIs into the same shape (in its web wrapper), so both render one body.+ *+ * The route populates every field its endpoint actually returns — symbol,+ * graph (callers/callees + degrees), function-blame, governing decisions, and+ * file_context. It deliberately leaves file-level git intelligence (git,+ * co_changes, dead_code) and the graph-percentile / entry-point / heritage+ * feeds undefined: `SymbolDetailResponse` does not carry them, so the body's+ * presence-guards hide those blocks rather than the mapping fabricating data.+ * Governing decisions are passed through and rendered inside `SymbolDetailBody`+ * (not the header) so they appear exactly once on both surfaces.+ */+export function normalizeSymbolDetailResponse(+ data: SymbolDetailResponse,+): SymbolDetailData {+ const s = data.symbol;+ return {+ identity: {+ name: s.name,+ qualified_name: s.qualified_name,+ kind: s.kind,+ visibility: s.visibility,+ language: s.language,+ is_async: s.is_async,+ file_path: s.file_path,+ start_line: s.start_line,+ parent_name: s.parent_name,+ file_is_hotspot: s.file_is_hotspot ?? null,+ },+ signature: s.signature,+ docstring: s.docstring,+ importance_score: s.importance_score ?? null,+ complexity_estimate: s.complexity_estimate,+ blame_mod_count: s.blame_mod_count ?? null,+ blame_recent_mod_count: s.blame_recent_mod_count ?? null,+ blame_median_author_time: s.blame_median_author_time ?? null,+ blame_owner_name: s.blame_owner_name ?? null,+ blame_owner_line_pct: s.blame_owner_line_pct ?? null,+ graph: {+ in_degree: data.graph.in_degree,+ out_degree: data.graph.out_degree,+ callers: data.graph.callers.map((c) => ({+ symbol_id: c.symbol_id,+ name: c.name,+ file: c.file,+ edge_type: c.edge_type,+ confidence: c.confidence,+ })),+ callees: data.graph.callees.map((c) => ({+ symbol_id: c.symbol_id,+ name: c.name,+ file: c.file,+ edge_type: c.edge_type,+ confidence: c.confidence,+ })),+ },+ governing_decisions: data.governing_decisions,+ file_context: {+ health_score: data.file_context.health_score,+ language: data.file_context.language,+ },+ };}/**- * The canonical symbol page: signature + docstring, function blame (churn,- * age, owner), callers/callees linking to sibling symbol pages, governing- * decisions, and the parent-file context. Purely presentational.+ * The canonical routed symbol page: a standardized entity header (eyebrow,+ * breadcrumb, identity, one-line summary, primary signal) over the shared+ * `SymbolDetailBody`.*/-export function SymbolPage({ data, repoId, linkPrefix }: SymbolPageProps) {+export function SymbolPage({+ data,+ repoId,+ linkPrefix,+ breadcrumb,+ LinkComponent,+ onOpenBlastRadius,+}: SymbolPageProps) {const prefix = linkPrefix ?? `/repos/${repoId}`;const s = data.symbol;- const symbolHref = (id: string) => symbolEntityPath(prefix, id);- const fileHref = fileEntityPath(prefix, data.file_context.file_path);- const age = ageDays(s.blame_median_author_time);+ const normalized = normalizeSymbolDetailResponse(data);return (<div className="space-y-4">- {/* ── Header ── */}- <div className="space-y-2">- <div className="flex flex-wrap items-baseline gap-x-2 gap-y-1">- <h1 className="font-mono text-lg text-[var(--color-text-primary)] break-all">+ <EntityHeader+ eyebrow="SYMBOL"+ breadcrumb={breadcrumb ?? []}+ identity={+ <span className="font-mono break-all" title={s.qualified_name || s.name}>{s.name}- </h1>- <Badge variant="outline" className="text-[10px] h-5">- {s.kind}- </Badge>- {s.is_async && (- <Badge variant="outline" className="text-[10px] h-5">- async+ </span>+ }+ summary={symbolSummary(data)}+ metaBadges={+ <>+ <Badge variant="outline" className="h-5 text-[10px]">+ {s.kind}</Badge>- )}- <Badge variant="outline" className="text-[10px] h-5 capitalize">- {s.visibility}- </Badge>- {s.file_is_hotspot && (- <Badge variant="outline" className="text-[10px] h-5 text-[var(--color-error)] border-[var(--color-error)]/30">- <Flame className="h-2.5 w-2.5" /> hot file+ {s.is_async && (+ <Badge variant="outline" className="h-5 text-[10px]">+ async+ </Badge>+ )}+ <Badge variant="outline" className="h-5 text-[10px] capitalize">+ {s.visibility}</Badge>- )}- </div>- <a- href={fileHref}- className="inline-block text-xs font-mono text-[var(--color-text-secondary)] hover:text-[var(--color-accent-primary)] hover:underline break-all"- >- {s.file_path}:{s.start_line}- </a>- {data.governing_decisions.length > 0 && (- <div className="flex flex-wrap items-center gap-1.5">- <span className="text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">- Governed by- </span>- {data.governing_decisions.map((d) => (- <a- key={d.id}- href={`${prefix}/decisions/${d.id}`}- className="rounded border border-[var(--color-border-default)] px-1.5 py-0.5 text-[11px] text-[var(--color-text-secondary)] hover:text-[var(--color-accent-primary)] hover:border-[var(--color-accent-primary)] transition-colors"- >- {d.title}- </a>- ))}- </div>- )}- </div>-- {/* ── Signature + docstring ── */}- {s.signature && (- <pre className="overflow-x-auto rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-3 text-xs font-mono text-[var(--color-text-primary)]">- {s.signature}- </pre>- )}- {s.docstring && (- <p className="text-xs text-[var(--color-text-secondary)] whitespace-pre-wrap leading-relaxed">- {s.docstring}- </p>- )}-- {/* ── Signals strip ── */}- <div className="grid grid-cols-2 gap-3 sm:grid-cols-4 lg:grid-cols-6">- <Stat- label="Importance"- value={s.importance_score != null ? s.importance_score.toFixed(3) : "—"}- />- <Stat label="Complexity" value={String(s.complexity_estimate)} />- <Stat label="Callers" value={String(data.graph.in_degree)} />- <Stat label="Callees" value={String(data.graph.out_degree)} />- <Stat- label="Modifications"- value={s.blame_mod_count != null ? String(s.blame_mod_count) : "—"}- hint={- s.blame_recent_mod_count != null- ? `${s.blame_recent_mod_count} recent`- : undefined- }- />- <Stat label="Median age" value={age != null ? `${age}d` : "—"} />- </div>-- {(s.blame_owner_name || data.file_context.primary_owner) && (- <p className="text-xs text-[var(--color-text-secondary)]">- {s.blame_owner_name ? (- <>- Blame owner{" "}- <a- href={`${prefix}/owners/${encodeURIComponent(s.blame_owner_name)}`}- className="font-medium hover:text-[var(--color-accent-primary)] hover:underline"- >- {s.blame_owner_name}- </a>- {s.blame_owner_line_pct != null &&- ` (${Math.round(s.blame_owner_line_pct * 100)}% of lines)`}- </>- ) : (- <>- File owner{" "}- <a- href={`${prefix}/owners/${encodeURIComponent(data.file_context.primary_owner!)}`}- className="font-medium hover:text-[var(--color-accent-primary)] hover:underline"+ {s.file_is_hotspot && (+ <Badge+ variant="outline"+ className="h-5 text-[10px] text-[var(--color-error)] border-[var(--color-error)]/30">- {data.file_context.primary_owner}- </a>- </>- )}- </p>- )}-- {/* ── Callers / callees ── */}- <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">- <CallList- title="Callers"- icon={<ArrowDownLeft className="h-4 w-4 text-[var(--color-text-secondary)]" />}- entries={data.graph.callers}- symbolHref={symbolHref}- />- <CallList- title="Callees"- icon={<ArrowUpRight className="h-4 w-4 text-[var(--color-text-secondary)]" />}- entries={data.graph.callees}- symbolHref={symbolHref}- />- </div>-- {/* ── Parent file context ── */}- <Card>- <CardHeader className="pb-2">- <CardTitle className="text-sm font-medium">Parent file</CardTitle>- </CardHeader>- <CardContent className="flex flex-wrap items-center gap-3">- <a- href={fileHref}- className="text-xs font-mono text-[var(--color-accent-primary)] hover:underline break-all"- >- {data.file_context.file_path}- </a>- {data.file_context.health_score != null && (- <span- className={`inline-flex items-baseline rounded px-1.5 py-0.5 text-xs font-bold tabular-nums ${scoreBadgeClass(data.file_context.health_score)}`}+ <Flame className="h-2.5 w-2.5" /> hot file+ </Badge>+ )}+ <a+ href={fileEntityPath(prefix, s.file_path)}+ title={`${s.file_path}:${s.start_line}`}+ className="block max-w-full truncate font-mono text-xs text-[var(--color-text-secondary)] hover:text-[var(--color-accent-primary)] hover:underline">- {data.file_context.health_score.toFixed(1)}- <span className="ml-0.5 text-[9px] font-normal opacity-70">/10</span>- </span>- )}- {data.file_context.language && (- <Badge variant="outline" className="text-[10px] h-5 capitalize">- {data.file_context.language}- </Badge>- )}- </CardContent>- </Card>+ {s.file_path}:{s.start_line}+ </a>+ </>+ }+ {...(LinkComponent ? { LinkComponent } : {})}+ />++ <SymbolDetailBody+ data={normalized}+ symbolHref={(symId) => symbolEntityPath(prefix, symId)}+ fileHref={(p) => fileEntityPath(prefix, p)}+ {...(onOpenBlastRadius ? { onOpenBlastRadius } : {})}+ /></div>);}-function Stat({- label,- value,- hint,-}: {- label: string;- value: string;- hint?: string | undefined;-}) {- return (- <div className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-2.5">- <p className="text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)] mb-0.5">- {label}- </p>- <p className="text-sm font-semibold tabular-nums text-[var(--color-text-primary)]">{value}</p>- {hint && <p className="text-[10px] text-[var(--color-text-tertiary)]">{hint}</p>}- </div>- );+/** Synthesised "what is this" one-liner for a symbol — the missing summary. */+function symbolSummary(data: SymbolDetailResponse): string {+ const s = data.symbol;+ if (s.docstring) {+ const firstLine = s.docstring.split("\n").find((l) => l.trim()) ?? "";+ if (firstLine.trim()) return firstLine.trim();+ }+ const kind = s.kind || "symbol";+ const article = /^[aeiou]/i.test(kind) ? "An" : "A";+ const where = s.file_path.split("/").pop() ?? s.file_path;+ return `${article} undocumented ${kind} in ${where}.`;}diff --git a/packages/ui/src/symbols/symbol-table.tsx b/packages/ui/src/symbols/symbol-table.tsxindex 31f01abd2..71cf436af 100644--- a/packages/ui/src/symbols/symbol-table.tsx+++ b/packages/ui/src/symbols/symbol-table.tsx@@ -65,7 +65,7 @@ function ImportanceBar({ score }: { score: number | null | undefined }) {pct >= 70? "bg-[var(--color-accent-primary)]": pct >= 40- ? "bg-yellow-500"+ ? "bg-[var(--color-warning)]": "bg-[var(--color-text-tertiary)]";return (<div className="flex items-center gap-1.5">@@ -91,10 +91,10 @@ function SignalChips({ sym }: { sym: CodeSymbol }) {className={cn("inline-flex items-center gap-0.5 rounded px-1 py-0.5 text-[10px] font-medium",isPublic- ? "bg-emerald-500/15 text-emerald-400"+ ? "bg-[var(--color-success)]/15 text-[var(--color-success)]": isPrivate- ? "bg-slate-500/15 text-slate-400"- : "bg-amber-500/15 text-amber-400",+ ? "bg-[var(--color-bg-inset)] text-[var(--color-text-tertiary)]"+ : "bg-[var(--color-warning)]/15 text-[var(--color-warning)]",)}title={`Visibility: ${sym.visibility}`}>@@ -103,7 +103,7 @@ function SignalChips({ sym }: { sym: CodeSymbol }) {</span>{sym.is_entry_point && (<span- className="inline-flex items-center gap-0.5 rounded bg-blue-500/15 px-1 py-0.5 text-[10px] font-medium text-blue-400"+ className="inline-flex items-center gap-0.5 rounded bg-[var(--color-info)]/15 px-1 py-0.5 text-[10px] font-medium text-[var(--color-info)]"title="Lives in an entry-point file"><Rocket className="h-2.5 w-2.5" />@@ -112,7 +112,7 @@ function SignalChips({ sym }: { sym: CodeSymbol }) {)}{sym.file_is_hotspot && (<span- className="inline-flex items-center gap-0.5 rounded bg-red-500/15 px-1 py-0.5 text-[10px] font-medium text-red-400"+ className="inline-flex items-center gap-0.5 rounded bg-[var(--color-error)]/15 px-1 py-0.5 text-[10px] font-medium text-[var(--color-error)]"title="File is a churn hotspot"><Flame className="h-2.5 w-2.5" />@@ -121,7 +121,7 @@ function SignalChips({ sym }: { sym: CodeSymbol }) {)}{complex && (<span- className="inline-flex items-center gap-0.5 rounded bg-yellow-500/15 px-1 py-0.5 text-[10px] font-medium text-yellow-400"+ className="inline-flex items-center gap-0.5 rounded bg-[var(--color-caution)]/15 px-1 py-0.5 text-[10px] font-medium text-[var(--color-caution)]"title="High complexity"><Sparkles className="h-2.5 w-2.5" />@@ -343,9 +343,9 @@ export function SymbolTable({<spanclassName={cn(sym.complexity_estimate > 15- ? "text-red-500"+ ? "text-[var(--color-error)]": sym.complexity_estimate > 8- ? "text-yellow-500"+ ? "text-[var(--color-warning)]": "",)}>diff --git a/packages/ui/src/symbols/top-symbols-row.tsx b/packages/ui/src/symbols/top-symbols-row.tsxindex 82d47e932..72f1a1ea4 100644--- a/packages/ui/src/symbols/top-symbols-row.tsx+++ b/packages/ui/src/symbols/top-symbols-row.tsx@@ -48,7 +48,7 @@ export function TopSymbolsRow({if (loading && (!symbols || symbols.length === 0)) {return (<div className={cn("space-y-2", className)}>- <div className="text-[11px] font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">+ <div className="text-xs font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">Top symbols</div><div className="grid gap-1.5 sm:grid-cols-2 lg:grid-cols-3">@@ -68,7 +68,7 @@ export function TopSymbolsRow({className,)}>- <AlertCircle className="h-3.5 w-3.5 text-red-400" />+ <AlertCircle className="h-3.5 w-3.5 text-[var(--color-error)]" />Couldn't load symbols: {error}</div>);@@ -85,13 +85,13 @@ export function TopSymbolsRow({return (<div className={cn("space-y-2", className)}><div className="flex items-center justify-between">- <div className="text-[11px] font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">+ <div className="text-xs font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">Top symbols ({symbols.length})</div>{seeAllHref && (<ahref={seeAllHref}- className="inline-flex items-center gap-0.5 text-[11px] text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]"+ className="inline-flex items-center gap-0.5 text-xs text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]">See all<ChevronRight className="h-3 w-3" />diff --git a/packages/ui/src/ui/card.tsx b/packages/ui/src/ui/card.tsxindex 08c84f124..fe0b867e2 100644--- a/packages/ui/src/ui/card.tsx+++ b/packages/ui/src/ui/card.tsx@@ -6,7 +6,7 @@ const Card = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElemen<divref={ref}className={cn(- "rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] text-[var(--color-text-primary)] shadow-sm",+ "rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] text-[var(--color-text-primary)] shadow-[var(--card-shadow)]",className,)}{...props}diff --git a/packages/ui/src/ui/confirm-dialog.tsx b/packages/ui/src/ui/confirm-dialog.tsxindex bc2bd3de1..41afb6587 100644--- a/packages/ui/src/ui/confirm-dialog.tsx+++ b/packages/ui/src/ui/confirm-dialog.tsx@@ -56,7 +56,7 @@ export function ConfirmDialog({disabled={loading}className={destructive- ? "bg-red-600 text-white hover:bg-red-700"+ ? "bg-[var(--color-error)] text-white hover:bg-[var(--color-error)]/90": undefined}>diff --git a/packages/ui/src/ui/input.tsx b/packages/ui/src/ui/input.tsxindex d9c523b68..5770587d5 100644--- a/packages/ui/src/ui/input.tsx+++ b/packages/ui/src/ui/input.tsx@@ -7,7 +7,7 @@ const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<"input">>(<inputtype={type}className={cn(- "flex h-9 w-full rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-3 py-1 text-sm text-[var(--color-text-primary)] shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-[var(--color-text-tertiary)] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[var(--color-accent-primary)] disabled:cursor-not-allowed disabled:opacity-50",+ "flex h-9 w-full rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-3 py-1 text-sm text-[var(--color-text-primary)] transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-[var(--color-text-tertiary)] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[var(--color-accent-primary)] disabled:cursor-not-allowed disabled:opacity-50",className,)}ref={ref}diff --git a/packages/ui/src/ui/select.tsx b/packages/ui/src/ui/select.tsxindex 2543e3fbe..208bdd70e 100644--- a/packages/ui/src/ui/select.tsx+++ b/packages/ui/src/ui/select.tsx@@ -16,7 +16,7 @@ const SelectTrigger = React.forwardRef<<SelectPrimitive.Triggerref={ref}className={cn(- "flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-3 py-2 text-sm text-[var(--color-text-primary)] shadow-sm ring-offset-[var(--color-bg-root)] placeholder:text-[var(--color-text-tertiary)] focus:outline-none focus:ring-1 focus:ring-[var(--color-accent-primary)] disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",+ "flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-3 py-2 text-sm text-[var(--color-text-primary)] ring-offset-[var(--color-bg-root)] placeholder:text-[var(--color-text-tertiary)] focus:outline-none focus:ring-1 focus:ring-[var(--color-accent-primary)] disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",className,)}{...props}diff --git a/packages/ui/src/ui/tabs.tsx b/packages/ui/src/ui/tabs.tsxindex f67195985..d0fdc4a96 100644--- a/packages/ui/src/ui/tabs.tsx+++ b/packages/ui/src/ui/tabs.tsx@@ -13,7 +13,7 @@ const TabsList = React.forwardRef<<TabsPrimitive.Listref={ref}className={cn(- "inline-flex h-9 items-center justify-center rounded-lg bg-[var(--color-bg-elevated)] p-1 text-[var(--color-text-secondary)]",+ "inline-flex items-center gap-4 border-b border-[var(--color-border-default)] text-[var(--color-text-secondary)]",className,)}{...props}@@ -28,7 +28,7 @@ const TabsTrigger = React.forwardRef<<TabsPrimitive.Triggerref={ref}className={cn(- "inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-[var(--color-bg-root)] transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)] focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-[var(--color-bg-surface)] data-[state=active]:text-[var(--color-text-primary)] data-[state=active]:shadow-sm",+ "inline-flex items-center justify-center whitespace-nowrap border-b-2 border-transparent px-1 pb-2 -mb-px text-sm font-medium text-[var(--color-text-secondary)] ring-offset-[var(--color-bg-root)] transition-colors hover:text-[var(--color-text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)] focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:text-[var(--color-text-primary)] data-[state=active]:border-b-2 data-[state=active]:border-[var(--color-accent-primary)]",className,)}{...props}diff --git a/packages/ui/src/wiki/confidence-badge.tsx b/packages/ui/src/wiki/confidence-badge.tsxindex 45488bd06..1db52c981 100644--- a/packages/ui/src/wiki/confidence-badge.tsx+++ b/packages/ui/src/wiki/confidence-badge.tsx@@ -41,9 +41,9 @@ export function ConfidenceBadge({<spanclassName={cn("h-1.5 w-1.5 rounded-full",- status === "fresh" && "bg-green-500",- status === "stale" && "animate-pulse bg-yellow-500",- status === "outdated" && "bg-red-500",+ status === "fresh" && "bg-[var(--color-success)]",+ status === "stale" && "animate-pulse bg-[var(--color-warning)]",+ status === "outdated" && "bg-[var(--color-error)]",)}/>{label}diff --git a/packages/ui/src/wiki/git-history-panel.tsx b/packages/ui/src/wiki/git-history-panel.tsxindex e463a7d0b..2a9835f4e 100644--- a/packages/ui/src/wiki/git-history-panel.tsx+++ b/packages/ui/src/wiki/git-history-panel.tsx@@ -40,7 +40,7 @@ function AuthorAvatar({ name }: { name: string }) {return (<div- className={`flex h-5 w-5 shrink-0 items-center justify-center rounded-full text-[9px] font-semibold text-white ${color}`}+ className={`flex h-5 w-5 shrink-0 items-center justify-center rounded-full text-[10px] font-semibold text-white ${color}`}aria-label={name}title={name}>diff --git a/packages/ui/src/wiki/human-notes.tsx b/packages/ui/src/wiki/human-notes.tsxnew file mode 100644index 000000000..450a42835--- /dev/null+++ b/packages/ui/src/wiki/human-notes.tsx@@ -0,0 +1,115 @@+"use client";++import { useState } from "react";+import { Pencil, StickyNote, X } from "lucide-react";+import { Button } from "../ui/button";++/**+ * Human-curated note pinned above a page's generated content, editable in+ * place. Pure view/edit shell — the host supplies ``onSave`` (which persists+ * server-side; notes survive regeneration) and toast feedback.+ */+export function HumanNotes({+ initialNotes,+ onSave,+}: {+ initialNotes: string | null;+ /** Persist the note. Resolves to the stored value (or null when removed). */+ onSave: (value: string | null) => Promise<string | null>;+}) {+ const [notes, setNotes] = useState(initialNotes);+ const [editing, setEditing] = useState(false);+ const [draft, setDraft] = useState(initialNotes ?? "");+ const [saving, setSaving] = useState(false);++ async function save() {+ setSaving(true);+ try {+ const stored = await onSave(draft.trim() || null);+ setNotes(stored);+ setDraft(stored ?? "");+ setEditing(false);+ } finally {+ setSaving(false);+ }+ }++ if (!editing && !notes) {+ return (+ <button+ onClick={() => setEditing(true)}+ className="mb-5 inline-flex items-center gap-1.5 text-xs text-[var(--color-text-tertiary)] transition-colors hover:text-[var(--color-text-secondary)]"+ >+ <StickyNote className="h-3.5 w-3.5" />+ Add a note for your team — it survives regeneration+ </button>+ );+ }++ return (+ <div className="mb-5 rounded-lg border border-[var(--color-border-accent)] bg-[var(--color-accent-blue)]/5 px-4 py-3">+ <div className="mb-1.5 flex items-center gap-1.5">+ <StickyNote className="h-3.5 w-3.5 text-[var(--color-accent-blue)]" />+ <span className="text-xs font-medium uppercase tracking-wider text-[var(--color-accent-blue)]">+ Human Notes+ </span>+ {!editing && (+ <button+ onClick={() => setEditing(true)}+ aria-label="Edit note"+ className="ml-auto text-[var(--color-text-tertiary)] transition-colors hover:text-[var(--color-text-primary)]"+ >+ <Pencil className="h-3 w-3" />+ </button>+ )}+ {editing && (+ <button+ onClick={() => {+ setEditing(false);+ setDraft(notes ?? "");+ }}+ aria-label="Cancel editing"+ className="ml-auto text-[var(--color-text-tertiary)] transition-colors hover:text-[var(--color-text-primary)]"+ >+ <X className="h-3 w-3" />+ </button>+ )}+ </div>+ {editing ? (+ <div className="space-y-2">+ <textarea+ value={draft}+ onChange={(e) => setDraft(e.target.value)}+ rows={4}+ autoFocus+ aria-label="Human note"+ placeholder="Context the generated docs can't know — gotchas, history, plans…"+ className="w-full resize-y rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-3 py-2 text-sm text-[var(--color-text-primary)] outline-none placeholder:text-[var(--color-text-tertiary)]"+ />+ <div className="flex items-center gap-2">+ <Button size="sm" onClick={() => void save()} disabled={saving}>+ {saving ? "Saving…" : "Save note"}+ </Button>+ {notes && (+ <Button+ size="sm"+ variant="ghost"+ disabled={saving}+ onClick={() => {+ setDraft("");+ void save();+ }}+ >+ Remove note+ </Button>+ )}+ </div>+ </div>+ ) : (+ <p className="whitespace-pre-wrap text-sm leading-relaxed text-[var(--color-text-secondary)]">+ {notes}+ </p>+ )}+ </div>+ );+}diff --git a/packages/ui/src/wiki/index.ts b/packages/ui/src/wiki/index.tsindex fecd0ed6e..0b0712493 100644--- a/packages/ui/src/wiki/index.ts+++ b/packages/ui/src/wiki/index.ts@@ -2,6 +2,7 @@ export * from "./backlinks-panel";export * from "./code-block";export * from "./confidence-badge";export * from "./git-history-panel";+export * from "./human-notes";export * from "./mermaid-diagram";export * from "./regenerate-button";export * from "./security-panel";diff --git a/packages/ui/src/wiki/mermaid-diagram.tsx b/packages/ui/src/wiki/mermaid-diagram.tsxindex af8bd56a8..885a9d8cd 100644--- a/packages/ui/src/wiki/mermaid-diagram.tsx+++ b/packages/ui/src/wiki/mermaid-diagram.tsx@@ -4,8 +4,17 @@ import { useEffect, useRef, useState } from "react";import { Maximize2, X, ZoomIn, ZoomOut, RotateCcw } from "lucide-react";import { resolveToken, useThemeVersion } from "../shared/use-theme-tokens";+type MermaidSecurityLevel = "strict" | "loose";+interface MermaidDiagramProps {chart: string;+ /**+ * Mermaid's HTML/script sandbox level. Defaults to "strict" (the safe+ * choice) so untrusted, LLM-authored content — e.g. rendered inline in+ * chat — can't inject markup. The wiki renderer opts into "loose" for+ * richer HTML labels in trusted, pipeline-generated diagrams.+ */+ securityLevel?: MermaidSecurityLevel;}/**@@ -81,10 +90,12 @@ function mermaidThemeConfig() {let mermaidSignature = "";-async function ensureMermaid() {+async function ensureMermaid(securityLevel: MermaidSecurityLevel) {const { default: mermaid } = await import("mermaid");const config = mermaidThemeConfig();- const signature = JSON.stringify([config.themeVariables, config.themeCSS]);+ // mermaid.initialize is global/singleton, so the security level is folded+ // into the signature: a strict→loose (or palette) change reconfigures it.+ const signature = JSON.stringify([config.themeVariables, config.themeCSS, securityLevel]);// Re-initialize when the resolved palette changes (i.e. on theme switch);// mermaid.initialize is global, so a new signature reconfigures it in place.if (signature !== mermaidSignature) {@@ -108,14 +119,18 @@ async function ensureMermaid() {state: { useMaxWidth: false },class: { useMaxWidth: false },er: { useMaxWidth: false },- securityLevel: "loose",+ securityLevel,});mermaidSignature = signature;}return mermaid;}-function useMermaidRender(chart: string, target: HTMLDivElement | null) {+function useMermaidRender(+ chart: string,+ target: HTMLDivElement | null,+ securityLevel: MermaidSecurityLevel,+) {const [error, setError] = useState<string | null>(null);// Bumped after every successful render so consumers (fit-to-viewport in the// dialog) can react once the SVG actually exists.@@ -126,7 +141,7 @@ function useMermaidRender(chart: string, target: HTMLDivElement | null) {if (!target) return;let cancelled = false;setError(null);- ensureMermaid().then((mermaid) => {+ ensureMermaid(securityLevel).then((mermaid) => {const id = `mermaid-${Math.random().toString(36).slice(2)}`;mermaid.render(id, chart)@@ -149,7 +164,7 @@ function useMermaidRender(chart: string, target: HTMLDivElement | null) {return () => {cancelled = true;};- }, [chart, target, themeVersion]);+ }, [chart, target, themeVersion, securityLevel]);return { error, renderTick };}@@ -173,13 +188,21 @@ const GRID_BACKGROUND: React.CSSProperties = {backgroundSize: "24px 24px",};-function MaximizedDialog({ chart, onClose }: { chart: string; onClose: () => void }) {+function MaximizedDialog({+ chart,+ securityLevel,+ onClose,+}: {+ chart: string;+ securityLevel: MermaidSecurityLevel;+ onClose: () => void;+}) {const [container, setContainer] = useState<HTMLDivElement | null>(null);const [zoom, setZoom] = useState(1);const [pan, setPan] = useState({ x: 0, y: 0 });const viewportRef = useRef<HTMLDivElement | null>(null);const dragRef = useRef<{ startX: number; startY: number; panX: number; panY: number } | null>(null);- const { error, renderTick } = useMermaidRender(chart, container);+ const { error, renderTick } = useMermaidRender(chart, container, securityLevel);useEffect(() => {const onKey = (e: KeyboardEvent) => {@@ -327,10 +350,10 @@ function MaximizedDialog({ chart, onClose }: { chart: string; onClose: () => voi);}-export function MermaidDiagram({ chart }: MermaidDiagramProps) {+export function MermaidDiagram({ chart, securityLevel = "strict" }: MermaidDiagramProps) {const [container, setContainer] = useState<HTMLDivElement | null>(null);const [maximized, setMaximized] = useState(false);- const { error } = useMermaidRender(chart, container);+ const { error } = useMermaidRender(chart, container, securityLevel);if (error) {return (@@ -364,7 +387,13 @@ export function MermaidDiagram({ chart }: MermaidDiagramProps) {</div></figure>- {maximized && <MaximizedDialog chart={chart} onClose={() => setMaximized(false)} />}+ {maximized && (+ <MaximizedDialog+ chart={chart}+ securityLevel={securityLevel}+ onClose={() => setMaximized(false)}+ />+ )}</>);}diff --git a/packages/ui/src/wiki/version-history.tsx b/packages/ui/src/wiki/version-history.tsxindex 40ab197b3..493e2754a 100644--- a/packages/ui/src/wiki/version-history.tsx+++ b/packages/ui/src/wiki/version-history.tsx@@ -155,8 +155,8 @@ function DiffView({ oldContent, newContent }: { oldContent: string; newContent:key={i}className={cn("px-2 py-0.5 whitespace-pre-wrap break-all",- line.type === "added" && "bg-green-500/10 text-green-400",- line.type === "removed" && "bg-red-500/10 text-red-400",+ line.type === "added" && "bg-[var(--color-success)]/10 text-[var(--color-success)]",+ line.type === "removed" && "bg-[var(--color-error)]/10 text-[var(--color-error)]",line.type === "unchanged" && "text-[var(--color-text-tertiary)]",)}>diff --git a/packages/ui/src/wiki/wiki-markdown.tsx b/packages/ui/src/wiki/wiki-markdown.tsxindex c3bb16755..f8864bc63 100644--- a/packages/ui/src/wiki/wiki-markdown.tsx+++ b/packages/ui/src/wiki/wiki-markdown.tsx@@ -168,7 +168,7 @@ function buildComponents(const trimmed = code.replace(/\n$/, "");if (lang === "mermaid") {- return <MermaidDiagram chart={trimmed} />;+ return <MermaidDiagram chart={trimmed} securityLevel="loose" />;}return <ClientCodeBlock code={trimmed} language={lang} />;diff --git a/packages/ui/src/workspace/co-change-table.tsx b/packages/ui/src/workspace/co-change-table.tsxindex 0f0c8de4a..cfaeff9dd 100644--- a/packages/ui/src/workspace/co-change-table.tsx+++ b/packages/ui/src/workspace/co-change-table.tsx@@ -22,7 +22,7 @@ export function CoChangeTable({ coChanges, compact }: CoChangeTableProps) {cellClassName: "min-w-[160px] max-w-[280px]",render: (cc) => (<div className="flex flex-col gap-0.5">- <Badge variant="default" className="w-fit text-[11px]">{cc.source_repo}</Badge>+ <Badge variant="default" className="w-fit text-xs">{cc.source_repo}</Badge><span className="text-xs font-mono text-[var(--color-text-secondary)] truncate block" title={cc.source_file}>{cc.source_file}</span>@@ -36,7 +36,7 @@ export function CoChangeTable({ coChanges, compact }: CoChangeTableProps) {cellClassName: "min-w-[160px] max-w-[280px]",render: (cc) => (<div className="flex flex-col gap-0.5">- <Badge variant="default" className="w-fit text-[11px]">{cc.target_repo}</Badge>+ <Badge variant="default" className="w-fit text-xs">{cc.target_repo}</Badge><span className="text-xs font-mono text-[var(--color-text-secondary)] truncate block" title={cc.target_file}>{cc.target_file}</span>diff --git a/packages/ui/src/workspace/contract-type-badge.tsx b/packages/ui/src/workspace/contract-type-badge.tsxindex aafbac701..9246f5462 100644--- a/packages/ui/src/workspace/contract-type-badge.tsx+++ b/packages/ui/src/workspace/contract-type-badge.tsx@@ -13,7 +13,7 @@ export function ContractTypeBadge({ type }: { type: string }) {return (<spanclassName={cn(- "inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-medium",+ "inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium",style.bg,style.text,)}@@ -28,7 +28,7 @@ export function RoleBadge({ role }: { role: string }) {return (<spanclassName={cn(- "inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-medium",+ "inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium",isProvider? "bg-green-500/10 text-green-400": "bg-yellow-500/10 text-yellow-400",diff --git a/packages/ui/src/workspace/cross-repo-summary.tsx b/packages/ui/src/workspace/cross-repo-summary.tsxindex f525f6c15..f8b2797b7 100644--- a/packages/ui/src/workspace/cross-repo-summary.tsx+++ b/packages/ui/src/workspace/cross-repo-summary.tsx@@ -29,18 +29,18 @@ export function CrossRepoSummary({ crossRepo, contracts }: CrossRepoSummaryProps<StatCardlabel="Package Deps"value={crossRepo?.package_dep_count ?? 0}- icon={<Package className="h-4 w-4 text-purple-400" />}+ icon={<Package className="h-4 w-4 text-[var(--color-accent-secondary)]" />}/><StatCardlabel="Contract Links"value={contracts?.total_links ?? 0}- icon={<Link2 className="h-4 w-4 text-blue-400" />}+ icon={<Link2 className="h-4 w-4 text-[var(--color-info)]" />}/><StatCardlabel="Contracts Detected"value={contracts?.total_contracts ?? 0}{...(byTypeDescription ? { description: byTypeDescription } : {})}- icon={<Link2 className="h-4 w-4 text-orange-400" />}+ icon={<Link2 className="h-4 w-4 text-[var(--color-warning)]" />}/></div>);diff --git a/packages/ui/src/workspace/package-deps-table.tsx b/packages/ui/src/workspace/package-deps-table.tsxindex 0b8f81dd2..4c93152da 100644--- a/packages/ui/src/workspace/package-deps-table.tsx+++ b/packages/ui/src/workspace/package-deps-table.tsx@@ -16,7 +16,7 @@ const COLUMNS: ResponsiveColumn<WorkspacePackageDepEntry>[] = [header: "Source",priority: 1,render: (d) => (- <Badge variant="default" className="text-[11px]">+ <Badge variant="default" className="text-xs">{d.source_repo}</Badge>),@@ -26,7 +26,7 @@ const COLUMNS: ResponsiveColumn<WorkspacePackageDepEntry>[] = [header: "Target",priority: 1,render: (d) => (- <Badge variant="default" className="text-[11px]">+ <Badge variant="default" className="text-xs">{d.target_repo}</Badge>),diff --git a/packages/ui/src/workspace/repo-card-compact.tsx b/packages/ui/src/workspace/repo-card-compact.tsxindex 41953e52d..cca62a7af 100644--- a/packages/ui/src/workspace/repo-card-compact.tsx+++ b/packages/ui/src/workspace/repo-card-compact.tsx@@ -61,7 +61,7 @@ export function RepoCardCompact({onRemove();}}disabled={removing}- className="p-1.5 rounded-md text-[var(--color-text-tertiary)] hover:text-red-400 hover:bg-red-500/10 transition disabled:opacity-50"+ className="p-1.5 rounded-md text-[var(--color-text-tertiary)] hover:text-[var(--color-error)] hover:bg-[var(--color-error)]/10 transition disabled:opacity-50"><Trash2 className="h-3.5 w-3.5" /></button>diff --git a/packages/ui/src/workspace/repo-card.tsx b/packages/ui/src/workspace/repo-card.tsxindex 4df82f4ab..8594a0973 100644--- a/packages/ui/src/workspace/repo-card.tsx+++ b/packages/ui/src/workspace/repo-card.tsx@@ -102,7 +102,7 @@ export function RepoCard({</div>{docsSkipReason && (- <p className="mt-3 text-[11px] text-[var(--color-text-tertiary)] leading-snug">+ <p className="mt-3 text-xs text-[var(--color-text-tertiary)] leading-snug"><span className="font-medium">Docs skipped:</span> {docsSkipReason}</p>)}diff --git a/packages/ui/src/workspace/workspace-graph-node.tsx b/packages/ui/src/workspace/workspace-graph-node.tsxindex 8b18ba5a7..acb7374fd 100644--- a/packages/ui/src/workspace/workspace-graph-node.tsx+++ b/packages/ui/src/workspace/workspace-graph-node.tsx@@ -125,7 +125,7 @@ function WorkspaceGraphNodeInner({ data }: NodeProps) {</div><div- className="mt-2 text-[9px] font-medium px-1.5 py-0.5 rounded-full text-center"+ className="mt-2 text-[10px] font-medium px-1.5 py-0.5 rounded-full text-center"style={{background: `${langColor}30`,color: langColor,diff --git a/packages/ui/styles/globals.css b/packages/ui/styles/globals.cssindex dec74fb51..eb98bd811 100644--- a/packages/ui/styles/globals.css+++ b/packages/ui/styles/globals.css@@ -103,7 +103,7 @@--color-success: #1d8155;--color-warning: #9a6614;--color-error: #b23a2e;- --color-info: #58436c;+ --color-info: #3f6ea5; /* muted blue — distinct from the plum accent-secondary */--color-caution: #a8821f; /* between warning and success; medium severity / fair score band *//* Aliases — short names used in component class strings. Keep in sync. */@@ -189,6 +189,12 @@--color-viz-diff-changed: var(--color-error);--color-viz-diff-affected: var(--color-warning);+ /* Savings surfaces — two categorical hues distinguishing the distill ledger+ from MCP-tool answers in the Costs savings card. Plum + brand-orange so the+ split reads in both themes without a third brand color. */+ --color-savings-distill: var(--color-accent-fill);+ --color-savings-mcp: var(--color-accent-secondary);+/* ================================================================== *//* Signature gradients (theme-independent) *//* ================================================================== */@@ -214,6 +220,9 @@--shadow-xl: 0 16px 48px rgba(36, 27, 44, 0.14), 0 4px 12px rgba(36, 27, 44, 0.08);--shadow-button: 0 1px 2px rgba(214, 127, 16, 0.22);+ /* Card elevation dial: flat by default, flip to a shadow token to float. */+ --card-shadow: none;+/* ================================================================== *//* Non-color tokens (theme-independent) *//* ================================================================== */@@ -246,6 +255,10 @@--spacing-12: 3rem;--spacing-16: 4rem;+ /* Page-level rhythm: outer padding + gap between major sections. */+ --page-pad: var(--spacing-6);+ --section-gap: var(--spacing-6);+--radius-sm: 6px;--radius-md: 8px;--radius-lg: 10px;@@ -310,7 +323,7 @@--color-success: #34d399;--color-warning: #f2a03d;--color-error: #e06a5a;- --color-info: #a98fc4;+ --color-info: #7da7d9; /* muted blue — distinct from the plum accent-secondary */--color-caution: #d9b04a;--color-node-undocumented: #6f6678;diff --git a/packages/web/src/app/error.tsx b/packages/web/src/app/error.tsxindex db26f9315..e463291ca 100644--- a/packages/web/src/app/error.tsx+++ b/packages/web/src/app/error.tsx@@ -17,8 +17,8 @@ export default function GlobalError({return (<div className="flex h-full min-h-[400px] flex-col items-center justify-center gap-4 p-6 text-center">- <div className="flex h-12 w-12 items-center justify-center rounded-full bg-red-500/10">- <AlertTriangle className="h-6 w-6 text-red-500" />+ <div className="flex h-12 w-12 items-center justify-center rounded-full bg-[var(--color-error)]/10">+ <AlertTriangle className="h-6 w-6 text-[var(--color-error)]" /></div><div><h2 className="text-base font-semibold text-[var(--color-text-primary)]">diff --git a/packages/web/src/app/page.tsx b/packages/web/src/app/page.tsxindex 4e803ecf9..6fc63893e 100644--- a/packages/web/src/app/page.tsx+++ b/packages/web/src/app/page.tsx@@ -98,13 +98,13 @@ export default async function DashboardPage() {label="Fresh Pages"value={formatNumber(freshPages)}description="Confidence ≥ 80%"- icon={<CheckCircle2 className="h-4 w-4 text-green-500" />}+ icon={<CheckCircle2 className="h-4 w-4 text-[var(--color-success)]" />}/><StatCardlabel="Stale Pages"value={formatNumber(stalePages)}description="Need regeneration"- icon={<AlertCircle className="h-4 w-4 text-yellow-500" />}+ icon={<AlertCircle className="h-4 w-4 text-[var(--color-warning)]" />}/><StatCardlabel="Dead Code"@@ -280,10 +280,10 @@ function JobStatusIcon({ status }: { status: string }) {);}if (status === "completed") {- return <CheckCircle2 className="h-4 w-4 shrink-0 text-green-500" />;+ return <CheckCircle2 className="h-4 w-4 shrink-0 text-[var(--color-success)]" />;}if (status === "failed") {- return <AlertCircle className="h-4 w-4 shrink-0 text-red-500" />;+ return <AlertCircle className="h-4 w-4 shrink-0 text-[var(--color-error)]" />;}return <Clock className="h-4 w-4 shrink-0 text-[var(--color-text-tertiary)]" />;}diff --git a/packages/web/src/app/repos/[id]/architecture/page.tsx b/packages/web/src/app/repos/[id]/architecture/page.tsxindex 3b2166634..4ce04c757 100644--- a/packages/web/src/app/repos/[id]/architecture/page.tsx+++ b/packages/web/src/app/repos/[id]/architecture/page.tsx@@ -3,56 +3,63 @@/*** Architecture — `/repos/[id]/architecture`.*- * One destination for "how is this built", with five modes behind `?view=`:- * - map — the constellation Knowledge Graph (community super-graph)- * - layers — the curated layered architecture view (tour, personas)- * - explore — the full / module dependency graph with dead/hot overlays- * - symbols — the searchable symbol index- * - deps — the third-party dependency registry- * The legacy C4 diagram stays reachable behind `?view=c4` until the layered- * view reaches full parity.+ * The "how the code is wired" destination, with tabs behind `?view=`:+ * - map — the constellation, surfaced as the "Communities" tab+ * - explore — the full / module dependency graph with dead/hot overlays+ * - symbols — the searchable symbol index+ * - deps — the third-party dependency registry*- * Map and Explore share one canvas component (GraphFlow) and therefore one- * search, one path finder, one legend and one inspector; switching scope- * inside the canvas keeps `?view=` in sync without remounting.+ * The curated layered view ("Knowledge Graph") is a separate top-level route+ * (`/knowledge-graph`); the legacy `?view=layers` alias redirects there.+ *+ * Communities and Explore are the SAME `GraphFlow` canvas differing only by+ * scope: Communities locks it to the constellation (radial) scope, Explore+ * mounts it at full/module scope. Switching scope inside Explore keeps `?view=`+ * in sync without remounting.*/-import { use, useCallback } from "react";+import { use, useCallback, useEffect } from "react";+import { useRouter } from "next/navigation";import { useQueryState, parseAsStringLiteral } from "nuqs";import { Code2 } from "lucide-react";-import { cn } from "@/lib/utils/cn";+import { ViewTabs } from "@repowise-dev/ui/shared/view-tabs";import { GraphView } from "@/components/architecture/graph-view";-import { C4View } from "@/components/architecture/c4-view";import { DependenciesView } from "@/components/architecture/dependencies-view";import { SymbolTableWrapper as SymbolTable } from "@/components/symbols/symbol-table-wrapper";+import { SymbolIndexHeader } from "@repowise-dev/ui/symbols";+import { COUPLING_DISCLAIMER } from "@repowise-dev/ui/coupling";+import { CouplingTab } from "@/components/coupling/coupling-tab";-// "graph" and "c4" are accepted as legacy aliases from pre-merge URLs and-// normalized below; only the five canonical views render switcher buttons.-const VIEWS = ["map", "layers", "explore", "symbols", "deps", "graph", "c4"] as const;-type ArchView = (typeof VIEWS)[number];--const CANONICAL_VIEWS: ArchView[] = ["map", "layers", "explore", "symbols", "deps"];+// The curated layered view now lives under the dedicated Knowledge Graph route.+const KNOWLEDGE_GRAPH_VIEWS = new Set(["layers"]);-const VIEW_LABELS: Record<ArchView, string> = {- map: "Map",- layers: "Layers",- explore: "Explore",- symbols: "Symbols",- deps: "Dependencies",- graph: "Map",- c4: "C4 (legacy)",-};+// Accepted `?view=` values. "graph" and "layers" are legacy aliases that are+// normalized / redirected below; only the canonical tabs render a tab.+const VIEWS = [+ "map",+ "explore",+ "deps",+ "symbols",+ "coupling",+ "graph",+ "layers",+] as const;+type ArchView = (typeof VIEWS)[number];-const VIEW_HINTS: Record<string, string> = {- map: "Constellation of detected communities",- layers: "Curated layered view with a guided tour",- explore: "Full dependency graph with dead/hot overlays",- symbols: "Every function, class and export",- deps: "Declared third-party dependencies",-};+// IA-as-data. Communities first (today's `map`), then the wiring surfaces.+// Coupling is added here in a later phase — the structure is kept easy to+// extend (append a `{ id: "coupling", ... }` row + a panel branch).+const CANONICAL_VIEWS: { id: Extract<ArchView, "map" | "explore" | "deps" | "symbols" | "coupling">; label: string; hint: string }[] = [+ { id: "map", label: "Communities", hint: "Constellation of detected communities" },+ { id: "explore", label: "Explore", hint: "Full dependency graph with dead/hot overlays" },+ { id: "coupling", label: "Coupling", hint: "Files that tend to change together" },+ { id: "deps", label: "Dependencies", hint: "Declared third-party dependencies" },+ { id: "symbols", label: "Symbols", hint: "Every function, class and export" },+];// Legacy ?view=graph deep links carried the graph scope in ?viewMode=. Scopes-// that render file-level graphs map to Explore; the constellation maps to Map.+// that render file-level graphs map to Explore; the constellation maps to the+// Communities tab.const EXPLORE_VIEW_MODES = new Set(["module", "full", "dead", "hotfiles", "unified"]);export default function ArchitecturePage({@@ -61,21 +68,27 @@ export default function ArchitecturePage({params: Promise<{ id: string }>;}) {const { id: repoId } = use(params);+ const router = useRouter();const [rawView, setView] = useQueryState("view",parseAsStringLiteral(VIEWS).withDefault("map"),);const [viewModeParam] = useQueryState("viewMode");- const [modeParam] = useQueryState("mode");- // Normalize legacy aliases without a URL rewrite (cheap, shareable links- // keep working): graph → map/explore by scope; c4 + mode=architecture was- // the curated view (now Layers); c4 + mode=c4 stays the frozen legacy mode.+ // The curated layers view now lives at /knowledge-graph. `?view=layers`+ // redirects there so shared links keep working.+ const redirectsToKnowledgeGraph = KNOWLEDGE_GRAPH_VIEWS.has(rawView);+ useEffect(() => {+ if (redirectsToKnowledgeGraph) {+ router.replace(`/repos/${repoId}/knowledge-graph`);+ }+ }, [redirectsToKnowledgeGraph, repoId, router]);++ // Normalize the remaining legacy alias without a URL rewrite: ?view=graph →+ // map/explore by scope.let view: ArchView = rawView;if (rawView === "graph") {view = EXPLORE_VIEW_MODES.has(viewModeParam ?? "") ? "explore" : "map";- } else if (rawView === "c4" && modeParam !== "c4") {- view = "layers";}const handleScopeViewChange = useCallback(@@ -85,58 +98,61 @@ export default function ArchitecturePage({[setView],);- const isGraphCanvas = view === "map" || view === "explore";+ // The active canonical tab. Map/Explore are the only graph-canvas tabs;+ // everything else resolves to its own panel.+ const activeTab: (typeof CANONICAL_VIEWS)[number]["id"] =+ view === "explore" || view === "deps" || view === "symbols" || view === "coupling"+ ? view+ : "map";++ if (redirectsToKnowledgeGraph) {+ return null;+ }return (<div className="flex h-full flex-col">- {/* View switcher */}- <div className="flex shrink-0 items-center gap-1 border-b border-[var(--color-border-default)] px-4 py-2 sm:px-6 overflow-x-auto">- {CANONICAL_VIEWS.map((v) => (- <button- key={v}- onClick={() => void setView(v)}- title={VIEW_HINTS[v]}- className={cn(- "rounded-md px-3 py-1.5 text-xs font-medium whitespace-nowrap transition-colors",- view === v- ? "bg-[var(--color-accent-muted)] text-[var(--color-accent-primary)]"- : "text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]",- )}- >- {VIEW_LABELS[v]}- </button>- ))}- {view === "c4" && (- <span className="rounded-md bg-[var(--color-accent-muted)] px-3 py-1.5 text-xs font-medium text-[var(--color-accent-primary)] whitespace-nowrap">- C4 (legacy)- </span>- )}+ <div className="shrink-0 px-4 pt-3 sm:px-6">+ <ViewTabs+ tabs={CANONICAL_VIEWS.map((v) => ({ id: v.id, label: v.label }))}+ value={activeTab}+ onValueChange={(id) => void setView(id as ArchView)}+ /></div><div className="min-h-0 flex-1 overflow-auto">- {isGraphCanvas && (+ {activeTab === "map" && (<GraphViewrepoId={repoId}- scope={view as "map" | "explore"}+ scope="map"onScopeViewChange={handleScopeViewChange}/>)}- {(view === "layers" || view === "c4") && (- <C4View repoId={repoId} legacy={view === "c4"} />+ {activeTab === "explore" && (+ <GraphView+ repoId={repoId}+ scope="explore"+ onScopeViewChange={handleScopeViewChange}+ />)}- {view === "deps" && <DependenciesView repoId={repoId} />}- {view === "symbols" && (+ {activeTab === "deps" && <DependenciesView repoId={repoId} />}+ {activeTab === "symbols" && (<div className="max-w-[1600px] space-y-6 p-4 sm:p-6">- <div>+ <SymbolIndexHeader />+ <SymbolTable repoId={repoId} />+ </div>+ )}+ {activeTab === "coupling" && (+ <div className="mx-auto max-w-[1100px] p-4 sm:p-6">+ <div className="mb-2"><h1 className="mb-1 flex items-center gap-2 text-xl font-semibold text-[var(--color-text-primary)]"><Code2 className="h-5 w-5 text-[var(--color-accent-primary)]" />- Symbol Index+ Change coupling</h1><p className="text-sm text-[var(--color-text-secondary)]">- Searchable index of all functions, classes, and exports.+ {COUPLING_DISCLAIMER}</p></div>- <SymbolTable repoId={repoId} />+ <CouplingTab repoId={repoId} /></div>)}</div>diff --git a/packages/web/src/app/repos/[id]/c4/page.tsx b/packages/web/src/app/repos/[id]/c4/page.tsxindex aa5e9da28..53a8138b1 100644--- a/packages/web/src/app/repos/[id]/c4/page.tsx+++ b/packages/web/src/app/repos/[id]/c4/page.tsx@@ -1,22 +1,11 @@import { redirect } from "next/navigation";-/** Legacy route — the knowledge graph now lives under Architecture. */+/** Legacy route — the C4 diagram is superseded by the curated Knowledge Graph. */export default async function LegacyC4Redirect({params,- searchParams,}: {params: Promise<{ id: string }>;- searchParams: Promise<Record<string, string | string[] | undefined>>;}) {const { id } = await params;- const sp = await searchParams;- const qs = new URLSearchParams({ view: "c4" });- for (const [key, value] of Object.entries(sp)) {- if (typeof value !== "string") continue;- // The c4 view's own "view" param (overview/groups/detail) was renamed to- // "c4view" when the page moved under Architecture.- if (key === "view") qs.set("c4view", value);- else qs.set(key, value);- }- redirect(`/repos/${id}/architecture?${qs.toString()}`);+ redirect(`/repos/${id}/knowledge-graph`);}diff --git a/packages/web/src/app/repos/[id]/code-health/page.tsx b/packages/web/src/app/repos/[id]/code-health/page.tsxindex 14f3b53a6..f3f83cbab 100644--- a/packages/web/src/app/repos/[id]/code-health/page.tsx+++ b/packages/web/src/app/repos/[id]/code-health/page.tsx@@ -3,56 +3,73 @@/*** Code Health — `/repos/[id]/code-health`.*- * One "what do I fix next" section: Triage (the ranked fix-next queue),- * Hotspots & Churn (the only place called "hotspots"), Modules, Coverage,- * Dead code, Impact, Security, and Trend — one chrome, one tab row,- * URL-synced via `?tab=`.+ * One living map + a thin drill-down. The galaxy map is the page spine; a lens+ * switcher recolors the same field (health / coverage / churn — the three lenses+ * backed by per-file map data) so the cross-tab redundancy collapses. Dead-code+ * and security have no per-file map signal and stay on their own tabs. Surviving+ * tabs — Triage+ * (the map spine), Hotspots, Coverage, Dead code, Impact, Security — are+ * URL-synced via `?tab=`; the active lens via `?lens=`. Modules folded into the+ * map's hub layer and Trend into a compact section.*/import { useParams, useRouter, useSearchParams } from "next/navigation";-import { useCallback } from "react";+import { useCallback, useMemo } from "react";import useSWR from "swr";import { HeartPulse, RotateCw } from "lucide-react";-import {- Tabs,- TabsContent,- ScrollableTabsList,- TabsTrigger,-} from "@repowise-dev/ui/ui/tabs";+import { PageShell } from "@repowise-dev/ui/shared/page-shell";+import { ViewTabs } from "@repowise-dev/ui/shared/view-tabs";+import { CollapsibleSection } from "@repowise-dev/ui/shared/collapsible-section";import { Button } from "@repowise-dev/ui/ui/button";+import type { CodeHealthOverlay } from "@repowise-dev/ui/health";import { TriageTab } from "@/components/code-health/triage-tab";import { CoverageTab } from "@/components/code-health/coverage-tab";-import { TrendTab } from "@/components/code-health/trend-tab";+import { TrendSection } from "@/components/code-health/trend-tab";import { HotspotsTab } from "@/components/risk/hotspots-tab";import { DeadCodeTab } from "@/components/risk/dead-code-tab";import { ImpactTab } from "@/components/risk/impact-tab";-import { ModulesTab } from "@/components/risk/modules-tab";import { SecurityTab } from "@/components/risk/security-tab";-import { RiskSummaryStrip } from "@/components/risk/risk-summary-strip";import {+ getChurnComplexity,getHealthOverview,+ getHealthTrend,+ listHealthFiles,+ type ChurnComplexityResponse,type HealthOverviewResponse,+ type HealthTrendResponse,+ type HealthFilesResponse,} from "@/lib/api/code-health";-const TABS = [- "triage",- "hotspots",- "modules",- "coverage",- "dead-code",- "impact",- "security",- "trend",-] as const;+const TABS = ["triage", "hotspots", "coverage", "dead-code", "impact", "security"] as const;type TabId = (typeof TABS)[number];-/** Legacy tab ids from the old /risk page → their new home. */+const TAB_LABELS: Record<TabId, string> = {+ triage: "Triage",+ hotspots: "Hotspots",+ coverage: "Coverage",+ "dead-code": "Dead code",+ impact: "Impact",+ security: "Security",+};++/**+ * Legacy tab ids → their new home. `heatmap` was the old churn tab; `modules`+ * folded into the map's hub layer; `trend` folded into the compact section that+ * lives under Triage.+ */const TAB_ALIASES: Record<string, TabId> = {heatmap: "hotspots",+ modules: "triage",+ trend: "triage",};-/** Tabs that came from the Risk page and share the summary strip. */-const STRIP_TABS = new Set<TabId>(["hotspots", "modules", "dead-code", "impact", "security"]);+/**+ * Lenses selectable on the map. Only the three backed by per-file map data are+ * offered; an unrecognized `?lens=` (including the retired `dead-code`/+ * `security` values, which now live solely on their own tabs) falls back to+ * `health` so a stale URL never renders an all-grey map.+ */+const OVERLAYS: CodeHealthOverlay[] = ["health", "coverage", "churn"];export default function CodeHealthPage() {const params = useParams<{ id: string }>();@@ -66,6 +83,11 @@ export default function CodeHealthPage() {aliased ??(rawTab && (TABS as readonly string[]).includes(rawTab) ? (rawTab as TabId) : "triage");+ const rawLens = searchParams.get("lens");+ const overlay: CodeHealthOverlay = (OVERLAYS as readonly string[]).includes(rawLens ?? "")+ ? (rawLens as CodeHealthOverlay)+ : "health";+// Shares the SWR key with TriageTab — the meta line costs no extra request.const { data: overview, mutate } = useSWR<HealthOverviewResponse>(`code-health-overview:${repoId}`,@@ -74,6 +96,53 @@ export default function CodeHealthPage() {);const meta = overview?.meta;+ // Trend fetched ONCE here, fed to both the KPI sparklines (Triage) and the+ // folded Trend section — no second fetch, no second SWR key.+ const { data: trend, isLoading: trendLoading, error: trendError } =+ useSWR<HealthTrendResponse>(+ `code-health-trend:${repoId}`,+ () => getHealthTrend(repoId, 20),+ { revalidateOnFocus: false },+ );++ // Every file (NLOC-first) for the circle-packing map — one big pull, shared+ // across overlays so switching the lens never refetches.+ const { data: mapFiles } = useSWR<HealthFilesResponse>(+ `code-health-map-files:${repoId}`,+ () => listHealthFiles(repoId, { limit: 2000, sort: "nloc", order: "desc" }),+ { revalidateOnFocus: false },+ );++ // Churn percentiles for the churn lens. Shares the SWR key the Hotspots tab+ // already uses (`health-churn-complexity:`), so the two surfaces dedupe onto+ // one request rather than double-fetching.+ const { data: churn, isLoading: churnLoading } = useSWR<ChurnComplexityResponse>(+ `health-churn-complexity:${repoId}`,+ () => getChurnComplexity(repoId),+ { revalidateOnFocus: false },+ );++ // The churn lens recolors by `churn_percentile`, which arrives from a separate+ // request. Until it resolves every node falls back to NEUTRAL_FILL — visually+ // identical to "no data". Flag the in-flight state so the map shows a loading+ // legend instead of a misleading empty one.+ const overlayLoading = overlay === "churn" && churnLoading && !churn;++ // Merge churn_percentile onto each map file (join by path) so the churn lens+ // colors real data. Re-runs only when either source changes.+ const mapFilesWithChurn: HealthFilesResponse | undefined = useMemo(() => {+ if (!mapFiles) return undefined;+ if (!churn) return mapFiles;+ const byPath = new Map(churn.points.map((p) => [p.file_path, p.churn_percentile]));+ return {+ ...mapFiles,+ files: mapFiles.files.map((file) => ({+ ...file,+ churn_percentile: byPath.get(file.file_path) ?? null,+ })),+ };+ }, [mapFiles, churn]);+const setTab = useCallback((next: string) => {const sp = new URLSearchParams(searchParams.toString());@@ -85,72 +154,65 @@ export default function CodeHealthPage() {[router, searchParams],);+ const setOverlay = useCallback(+ (next: CodeHealthOverlay) => {+ const sp = new URLSearchParams(searchParams.toString());+ if (next === "health") sp.delete("lens");+ else sp.set("lens", next);+ const qs = sp.toString();+ router.replace(qs ? `?${qs}` : "?", { scroll: false });+ },+ [router, searchParams],+ );+return (- <div className="p-4 sm:p-6 space-y-4 max-w-[1600px]">- <header className="flex flex-wrap items-start gap-3">- <div className="min-w-0 flex-1 space-y-1">- <h1 className="flex items-center gap-2 text-lg font-semibold text-[var(--color-text-primary)]">- <HeartPulse className="h-5 w-5 text-[var(--color-success)]" />- Code Health- </h1>- <p className="text-sm text-[var(--color-text-secondary)]">- Per-file health scores from complexity, duplication, coverage, churn,- and ownership biomarkers — ranked into a fix-next queue.- </p>- {meta ? (- <p className="text-xs text-[var(--color-text-tertiary)]">- {meta.last_indexed_at- ? `Indexed ${new Date(meta.last_indexed_at).toLocaleString()}`- : "Not indexed yet"}- {meta.head_commit ? ` · ${meta.head_commit.slice(0, 8)}` : ""}- {` · ${meta.snapshot_count} snapshot${meta.snapshot_count === 1 ? "" : "s"}`}- </p>- ) : null}- </div>+ <PageShell+ title="Code Health"+ icon={<HeartPulse className="h-5 w-5 text-[var(--color-success)]" />}+ description="Per-file health scores from complexity, duplication, coverage, churn, and ownership biomarkers — ranked into a fix-next queue."+ maxWidth="wide"+ actions={<Button size="sm" variant="outline" onClick={() => mutate()}><RotateCw className="h-3.5 w-3.5 mr-1.5" /> Refresh</Button>- </header>-- <Tabs value={activeTab} onValueChange={setTab} className="space-y-4">- <ScrollableTabsList>- <TabsTrigger value="triage">Triage</TabsTrigger>- <TabsTrigger value="hotspots">Hotspots & churn</TabsTrigger>- <TabsTrigger value="modules">Modules</TabsTrigger>- <TabsTrigger value="coverage">Coverage</TabsTrigger>- <TabsTrigger value="dead-code">Dead code</TabsTrigger>- <TabsTrigger value="impact">Impact</TabsTrigger>- <TabsTrigger value="security">Security</TabsTrigger>- <TabsTrigger value="trend">Trend</TabsTrigger>- </ScrollableTabsList>-- {STRIP_TABS.has(activeTab) && <RiskSummaryStrip repoId={repoId} />}-- <TabsContent value="triage" className="space-y-6">- <TriageTab repoId={repoId} />- </TabsContent>- <TabsContent value="hotspots" className="space-y-6">- <HotspotsTab repoId={repoId} />- </TabsContent>- <TabsContent value="modules" className="space-y-6">- <ModulesTab repoId={repoId} />- </TabsContent>- <TabsContent value="coverage" className="space-y-6">- <CoverageTab repoId={repoId} />- </TabsContent>- <TabsContent value="dead-code" className="space-y-6">- <DeadCodeTab repoId={repoId} />- </TabsContent>- <TabsContent value="impact" className="space-y-6">- <ImpactTab repoId={repoId} />- </TabsContent>- <TabsContent value="security" className="space-y-6">- <SecurityTab repoId={repoId} />- </TabsContent>- <TabsContent value="trend" className="space-y-6">- <TrendTab repoId={repoId} />- </TabsContent>- </Tabs>- </div>+ }+ >+ {meta ? (+ <p className="-mt-3 text-xs text-[var(--color-text-tertiary)]">+ {meta.last_indexed_at+ ? `Indexed ${new Date(meta.last_indexed_at).toLocaleString()}`+ : "Not indexed yet"}+ {meta.head_commit ? ` · ${meta.head_commit.slice(0, 8)}` : ""}+ {` · ${meta.snapshot_count} snapshot${meta.snapshot_count === 1 ? "" : "s"}`}+ </p>+ ) : null}++ <ViewTabs+ tabs={TABS.map((id) => ({ id, label: TAB_LABELS[id] }))}+ value={activeTab}+ onValueChange={setTab}+ >+ {activeTab === "triage" && (+ <div className="space-y-6">+ <TriageTab+ repoId={repoId}+ trend={trend}+ overlay={overlay}+ onOverlayChange={setOverlay}+ mapFiles={mapFilesWithChurn}+ overlayLoading={overlayLoading}+ />+ <CollapsibleSection title="Health trend" defaultOpen={false}>+ <TrendSection data={trend} isLoading={trendLoading} error={trendError} />+ </CollapsibleSection>+ </div>+ )}+ {activeTab === "hotspots" && <HotspotsTab repoId={repoId} />}+ {activeTab === "coverage" && <CoverageTab repoId={repoId} />}+ {activeTab === "dead-code" && <DeadCodeTab repoId={repoId} />}+ {activeTab === "impact" && <ImpactTab repoId={repoId} />}+ {activeTab === "security" && <SecurityTab repoId={repoId} />}+ </ViewTabs>+ </PageShell>);}diff --git a/packages/web/src/app/repos/[id]/commits/page.tsx b/packages/web/src/app/repos/[id]/commits/page.tsxindex 65ae5c218..d97a74829 100644--- a/packages/web/src/app/repos/[id]/commits/page.tsx+++ b/packages/web/src/app/repos/[id]/commits/page.tsx@@ -1,5 +1,6 @@import type { Metadata } from "next";import { GitCommitHorizontal } from "lucide-react";+import { PageShell } from "@repowise-dev/ui/shared/page-shell";import { CommitsExplorer } from "@/components/commits/commits-explorer";export const metadata: Metadata = { title: "Commits" };@@ -12,19 +13,13 @@ export default async function CommitsPage({const { id } = await params;return (- <div className="p-4 sm:p-6 space-y-6 max-w-[1600px]">- <div>- <h1 className="text-xl font-semibold text-[var(--color-text-primary)] mb-1 flex items-center gap-2">- <GitCommitHorizontal className="h-5 w-5 text-[var(--color-accent-primary)]" />- Commits- </h1>- <p className="text-sm text-[var(--color-text-secondary)]">- A review-priority queue — every indexed commit scored for change-risk and ranked- relative to this repo's own history. Open a commit for its per-feature breakdown.- </p>- </div>-+ <PageShell+ maxWidth="wide"+ icon={<GitCommitHorizontal className="h-5 w-5 text-[var(--color-accent-primary)]" />}+ title="Commits"+ description="A review-priority queue — every indexed commit scored for change-risk and ranked relative to this repo's own history. Open a commit for its per-feature breakdown."+ ><CommitsExplorer repoId={id} />- </div>+ </PageShell>);}diff --git a/packages/web/src/app/repos/[id]/costs/page.tsx b/packages/web/src/app/repos/[id]/costs/page.tsxindex f9c70a0ed..c5f09b574 100644--- a/packages/web/src/app/repos/[id]/costs/page.tsx+++ b/packages/web/src/app/repos/[id]/costs/page.tsx@@ -4,20 +4,15 @@ import { useState } from "react";import useSWR from "swr";import { useParams } from "next/navigation";import { DollarSign } from "lucide-react";-import {- BarChart,- Bar,- XAxis,- YAxis,- Tooltip,- ResponsiveContainer,-} from "recharts";import { StatCard } from "@repowise-dev/ui/shared/stat-card";+import { MetricCard } from "@repowise-dev/ui/shared/metric-card";+import { PageShell } from "@repowise-dev/ui/shared/page-shell";import { Card, CardContent, CardHeader, CardTitle } from "@repowise-dev/ui/ui/card";import { Skeleton } from "@repowise-dev/ui/ui/skeleton";import { Tabs, ScrollableTabsList, TabsTrigger, TabsContent } from "@repowise-dev/ui/ui/tabs";import {CostHeatmap,+ DailySpendChart,DistillSavingsCard,ProviderComparison,OperationBreakdown,@@ -62,17 +57,12 @@ export default function CostsPage() {);return (- <div className="p-4 sm:p-6 space-y-6 max-w-[1600px]">- <div>- <h1 className="text-xl font-semibold text-[var(--color-text-primary)] mb-1 flex items-center gap-2">- <DollarSign className="h-5 w-5 text-green-500" />- Cost Tracking- </h1>- <p className="text-sm text-[var(--color-text-secondary)]">- What repowise saved your coding agent — and what generating the docs cost.- </p>- </div>-+ <PageShell+ maxWidth="wide"+ icon={<DollarSign className="h-5 w-5 text-[var(--color-success)]" />}+ title="Cost Tracking"+ description="What repowise saved your coding agent — and what generating the docs cost."+ >{/* Hero: the honest results surface — all tokens & dollars saved for thecoding agent, across distill (CLI + hook) and MCP tool responses. */}<DistillSavingsCard data={distillSavings} />@@ -94,97 +84,50 @@ export default function CostsPage() {<CardContent className="pt-0">{loadingDay ? (<Skeleton className="h-48 w-full" />- ) : dayGroups && dayGroups.length > 0 ? (- <ResponsiveContainer width="100%" height={220}>- <BarChart- data={[...dayGroups].sort((a, b) => a.group.localeCompare(b.group))}- margin={{ top: 8, right: 8, bottom: 0, left: 0 }}- >- <XAxis- dataKey="group"- tick={{ fill: "var(--color-text-tertiary)", fontSize: 11 }}- axisLine={false}- tickLine={false}- interval="preserveStartEnd"- minTickGap={24}- tickFormatter={(v: string) => {- const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(v);- return m ? `${Number(m[2])}/${Number(m[3])}` : v;- }}- />- <YAxis- tick={{ fill: "var(--color-text-tertiary)", fontSize: 10 }}- axisLine={false}- tickLine={false}- tickFormatter={(v: number) => `$${v.toFixed(3)}`}- />- <Tooltip- cursor={{ fill: "var(--color-bg-elevated)" }}- contentStyle={{- background: "var(--color-bg-overlay)",- border: "1px solid var(--color-border-default)",- borderRadius: "6px",- fontSize: "12px",- color: "var(--color-text-primary)",- }}- formatter={(value: number) => [formatCost(value), "Cost"]}- labelFormatter={(label: string) => `Date: ${label}`}- />- <Bar dataKey="cost_usd" fill="var(--color-accent-primary)" radius={[4, 4, 0, 0]} />- </BarChart>- </ResponsiveContainer>) : (- <p className="text-sm text-[var(--color-text-secondary)] py-8 text-center">- No cost data available.- </p>+ <DailySpendChart groups={dayGroups ?? []} />)}</CardContent></Card></TabsContent>- {/* Cache analytics aren't wired to real data yet — the placeholder- CacheHitRatioCard is cut rather than shown empty; the tab keeps- the real per-call efficiency numbers. */}+ {/* Cache analytics aren't wired to real data yet; the tab shows the+ real per-call efficiency numbers as a compact stat strip. */}<TabsContent value="efficiency" className="mt-4">- <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">- <Card>- <CardHeader className="pb-2">- <CardTitle className="text-sm">Token efficiency</CardTitle>- </CardHeader>- <CardContent className="pt-0">- {summary ? (- <div className="space-y-2 text-xs text-[var(--color-text-secondary)]">- <div className="flex justify-between">- <span>Avg input tokens / call</span>- <span className="tabular-nums text-[var(--color-text-primary)]">- {summary.total_calls > 0- ? Math.round(summary.total_input_tokens / summary.total_calls).toLocaleString()- : "—"}- </span>- </div>- <div className="flex justify-between">- <span>Avg output tokens / call</span>- <span className="tabular-nums text-[var(--color-text-primary)]">- {summary.total_calls > 0- ? Math.round(summary.total_output_tokens / summary.total_calls).toLocaleString()- : "—"}- </span>- </div>- <div className="flex justify-between">- <span>Avg cost / call</span>- <span className="tabular-nums text-[var(--color-text-primary)]">- {summary.total_calls > 0- ? formatCost(summary.total_cost_usd / summary.total_calls)- : "—"}- </span>- </div>- </div>- ) : (- <Skeleton className="h-24 w-full" />- )}- </CardContent>- </Card>- </div>+ {summary ? (+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-3">+ <MetricCard+ label="Avg input / call"+ value={+ summary.total_calls > 0+ ? Math.round(summary.total_input_tokens / summary.total_calls).toLocaleString()+ : "—"+ }+ />+ <MetricCard+ label="Avg output / call"+ value={+ summary.total_calls > 0+ ? Math.round(summary.total_output_tokens / summary.total_calls).toLocaleString()+ : "—"+ }+ />+ <MetricCard+ label="Avg cost / call"+ value={+ summary.total_calls > 0+ ? formatCost(summary.total_cost_usd / summary.total_calls)+ : "—"+ }+ />+ </div>+ ) : (+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-3">+ {Array.from({ length: 3 }).map((_, i) => (+ <Skeleton key={i} className="h-24 w-full rounded-lg" />+ ))}+ </div>+ )}</TabsContent><TabsContent value="hotspots" className="mt-4">@@ -241,7 +184,7 @@ export default function CostsPage() {label="Indexing cost"value={formatCost(summary.total_cost_usd)}description="across all generation runs"- icon={<DollarSign className="h-4 w-4 text-green-500" />}+ icon={<DollarSign className="h-4 w-4 text-[var(--color-success)]" />}/><StatCardlabel="Total Calls"@@ -261,6 +204,6 @@ export default function CostsPage() {</div>) : null}</div>- </div>+ </PageShell>);}diff --git a/packages/web/src/app/repos/[id]/coupling/page.tsx b/packages/web/src/app/repos/[id]/coupling/page.tsxindex 824c7ad13..3644adbf6 100644--- a/packages/web/src/app/repos/[id]/coupling/page.tsx+++ b/packages/web/src/app/repos/[id]/coupling/page.tsx@@ -1,39 +1,11 @@-import { notFound } from "next/navigation";-import { getCoupling } from "@/lib/api/coupling";-import { ApiClientError } from "@/lib/api/client";-import { CouplingView } from "@/components/coupling/coupling-view";+import { redirect } from "next/navigation";-export const revalidate = 30;--interface Props {+/** Legacy route — change coupling now lives as an Architecture tab. */+export default async function LegacyRedirect({+ params,+}: {params: Promise<{ id: string }>;-}--export default async function CouplingPage({ params }: Props) {- const { id: repoId } = await params;-- let data;- try {- data = await getCoupling(repoId, { limit: 200 });- } catch (err) {- if (err instanceof ApiClientError && err.status === 404) {- notFound();- }- throw err;- }-- return (- <div className="space-y-6 p-6">- <div>- <h1 className="text-2xl font-semibold text-[var(--color-text-primary)]">- Change coupling- </h1>- <p className="mt-1 text-sm text-[var(--color-text-tertiary)]">- Files that tend to change together in the same commit. A temporal hint- for hidden relationships, not a verified code dependency.- </p>- </div>- <CouplingView data={data} />- </div>- );+}) {+ const { id } = await params;+ redirect(`/repos/${id}/architecture?view=coupling`);}diff --git a/packages/web/src/app/repos/[id]/dead-code/page.tsx b/packages/web/src/app/repos/[id]/dead-code/page.tsxindex 8767d9f5a..145a5cce4 100644--- a/packages/web/src/app/repos/[id]/dead-code/page.tsx+++ b/packages/web/src/app/repos/[id]/dead-code/page.tsx@@ -1,6 +1,6 @@import { redirect } from "next/navigation";-/** Legacy route — redirects into the consolidated IA. */+/** Legacy route — dead code now lives as a Code Health tab. */export default async function LegacyRedirect({params,}: {diff --git a/packages/web/src/app/repos/[id]/error.tsx b/packages/web/src/app/repos/[id]/error.tsxindex 5e623310f..8fe88506f 100644--- a/packages/web/src/app/repos/[id]/error.tsx+++ b/packages/web/src/app/repos/[id]/error.tsx@@ -18,8 +18,8 @@ export default function RepoError({return (<div className="flex h-full min-h-[400px] flex-col items-center justify-center gap-4 p-6 text-center">- <div className="flex h-12 w-12 items-center justify-center rounded-full bg-red-500/10">- <AlertTriangle className="h-6 w-6 text-red-500" />+ <div className="flex h-12 w-12 items-center justify-center rounded-full bg-[var(--color-error)]/10">+ <AlertTriangle className="h-6 w-6 text-[var(--color-error)]" /></div><div><h2 className="text-base font-semibold text-[var(--color-text-primary)]">diff --git a/packages/web/src/app/repos/[id]/files/[...path]/page.tsx b/packages/web/src/app/repos/[id]/files/[...path]/page.tsxindex 30310b031..00e9ea78c 100644--- a/packages/web/src/app/repos/[id]/files/[...path]/page.tsx+++ b/packages/web/src/app/repos/[id]/files/[...path]/page.tsx@@ -2,7 +2,7 @@ import type { Metadata } from "next";import { notFound } from "next/navigation";import { codeToHtml } from "shiki";import { getFileContent, getFileDetail } from "@/lib/api/files";-import { WikiRenderer } from "@/components/wiki/wiki-renderer";+import { WikiMarkdown } from "@repowise-dev/ui/wiki/wiki-markdown";import { FilePageHost } from "@/components/files/file-page-host";import { FILE_PAGE_TABS, type FilePageTab } from "@repowise-dev/ui/files";import type { FileDetailResponse } from "@repowise-dev/types/files";@@ -81,10 +81,10 @@ export default async function FileEntityPage({ params, searchParams }: Props) {: undefined;const docSlot = detail.wiki_page ? (- <WikiRenderer content={detail.wiki_page.content} repoId={id} />+ <WikiMarkdown content={detail.wiki_page.content} />) : undefined;const wikiHref = detail.wiki_page- ? `/repos/${id}/wiki/${encodeURIComponent(detail.wiki_page.id)}`+ ? `/repos/${id}/docs?page=${encodeURIComponent(detail.wiki_page.id)}`: undefined;return (diff --git a/packages/web/src/app/repos/[id]/knowledge-graph/loading.tsx b/packages/web/src/app/repos/[id]/knowledge-graph/loading.tsxnew file mode 100644index 000000000..a5d2d6771--- /dev/null+++ b/packages/web/src/app/repos/[id]/knowledge-graph/loading.tsx@@ -0,0 +1,5 @@+import { OwlLoader } from "@repowise-dev/ui/shared/owl-loader";++export default function Loading() {+ return <OwlLoader label="Loading knowledge graph…" />;+}diff --git a/packages/web/src/app/repos/[id]/knowledge-graph/page.tsx b/packages/web/src/app/repos/[id]/knowledge-graph/page.tsxnew file mode 100644index 000000000..ce9d1d4ca--- /dev/null+++ b/packages/web/src/app/repos/[id]/knowledge-graph/page.tsx@@ -0,0 +1,42 @@+"use client";++/**+ * Knowledge Graph — `/repos/[id]/knowledge-graph`.+ *+ * The single curated mental-model surface: the layered architecture view+ * (tour, personas, layered C4). This route claims the "Knowledge Graph" name+ * so it stops leaking across the constellation, the layers error copy and the+ * legacy C4 header. No lens toggle — Communities and the dependency graphs live+ * under Architecture.+ *+ * Mounts the layered view client-side (it drives a Zustand store and ReactFlow).+ */++import { use } from "react";+import { Waypoints } from "lucide-react";+import { PageShell } from "@repowise-dev/ui/shared/page-shell";+import { KnowledgeGraphView } from "@/components/architecture/c4-view";+import { useRepo } from "@/lib/hooks/use-repo";++export default function KnowledgeGraphPage({+ params,+}: {+ params: Promise<{ id: string }>;+}) {+ const { id: repoId } = use(params);+ const { repo } = useRepo(repoId);+ const repoName = repo?.name ?? "System";++ return (+ <PageShell+ title="Knowledge Graph"+ icon={<Waypoints className="h-5 w-5 text-[var(--color-accent-primary)]" />}+ description="The curated layered view of the system — tour it, switch personas, drill into a layer."+ maxWidth="wide"+ >+ <div className="flex h-[calc(100vh-13rem)] min-h-[480px] flex-col overflow-hidden rounded-lg">+ <KnowledgeGraphView repoId={repoId} repoName={repoName} />+ </div>+ </PageShell>+ );+}diff --git a/packages/web/src/app/repos/[id]/modules/[path]/page.tsx b/packages/web/src/app/repos/[id]/modules/[path]/page.tsxindex 19f937454..cf74f5308 100644--- a/packages/web/src/app/repos/[id]/modules/[path]/page.tsx+++ b/packages/web/src/app/repos/[id]/modules/[path]/page.tsx@@ -3,8 +3,11 @@import { useParams, useRouter } from "next/navigation";import useSWR from "swr";import Link from "next/link";-import { ArrowLeft, Folder } from "lucide-react";-import { ModuleHealthDetailView } from "@repowise-dev/ui/modules/module-health-detail";+import { Folder } from "lucide-react";+import {+ ModuleHealthDetailView,+ ModuleDetailShell,+} from "@repowise-dev/ui/modules";import { fileEntityPath } from "@repowise-dev/ui/shared/entity";import { Skeleton } from "@repowise-dev/ui/ui/skeleton";import { EmptyState } from "@repowise-dev/ui/shared/empty-state";@@ -23,16 +26,10 @@ export default function ModuleHealthPage() {);return (- <div className="p-4 sm:p-6 space-y-4 max-w-[1600px]">- <div className="flex items-center justify-between">- <Link- href={`/repos/${id}/code-health?tab=modules`}- className="inline-flex items-center gap-1 text-xs text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]"- >- <ArrowLeft className="h-3 w-3" /> All modules- </Link>- </div>-+ <ModuleDetailShell+ backHref={`/repos/${id}/code-health?tab=modules`}+ LinkComponent={Link}+ >{isLoading && (<div className="space-y-4"><Skeleton className="h-40 w-full" />@@ -54,6 +51,11 @@ export default function ModuleHealthPage() {{data && (<ModuleHealthDetailViewmodule={data}+ breadcrumb={[+ { label: "Modules", href: `/repos/${id}/code-health?tab=modules` },+ { label: modulePath.split("/").pop() || modulePath },+ ]}+ LinkComponent={Link}onSelectOwner={(o) => {const key = o.email ?? `name:${o.name}`;router.push(`/repos/${id}/owners/${encodeURIComponent(key)}`);@@ -64,6 +66,6 @@ export default function ModuleHealthPage() {}/>)}- </div>+ </ModuleDetailShell>);}diff --git a/packages/web/src/app/repos/[id]/overview/page.tsx b/packages/web/src/app/repos/[id]/overview/page.tsxindex c43666599..e0ae7a8ad 100644--- a/packages/web/src/app/repos/[id]/overview/page.tsx+++ b/packages/web/src/app/repos/[id]/overview/page.tsx@@ -1,20 +1,20 @@import type { Metadata } from "next";import { notFound } from "next/navigation";import { Hash } from "lucide-react";+import Link from "next/link";import { getOverviewSummary } from "@/lib/api/overview";import { getProviders } from "@/lib/api/providers";import { Badge } from "@repowise-dev/ui/ui/badge";-import { Card } from "@repowise-dev/ui/ui/card";-import { EmptyState } from "@repowise-dev/ui/shared";-import { HealthScoreBadge } from "@repowise-dev/ui/dashboard/health-score-badge";+import { EmptyState, PageShell } from "@repowise-dev/ui/shared";import { HealthOverviewCard } from "@repowise-dev/ui/dashboard/health-overview-card";-import { WhereToStartCard } from "@repowise-dev/ui/dashboard/where-to-start";+import { AttentionPanel } from "@repowise-dev/ui/dashboard/attention-panel";+import { KpiStrip, kpiDelta, type KpiItem } from "@repowise-dev/ui/dashboard/kpi-strip";+import { OverviewGrid } from "@repowise-dev/ui/dashboard/overview-grid";import { SavingsMini } from "@repowise-dev/ui/dashboard/savings-mini";import { LanguageDonut } from "@repowise-dev/ui/dashboard/language-donut";import { QuickActionsWrapper as QuickActions } from "@/components/dashboard/quick-actions-wrapper";import { OverviewTabs } from "@/components/overview/overview-tabs";import { ContributorsStripCard } from "@/components/overview/contributors-strip-card";-import { computeHealthScore } from "@/lib/utils/health-score";import { formatNumber, formatRelativeTime } from "@repowise-dev/ui/lib/format";export const metadata: Metadata = { title: "Overview" };@@ -31,56 +31,6 @@ async function safeFetch<T>(fn: () => Promise<T>): Promise<T | null> {}}-interface Kpi {- label: string;- value: string;- href: string;- delta?: { value: string; positive: boolean };-}--function kpiDelta(delta: number | null | undefined): Kpi["delta"] {- if (delta == null || delta === 0) return undefined;- return { value: `${delta > 0 ? "+" : ""}${delta}`, positive: delta > 0 };-}--/** Aligned enterprise-style KPI bar — one card, evenly divided cells. */-function KpiStrip({ items }: { items: Kpi[] }) {- return (- <Card className="overflow-hidden shadow-sm">- <div className="grid grid-cols-2 divide-x divide-y divide-[var(--color-border-default)] sm:grid-cols-3 sm:divide-y-0 lg:grid-cols-5">- {items.map((kpi) => (- <a- key={kpi.label}- href={kpi.href}- className="group flex flex-col gap-1 px-4 py-3.5 transition-colors hover:bg-[var(--color-bg-elevated)]"- >- <span className="text-[11px] font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">- {kpi.label}- </span>- <span className="flex items-baseline gap-1.5">- <span className="text-2xl font-bold tabular-nums leading-none text-[var(--color-text-primary)] group-hover:text-[var(--color-accent-primary)] transition-colors">- {kpi.value}- </span>- {kpi.delta && (- <span- className="text-xs font-medium tabular-nums"- style={{- color: kpi.delta.positive- ? "var(--color-success)"- : "var(--color-error)",- }}- >- {kpi.delta.positive ? "↑" : "↓"} {kpi.delta.value}- </span>- )}- </span>- </a>- ))}- </div>- </Card>- );-}-export default async function OverviewPage({ params }: Props) {const { id } = await params;@@ -93,23 +43,13 @@ export default async function OverviewPage({ params }: Props) {const { repo, stats, health, sync } = summary;const isFresh = stats.file_count === 0;- const healthScore = computeHealthScore({- docCoveragePct: stats.doc_coverage_pct,- freshnessScore: stats.freshness_score,- deadExportCount: stats.dead_export_count,- symbolCount: stats.symbol_count || 1,- hotspotCount: stats.hotspot_count,- totalFiles: stats.file_count || 1,- siloCount: stats.silo_count,- totalModules: stats.module_count || 1,- });-- const kpis: Kpi[] = [+ const kpis: KpiItem[] = [{label: "Files",value: formatNumber(stats.file_count),href: `/repos/${id}/architecture?view=graph`,- delta: kpiDelta(stats.deltas.file_count),+ // File-count growth is neutral, not "good" — render the delta uncolored.+ delta: kpiDelta(stats.deltas.file_count, true),},{label: "Symbols",@@ -120,6 +60,7 @@ export default async function OverviewPage({ params }: Props) {label: "Doc Coverage",value: `${Math.round(stats.doc_coverage_pct)}%`,href: `/repos/${id}/docs/coverage`,+ gauge: stats.doc_coverage_pct,},{label: "Dead Exports",@@ -127,63 +68,58 @@ export default async function OverviewPage({ params }: Props) {href: `/repos/${id}/code-health?tab=dead-code`,},{- label: "Hotspots",- value: formatNumber(stats.hotspot_count),- href: `/repos/${id}/code-health?tab=hotspots`,+ label: "Entry Points",+ value: formatNumber(stats.entry_point_count),+ href: `/repos/${id}/architecture?view=graph&viewMode=architecture`,},];const langDistribution: Record<string, number> = {};for (const l of summary.languages) langDistribution[l.language] = l.file_count;+ const attentionItems = summary.attention.map((a) => ({+ id: a.id,+ type: a.type,+ title: a.title,+ description: a.description,+ severity: a.severity,+ target_id: a.target_id,+ }));+const lastActivityAt = sync.last_sync_at ?? sync.last_resync_at ?? health.last_indexed_at;+ const headerMeta = (+ <div className="flex flex-wrap items-center gap-2">+ {repo.head_commit && (+ <Badge variant="outline" className="text-[10px] h-5 shrink-0">+ <Hash className="h-2.5 w-2.5" />+ {repo.head_commit.slice(0, 7)}+ </Badge>+ )}+ <Badge variant="outline" className="text-[10px] h-5 shrink-0">+ {repo.default_branch}+ </Badge>+ {lastActivityAt && (+ <span+ className="text-xs text-[var(--color-text-tertiary)]"+ title={new Date(lastActivityAt).toLocaleString()}+ >+ synced {formatRelativeTime(lastActivityAt)}+ </span>+ )}+ </div>+ );+return (- <div className="p-4 sm:p-6 space-y-6 max-w-[1600px]">- {/* ── Compact header ── */}- <div className="space-y-3">- <div className="flex flex-wrap items-center gap-x-3 gap-y-2">- <h1 className="text-xl font-semibold text-[var(--color-text-primary)] truncate">- {repo.name}- </h1>- {repo.head_commit && (- <Badge variant="outline" className="text-[10px] h-5 shrink-0">- <Hash className="h-2.5 w-2.5" />- {repo.head_commit.slice(0, 7)}- </Badge>- )}- <Badge variant="outline" className="text-[10px] h-5 shrink-0">- {repo.default_branch}- </Badge>- {!isFresh && (- <HealthScoreBadge- score={healthScore.score}- components={healthScore.components}- note={healthScore.note}- history={health.history}- />- )}- {lastActivityAt && (- <span- className="text-[11px] text-[var(--color-text-tertiary)]"- title={new Date(lastActivityAt).toLocaleString()}- >- synced {formatRelativeTime(lastActivityAt)}- </span>- )}- </div>- <p className="text-xs font-mono text-[var(--color-text-tertiary)] truncate -mt-1">- {repo.local_path}- </p>- <QuickActions- repoId={id}- repoName={repo.name}- pageCount={sync.page_count || stats.file_count}- modelName={providers?.active.model ?? sync.last_sync_model ?? ""}- lastSyncAt={sync.last_sync_at}- lastResyncAt={sync.last_resync_at}- />- </div>+ <PageShell title={repo.name} description={repo.local_path} actions={headerMeta} maxWidth="wide">+ <QuickActions+ repoId={id}+ repoName={repo.name}+ pageCount={sync.page_count || stats.file_count}+ modelName={providers?.active.model ?? sync.last_sync_model ?? ""}+ lastSyncAt={sync.last_sync_at}+ lastResyncAt={sync.last_resync_at}+ />{isFresh ? (<EmptyState@@ -197,24 +133,28 @@ export default async function OverviewPage({ params }: Props) {) : (<>{/* ── KPI bar leads ── */}- <KpiStrip items={kpis} />-- {/* ── Code Health (our moat) leads, with onboarding + savings rail ── */}- <div className="grid grid-cols-1 gap-4 lg:grid-cols-3">- <div className="space-y-4 lg:col-span-2">- <HealthOverviewCard- data={health}- repoId={id}- averageDelta={stats.deltas.average_health}- hotspotDelta={stats.deltas.hotspot_health}- />- <ContributorsStripCard repoId={id} />- </div>- <div className="space-y-4">- <WhereToStartCard targets={summary.onboarding_targets} repoId={id} />- <SavingsMini data={summary.savings} repoId={id} />- </div>- </div>+ <KpiStrip items={kpis} LinkComponent={Link} />++ {/* ── Code Health (our moat) leads, with triage + savings rail ── */}+ <OverviewGrid+ main={+ <>+ <HealthOverviewCard+ data={health}+ repoId={id}+ averageDelta={stats.deltas.average_health}+ hotspotDelta={stats.deltas.hotspot_health}+ />+ <ContributorsStripCard repoId={id} />+ </>+ }+ rail={+ <>+ <SavingsMini data={summary.savings} repoId={id} />+ <AttentionPanel items={attentionItems} repoId={id} previewCount={5} />+ </>+ }+ />{/* ── Pulse / Structure ── */}<OverviewTabs@@ -224,7 +164,7 @@ export default async function OverviewPage({ params }: Props) {decisions={summary.recent_decisions}/>- {/* ── Languages (moved out of the savings card) ── */}+ {/* ── Languages (single canonical donut) ── */}{summary.languages.length > 0 && (<div className="grid grid-cols-1 gap-4 lg:grid-cols-3"><LanguageDonut@@ -235,6 +175,6 @@ export default async function OverviewPage({ params }: Props) {)}</>)}- </div>+ </PageShell>);}diff --git a/packages/web/src/app/repos/[id]/owners/page.tsx b/packages/web/src/app/repos/[id]/owners/page.tsxindex d1ce3ed6b..61310295a 100644--- a/packages/web/src/app/repos/[id]/owners/page.tsx+++ b/packages/web/src/app/repos/[id]/owners/page.tsx@@ -8,6 +8,7 @@ import {OwnerDirectory,type OwnerDirectoryFilters,} from "@repowise-dev/ui/owners/owner-directory";+import { PageShell } from "@repowise-dev/ui/shared/page-shell";import { useDebounce } from "@/lib/hooks/use-debounce";import { listOwnersPage } from "@/lib/api/owners";import type { OwnerListEntry, Paginated } from "@/lib/api/types";@@ -53,18 +54,12 @@ export default function OwnersDirectoryPage() {const hasMore = data ? data[data.length - 1].has_more : false;return (- <div className="p-4 sm:p-6 space-y-6 max-w-[1600px]">- <div>- <h1 className="text-xl font-semibold text-[var(--color-text-primary)] mb-1 flex items-center gap-2">- <Users className="h-5 w-5 text-[var(--color-accent-primary)]" />- Contributors- </h1>- <p className="text-sm text-[var(--color-text-secondary)]">- Who is doing what — ownership, hotspots, dead-code burden, and bus-factor risk- per person. Click any card to open the full profile.- </p>- </div>-+ <PageShell+ maxWidth="wide"+ icon={<Users className="h-5 w-5 text-[var(--color-accent-primary)]" />}+ title="Contributors"+ description="Who is doing what — ownership, hotspots, dead-code burden, and bus-factor risk per person. Click any card to open the full profile."+ ><OwnerDirectoryowners={items}isLoading={isLoading}@@ -78,6 +73,6 @@ export default function OwnersDirectoryPage() {router.push(`/repos/${id}/owners/${encodeURIComponent(o.key)}`)}/>- </div>+ </PageShell>);}diff --git a/packages/web/src/app/repos/[id]/security/page.tsx b/packages/web/src/app/repos/[id]/security/page.tsxindex 9384e5e57..2780ca119 100644--- a/packages/web/src/app/repos/[id]/security/page.tsx+++ b/packages/web/src/app/repos/[id]/security/page.tsx@@ -1,6 +1,6 @@import { redirect } from "next/navigation";-/** Legacy route — redirects into the consolidated IA. */+/** Legacy route — security now lives as a Code Health tab. */export default async function LegacyRedirect({params,}: {diff --git a/packages/web/src/app/repos/[id]/settings/page.tsx b/packages/web/src/app/repos/[id]/settings/page.tsxindex a422d6a0d..16f6c0dd7 100644--- a/packages/web/src/app/repos/[id]/settings/page.tsx+++ b/packages/web/src/app/repos/[id]/settings/page.tsx@@ -10,6 +10,7 @@ import { CoordinatorHealthPanel } from "@/components/repos/coordinator-health-paimport { DeleteRepoButton } from "@/components/repos/delete-repo-button";import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@repowise-dev/ui/ui/card";import { Separator } from "@repowise-dev/ui/ui/separator";+import { PageShell } from "@repowise-dev/ui/shared/page-shell";import { OperationsPanel } from "@/components/repos/operations-panel";interface Props {@@ -39,17 +40,12 @@ export default async function RepoSettingsPage({ params }: Props) {const coordinatorHealth = await getCoordinatorHealth(id).catch(() => null);return (- <div className="p-4 sm:p-6 space-y-6 max-w-2xl">- <div>- <h1 className="text-xl font-semibold text-[var(--color-text-primary)] flex items-center gap-2">- <Settings className="h-5 w-5 text-[var(--color-accent-primary)]" />- Repository Settings- </h1>- <p className="text-sm text-[var(--color-text-secondary)] mt-0.5">- Manage {repo.name}- </p>- </div>-+ <PageShell+ className="max-w-2xl"+ icon={<Settings className="h-5 w-5 text-[var(--color-accent-primary)]" />}+ title="Repository Settings"+ description={`Manage ${repo.name}`}+ ><Card><CardHeader><CardTitle className="text-sm font-medium">General</CardTitle>@@ -115,6 +111,6 @@ export default async function RepoSettingsPage({ params }: Props) {<DeleteRepoButton repoId={id} repoName={repo.name} variant="button" redirectTo="/" /></CardContent></Card>- </div>+ </PageShell>);}diff --git a/packages/web/src/app/repos/[id]/symbols/[symbolId]/page.tsx b/packages/web/src/app/repos/[id]/symbols/[symbolId]/page.tsxindex 200c63c85..5b31229eb 100644--- a/packages/web/src/app/repos/[id]/symbols/[symbolId]/page.tsx+++ b/packages/web/src/app/repos/[id]/symbols/[symbolId]/page.tsx@@ -1,7 +1,9 @@import type { Metadata } from "next";+import Link from "next/link";import { notFound } from "next/navigation";import { getSymbolDetail } from "@/lib/api/symbols";import { SymbolPage } from "@repowise-dev/ui/symbols";+import { fileEntityPath } from "@repowise-dev/ui/shared/entity";import type { SymbolDetailResponse } from "@repowise-dev/types/symbols";interface Props {@@ -25,9 +27,19 @@ export default async function SymbolEntityPage({ params }: Props) {notFound();}+ const filePath = detail.symbol.file_path;+return (- <div className="p-4 sm:p-6 max-w-[1100px]">- <SymbolPage data={detail} repoId={id} />+ <div className="mx-auto w-full max-w-[1100px] p-4 sm:p-6">+ <SymbolPage+ data={detail}+ repoId={id}+ LinkComponent={Link}+ breadcrumb={[+ { label: filePath.split("/").pop() || filePath, href: fileEntityPath(`/repos/${id}`, filePath) },+ { label: detail.symbol.name },+ ]}+ /></div>);}diff --git a/packages/web/src/app/repos/[id]/wiki/[...slug]/page.tsx b/packages/web/src/app/repos/[id]/wiki/[...slug]/page.tsxindex 65637986b..b92d482d5 100644--- a/packages/web/src/app/repos/[id]/wiki/[...slug]/page.tsx+++ b/packages/web/src/app/repos/[id]/wiki/[...slug]/page.tsx@@ -1,335 +1,30 @@import type { Metadata } from "next";-import Link from "next/link";-import { notFound } from "next/navigation";-import { ApiClientError } from "@/lib/api/client";-import { getRepo } from "@/lib/api/repos";-import { getPageById, getPageVersions } from "@/lib/api/pages";-import { getGitMetadata } from "@/lib/api/git";-import { getGraphMetrics } from "@/lib/api/graph";-import { ConfidenceBadge } from "@repowise-dev/ui/wiki/confidence-badge";-import { WikiRenderer } from "@/components/wiki/wiki-renderer";-import { TableOfContents } from "@repowise-dev/ui/wiki/table-of-contents";-import { RegenerateButtonWrapper } from "@/components/wiki/regenerate-button";-import { GitHistoryPanel } from "@repowise-dev/ui/wiki/git-history-panel";-import { SecurityPanelWrapper } from "@/components/wiki/security-panel";-import { BacklinksPanel } from "@repowise-dev/ui/wiki/backlinks-panel";-import {- getBacklinks,- getWikiLinks,-} from "@repowise-dev/ui/wiki/wiki-links-types";-import { Badge } from "@repowise-dev/ui/ui/badge";-import { Separator } from "@repowise-dev/ui/ui/separator";-import { formatRelativeTime, formatTokens } from "@repowise-dev/ui/lib/format";-import { CoChangeList } from "@repowise-dev/ui/git/co-change-list";-import { Hash, Cpu, FileCode2 } from "lucide-react";-import { fileEntityPath } from "@repowise-dev/ui/shared/entity";-import { HumanNotes } from "@/components/wiki/human-notes";-import { VersionHistoryWrapper } from "@/components/wiki/version-history";-import type { GraphMetricsResponse } from "@/lib/api/types";+import { redirect } from "next/navigation";+import { getPageById } from "@/lib/api/pages";interface Props {params: Promise<{ id: string; slug: string[] }>;}export async function generateMetadata({ params }: Props): Promise<Metadata> {- const { id, slug } = await params;+ const { slug } = await params;const pageId = slug.join("/");try {const page = await getPageById(pageId);return { title: page.title };} catch {- return { title: "Wiki Page" };+ return { title: "Documentation" };}}+/**+ * Deep-link alias. Docs and Wiki are one reader surface now; ``/wiki/{pageId}``+ * stays a permanent, shareable entry point that opens that page inside the+ * unified reader (tree + reader + intelligence rail) rather than a second+ * front-end. All historical wiki links keep resolving — no dead-ends.+ */export default async function WikiPageRoute({ params }: Props) {const { id, slug } = await params;const pageId = slug.join("/");-- let page;- try {- page = await getPageById(pageId);- } catch (err) {- if (err instanceof ApiClientError && err.status === 404) {- notFound();- }- throw err;- }-- const [repo, versions, gitMeta, graphMetricsResult] = await Promise.allSettled([- getRepo(id),- getPageVersions(pageId),- page.target_path ? getGitMetadata(id, page.target_path) : Promise.reject(),- page.target_path ? getGraphMetrics(id, page.target_path) : Promise.reject(),- ]);-- const repoData = repo.status === "fulfilled" ? repo.value : null;- const versionList = versions.status === "fulfilled" ? versions.value : [];- const git = gitMeta.status === "fulfilled" ? gitMeta.value : null;- const graphMetrics: GraphMetricsResponse | null =- graphMetricsResult.status === "fulfilled" ? graphMetricsResult.value : null;-- return (- <div className="flex h-full min-h-0">- {/* Main content */}- <div className="flex-1 min-w-0 overflow-auto">- {/* Top bar */}- <div className="sticky top-0 z-[var(--z-elevated)] flex items-center gap-2 border-b border-[var(--color-border-default)] bg-[var(--color-bg-surface)]/95 backdrop-blur px-3 sm:px-6 py-2.5 flex-wrap sm:flex-nowrap">- {/* Breadcrumb */}- <div className="flex items-center gap-1.5 text-xs text-[var(--color-text-tertiary)] min-w-0 flex-1">- {repoData && (- <>- <span className="hidden sm:block truncate max-w-[80px]">{repoData.name}</span>- <span className="hidden sm:block">/</span>- </>- )}- <span className="font-mono truncate text-[var(--color-text-secondary)] max-w-[180px] sm:max-w-none" title={page.target_path || page.page_type}>- {page.target_path || page.page_type}- </span>- </div>-- {/* Confidence badge */}- <ConfidenceBadge- score={page.confidence}- status={page.freshness_status}- showScore- />-- {/* Provider badge */}- <Badge variant="outline" className="font-mono text-xs hidden sm:flex shrink-0">- <Cpu className="h-3 w-3 mr-1" />- <span className="truncate max-w-[200px]" title={`${page.provider_name}/${page.model_name}`}>{page.provider_name}/{page.model_name}</span>- </Badge>-- {/* Commit */}- {page.source_hash && (- <Badge variant="outline" className="font-mono text-xs hidden md:flex shrink-0">- <Hash className="h-3 w-3 mr-1" />- {page.source_hash.slice(0, 7)}- </Badge>- )}-- {/* Canonical file page — everything about this file in one place. */}- {page.page_type === "file_page" && page.target_path && (- <Link- href={fileEntityPath(`/repos/${id}`, page.target_path)}- className="hidden sm:inline-flex shrink-0 items-center gap-1 rounded-md border border-[var(--color-border-default)] px-2 py-0.5 text-xs text-[var(--color-text-secondary)] transition-colors hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]"- >- <FileCode2 className="h-3 w-3" />- File page- </Link>- )}-- {/* Regenerate */}- <RegenerateButtonWrapper pageId={page.id} repoId={id} />- </div>-- {/* Page content */}- <div className="px-4 sm:px-6 py-6 max-w-[768px] mx-auto">- <h1 className="text-xl font-semibold text-[var(--color-text-primary)] mb-4 break-words">- {page.title}- </h1>-- <HumanNotes pageId={page.id} initialNotes={page.human_notes ?? null} />-- {/* Inline collapsible ToC for viewports without the right sidebar. */}- <details className="xl:hidden mb-5 rounded-lg border border-[var(--color-border-default)] px-4 py-2.5">- <summary className="cursor-pointer text-xs font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">- On this page- </summary>- <div className="pt-2">- <TableOfContents content={page.content} />- </div>- </details>-- <article className="prose prose-invert max-w-none leading-relaxed overflow-hidden">- <WikiRenderer- content={page.content}- wikiLinks={getWikiLinks(page.metadata)}- repoId={id}- />- </article>-- {/* Hallucination warnings */}- {Array.isArray(page.metadata?.hallucination_warnings) && (page.metadata.hallucination_warnings as string[]).length > 0 && (- <div className="mt-6 rounded-lg border border-[var(--color-warning)]/40 bg-[var(--color-warning)]/10 px-4 py-3">- <p className="text-xs font-medium text-[var(--color-warning)] mb-1.5">- Possible inaccuracies detected- </p>- <ul className="space-y-0.5">- {(page.metadata.hallucination_warnings as string[]).map((w, i) => (- <li key={i} className="text-xs text-[var(--color-text-secondary)] font-mono">- {String(w)}- </li>- ))}- </ul>- </div>- )}- </div>-- {/* Version changelog — full content history with diffs */}- {versionList.length > 0 && (- <div className="px-4 sm:px-6 pb-6 max-w-[768px] mx-auto">- <p className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-2">- Version history- </p>- <VersionHistoryWrapper- pageId={page.id}- currentVersion={page.version}- currentContent={page.content}- />- </div>- )}-- {/* Bottom bar */}- <div className="border-t border-[var(--color-border-default)] px-4 sm:px-6 py-3 flex flex-wrap items-center gap-x-4 gap-y-1.5 text-xs text-[var(--color-text-tertiary)]">- <span>Generated {formatRelativeTime(page.updated_at)}</span>- <Separator orientation="vertical" className="h-4 hidden sm:block" />- <span className="font-mono">- {formatTokens(page.input_tokens)} in · {formatTokens(page.output_tokens)} out- </span>- {versionList.length > 0 && (- <>- <Separator orientation="vertical" className="h-4 hidden sm:block" />- <span>v{page.version} ({versionList.length} versions)</span>- </>- )}- </div>- </div>-- {/* Context panel (right sidebar) */}- <div- className="hidden xl:flex flex-col border-l border-[var(--color-border-default)] bg-[var(--color-bg-surface)] shrink-0"- style={{ width: "280px" }}- >- <div className="overflow-auto flex-1 p-4 space-y-5">- {/* Table of contents */}- <TableOfContents content={page.content} />-- {/* Git history panel */}- {git && (- <div>- <p className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-2">- Git History- </p>- <div className="space-y-1.5 mb-3">- <div className="flex justify-between text-xs">- <span className="text-[var(--color-text-tertiary)]">Commits (90d)</span>- <span className="text-[var(--color-text-secondary)] tabular-nums">- {git.commit_count_90d}- </span>- </div>- <div className="flex justify-between text-xs">- <span className="text-[var(--color-text-tertiary)]">Churn</span>- <span className="text-[var(--color-text-secondary)] tabular-nums">- {Math.round(git.churn_percentile)}th pct- </span>- </div>- {git.is_hotspot && (- <Badge variant="stale" className="text-xs">Hotspot</Badge>- )}- </div>- <GitHistoryPanel git={git} />- </div>- )}-- {/* Graph Intelligence */}- {graphMetrics && (- <div>- <p className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-2">- Graph Intelligence- </p>- <div className="space-y-1.5">- {graphMetrics.community_label && (- <div className="flex justify-between text-xs">- <span className="text-[var(--color-text-tertiary)]">Community</span>- <Link- href={`/repos/${id}/architecture?view=graph&colorMode=community`}- className="text-[var(--color-accent)] hover:underline font-mono text-[11px]"- >- {graphMetrics.community_label}- </Link>- </div>- )}- <div className="flex justify-between text-xs">- <span className="text-[var(--color-text-tertiary)]">PageRank</span>- <span className={`tabular-nums font-mono text-[11px] ${graphMetrics.pagerank_percentile >= 75 ? "text-green-400" : graphMetrics.pagerank_percentile >= 50 ? "text-yellow-400" : "text-[var(--color-text-secondary)]"}`}>- Top {100 - graphMetrics.pagerank_percentile}%- </span>- </div>- <div className="flex justify-between text-xs">- <span className="text-[var(--color-text-tertiary)]">Betweenness</span>- <span className={`tabular-nums font-mono text-[11px] ${graphMetrics.betweenness_percentile >= 75 ? "text-green-400" : graphMetrics.betweenness_percentile >= 50 ? "text-yellow-400" : "text-[var(--color-text-secondary)]"}`}>- Top {100 - graphMetrics.betweenness_percentile}%- </span>- </div>- <div className="flex justify-between text-xs">- <span className="text-[var(--color-text-tertiary)]">Degree</span>- <span className="text-[var(--color-text-secondary)] tabular-nums font-mono text-[11px]">- {graphMetrics.in_degree} in · {graphMetrics.out_degree} out- </span>- </div>- {graphMetrics.is_entry_point && (- <Badge variant="accent" className="text-xs">Entry Point</Badge>- )}- </div>- </div>- )}-- {/* Backlinks — pages mentioning this one. Hidden when empty- so legacy pages without interlinking metadata don't show- an awkward "Linked by (0)" header. */}- <BacklinksPanel- backlinks={getBacklinks(page.metadata)}- repoId={id}- renderLink={({ href, className, title, children }) => (- <Link href={href} className={className} title={title}>- {children}- </Link>- )}- />-- {/* Security findings panel */}- {page.target_path && (- <div>- <p className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-2">- Security Signals- </p>- <SecurityPanelWrapper repoId={id} filePath={page.target_path} />- </div>- )}-- {/* Page metadata */}- <div>- <p className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-2">- Page Info- </p>- <div className="space-y-1.5 text-xs">- <div className="flex justify-between gap-2">- <span className="text-[var(--color-text-tertiary)] shrink-0">Type</span>- <span className="text-[var(--color-text-secondary)] font-mono truncate">{page.page_type}</span>- </div>- <div className="flex justify-between gap-2">- <span className="text-[var(--color-text-tertiary)] shrink-0">Version</span>- <span className="text-[var(--color-text-secondary)] tabular-nums">v{page.version}</span>- </div>- <div className="flex justify-between gap-2">- <span className="text-[var(--color-text-tertiary)] shrink-0">Level</span>- <span className="text-[var(--color-text-secondary)] tabular-nums">{page.generation_level}</span>- </div>- {Array.isArray(page.metadata?.hallucination_warnings) && (page.metadata.hallucination_warnings as string[]).length > 0 && (- <div className="flex justify-between gap-2">- <span className="text-[var(--color-text-tertiary)] shrink-0">Warnings</span>- <Badge variant="stale" className="text-[10px]">- {(page.metadata.hallucination_warnings as string[]).length}- </Badge>- </div>- )}- </div>- </div>- </div>- </div>- </div>- );+ redirect(`/repos/${id}/docs?page=${encodeURIComponent(pageId)}`);}-diff --git a/packages/web/src/app/repos/[id]/wiki/page.tsx b/packages/web/src/app/repos/[id]/wiki/page.tsxnew file mode 100644index 000000000..c0254b027--- /dev/null+++ b/packages/web/src/app/repos/[id]/wiki/page.tsx@@ -0,0 +1,15 @@+import { redirect } from "next/navigation";++interface Props {+ params: Promise<{ id: string }>;+}++/**+ * Wiki home. There is one documentation reader now, so the wiki index opens it+ * at its default landing (the Guided Tour spine) rather than dead-ending on a+ * bare slug. Keeps ``/repos/{id}/wiki`` a valid, shareable entry point.+ */+export default async function WikiIndexRoute({ params }: Props) {+ const { id } = await params;+ redirect(`/repos/${id}/docs`);+}diff --git a/packages/web/src/app/workspace/co-changes/page.tsx b/packages/web/src/app/workspace/co-changes/page.tsxindex 5e2d5077d..f277b69e0 100644--- a/packages/web/src/app/workspace/co-changes/page.tsx+++ b/packages/web/src/app/workspace/co-changes/page.tsx@@ -58,7 +58,7 @@ export default function CoChangesPage() {).size: "—"}- icon={<GitMerge className="h-4 w-4 text-purple-400" />}+ icon={<GitMerge className="h-4 w-4 text-[var(--color-accent-secondary)]" />}/><StatCardlabel="Avg Strength"@@ -71,7 +71,7 @@ export default function CoChangesPage() {) / 10: "—"}- icon={<GitMerge className="h-4 w-4 text-orange-400" />}+ icon={<GitMerge className="h-4 w-4 text-[var(--color-accent-primary)]" />}/></div>diff --git a/packages/web/src/app/workspace/contracts/page.tsx b/packages/web/src/app/workspace/contracts/page.tsxindex 4d910a741..c93197b33 100644--- a/packages/web/src/app/workspace/contracts/page.tsx+++ b/packages/web/src/app/workspace/contracts/page.tsx@@ -74,13 +74,13 @@ export default function ContractsPage() {<StatCardlabel="Matched Links"value={data?.total_links ?? "—"}- icon={<Link2 className="h-4 w-4 text-green-400" />}+ icon={<Link2 className="h-4 w-4 text-[var(--color-success)]" />}/><StatCardlabel="Unmatched"value={isLoading ? "—" : unmatchedCount}description="No matching provider or consumer"- icon={<Link2 className="h-4 w-4 text-yellow-400" />}+ icon={<Link2 className="h-4 w-4 text-[var(--color-warning)]" />}/><StatCardlabel="By Type"@@ -96,7 +96,7 @@ export default function ContractsPage() {.join(", "): undefined}- icon={<Filter className="h-4 w-4 text-purple-400" />}+ icon={<Filter className="h-4 w-4 text-[var(--color-accent-secondary)]" />}/></div>diff --git a/packages/web/src/app/workspace/page.tsx b/packages/web/src/app/workspace/page.tsxindex b6b5d5a82..3b6a8c949 100644--- a/packages/web/src/app/workspace/page.tsx+++ b/packages/web/src/app/workspace/page.tsx@@ -145,7 +145,7 @@ export default async function WorkspaceDashboardPage() {<StatCardlabel="Hotspots"value={totalHotspots}- icon={<Flame className="h-4 w-4 text-orange-400" />}+ icon={<Flame className="h-4 w-4 text-[var(--color-warning)]" />}/><StatCardlabel="Pages"diff --git a/packages/web/src/app/workspace/sync-buttons.tsx b/packages/web/src/app/workspace/sync-buttons.tsxindex f2e97b6a5..39e7b7609 100644--- a/packages/web/src/app/workspace/sync-buttons.tsx+++ b/packages/web/src/app/workspace/sync-buttons.tsx@@ -76,12 +76,12 @@ export function SyncButton({{state.kind === "running" ? "Syncing…" : buttonText}</button>{state.kind === "ok" && (- <span className="text-[11px] text-[var(--color-text-tertiary)]">+ <span className="text-xs text-[var(--color-text-tertiary)]">{summarizeResults(state.results)}</span>)}{state.kind === "error" && (- <span className="text-[11px] text-[var(--color-outdated)]">+ <span className="text-xs text-[var(--color-outdated)]">{state.message}</span>)}diff --git a/packages/web/src/components/architecture/c4-view.tsx b/packages/web/src/components/architecture/c4-view.tsxindex a34df106d..2617642a7 100644--- a/packages/web/src/components/architecture/c4-view.tsx+++ b/packages/web/src/components/architecture/c4-view.tsx@@ -1,62 +1,36 @@"use client";/**- * C4 / Architecture diagrams — `/repos/[id]/c4`.- *- * Supports two modes:- * - mode=c4 — legacy C4 three-level diagram- * - mode=architecture — new unified architecture view (default)+ * Knowledge Graph view — the curated layered architecture surface.** URL params are synced bidirectionally with the Zustand store so that* refresh + share preserve the view state.*/import { useCallback, useEffect, useRef, useState } from "react";-import { useQueryState, parseAsInteger, parseAsString, parseAsStringLiteral } from "nuqs";+import { useQueryState, parseAsString, parseAsStringLiteral } from "nuqs";import {- C4Diagram,- type C4Level,+ ArchCanvas,useArchitectureStore,useArchitectureLayout,useArchitectureNavigation,- archNodeTypes,- archEdgeTypes,SearchBar,ArchBreadcrumb,- ArchLegend,PersonaSelector,NodeTypeCategoryFilters,FilterPanel,CodeViewer,PathFinderModal,type Persona,- KEYFRAMES,} from "@repowise-dev/ui/c4";-import {- Background,- BackgroundVariant,- Controls,- MiniMap,- ReactFlow,- ReactFlowProvider,- useReactFlow,-} from "@xyflow/react";-import "@xyflow/react/dist/style.css";-import { useC4L1, useC4L2, useC4L3 } from "@/lib/hooks/use-c4";+import { ReactFlowProvider, useReactFlow, type Node } from "@xyflow/react";import { useArchitectureView } from "@/lib/hooks/use-architecture";-import { useC4DocsPathSet } from "@/lib/hooks/use-c4-context";-import { useRepo } from "@/lib/hooks/use-repo";-import { getC4Mermaid } from "@/lib/api/c4";-import { C4DetailPanelHost } from "@/components/c4/c4-detail-panel-host";import { ArchDetailPanelHost } from "@/components/c4/arch-detail-panel-host";-import { EmptyState } from "@repowise-dev/ui/shared/empty-state";-import { OwlLoader } from "@repowise-dev/ui/shared/owl-loader";-import { AlertTriangle, Compass } from "lucide-react";+import { Compass } from "lucide-react";// First-visit discoverability flag for the guided tour.const TOUR_SEEN_KEY = "repowise:arch-tour-seen";-const MODE_VALUES = ["c4", "architecture"] as const;const VIEW_VALUES = ["overview", "groups", "detail"] as const;const PERSONA_VALUES = ["overview", "learn", "deep-dive"] as const;// Unified click grammar (kg-ux plan B5): single click = select + inspect on@@ -64,45 +38,36 @@ const PERSONA_VALUES = ["overview", "learn", "deep-dive"] as const;// navigation stubs, the scope frame is a pointer-events-none underlay.const SYNTHETIC_NODE_TYPES = new Set(["portal", "scopeFrame"]);-function clampLevel(n: number | null): C4Level {- return n === 1 ? 1 : n === 3 ? 3 : 2;-}--export function C4View({ repoId, legacy }: { repoId: string; legacy?: boolean }) {- const { repo } = useRepo(repoId);-- // The hosting Architecture page decides Layers vs legacy C4 via `?view=`;- // `?mode=c4` is honored as a legacy deep-link fallback.- const [mode] = useQueryState(- "mode",- parseAsStringLiteral(MODE_VALUES).withDefault("architecture"),- );- const showLegacy = legacy ?? mode === "c4";-- return (- <div className="flex flex-col h-full">- {showLegacy ? (- <LegacyC4View repoId={repoId} repoName={repo?.name ?? "System"} />- ) : (- <ArchitectureViewPage repoId={repoId} repoName={repo?.name ?? "System"} />- )}- </div>- );-}--// ----------------------------------------------------------------------------// Architecture View (new)-// -----------------------------------------------------------------------------function ArchitectureViewPage({ repoId, repoName }: { repoId: string; repoName: string }) {+/**+ * The curated layered architecture view, ready to mount client-side. The+ * Knowledge Graph route renders this inside a `PageShell` (passing+ * `embedded` so the inner title band is suppressed and the page owns the+ * heading). Must be a client component because it drives a Zustand store and+ * `useReactFlow`.+ */+export function KnowledgeGraphView({+ repoId,+ repoName,+}: {+ repoId: string;+ repoName: string;+}) {return (<ReactFlowProvider>- <ArchitectureViewInner repoId={repoId} repoName={repoName} />+ <ArchitectureViewInner repoId={repoId} repoName={repoName} embedded /></ReactFlowProvider>);}-function ArchitectureViewInner({ repoId, repoName }: { repoId: string; repoName: string }) {+function ArchitectureViewInner({+ repoId,+ repoName,+ embedded,+}: {+ repoId: string;+ repoName: string;+ embedded?: boolean;+}) {const { view, error, isLoading } = useArchitectureView(repoId);const { fitView } = useReactFlow();@@ -238,7 +203,7 @@ function ArchitectureViewInner({ repoId, repoName }: { repoId: string; repoName:}, [selectedNodeId, nodes, fitView]);const handleNodeClick = useCallback(- (_: React.MouseEvent, node: { id: string; type?: string }) => {+ (_: React.MouseEvent, node: Node) => {if (SYNTHETIC_NODE_TYPES.has(node.type ?? "")) return;selectNode(node.id);},@@ -248,7 +213,7 @@ function ArchitectureViewInner({ repoId, repoName }: { repoId: string; repoName:// Double click = drill (grammar): layer → groups/detail, group → detail,// folder → expand/collapse. (Drilling clears selection in the store.)const handleNodeDoubleClick = useCallback(- (_: React.MouseEvent, node: { id: string; type?: string }) => {+ (_: React.MouseEvent, node: Node) => {if (node.type === "layerCluster") {drillIntoLayer(node.id);} else if (node.type === "subGroupCluster") {@@ -293,14 +258,18 @@ function ArchitectureViewInner({ repoId, repoName }: { repoId: string; repoName:<><div className="shrink-0 px-4 sm:px-6 py-3 border-b border-[var(--color-border-default)]"><div className="flex items-center justify-between">- <div>- <h1 className="text-lg font-semibold text-[var(--color-text-primary)]">- Layers- </h1>- <p className="text-xs text-[var(--color-text-secondary)] mt-0.5">- {repoName} — curated layered view of the system.- </p>- </div>+ {!embedded ? (+ <div>+ <h1 className="text-lg font-semibold text-[var(--color-text-primary)]">+ Layers+ </h1>+ <p className="text-xs text-[var(--color-text-secondary)] mt-0.5">+ {repoName} — curated layered view of the system.+ </p>+ </div>+ ) : (+ <span aria-hidden />+ )}<div className="flex items-center gap-3">{view && view.tour.length > 0 && !tourActive && (<button@@ -325,196 +294,29 @@ function ArchitectureViewInner({ repoId, repoName }: { repoId: string; repoName:</div></div>- <style>{KEYFRAMES.accentPulse}{KEYFRAMES.edgeFlow}{`- /* Zoom-into-tier feel: nodes glide to their next slot (plan D). */- @media (prefers-reduced-motion: no-preference) {- .react-flow__node { transition: transform 180ms ease; }- }- `}</style>- <div className="flex-1 min-h-0 relative bg-[var(--color-bg-canvas)]">- {error && (- <div className="absolute inset-0 flex items-center justify-center z-10">- <EmptyState- icon={<AlertTriangle className="h-5 w-5" aria-hidden />}- title="Couldn't load the knowledge graph"- description={error.message}- className="max-w-md p-8"- />- </div>- )}- {anyLoading && nodes.length === 0 && !error && (- <div className="absolute inset-0 flex items-center justify-center z-10 pointer-events-none">- <OwlLoader size={120} label="Loading knowledge graph…" className="min-h-0" />- </div>- )}- {/* Re-layout feedback (B6): ELK stage-2 on big layers used to freeze- silently — a small owl chip says the canvas is thinking. */}- {anyLoading && nodes.length > 0 && !error && (- <div className="absolute top-3 left-1/2 -translate-x-1/2 z-10 pointer-events-none rounded-full border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]/95 px-3 py-1 shadow-sm">- <OwlLoader size={28} label="Laying out…" className="min-h-0 flex-row gap-2 text-[10px]" />- </div>- )}-- <ReactFlow+ <div className="flex-1 min-h-0 relative">+ {/* The layered canvas chrome (ReactFlow host, controls, minimap, owl+ chips, weaker-link chip, legend) now lives in `ui/c4` so it upgrades+ via a package bump. Web keeps store/data wiring and the panel hosts. */}+ <ArchCanvasnodes={nodes}edges={edges}- nodeTypes={archNodeTypes}- edgeTypes={archEdgeTypes}+ loading={anyLoading}+ error={error}+ hiddenEdgeCount={hiddenEdgeCount}+ onInit={setReactFlowInstance}onNodeClick={handleNodeClick}onNodeDoubleClick={handleNodeDoubleClick}onPaneClick={handlePaneClick}- onInit={setReactFlowInstance}- fitView- fitViewOptions={{ padding: 0.2 }}- minZoom={0.1}- maxZoom={3}- proOptions={{ hideAttribution: true }}- nodesDraggable={false}- nodesConnectable={false}+ errorTitle="Couldn't load the architecture layers"+ loadingLabel="Loading layers…">- {/* Blueprint graph paper: 24px line grid on the warm canvas, matching- the mermaid container (kg-ux plan §2.1). */}- <Background variant={BackgroundVariant.Lines} gap={24} size={1} color="var(--color-diagram-grid)" />- <Controls showInteractive={false} />- {/* maskColor comes from --xy-minimap-mask-background (theme-aware). */}- <MiniMap pannable zoomable />- </ReactFlow>-- {/* Orientation (plan C-1) and the tour player (C-2) render in the- right Sidebar only — the floating left asides duplicated them- (user feedback 2026-06-05: one place). */}-- {hiddenEdgeCount > 0 && (- <div- className="absolute bottom-4 left-14 z-10 rounded-full border border-[var(--color-border-default)] bg-[var(--color-bg-secondary)]/90 px-3 py-1 text-xs text-[var(--color-text-secondary)]"- title="Weakest aggregated connections are hidden to keep the view legible. Drill in to see them."- >- +{hiddenEdgeCount} weaker link{hiddenEdgeCount === 1 ? "" : "s"} hidden- </div>- )}-- {/* Decoder ring — collapsible, every tier (B6). */}- <div className="absolute bottom-4 right-[224px] z-10">- <ArchLegend />- </div>-- <ArchDetailPanelHost repoId={repoId} />-- <FilterPanel />-- <CodeViewer fetchContent={fetchContent} />-- {pathFinderOpen && <PathFinderModal />}- </div>- </>- );-}--// ----------------------------------------------------------------------------// Legacy C4 View (preserved for backward compat)-// -----------------------------------------------------------------------------function LegacyC4View({ repoId, repoName }: { repoId: string; repoName: string }) {- const [levelParam, setLevelParam] = useQueryState(- "level",- parseAsInteger.withDefault(2),- );- const [containerParam, setContainerParam] = useQueryState(- "container",- parseAsString,- );-- const level = clampLevel(levelParam);- const activeContainerId = containerParam || null;-- const { view: l1View, error: l1Err, isLoading: l1Loading } = useC4L1(level === 1 ? repoId : null);- const { view: l2View, error: l2Err, isLoading: l2Loading } = useC4L2(level >= 2 ? repoId : null);- const { view: l3View, error: l3Err, isLoading: l3Loading } = useC4L3(- level === 3 ? repoId : null,- level === 3 ? activeContainerId : null,- );-- const setLevel = useCallback(- (next: C4Level) => {- void setLevelParam(next);- if (next !== 3) void setContainerParam(null);- },- [setContainerParam, setLevelParam],- );-- const drillInto = useCallback(- (containerId: string) => {- void setLevelParam(3);- void setContainerParam(containerId);- },- [setContainerParam, setLevelParam],- );-- const drillOut = useCallback(() => {- if (level === 3) {- void setLevelParam(2);- void setContainerParam(null);- } else if (level === 2) {- void setLevelParam(1);- }- }, [level, setContainerParam, setLevelParam]);-- const loading = level === 1 ? l1Loading : level === 2 ? l2Loading : l3Loading;- const error = level === 1 ? l1Err : level === 2 ? l2Err : l3Err;-- const { pathSet: docsPathSet, pageIdByPath } = useC4DocsPathSet(repoId);-- const fetchMermaid = useCallback(- () => getC4Mermaid(repoId, level, activeContainerId),- [activeContainerId, level, repoId],- );-- return (- <>- <div className="shrink-0 px-4 sm:px-6 py-3 border-b border-[var(--color-border-default)]">- <div className="flex items-center justify-between gap-4">- <div>- <h1 className="text-lg font-semibold text-[var(--color-text-primary)]">- Knowledge Graph- </h1>- <p className="text-xs text-[var(--color-text-secondary)] mt-0.5">- System context, containers, and components — drill in to navigate.- </p>- </div>- {/* Legacy mode is frozen (locked decision 4) — point at the new view. */}- <a- href="?view=layers"- className="shrink-0 rounded-full border border-[var(--color-accent-primary,#f59520)]/50 bg-[var(--color-accent-primary,#f59520)]/10 px-3 py-1 text-xs text-[var(--color-accent-primary,#f59520)] hover:bg-[var(--color-accent-primary,#f59520)]/20"- >- Try the new architecture view →- </a>- </div>- </div>- <div className="flex-1 min-h-0">- <C4Diagram- level={level}- activeContainerId={activeContainerId}- systemName={repoName}- l1View={l1View}- l2View={l2View}- l3View={l3View}- loading={loading}- error={error}- onLevelChange={setLevel}- onDrillInto={drillInto}- onDrillOut={drillOut}- docsPathSet={docsPathSet}- fetchMermaid={fetchMermaid}- renderInspector={({ data, onClose, onDrillIn }) => (- <C4DetailPanelHost- repoId={repoId}- data={data}- pageIdByPath={pageIdByPath}- onClose={onClose}- onDrillIn={onDrillIn}- />- )}- />+ {/* Orientation and the tour player render in the right Sidebar only. */}+ <ArchDetailPanelHost repoId={repoId} />+ <FilterPanel />+ <CodeViewer fetchContent={fetchContent} />+ {pathFinderOpen && <PathFinderModal />}+ </ArchCanvas></div></>);diff --git a/packages/web/src/components/architecture/graph-view.tsx b/packages/web/src/components/architecture/graph-view.tsxindex 116daddb4..1e0fefb75 100644--- a/packages/web/src/components/architecture/graph-view.tsx+++ b/packages/web/src/components/architecture/graph-view.tsx@@ -6,6 +6,7 @@ import { useQueryState } from "nuqs";import { useSearchParams } from "next/navigation";import { GraphFlow } from "@/components/graph/graph-flow";import { GraphDocPanel } from "@/components/graph/graph-doc-panel";+import { GraphCanvasShell } from "@repowise-dev/ui/graph/graph-canvas-shell";import { GraphTruncationBanner } from "@repowise-dev/ui/graph/graph-truncation-banner";import { getGraph } from "@/lib/api/graph";import type { GraphExportResponse } from "@/lib/api/types";@@ -142,24 +143,18 @@ export function GraphView({const isMap = scope === "map" && !initialNode;return (- <div className="flex flex-col h-full">- {/* Header */}- <div className="shrink-0 px-4 sm:px-6 py-3 border-b border-[var(--color-border-default)]">- <h1 className="text-lg font-semibold text-[var(--color-text-primary)]">- {isMap ? "Architecture Map" : "Dependency Explorer"}- </h1>- <p className="text-xs text-[var(--color-text-secondary)] mt-0.5">- {isMap- ? "Detected communities and how they connect — double-click a hub to blossom it"- : "Explore dependencies, overlays and trace paths between files"}- </p>- </div>-- {/* Truncation banner — shown only when the current scope renders the- capped full graph and the server actually capped it. Constellation /- module scopes use their own endpoints, so the banner stays hidden. */}- {usesFullGraph && graphData?.truncated && graphData.total_node_count != null && (- <div className="shrink-0 px-4 sm:px-6 pt-3">+ <GraphCanvasShell+ title={isMap ? "Communities" : "Dependency Explorer"}+ description={+ isMap+ ? "Detected communities and how they connect — double-click a hub to blossom it"+ : "Explore dependencies, overlays and trace paths between files"+ }+ banner={+ // Shown only when the current scope renders the capped full graph and+ // the server actually capped it. Constellation / module scopes use+ // their own endpoints, so the banner stays hidden.+ usesFullGraph && graphData?.truncated && graphData.total_node_count != null ? (<GraphTruncationBannershown={graphData.nodes.length}total={graphData.total_node_count}@@ -167,35 +162,35 @@ export function GraphView({onLoadMore={(nextLimit) => setGraphLimit(nextLimit)}onSwitchToArchitecture={handleSwitchToArchitecture}/>- </div>- )}-- {/* Graph area */}- <div className="flex-1 overflow-hidden p-3">- <div className="h-full w-full rounded-lg border border-[var(--color-border-default)] overflow-hidden relative">- <GraphFlow- key={flowKey}+ ) : undefined+ }+ overlay={+ // Doc panel — shows on file click. Single right-rail surface.+ docNodeId ? (+ <GraphDocPanelrepoId={repoId}- initialViewMode={forcedViewMode ?? mountViewMode}- initialColorMode={initialColorMode}- initialSelectedNode={initialNode}- onNodeClick={handleNodeClick}- onNodeViewDocs={handleNodeViewDocs}- onCommunityPanelOpen={handleCommunityPanelOpen}- onViewModeChange={handleViewModeChange}- onColorModeChange={handleColorModeChange}+ nodeId={docNodeId}+ onClose={() => setDocNodeId(null)}/>-- {/* Doc panel — shows on file click. Single right-rail surface. */}- {docNodeId && (- <GraphDocPanel- repoId={repoId}- nodeId={docNodeId}- onClose={() => setDocNodeId(null)}- />- )}- </div>- </div>- </div>+ ) : undefined+ }+ >+ <GraphFlow+ key={flowKey}+ repoId={repoId}+ initialViewMode={forcedViewMode ?? mountViewMode}+ initialColorMode={initialColorMode}+ initialSelectedNode={initialNode}+ // Communities locks to the constellation; Explore drops the+ // constellation scope (it lives in the Knowledge Graph view) so the+ // toolbar offers only Modules / Full.+ availableScopes={scope === "explore" ? ["modules", "full"] : undefined}+ onNodeClick={handleNodeClick}+ onNodeViewDocs={handleNodeViewDocs}+ onCommunityPanelOpen={handleCommunityPanelOpen}+ onViewModeChange={handleViewModeChange}+ onColorModeChange={handleColorModeChange}+ />+ </GraphCanvasShell>);}diff --git a/packages/web/src/components/code-health/coverage-tab.tsx b/packages/web/src/components/code-health/coverage-tab.tsxindex 6375963ad..f1eaa0440 100644--- a/packages/web/src/components/code-health/coverage-tab.tsx+++ b/packages/web/src/components/code-health/coverage-tab.tsx@@ -25,6 +25,8 @@ import {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 { fileEntityPath } from "@repowise-dev/ui/shared/entity";import {@@ -258,37 +260,42 @@ function CoverageView({return (<div className="space-y-6"><div className="grid grid-cols-1 gap-3 sm:grid-cols-4">- <SummaryCard label="Files">- <span className="text-2xl font-bold tabular-nums text-[var(--color-text-primary)]">- {summary.file_count.toLocaleString()}- </span>- </SummaryCard>- <SummaryCard label="Line coverage">- <span className="text-2xl font-bold tabular-nums text-[var(--color-text-primary)]">- {summary.line_coverage_pct == null+ <MetricCard label="Files" value={summary.file_count.toLocaleString()} />+ <MetricCard+ label="Line coverage"+ value={+ summary.line_coverage_pct == null? "—"- : `${summary.line_coverage_pct.toFixed(1)}%`}- </span>- <p className="text-xs text-[var(--color-text-tertiary)] mt-1 tabular-nums">- {summary.covered_lines.toLocaleString()} /{" "}- {summary.total_lines.toLocaleString()} lines- </p>- </SummaryCard>- <SummaryCard label="Branch coverage">- <span className="text-2xl font-bold tabular-nums text-[var(--color-text-primary)]">- {summary.branch_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)}%`}- </span>- </SummaryCard>- <SummaryCard label="Source">- <span className="text-lg font-semibold text-[var(--color-text-primary)] uppercase">- {summary.source_format ?? "—"}- </span>- <p className="text-xs text-[var(--color-text-tertiary)] mt-1">- {summary.ingested_at ? new Date(summary.ingested_at).toLocaleString() : "never"}- </p>- </SummaryCard>+ : `${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)} />@@ -302,11 +309,14 @@ function CoverageView({<ModuleCoverageList modules={modules} /></section>- <section className="space-y-2">+ <CollapsibleSection+ title={`Files (${filteredFiles.length.toLocaleString()})`}+ defaultOpen={false}+ ><div className="flex items-center gap-2">- <h2 className="text-sm font-semibold text-[var(--color-text-primary)] mr-auto">- Files ({filteredFiles.length.toLocaleString()})- </h2>+ <span className="mr-auto text-xs text-[var(--color-text-tertiary)]">+ Per-file coverage — click a row for the line-level heatmap.+ </span><inputvalue={search}onChange={(e) => setSearch(e.target.value)}@@ -327,24 +337,7 @@ function CoverageView({/>}/>- </section>- </div>- );-}--function SummaryCard({- label,- children,-}: {- label: string;- children: React.ReactNode;-}) {- return (- <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-4">- <p className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-1">- {label}- </p>- {children}+ </CollapsibleSection></div>);}diff --git a/packages/web/src/components/code-health/trend-tab.tsx b/packages/web/src/components/code-health/trend-tab.tsxindex 3e92b9227..b10622eea 100644--- a/packages/web/src/components/code-health/trend-tab.tsx+++ b/packages/web/src/components/code-health/trend-tab.tsx@@ -1,33 +1,35 @@"use client";/**- * Trend tab — KPI history over recent indexes. Handles the single-snapshot- * case explicitly (no misleading flat chart) and renders per-file deltas on- * a ResponsiveTable.+ * 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.*/-import { AlertTriangle, TrendingDown, TrendingUp } from "lucide-react";-import useSWR from "swr";+import { AlertTriangle, TrendingUp } from "lucide-react";import { Skeleton } from "@repowise-dev/ui/ui/skeleton";-import { TrendChart, deltaColor, formatDelta } from "@repowise-dev/ui/health";-import { EmptyState } from "@repowise-dev/ui/shared/empty-state";-import { ResponsiveTable, type ResponsiveColumn } from "@repowise-dev/ui/shared";-import {- getHealthTrend,- type HealthTrendResponse,-} from "@/lib/api/code-health";--type FileDelta = HealthTrendResponse["file_deltas"][number];+ 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";-export function TrendTab({ repoId: id }: { repoId: string }) {- const { data, isLoading, error } = useSWR<HealthTrendResponse>(- `code-health-trend:${id}`,- () => getHealthTrend(id, 20),- { revalidateOnFocus: false },- );+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 (@@ -40,82 +42,30 @@ export function TrendTab({ repoId: id }: { repoId: string }) {const singleSnapshot = data.snapshot_count <= 1;- const deltaColumns: ResponsiveColumn<FileDelta>[] = [- {- key: "file_path",- header: "File",- priority: 1,- render: (d) => (- <span- className="font-mono text-xs text-[var(--color-text-primary)] truncate max-w-[420px] inline-block"- title={d.file_path}- >- {d.file_path}- </span>- ),- },- {- key: "before",- header: "Before",- priority: 2,- align: "right",- render: (d) => (- <span className="tabular-nums text-[var(--color-text-secondary)]">- {d.before.toFixed(1)}- </span>- ),- },- {- key: "after",- header: "After",- priority: 2,- align: "right",- render: (d) => (- <span className="tabular-nums text-[var(--color-text-secondary)]">- {d.after.toFixed(1)}- </span>- ),- },- {- key: "delta",- header: "Δ",- priority: 1,- align: "right",- render: (d) => (- <span className={`tabular-nums inline-flex items-center gap-1 ${deltaColor(d.delta)}`}>- {d.delta < 0 ? <TrendingDown className="h-3 w-3" /> : null}- {formatDelta(d.delta)}- </span>- ),- },- ];-return (<div className="space-y-6"><div className="grid grid-cols-1 md:grid-cols-3 gap-3">- <DeltaCard+ <DeltaMetriclabel="Average health"current={data.summary.current_average_health}previous={data.summary.previous_average_health}delta={data.summary.average_delta}/>- <DeltaCard+ <DeltaMetriclabel="Hotspot health"current={data.summary.current_hotspot_health}previous={data.summary.previous_hotspot_health}delta={data.summary.hotspot_delta}/>- <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-4">- <p className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider">- Snapshots- </p>- <p className="mt-1 text-2xl font-bold text-[var(--color-text-primary)] tabular-nums">- {data.snapshot_count}- </p>- <p className="text-[11px] text-[var(--color-text-tertiary)] mt-1">- rolling window: 50 max- </p>- </div>+ <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 ? (@@ -171,19 +121,14 @@ export function TrendTab({ repoId: id }: { repoId: string }) {}/>) : (- <ResponsiveTable- columns={deltaColumns}- rows={data.file_deltas}- rowKey={(d) => d.file_path}- stacked="sm"- />+ <TrendSlopeChart points={data.file_deltas} />)}</section></div>);}-function DeltaCard({+function DeltaMetric({label,current,previous,@@ -195,19 +140,23 @@ function DeltaCard({delta: number | null;}) {return (- <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-4">- <p className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider">- {label}- </p>- <p className="mt-1 text-2xl font-bold text-[var(--color-text-primary)] tabular-nums">- {current.toFixed(1)}- <span className="text-base font-normal text-[var(--color-text-secondary)]">/10</span>- </p>- <p className={`text-[11px] tabular-nums mt-0.5 ${deltaColor(delta)}`}>- {delta == null- ? "no prior snapshot"- : `${formatDelta(delta)} vs. ${previous?.toFixed(1) ?? "—"}`}- </p>- </div>+ <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/web/src/components/code-health/triage-tab.tsx b/packages/web/src/components/code-health/triage-tab.tsxindex eb69d39eb..a5931d1c4 100644--- a/packages/web/src/components/code-health/triage-tab.tsx+++ b/packages/web/src/components/code-health/triage-tab.tsx@@ -20,21 +20,28 @@ import {BiomarkerList,HotFunctionsPanel,HiddenCouplingList,- ImpactEffortQuadrant,+ CodeHealthMap,RecalibrationBanner,RefactoringTargetList,DefectAccuracyCard,+ FileSpotlight,+ FilterSelect,+ FilterChip,+ ViewToggle,+ ImpactEffortQuadrant,biomarkerLabel,buildAiPrompt,+ type CodeHealthMapFile,+ type CodeHealthOverlay,type FileSortField,type FindingStatus,type RefactoringTarget,type Severity,} from "@repowise-dev/ui/health";+import { CollapsibleSection } from "@repowise-dev/ui/shared/collapsible-section";import { Search } from "lucide-react";import {getHealthOverview,- getHealthTrend,getRefactoringTargets,listHealthFiles,listHealthFindings,@@ -62,7 +69,25 @@ const EFFORT_LABEL: Record<string, string> = {XL: "Extra large (>400 NLOC)",};-export function TriageTab({ repoId: id }: { repoId: string }) {+export function TriageTab({+ repoId: id,+ trend,+ overlay = "health",+ onOverlayChange,+ mapFiles,+ overlayLoading,+}: {+ repoId: string;+ /** Trend fetched once at the page level — feeds the KPI sparklines. */+ trend?: HealthTrendResponse;+ /** Active map lens, owned by the page so the spine is shared across tabs. */+ overlay?: CodeHealthOverlay;+ onOverlayChange?: (overlay: CodeHealthOverlay) => void;+ /** Map files fetched once at the page level (shared across overlays). */+ mapFiles?: HealthFilesResponse;+ /** 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),@@ -98,12 +123,6 @@ export function TriageTab({ repoId: id }: { repoId: string }) {{ revalidateOnFocus: false },);- const { data: trend } = useSWR<HealthTrendResponse>(- `code-health-trend:${id}`,- () => getHealthTrend(id, 20),- { 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");@@ -114,7 +133,10 @@ export function TriageTab({ repoId: id }: { repoId: string }) {const [view, setView] = useState<QueueView>("queue");const [selectedFile, setSelectedFile] = useState<string | null>(null);const [promptTarget, setPromptTarget] = useState<RefactoringTarget | null>(null);- const [highlighted, setHighlighted] = useState<string | null>(null);++ // ---- Map-driven UI: rail spotlight + filename dim + collapsible list ----+ const [hoverFile, setHoverFile] = useState<CodeHealthMapFile | null>(null);+ const [mapQuery, setMapQuery] = useState("");const queueKey = useMemo(() => JSON.stringify({ id, biomarker, minSeverity, maxEffort, sort, queueLimit }),@@ -217,20 +239,6 @@ export function TriageTab({ repoId: id }: { repoId: string }) {return [...groups.entries()].map(([key, targets]) => ({ key, targets }));}, [queue, groupBy]);- // Quadrant dot click → highlight + scroll to the card.- const highlightTarget = (path: string) => {- setHighlighted(path);- requestAnimationFrame(() => {- document- .querySelector(`[data-refactoring-card="${CSS.escape(path)}"]`)- ?.scrollIntoView({ behavior: "smooth", block: "center" });- });- window.setTimeout(- () => setHighlighted((p) => (p === path ? null : p)),- 2400,- );- };-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@@ -268,30 +276,105 @@ export function TriageTab({ repoId: id }: { repoId: string }) {<DefectAccuracyCard data={overview.defect_accuracy} collapsible />) : null}- <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">- <div className="lg:col-span-2 space-y-3">- <div className="flex flex-wrap items-center gap-2">+ {/* 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 className="flex items-center gap-2"><h2 className="text-sm font-medium uppercase tracking-wider text-[var(--color-text-tertiary)] mr-auto">- Fix next+ Findings</h2>- <ViewToggle view={view} onChange={setView} />+ <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}+ onSelect={(f) => setSelectedFile(f.file_path)}+ />+ </div>+ </aside>+ </div>++ {/* Collapsible: the full ranked queue + file inventory. The severity+ filter is shared with the rail above (one control, no duplicate). */}+ <CollapsibleSection+ title="Targets & 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="Severity"- value={minSeverity}- onChange={(v) => setMinSeverity(v as Severity | "all")}- options={[- { value: "all", label: "Any severity" },- { value: "low", label: "Low+" },- { value: "medium", label: "Medium+" },- { value: "high", label: "High+" },- { value: "critical", label: "Critical only" },- ]}- /><FilterSelectlabel="Biomarker"value={biomarker}@@ -349,17 +432,19 @@ export function TriageTab({ repoId: id }: { repoId: string }) {/>) : (<>+ {/* 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) => ({+ 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) => highlightTarget(p.file_path)}+ onSelect={(p) => setSelectedFile(p.file_path)}/>-<div className="space-y-6">{grouped.map((g) => (<section key={g.key} className="space-y-2">@@ -376,7 +461,6 @@ export function TriageTab({ repoId: id }: { repoId: string }) {onSelect={(t) => setSelectedFile(t.file_path)}onStatusChange={handleStatus}onGeneratePrompt={(t) => setPromptTarget(t)}- highlightedPath={highlighted}/></section>))}@@ -469,37 +553,12 @@ export function TriageTab({ repoId: id }: { repoId: string }) {</>)}</div>-- <div className="space-y-3">- <div className="flex items-center gap-2">- <h2 className="text-sm font-medium uppercase tracking-wider text-[var(--color-text-tertiary)] mr-auto">- Findings- </h2>- <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>- <BiomarkerList- findings={overview.top_findings}- grouped- minSeverity={minSeverity === "all" ? undefined : minSeverity}- onSelect={(f) => setSelectedFile(f.file_path)}- />- </div>- </div>+ </CollapsibleSection>{hotFunctionFindings && hotFunctionFindings.length >= 3 ? (<HotFunctionsPanelfindings={hotFunctionFindings}+ collapsibleonSelect={(f) => setSelectedFile(f.file_path)}symbolHrefFor={(f) =>f.symbol_id ? symbolEntityPath(`/repos/${id}`, f.symbol_id) : undefined@@ -510,6 +569,7 @@ export function TriageTab({ repoId: id }: { repoId: string }) {{couplingFindings && couplingFindings.length >= 3 ? (<HiddenCouplingListfindings={couplingFindings}+ collapsibleonSelect={(path) => setSelectedFile(path)}/>) : null}@@ -539,88 +599,3 @@ export function TriageTab({ repoId: id }: { repoId: string }) {</div>);}--function ViewToggle({- view,- onChange,-}: {- view: QueueView;- onChange: (v: QueueView) => void;-}) {- return (- <div className="flex rounded-md border border-[var(--color-border-default)] overflow-hidden text-xs">- {(- [- { value: "queue", label: "Queue" },- { value: "files", label: "All files" },- ] as { value: QueueView; label: string }[]- ).map((opt) => (- <button- key={opt.value}- type="button"- onClick={() => onChange(opt.value)}- className={`px-3 py-1.5 font-medium transition-colors ${- view === opt.value- ? "bg-[var(--color-accent-primary)] text-[var(--color-text-inverse)]"- : "bg-transparent text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)]"- }`}- >- {opt.label}- </button>- ))}- </div>- );-}--function FilterSelect({- label,- value,- onChange,- options,-}: {- label: string;- value: string;- onChange: (v: string) => void;- options: { value: string; label: string }[];-}) {- return (- <label className="inline-flex items-center gap-1.5 text-xs text-[var(--color-text-tertiary)]">- <span className="uppercase tracking-wider">{label}</span>- <select- value={value}- onChange={(e) => onChange(e.target.value)}- className="text-xs px-2 py-1 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] text-[var(--color-text-primary)]"- >- {options.map((o) => (- <option key={o.value} value={o.value}>- {o.label}- </option>- ))}- </select>- </label>- );-}--function FilterChip({- active,- onClick,- children,-}: {- active: boolean;- onClick: () => void;- children: React.ReactNode;-}) {- return (- <button- type="button"- onClick={onClick}- className={`text-xs rounded-md px-2 py-1 border transition-colors ${- active- ? "bg-[var(--color-accent-muted)] text-[var(--color-accent-primary)] border-[var(--color-accent-primary)]/50"- : "border-[var(--color-border-default)] text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] hover:border-[var(--color-border-strong)]"- }`}- >- {children}- </button>- );-}diff --git a/packages/web/src/components/commits/commits-explorer.tsx b/packages/web/src/components/commits/commits-explorer.tsxindex b222b3bca..7656833ec 100644--- a/packages/web/src/components/commits/commits-explorer.tsx+++ b/packages/web/src/components/commits/commits-explorer.tsx@@ -20,7 +20,8 @@ import {import { CommitDetailCard } from "@repowise-dev/ui/commits/commit-detail-card";import { CredibilityStrip } from "@repowise-dev/ui/commits/credibility-strip";import { AgentTrendStrip } from "@repowise-dev/ui/commits/agent-trend-strip";-import { getAgentTrend, getCommit, getCommitsPage } from "@/lib/api/git";+import { RiskDistributionChart } from "@repowise-dev/ui/git/risk-distribution-chart";+import { getAgentTrend, getCommit, getCommitsPage, getHotspots } from "@/lib/api/git";import type { CommitResponse, Paginated } from "@/lib/api/types";const PAGE_SIZE = 50;@@ -45,6 +46,14 @@ export function CommitsExplorer({ repoId }: { repoId: string }) {{ revalidateOnFocus: false },);+ // Repo-relative risk distribution — turns the credibility strip's+ // "relative to this repo" claim into a picture.+ const { data: hotspots } = useSWR(+ `commits-risk-dist:${repoId}`,+ () => getHotspots(repoId, 25),+ { revalidateOnFocus: false },+ );+const { data: detail, isLoading: detailLoading } = useSWR(selectedSha ? `commit:${repoId}:${selectedSha}` : null,() => getCommit(repoId, selectedSha as string),@@ -84,6 +93,15 @@ export function CommitsExplorer({ repoId }: { repoId: string }) {<div className="space-y-6"><CredibilityStrip />+ {hotspots && hotspots.length > 0 && (+ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-4">+ <p className="mb-2 text-xs font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">+ Risk distribution across the riskiest files+ </p>+ <RiskDistributionChart hotspots={hotspots} maxBars={25} />+ </div>+ )}+{trend && <AgentTrendStrip trend={trend} />}<div className="grid grid-cols-2 gap-3 sm:grid-cols-4">diff --git a/packages/web/src/components/coupling/coupling-tab.tsx b/packages/web/src/components/coupling/coupling-tab.tsxnew file mode 100644index 000000000..4b6289d06--- /dev/null+++ b/packages/web/src/components/coupling/coupling-tab.tsx@@ -0,0 +1,44 @@+"use client";++import useSWR from "swr";+import { ApiError } from "@repowise-dev/ui/shared/api-error";+import { Skeleton } from "@repowise-dev/ui/ui/skeleton";+import { getCoupling } from "@/lib/api/coupling";+import { CouplingView } from "@/components/coupling/coupling-view";++/**+ * Self-fetching host for the change-coupling Architecture tab. The Architecture+ * page is a client component, so coupling data is fetched here via SWR (mirrors+ * how the impact analyzer self-fetches) rather than on the server. The diagram+ * and table stay in `@repowise-dev/ui/coupling` so package bumps propagate them.+ */+export function CouplingTab({ repoId }: { repoId: string }) {+ const { data, error, isLoading, mutate } = useSWR(+ `coupling:${repoId}`,+ () => getCoupling(repoId, { limit: 200 }),+ { revalidateOnFocus: false },+ );++ return (+ <div className="space-y-6">+ {error ? (+ <ApiError+ title="Couldn't load change coupling"+ message={error instanceof Error ? error.message : String(error)}+ onRetry={() => void mutate()}+ />+ ) : isLoading || !data ? (+ <div className="space-y-4">+ <Skeleton className="mx-auto h-[420px] w-full max-w-[820px] rounded-xl" />+ <div className="space-y-2">+ {Array.from({ length: 6 }).map((_, i) => (+ <Skeleton key={i} className="h-10" />+ ))}+ </div>+ </div>+ ) : (+ <CouplingView data={data} />+ )}+ </div>+ );+}diff --git a/packages/web/src/components/coupling/coupling-view.tsx b/packages/web/src/components/coupling/coupling-view.tsxindex bd8f2b52a..bb0cb7be1 100644--- a/packages/web/src/components/coupling/coupling-view.tsx+++ b/packages/web/src/components/coupling/coupling-view.tsx@@ -2,6 +2,7 @@import { useState } from "react";import { CouplingGraph, CouplingTable } from "@repowise-dev/ui/coupling";+import { GraphCanvasShell } from "@repowise-dev/ui/graph/graph-canvas-shell";import type { CouplingGraphResponse } from "@repowise-dev/types/coupling";interface CouplingViewProps {@@ -12,22 +13,29 @@ interface CouplingViewProps {* Hosts the coupling diagram (centerpiece) and the precise ranked table below* it, sharing a single `focusedPath` so hovering the ring emphasizes the table* rows and clicking a row lifts the ring — one focus model across both.+ *+ * One airy column: an un-boxed diagram on the page background → thin divider →+ * borderless table. No card chrome, no in-diagram header (the surrounding tab+ * hint supplies the one-liner).*/export function CouplingView({ data }: CouplingViewProps) {const [focusedPath, setFocusedPath] = useState<string | null>(null);return (<div className="space-y-5">- <div className="mx-auto w-full max-w-[820px]">- <CouplingGraph- nodes={data.nodes}- edges={data.edges}- totalEdges={data.total_edges}- focusedPath={focusedPath}- onFocusChange={setFocusedPath}- />- </div>- <div className="rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-1.5">+ <GraphCanvasShell className="block h-auto">+ <div className="mx-auto w-full max-w-[820px]">+ <CouplingGraph+ nodes={data.nodes}+ edges={data.edges}+ totalEdges={data.total_edges}+ focusedPath={focusedPath}+ onFocusChange={setFocusedPath}+ />+ </div>+ </GraphCanvasShell>++ <div className="border-t border-[var(--color-border-default)] pt-4"><CouplingTableedges={data.edges}focusedPath={focusedPath}diff --git a/packages/web/src/components/decisions/decision-detail.tsx b/packages/web/src/components/decisions/decision-detail.tsxindex 0c5d5b391..e9504b7b9 100644--- a/packages/web/src/components/decisions/decision-detail.tsx+++ b/packages/web/src/components/decisions/decision-detail.tsx@@ -238,7 +238,7 @@ export function DecisionDetail({ decision, repoId }: DecisionDetailProps) {<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-red-500" : ""}>+ <span className={decision.staleness_score > 0.5 ? "text-[var(--color-error)]" : ""}>Staleness: {decision.staleness_score.toFixed(2)}</span>)}@@ -248,7 +248,7 @@ export function DecisionDetail({ decision, repoId }: DecisionDetailProps) {{/* Stale warning */}{decision.staleness_score > 0.5 && (- <div className="rounded-md border border-amber-400/30 bg-amber-50 px-4 py-3 text-sm text-amber-800 dark:bg-amber-900/20 dark:text-amber-200">+ <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>)}@@ -374,7 +374,7 @@ export function DecisionDetail({ decision, repoId }: DecisionDetailProps) {<buttononClick={() => handleStatusChange("deprecated")}disabled={loading}- className="rounded-md border border-red-300 px-3 py-1.5 text-sm text-red-600 hover:bg-red-50 dark:border-red-800 dark:text-red-400 dark:hover:bg-red-900/20 disabled:opacity-50"+ 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>diff --git a/packages/web/src/components/decisions/decision-graph-wrapper.tsx b/packages/web/src/components/decisions/decision-graph-wrapper.tsxindex 47647e1ec..88eda3d37 100644--- a/packages/web/src/components/decisions/decision-graph-wrapper.tsx+++ b/packages/web/src/components/decisions/decision-graph-wrapper.tsx@@ -9,16 +9,21 @@ import { getDecisionGraph } from "@/lib/api/decisions";interface DecisionGraphWrapperProps {repoId: string;+ /**+ * Graph-first: render the canvas as the primary surface (fetched immediately,+ * no collapse chrome). When false the graph stays a collapsible drill-down.+ */+ primary?: boolean;}/**- * Collapsible decision-graph section for the decisions list page. SWR-fetches- * the graph only once expanded, then renders the shared DecisionGraphView.+ * Decision-graph section. As the primary surface it fetches on mount and fills+ * a tall canvas; otherwise it is a collapsible that fetches once expanded.* Clicking a node navigates to that decision's detail page.*/-export function DecisionGraphWrapper({ repoId }: DecisionGraphWrapperProps) {+export function DecisionGraphWrapper({ repoId, primary = false }: DecisionGraphWrapperProps) {const router = useRouter();- const [open, setOpen] = React.useState(false);+ const [open, setOpen] = React.useState(primary);const { data, isLoading } = useSWR(open ? `decision-graph:${repoId}` : null,@@ -26,6 +31,18 @@ export function DecisionGraphWrapper({ repoId }: DecisionGraphWrapperProps) {{ revalidateOnFocus: false },);+ if (primary) {+ return (+ <div className="h-[560px] rounded-lg border border-[var(--color-border-default)]">+ <DecisionGraphView+ graph={data}+ isLoading={isLoading}+ onSelectDecision={(id) => router.push(`/repos/${repoId}/decisions/${id}`)}+ />+ </div>+ );+ }+return (<div className="rounded-lg border border-[var(--color-border-default)]"><buttondiff --git a/packages/web/src/components/decisions/decision-health-widget-wrapper.tsx b/packages/web/src/components/decisions/decision-health-widget-wrapper.tsxdeleted file mode 100644index 15fc470a1..000000000--- a/packages/web/src/components/decisions/decision-health-widget-wrapper.tsx+++ /dev/null@@ -1,20 +0,0 @@-"use client";--import useSWR from "swr";-import { DecisionHealthWidget } from "@repowise-dev/ui/decisions/decision-health-widget";-import { getDecisionHealth } from "@/lib/api/decisions";--interface DecisionHealthWidgetWrapperProps {- repoId: string;-}--export function DecisionHealthWidgetWrapper({- repoId,-}: DecisionHealthWidgetWrapperProps) {- const { data: health } = useSWR(- `/api/repos/${repoId}/decisions/health`,- () => getDecisionHealth(repoId),- );-- return <DecisionHealthWidget health={health} />;-}diff --git a/packages/web/src/components/docs/docs-header.tsx b/packages/web/src/components/docs/docs-header.tsxindex c08daf570..2ed7027f7 100644--- a/packages/web/src/components/docs/docs-header.tsx+++ b/packages/web/src/components/docs/docs-header.tsx@@ -2,62 +2,41 @@import Link from "next/link";import { useParams, usePathname } from "next/navigation";-import { BookOpen, BarChart3 } from "lucide-react";-import { cn } from "@/lib/utils/cn";+import {+ DocsHeader as DocsHeaderShell,+ type DocsHeaderTab,+} from "@repowise-dev/ui/docs/docs-header";// "Doc freshness", not "Coverage" — coverage means test coverage everywhere// else in the app; this tab is about documentation staleness.const TABS = [- { label: "Explorer", segment: "", icon: BookOpen },- { label: "Doc freshness", segment: "/coverage", icon: BarChart3 },-] as const;+ { label: "Explorer", segment: "", icon: "explorer" as const },+ { label: "Doc freshness", segment: "/coverage", icon: "freshness" as const },+];/**- * Single compact chrome row for the Docs surface: title, the- * Explorer / Coverage view switch as a segmented control, and a right-aligned- * slot for page-specific actions. Replaces the old two-row stack- * (underline tabs row + title/actions row).+ * Web wrapper: resolves the route-aware tab list and injects Next's ``Link``+ * into the presentational ``DocsHeader`` ui shell.*/export function DocsHeader({ children }: { children?: React.ReactNode }) {const pathname = usePathname();const { id } = useParams<{ id: string }>();const basePath = `/repos/${id}/docs`;- return (- <div className="shrink-0 flex h-12 items-center gap-3 border-b border-[var(--color-border-default)] px-4 sm:px-6">- <h1 className="text-sm font-semibold text-[var(--color-text-primary)]">- Documentation- </h1>-- <nav- className="flex items-center rounded-lg bg-[var(--color-bg-elevated)] p-0.5"- aria-label="Docs views"- >- {TABS.map((tab) => {- const href = `${basePath}${tab.segment}`;- const isActive =- tab.segment === "" ? pathname === basePath : pathname.startsWith(href);- const Icon = tab.icon;- return (- <Link- key={tab.segment}- href={href}- aria-current={isActive ? "page" : undefined}- className={cn(- "flex items-center gap-1.5 rounded-md px-2.5 py-1 text-xs font-medium transition-colors",- isActive- ? "bg-[var(--color-bg-surface)] text-[var(--color-text-primary)] shadow-sm"- : "text-[var(--color-text-tertiary)] hover:text-[var(--color-text-secondary)]",- )}- >- <Icon className="h-3.5 w-3.5" />- {tab.label}- </Link>- );- })}- </nav>+ const tabs: DocsHeaderTab[] = TABS.map((tab) => {+ const href = `${basePath}${tab.segment}`;+ return {+ label: tab.label,+ href,+ icon: tab.icon,+ isActive:+ tab.segment === "" ? pathname === basePath : pathname.startsWith(href),+ };+ });- <div className="ml-auto flex items-center gap-2">{children}</div>- </div>+ return (+ <DocsHeaderShell tabs={tabs} LinkComponent={Link}>+ {children}+ </DocsHeaderShell>);}diff --git a/packages/web/src/components/docs/docs-page-actions.tsx b/packages/web/src/components/docs/docs-page-actions.tsxindex 633b0769b..aba92a953 100644--- a/packages/web/src/components/docs/docs-page-actions.tsx+++ b/packages/web/src/components/docs/docs-page-actions.tsx@@ -1,32 +1,17 @@"use client";-import { useState } from "react";import {- ChevronDown,- Download,- ExternalLink,- FileText,- FolderArchive,- Loader2,- PanelRight,- PanelRightClose,-} from "lucide-react";-import { Button } from "@repowise-dev/ui/ui/button";-import { ConfidenceBadge } from "@repowise-dev/ui/wiki/confidence-badge";-import {- READER_PERSONAS,- type ReaderPersona,-} from "@repowise-dev/ui/docs/reader-persona";-import { cn } from "@/lib/utils/cn";+ DocsPageActions as DocsPageActionsShell,+ ExportMenu as ExportMenuShell,+ SidebarToggle,+} from "@repowise-dev/ui/docs/docs-page-actions";import { downloadTextFile } from "@/lib/utils/download";+import type { ReaderPersona } from "@repowise-dev/ui/docs/reader-persona";import type { PageResponse } from "@/lib/api/types";-/**- * Per-page controls for the DocsHeader row — the compact freshness badge and- * the reader-level control that used to live in a second sticky row above the- * article. The reader control renders only when filtering actually changes- * this page (see personaFilteringApplies); on curated pages it disappears.- */+export { SidebarToggle };++/** Web wrapper: maps the page object onto the presentational actions shell. */export function DocsPageActions({page,persona,@@ -39,85 +24,33 @@ export function DocsPageActions({personaHasEffect: boolean;}) {return (- <>- <ConfidenceBadge score={page.confidence} status={page.freshness_status} />- {personaHasEffect && (- <div- className="inline-flex items-center rounded-md border border-[var(--color-border-default)] p-0.5 shrink-0"- role="group"- aria-label="Reader level"- >- {READER_PERSONAS.map((p) => (- <button- key={p.value}- onClick={() => setPersona(p.value)}- title={p.hint}- className={cn(- "rounded px-1.5 py-0.5 text-[10px] font-medium transition-colors",- persona === p.value- ? "bg-[var(--color-accent-primary)] text-[var(--color-text-inverse)]"- : "text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)]",- )}- >- {p.label}- </button>- ))}- </div>- )}- </>- );-}--/** Insights-drawer toggle — header-resident; the drawer itself is lg-only. */-export function SidebarToggle({- open,- onToggle,-}: {- open: boolean;- onToggle: () => void;-}) {- return (- <button- onClick={onToggle}- className={cn(- "hidden lg:inline-flex rounded-md p-1.5 transition-colors",- open- ? "text-[var(--color-accent)] hover:bg-[var(--color-bg-elevated)]"- : "text-[var(--color-text-tertiary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-accent-primary)]",- )}- title={open ? "Hide insights" : "Show insights"}- aria-pressed={open}- >- {open ? (- <PanelRightClose className="h-3.5 w-3.5" />- ) : (- <PanelRight className="h-3.5 w-3.5" />- )}- </button>+ <DocsPageActionsShell+ confidence={page.confidence}+ freshnessStatus={page.freshness_status}+ persona={persona}+ setPersona={setPersona}+ personaHasEffect={personaHasEffect}+ />);}/**- * Single Export menu — the former standalone download/open-external icon- * buttons fold in here as per-page items, above the repo-wide exports.+ * Web wrapper around the Export menu shell — owns the actual download+ * side-effects (single-page + all-pages markdown writes).*/export function ExportMenu({isExporting,onExportAll,zipHref,page,- repoId,}: {isExporting: boolean;onExportAll: () => void;zipHref: string;page: PageResponse | null;- repoId: string;+ /** Accepted for call-site compatibility; the shell builds hrefs itself. */+ repoId?: string;}) {- const [open, setOpen] = useState(false);- const itemClass =- "flex w-full items-center gap-2 rounded px-2 py-1.5 text-xs text-[var(--color-text-secondary)] transition-colors hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]";-const exportPage = () => {if (!page) return;const filename = (page.target_path || page.title).replace(/\//g, "_") + ".md";@@ -126,79 +59,12 @@ export function ExportMenu({};return (- <div className="relative">- <Button- variant="outline"- size="sm"- onClick={() => setOpen((o) => !o)}- disabled={isExporting}- aria-haspopup="menu"- aria-expanded={open}- >- {isExporting ? (- <Loader2 className="h-3.5 w-3.5 mr-1.5 animate-spin" />- ) : (- <Download className="h-3.5 w-3.5 mr-1.5" />- )}- Export- <ChevronDown className="h-3 w-3 ml-1 opacity-60" />- </Button>- {open && (- <>- <div className="fixed inset-0 z-10" onClick={() => setOpen(false)} />- <div- role="menu"- className="absolute right-0 top-full z-20 mt-1 w-52 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-1 shadow-md"- >- {page && (- <>- <button- role="menuitem"- className={itemClass}- onClick={() => {- setOpen(false);- exportPage();- }}- >- <Download className="h-3.5 w-3.5 shrink-0" />- This page (Markdown)- </button>- <a- role="menuitem"- href={`/repos/${repoId}/wiki/${encodeURIComponent(page.id)}`}- className={itemClass}- onClick={() => setOpen(false)}- >- <ExternalLink className="h-3.5 w-3.5 shrink-0" />- Open full page- </a>- <div className="my-1 border-t border-[var(--color-border-default)]" />- </>- )}- <button- role="menuitem"- className={itemClass}- onClick={() => {- setOpen(false);- onExportAll();- }}- >- <FileText className="h-3.5 w-3.5 shrink-0" />- All pages (Markdown)- </button>- <a- role="menuitem"- href={zipHref}- download- className={itemClass}- onClick={() => setOpen(false)}- >- <FolderArchive className="h-3.5 w-3.5 shrink-0" />- ZIP archive- </a>- </div>- </>- )}- </div>+ <ExportMenuShell+ isExporting={isExporting}+ onExportPage={exportPage}+ onExportAll={onExportAll}+ zipHref={zipHref}+ hasPage={!!page}+ />);}diff --git a/packages/web/src/components/docs/docs-viewer.tsx b/packages/web/src/components/docs/docs-viewer.tsxindex 37f1da8d4..bfdf7ba83 100644--- a/packages/web/src/components/docs/docs-viewer.tsx+++ b/packages/web/src/components/docs/docs-viewer.tsx@@ -1,61 +1,45 @@"use client";-import { useCallback, useEffect, useMemo, useRef } from "react";+import { useCallback } from "react";import Link from "next/link";import useSWR from "swr";import {- FileText,- Clock,- Cpu,- StickyNote,- ArrowRight,- ArrowLeft,- Loader2,- Network,Activity,+ Network,GitBranch,- Layers,+ ArrowRight,Flame,- FileInput,} from "lucide-react";import { cn } from "@/lib/utils/cn";import { getGitMetadata } from "@/lib/api/git";-import { WikiMarkdown } from "@repowise-dev/ui/wiki/wiki-markdown";-import { getBacklinks, getWikiLinks } from "@repowise-dev/ui/wiki/wiki-links-types";-import { TableOfContents } from "@repowise-dev/ui/wiki/table-of-contents";-import { computeDocNav } from "@repowise-dev/ui/docs/doc-nav";-import { Breadcrumb } from "@repowise-dev/ui/shared/breadcrumb";-import { BacklinksPanel } from "@repowise-dev/ui/wiki/backlinks-panel";-import { getPageTypeLabel } from "@repowise-dev/ui/lib/page-types";-import {- type ReaderPersona,- filterMarkdownByPersona,-} from "@repowise-dev/ui/docs/reader-persona";-import { VersionHistoryWrapper } from "@/components/wiki/version-history";+import { DocsReader } from "@repowise-dev/ui/docs/docs-reader";import { Badge } from "@repowise-dev/ui/ui/badge";import { Skeleton } from "@repowise-dev/ui/ui/skeleton";-import { formatRelativeTime, formatTokens } from "@repowise-dev/ui/lib/format";+import { VersionHistoryWrapper } from "@/components/wiki/version-history";+import { SecurityPanelWrapper } from "@/components/wiki/security-panel";import { useGraphMetrics, useCallersCallees } from "@/lib/hooks/use-graph";+import type { ReaderPersona } from "@repowise-dev/ui/docs/reader-persona";+import type { DocPage } from "@repowise-dev/types/docs";import type { PageResponse } from "@/lib/api/types";function PercentileBar({ value, label }: { value: number; label: string }) {const pct = 100 - value;return (<div className="flex items-center justify-between gap-2">- <span className="text-[11px] text-[var(--color-text-tertiary)] shrink-0">{label}</span>+ <span className="text-xs text-[var(--color-text-tertiary)] shrink-0">{label}</span><div className="flex items-center gap-1.5"><div className="w-16 h-1.5 rounded-full bg-[var(--color-bg-elevated)] overflow-hidden"><divclassName={cn("h-full rounded-full",- value >= 75 ? "bg-green-400" : value >= 50 ? "bg-yellow-400" : "bg-[var(--color-text-tertiary)]",+ value >= 75 ? "bg-[var(--color-success)]" : value >= 50 ? "bg-[var(--color-warning)]" : "bg-[var(--color-text-tertiary)]",)}style={{ width: `${value}%` }}/></div><span className={cn("text-[10px] font-mono tabular-nums w-10 text-right",- value >= 75 ? "text-green-400" : value >= 50 ? "text-yellow-400" : "text-[var(--color-text-tertiary)]",+ value >= 75 ? "text-[var(--color-success)]" : value >= 50 ? "text-[var(--color-warning)]" : "text-[var(--color-text-tertiary)]",)}>Top {pct}%</span>@@ -90,7 +74,7 @@ function DocsSidebar({ repoId, targetPath }: { repoId: string; targetPath: strin<div><div className="flex items-center gap-1.5 mb-2"><Activity className="h-3 w-3 text-[var(--color-text-tertiary)]" />- <span className="text-[11px] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider">+ <span className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider">Importance</span></div>@@ -98,8 +82,8 @@ function DocsSidebar({ repoId, targetPath }: { repoId: string; targetPath: strin<PercentileBar value={metrics.pagerank_percentile} label="PageRank" /><PercentileBar value={metrics.betweenness_percentile} label="Centrality" /><div className="flex items-center justify-between">- <span className="text-[11px] text-[var(--color-text-tertiary)]">Degree</span>- <span className="text-[11px] font-mono text-[var(--color-text-secondary)]">+ <span className="text-xs text-[var(--color-text-tertiary)]">Degree</span>+ <span className="text-xs font-mono text-[var(--color-text-secondary)]">{metrics.in_degree} in · {metrics.out_degree} out</span></div>@@ -114,13 +98,13 @@ function DocsSidebar({ repoId, targetPath }: { repoId: string; targetPath: strin<div><div className="flex items-center gap-1.5 mb-2"><Network className="h-3 w-3 text-[var(--color-text-tertiary)]" />- <span className="text-[11px] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider">+ <span className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider">Community</span></div><Linkhref={`/repos/${repoId}/architecture?view=graph&colorMode=community`}- className="inline-flex items-center gap-1 text-[11px] text-[var(--color-accent)] hover:underline"+ className="inline-flex items-center gap-1 text-xs text-[var(--color-accent)] hover:underline">{metrics.community_label}<ArrowRight className="h-2.5 w-2.5" />@@ -133,7 +117,7 @@ function DocsSidebar({ repoId, targetPath }: { repoId: string; targetPath: strin<div><div className="flex items-center gap-1.5 mb-2"><GitBranch className="h-3 w-3 text-[var(--color-text-tertiary)]" />- <span className="text-[11px] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider">+ <span className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider">Call Graph</span></div>@@ -141,7 +125,7 @@ function DocsSidebar({ repoId, targetPath }: { repoId: string; targetPath: strin<div className="mb-2"><p className="text-[10px] text-[var(--color-text-tertiary)] mb-1">Called by ({callData.caller_count})</p>{callData.callers.slice(0, 5).map((c) => (- <p key={c.symbol_id} className="text-[11px] font-mono text-[var(--color-text-secondary)] truncate pl-2" title={c.symbol_id}>+ <p key={c.symbol_id} className="text-xs font-mono text-[var(--color-text-secondary)] truncate pl-2" title={c.symbol_id}>{c.name}</p>))}@@ -151,7 +135,7 @@ function DocsSidebar({ repoId, targetPath }: { repoId: string; targetPath: strin<div><p className="text-[10px] text-[var(--color-text-tertiary)] mb-1">Calls ({callData.callee_count})</p>{callData.callees.slice(0, 5).map((c) => (- <p key={c.symbol_id} className="text-[11px] font-mono text-[var(--color-text-secondary)] truncate pl-2" title={c.symbol_id}>+ <p key={c.symbol_id} className="text-xs font-mono text-[var(--color-text-secondary)] truncate pl-2" title={c.symbol_id}>{c.name}</p>))}@@ -165,8 +149,8 @@ function DocsSidebar({ repoId, targetPath }: { repoId: string; targetPath: strin/*** Consolidated "At a glance" signals for a file page — hotspot, ownership,- * churn, bus factor — pulled from the existing git-metadata endpoint so the- * reader doesn't have to leave the wiki to learn how risky/owned a file is.+ * churn, bus factor — pulled from the git-metadata endpoint so the reader+ * doesn't have to leave the doc to learn how risky/owned a file is.* Renders nothing for non-file pages or files without git history.*/function AtAGlance({ repoId, targetPath }: { repoId: string; targetPath: string }) {@@ -187,7 +171,7 @@ function AtAGlance({ repoId, targetPath }: { repoId: string; targetPath: string<div><div className="flex items-center gap-1.5 mb-2"><Flame className="h-3 w-3 text-[var(--color-text-tertiary)]" />- <span className="text-[11px] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider">+ <span className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider">At a glance</span></div>@@ -207,7 +191,7 @@ function AtAGlance({ repoId, targetPath }: { repoId: string; targetPath: string</Badge>)}</div>- <div className="mt-2 space-y-1 text-[11px] text-[var(--color-text-secondary)]">+ <div className="mt-2 space-y-1 text-xs text-[var(--color-text-secondary)]">{data.primary_owner_name && (<div className="flex items-center justify-between gap-2"><span className="text-[var(--color-text-tertiary)]">Owner</span>@@ -247,12 +231,16 @@ interface DocsViewerProps {isLoading?: boolean;/** Select another page in-place (breadcrumb / prev-next / wiki links). */onSelectPage?: (page: PageResponse) => void;- /** Reader level + insights-drawer state — owned by DocsExplorer, which- renders the controls in the DocsHeader row. */persona: ReaderPersona;sidebarOpen: boolean;}+/**+ * Web data wrapper around the presentational ``DocsReader`` ui shell. Owns the+ * data-bound rail sections (git "at a glance", graph intelligence, version+ * history) and the Next route shape; the reader layout itself lives in ui so+ * the redesign ships through the package bump.+ */export function DocsViewer({page,pages = [],@@ -262,480 +250,67 @@ export function DocsViewer({persona,sidebarOpen,}: DocsViewerProps) {- const scrollRef = useRef<HTMLDivElement>(null);-- // In-app navigation to another page by id (used by breadcrumbs, prev/next,- // and resolved wiki links). Falls back to the full wiki route when the- // target isn't in the loaded list or no handler was supplied.- const goToPageId = useCallback(- (pageId: string) => {- const target = pages.find((p) => p.id === pageId);- if (target && onSelectPage) onSelectPage(target);- else- window.location.href = `/repos/${repoId}/wiki/${encodeURIComponent(pageId)}`;- },- [pages, onSelectPage, repoId],- );-- // Scroll to top when page changes- useEffect(() => {- scrollRef.current?.scrollTo(0, 0);- }, [page?.id]);-- if (isLoading) {- return (- <div className="flex items-center justify-center h-full">- <Loader2 className="h-5 w-5 animate-spin text-[var(--color-accent-primary)]" />- </div>- );- }-- if (!page) {- return (- <div className="flex flex-col items-center justify-center h-full gap-4 text-center px-8">- <div className="rounded-full bg-[var(--color-bg-elevated)] border border-[var(--color-border-default)] p-4">- <FileText className="h-8 w-8 text-[var(--color-text-tertiary)]" />- </div>- <div className="space-y-1">- <h3 className="text-sm font-semibold text-[var(--color-text-primary)]">- Select a page- </h3>- <p className="text-xs text-[var(--color-text-secondary)] max-w-sm">- Choose a file or module from the tree to view its AI-generated documentation.- </p>- </div>- </div>- );- }-- const hasTargetPath = !!page.target_path;-- return (- <DocsViewerBody- page={page}- pages={pages}- repoId={repoId}- hasTargetPath={hasTargetPath}- sidebarOpen={sidebarOpen}- scrollRef={scrollRef}- goToPageId={goToPageId}- persona={persona}- />- );-}--function DocsViewerBody({- page,- pages,- repoId,- hasTargetPath,- sidebarOpen,- scrollRef,- goToPageId,- persona,-}: {- page: PageResponse;- pages: PageResponse[];- repoId: string;- hasTargetPath: boolean;- sidebarOpen: boolean;- scrollRef: React.RefObject<HTMLDivElement | null>;- goToPageId: (pageId: string) => void;- persona: ReaderPersona;-}) {- // Hierarchical breadcrumb + sibling prev/next, derived from the page list.- const nav = useMemo(() => computeDocNav(page, pages), [page, pages]);- const wikiLinks = useMemo(() => getWikiLinks(page.metadata), [page.metadata]);-- // Persona-filtered markdown — hides reference-heavy sections for the lighter- // reading levels. The TOC + download still operate on the full content.- const visibleContent = useMemo(- () => filterMarkdownByPersona(page.content, persona),- [page.content, persona],- );-- // Nearest ancestor that maps to a module page — the "zoom out" chip target.- const moduleSeg = useMemo(- () =>- [...nav.breadcrumbs]- .slice(0, -1)- .reverse()- .find((s) => s.pageId && s.pageId !== page.id),- [nav.breadcrumbs, page.id],- );-- const buildWikiHref = useCallback(+ const buildPageHref = useCallback((pageId: string) =>`/repos/${repoId}/docs?page=${encodeURIComponent(pageId)}`,[repoId],);- // Forward "Related" links: distinct wiki-link targets resolved to titles- // from the loaded page list. Pure metadata — no extra request.- const relatedLinks = useMemo(() => {- const byId = new Map(pages.map((p) => [p.id, p]));- const seen = new Set<string>();- const out: { id: string; title: string }[] = [];- for (const link of wikiLinks) {- const target = link.target_page_id;- if (target === page.id || seen.has(target)) continue;- const hit = byId.get(target);- if (!hit) continue;- seen.add(target);- out.push({ id: hit.id, title: hit.title });- }- return out;- }, [wikiLinks, pages, page.id]);-- // KG layer this file belongs to (the "layer Y" chip). Links to the layer- // page when one was generated, otherwise renders as a static chip.- const layerName =- typeof page.metadata?.layer_name === "string" ? page.metadata.layer_name : "";- // Layer pages are keyed by the layer's STABLE slug id (`layer:<slug>`), which- // survives the LLM rename of the display name. Join by that id; fall back to- // the legacy name-keyed target_path for pages generated before the slug fix.- const layerId =- typeof page.metadata?.layer_id === "string" ? page.metadata.layer_id : "";- const layerPage = useMemo(- () =>- layerId- ? pages.find(- (p) => p.page_type === "layer_page" && p.target_path === layerId,- ) ??- (layerName- ? pages.find(- (p) =>- p.page_type === "layer_page" &&- p.target_path === `layer:${layerName}`,- )- : undefined)- : layerName- ? pages.find(- (p) =>- p.page_type === "layer_page" &&- p.target_path === `layer:${layerName}`,- )- : undefined,- [pages, layerId, layerName],+ // Fall back to the wiki deep-link route only when the target isn't in the+ // loaded list (which itself opens the unified reader via redirect).+ const onNavigatePageId = useCallback(+ (pageId: string) => {+ window.location.href = `/repos/${repoId}/wiki/${encodeURIComponent(pageId)}`;+ },+ [repoId],);- // Provenance: the inputs this page was synthesised from (metadata.sources).- // Each is linked to its own page when one exists.- const sources = useMemo(() => {- const raw = page.metadata?.sources;- if (!Array.isArray(raw)) return [];- const byPath = new Map(pages.map((p) => [p.target_path, p]));- return (raw as Array<{ path?: string; kind?: string }>)- .map((s) => {- const path = typeof s?.path === "string" ? s.path : "";- return { path, kind: s?.kind ?? "", pageId: byPath.get(path)?.id };- })- .filter((s) => s.path);- }, [page.metadata, pages]);-- // Renders a resolved wiki link as an <a> with a real href (middle-click /- // open-in-new-tab still work) but intercepts plain clicks for in-app nav.- const WikiInlineLink = useMemo(() => {- function Comp({- href,- className,- title,- children,- }: {- href: string;- className?: string;- title?: string;- children: React.ReactNode;- }) {- return (- <a- href={href}- className={className}- title={title}- onClick={(e) => {- if (e.metaKey || e.ctrlKey || e.shiftKey || e.button !== 0) return;- try {- const u = new URL(href, window.location.origin);- const pid = u.searchParams.get("page");- if (pid) {- e.preventDefault();- goToPageId(pid);- }- } catch {- /* fall through to default navigation */- }- }}- >- {children}- </a>- );- }- return Comp;- }, [goToPageId]);+ const hasTargetPath = !!page?.target_path;+ const targetPath = page?.target_path ?? "";+ // Security findings only make sense for real source files.+ const isFilePath =+ hasTargetPath &&+ !targetPath.includes("::") &&+ !targetPath.startsWith("onboarding/") &&+ !targetPath.startsWith("layer:");return (- <div className="flex h-full">- {/* Main content */}- <div className="flex flex-col flex-1 min-w-0">- {/* Content. The old sticky control row lives in the DocsHeader now —- the article gets the full height. */}- <div ref={scrollRef} className="flex-1 overflow-y-auto">- <div className="px-4 sm:px-6 py-8 max-w-[768px] mx-auto">- {/* Hierarchical breadcrumb: module / file, ancestors clickable */}- <div className="mb-3 overflow-hidden">- <Breadcrumb- segments={nav.breadcrumbs.map((seg) => ({- label: seg.label,- ...(seg.pageId && seg.pageId !== page.id- ? { href: buildWikiHref(seg.pageId) }- : {}),- }))}- LinkComponent={WikiInlineLink}- />- </div>-- {/* Title */}- <h1 className="font-serif text-[2rem] leading-tight font-semibold tracking-tight text-[var(--color-text-primary)] mb-2 break-words">- {page.title}- </h1>-- {/* Context chips: page type + "in module" (zoom-out) */}- <div className="flex flex-wrap items-center gap-1.5 mb-2">- <span className="rounded-full bg-[var(--color-bg-elevated)] px-2 py-0.5 text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">- {getPageTypeLabel(page.page_type)}- </span>- {moduleSeg && (- <button- onClick={() => goToPageId(moduleSeg.pageId!)}- className="rounded-full border border-[var(--color-border-default)] px-2 py-0.5 text-[10px] text-[var(--color-text-secondary)] transition-colors hover:border-[var(--color-border-accent)] hover:text-[var(--color-accent-primary)]"- >- in {moduleSeg.label}- </button>- )}- {layerName &&- (layerPage ? (- <button- onClick={() => goToPageId(layerPage.id)}- className="inline-flex items-center gap-1 rounded-full border border-[var(--color-border-default)] px-2 py-0.5 text-[10px] text-[var(--color-text-secondary)] transition-colors hover:border-[var(--color-border-accent)] hover:text-[var(--color-accent-primary)]"- >- <Layers className="h-2.5 w-2.5" />- {layerName}- </button>- ) : (- <span className="inline-flex items-center gap-1 rounded-full bg-[var(--color-bg-elevated)] px-2 py-0.5 text-[10px] text-[var(--color-text-tertiary)]">- <Layers className="h-2.5 w-2.5" />- {layerName}- </span>- ))}- </div>-- {/* Low-confidence flag */}- {page.confidence > 0 && page.confidence < 0.5 && (- <div className="mb-4 flex items-start gap-1.5 rounded-md border border-[var(--color-warning)]/40 bg-[var(--color-warning)]/10 px-3 py-2">- <span className="text-xs text-[var(--color-text-primary)]">- This page was generated with low confidence — verify against the source before relying on it.- </span>- </div>- )}-- {/* Meta row */}- <div className="flex items-center gap-3 text-[10px] text-[var(--color-text-tertiary)] mb-6">- <span className="flex items-center gap-1">- <Clock className="h-3 w-3" />- {formatRelativeTime(page.updated_at)}- </span>- <span>v{page.version}</span>- <span className="font-mono">- {formatTokens(page.input_tokens)} in · {formatTokens(page.output_tokens)} out- </span>- {page.model_name && (- <span className="flex items-center gap-1 font-mono">- <Cpu className="h-3 w-3" />- {page.model_name}- </span>- )}- </div>-- {/* Human notes */}- {page.human_notes && (- <div className="mb-4 rounded-lg border border-[var(--color-border-accent)] bg-[var(--color-accent-blue)]/5 px-4 py-3">- <div className="flex items-center gap-1.5 mb-1.5">- <StickyNote className="h-3.5 w-3.5 text-[var(--color-accent-blue)]" />- <span className="text-xs font-medium text-[var(--color-accent-blue)] uppercase tracking-wider">- Human Notes- </span>- </div>- <p className="text-sm text-[var(--color-text-secondary)] whitespace-pre-wrap leading-relaxed">- {page.human_notes}- </p>- </div>- )}-- {/* Markdown content */}- <article className="prose prose-invert max-w-none leading-relaxed overflow-hidden">- <WikiMarkdown- content={visibleContent}- wikiLinks={wikiLinks}- buildHref={(pid) => buildWikiHref(pid)}- LinkComponent={WikiInlineLink}- />- </article>-- {/* Sibling prev / next */}- {(nav.prev || nav.next) && (- <nav className="mt-8 flex items-stretch gap-3 border-t border-[var(--color-border-default)] pt-4">- {nav.prev ? (- <button- onClick={() => goToPageId(nav.prev!.pageId)}- className="group flex flex-1 items-center gap-2 rounded-lg border border-[var(--color-border-default)] px-3 py-2 text-left transition-colors hover:border-[var(--color-border-accent)] hover:bg-[var(--color-bg-elevated)]"- >- <ArrowLeft className="h-3.5 w-3.5 shrink-0 text-[var(--color-text-tertiary)] group-hover:text-[var(--color-accent-primary)]" />- <span className="min-w-0">- <span className="block text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">- Previous- </span>- <span className="block truncate text-xs text-[var(--color-text-secondary)]">- {nav.prev.title}- </span>- </span>- </button>- ) : (- <span className="flex-1" />- )}- {nav.next && (- <button- onClick={() => goToPageId(nav.next!.pageId)}- className="group flex flex-1 items-center justify-end gap-2 rounded-lg border border-[var(--color-border-default)] px-3 py-2 text-right transition-colors hover:border-[var(--color-border-accent)] hover:bg-[var(--color-bg-elevated)]"- >- <span className="min-w-0">- <span className="block text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">- Next- </span>- <span className="block truncate text-xs text-[var(--color-text-secondary)]">- {nav.next.title}- </span>- </span>- <ArrowRight className="h-3.5 w-3.5 shrink-0 text-[var(--color-text-tertiary)] group-hover:text-[var(--color-accent-primary)]" />- </button>- )}- </nav>- )}-- {/* Version history */}- <div className="mt-8">- <VersionHistoryWrapper- pageId={page.id}- currentVersion={page.version}- currentContent={page.content}- />- </div>-- {/* Metadata warnings */}- {Array.isArray(page.metadata?.hallucination_warnings) && (page.metadata.hallucination_warnings as string[]).length > 0 && (- <div className="mt-4 rounded-lg border border-[var(--color-warning)]/40 bg-[var(--color-warning)]/10 px-4 py-3">- <p className="text-xs font-medium text-[var(--color-warning)] mb-1.5">- Possible inaccuracies detected- </p>- <ul className="space-y-0.5">- {(page.metadata.hallucination_warnings as string[]).map((w, i) => (- <li key={i} className="text-xs text-[var(--color-text-secondary)] font-mono">- {String(w)}- </li>- ))}- </ul>- </div>- )}- </div>- </div>- </div>-- {/* Right sidebar — on-page contents first, then graph intelligence.- Every section renders only when it has data, so the panel stays calm. */}- {sidebarOpen && (- <div className="hidden lg:block border-l border-[var(--color-border-default)] bg-[var(--color-bg-surface)] shrink-0 w-[260px] overflow-auto">- <div className="space-y-6 p-4">- <TableOfContents content={page.content} />- {hasTargetPath && (- <AtAGlance repoId={repoId} targetPath={page.target_path} />- )}- {sources.length > 0 && (- <div>- <div className="flex items-center gap-1.5 mb-2">- <FileInput className="h-3 w-3 text-[var(--color-text-tertiary)]" />- <span className="text-[11px] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider">- Built from- </span>- </div>- <ul className="space-y-1">- {sources.slice(0, 5).map((s) => (- <li key={s.path} className="text-[11px]">- {s.pageId ? (- <button- onClick={() => goToPageId(s.pageId!)}- className="truncate text-left font-mono text-[var(--color-text-secondary)] hover:text-[var(--color-accent-primary)] transition-colors w-full"- title={`${s.path} (${s.kind})`}- >- {s.path.split("/").pop()}- </button>- ) : (- <span- className="block truncate font-mono text-[var(--color-text-tertiary)]"- title={`${s.path} (${s.kind})`}- >- {s.path.split("/").pop()}- </span>- )}- </li>- ))}- </ul>- {sources.length > 5 && (- <p className="mt-1 text-[10px] text-[var(--color-text-tertiary)]">- + {sources.length - 5} more- </p>- )}- </div>- )}- {relatedLinks.length > 0 && (+ <DocsReader+ page={page as unknown as DocPage | null}+ pages={pages as unknown as DocPage[]}+ repoId={repoId}+ isLoading={isLoading}+ onSelectPage={onSelectPage as ((p: DocPage) => void) | undefined}+ onNavigatePageId={onNavigatePageId}+ persona={persona}+ sidebarOpen={sidebarOpen}+ buildPageHref={buildPageHref}+ LinkComponent={Link}+ versionHistorySlot={+ page ? (+ <VersionHistoryWrapper+ pageId={page.id}+ currentVersion={page.version}+ currentContent={page.content}+ />+ ) : undefined+ }+ intelligenceSlot={+ hasTargetPath ? (+ <>+ <AtAGlance repoId={repoId} targetPath={targetPath} />+ <DocsSidebar repoId={repoId} targetPath={targetPath} />+ {isFilePath && (<div>- <p className="text-[11px] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-2">- Related+ <p className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-2">+ Security signals</p>- <ul className="space-y-1.5">- {relatedLinks.slice(0, 5).map((r) => (- <li key={r.id} className="text-xs">- <button- onClick={() => goToPageId(r.id)}- className="truncate text-left text-[var(--color-text-secondary)] hover:text-[var(--color-accent-primary)] transition-colors w-full"- title={r.title}- >- {r.title}- </button>- </li>- ))}- </ul>- {relatedLinks.length > 5 && (- <p className="mt-1 text-[10px] text-[var(--color-text-tertiary)]">- + {relatedLinks.length - 5} more- </p>- )}+ <SecurityPanelWrapper repoId={repoId} filePath={targetPath} /></div>)}- <BacklinksPanel- backlinks={getBacklinks(page.metadata)}- repoId={repoId}- buildHref={(rid, pid) =>- `/repos/${rid}/docs?page=${encodeURIComponent(pid)}`- }- renderLink={({ href, className, title, children }) => (- <Link href={href} className={className} title={title}>- {children}- </Link>- )}- />- {hasTargetPath && <DocsSidebar repoId={repoId} targetPath={page.target_path} />}- </div>- </div>- )}- </div>+ </>+ ) : undefined+ }+ />);}diff --git a/packages/web/src/components/files/file-page-host.tsx b/packages/web/src/components/files/file-page-host.tsxindex 7612f3ee7..7518b4ef2 100644--- a/packages/web/src/components/files/file-page-host.tsx+++ b/packages/web/src/components/files/file-page-host.tsx@@ -1,6 +1,7 @@"use client";import type { ReactNode } from "react";+import Link from "next/link";import { useRouter } from "next/navigation";import { toast } from "sonner";import { FilePage, type FilePageTab, type FindingStatus } from "@repowise-dev/ui/files";@@ -30,7 +31,7 @@ export function FilePageHost({const onTabChange = (tab: FilePageTab) => {const sp = new URLSearchParams(window.location.search);- if (tab === "doc") sp.delete("tab");+ if (tab === "overview") sp.delete("tab");else sp.set("tab", tab);const qs = sp.toString();router.replace(qs ? `?${qs}` : window.location.pathname, { scroll: false });@@ -46,10 +47,18 @@ export function FilePageHost({}};+ const fileName = data.file_path.split("/").pop() || data.file_path;+ const dir = data.file_path.slice(0, data.file_path.length - fileName.length).replace(/\/$/, "");+return (<FilePagedata={data}repoId={repoId}+ LinkComponent={Link}+ breadcrumb={[+ ...(dir ? [{ label: dir }] : []),+ { label: fileName },+ ]}docSlot={docSlot}coverageCodeHtml={coverageCodeHtml}wikiHref={wikiHref}diff --git a/packages/web/src/components/graph/graph-flow.tsx b/packages/web/src/components/graph/graph-flow.tsxindex 9e9f09d19..3171418ef 100644--- a/packages/web/src/components/graph/graph-flow.tsx+++ b/packages/web/src/components/graph/graph-flow.tsx@@ -50,6 +50,8 @@ export interface GraphFlowProps {onViewModeChange?: (mode: ViewMode) => void;/** Fired when the node color mode changes so the page can sync the URL. */onColorModeChange?: GraphFlowShellProps["onColorModeChange"];+ /** Restricts the in-canvas scope cluster (Explore omits the constellation). */+ availableScopes?: GraphFlowShellProps["availableScopes"];}export function GraphFlow({@@ -63,6 +65,7 @@ export function GraphFlow({onCommunityPanelOpen,onViewModeChange,onColorModeChange,+ availableScopes,}: GraphFlowProps) {const router = useRouter();// Constellation (Knowledge Graph) is the default scope.@@ -139,6 +142,7 @@ export function GraphFlow({onViewModeChange?.(mode);}}onColorModeChange={onColorModeChange}+ availableScopes={availableScopes}onModulePathChange={setModulePath}onExpandedModulesChange={(expanded) => setHasExpandedModules(expanded.size > 0)}onNodeClick={onNodeClick}diff --git a/packages/web/src/components/layout/nav-items.ts b/packages/web/src/components/layout/nav-items.tsindex 175de7d09..cceacf417 100644--- a/packages/web/src/components/layout/nav-items.ts+++ b/packages/web/src/components/layout/nav-items.ts@@ -3,7 +3,8 @@* the mobile nav consume these — the two surfaces must never diverge again.** Repo IA (6 groups + Settings pinned last):- * Overview · Docs · Architecture · Code Health · People & History · Chat+ * Overview · Docs · Architecture · Knowledge Graph · Code Health ·+ * People & History · Chat*/import {@@ -56,8 +57,8 @@ export function repoNavGroups(repoId: string): NavGroup[] {{ label: "Overview", href: `${base}/overview`, icon: Activity },{ label: "Docs", href: `${base}/docs`, icon: BookOpen },{ label: "Architecture", href: `${base}/architecture`, icon: Boxes },+ { label: "Knowledge Graph", href: `${base}/knowledge-graph`, icon: Waypoints },{ label: "Code Health", href: `${base}/code-health`, icon: HeartPulse },- { label: "Coupling", href: `${base}/coupling`, icon: Waypoints },],},{diff --git a/packages/web/src/components/layout/repo-breadcrumb-label.ts b/packages/web/src/components/layout/repo-breadcrumb-label.tsindex 0ca83be6d..a3e9325af 100644--- a/packages/web/src/components/layout/repo-breadcrumb-label.ts+++ b/packages/web/src/components/layout/repo-breadcrumb-label.ts@@ -24,7 +24,7 @@ const SEGMENT_LABELS: Record<string, string> = {risk: "Risk",security: "Security",settings: "Settings",- c4: "Knowledge Graph",+ "knowledge-graph": "Knowledge Graph",files: "Files",};diff --git a/packages/web/src/components/layout/repo-breadcrumb.test.ts b/packages/web/src/components/layout/repo-breadcrumb.test.tsindex d2d67d75e..5928b6b41 100644--- a/packages/web/src/components/layout/repo-breadcrumb.test.ts+++ b/packages/web/src/components/layout/repo-breadcrumb.test.ts@@ -4,7 +4,7 @@ import { getRepoBreadcrumbSegmentLabel } from "./repo-breadcrumb-label";describe("getRepoBreadcrumbSegmentLabel", () => {it("keeps configured route segment labels", () => {expect(getRepoBreadcrumbSegmentLabel("dead-code")).toBe("Dead Code");- expect(getRepoBreadcrumbSegmentLabel("c4")).toBe("Knowledge Graph");+ expect(getRepoBreadcrumbSegmentLabel("knowledge-graph")).toBe("Knowledge Graph");});it("decodes dynamic path segments for display", () => {diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsxindex 5f087a5ef..fdf3995a4 100644--- a/packages/web/src/components/layout/sidebar.tsx+++ b/packages/web/src/components/layout/sidebar.tsx@@ -226,19 +226,50 @@ export function Sidebar({ repos = [], activeRepoId, workspace }: SidebarProps) {}if (isIconOnly) {+ // Collapsed: the active repo still exposes its full nav as+ // icons (so the repository-view options stay reachable, e.g.+ // on Docs where the sidebar auto-collapses); inactive repos+ // stay a single dot that jumps to their overview.+ if (isActive) {+ return (+ <div key={repo.id} className="space-y-0.5">+ <Tooltip>+ <TooltipTrigger asChild>+ <div+ className="flex w-full items-center justify-center rounded-md p-2 text-[var(--color-accent-primary)]"+ aria-label={repo.name}+ >+ <Circle className="h-2.5 w-2.5 fill-[var(--color-accent-primary)]" />+ </div>+ </TooltipTrigger>+ <TooltipContent side="right">{repo.name}</TooltipContent>+ </Tooltip>+ {navGroups.map((group, gi) => (+ <React.Fragment key={group.label ?? gi}>+ {gi > 0 && <Separator className="my-1.5" />}+ {group.items.map((item) => (+ <SidebarNavItem+ key={item.href}+ item={item}+ isActive={isNavItemActive(item, pathname)}+ iconOnly+ />+ ))}+ </React.Fragment>+ ))}+ </div>+ );+ }return (<Tooltip key={repo.id}><TooltipTrigger asChild>- <button- onClick={() => toggleRepo(repo.id)}- className={cn(- "flex w-full items-center justify-center rounded-md p-2 transition-colors hover:bg-[var(--color-bg-elevated)]",- isActive ? "text-[var(--color-accent-primary)]" : "text-[var(--color-text-tertiary)]",- )}+ <Link+ href={`/repos/${repo.id}/overview`}+ className="flex w-full items-center justify-center rounded-md p-2 text-[var(--color-text-tertiary)] transition-colors hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-secondary)]"aria-label={repo.name}>- <Circle className={cn("h-2.5 w-2.5", isActive ? "fill-[var(--color-accent-primary)]" : "fill-current")} />- </button>+ <Circle className="h-2.5 w-2.5 fill-current" />+ </Link></TooltipTrigger><TooltipContent side="right">{repo.name}</TooltipContent></Tooltip>diff --git a/packages/web/src/components/overview/pulse-tab.tsx b/packages/web/src/components/overview/pulse-tab.tsxindex 40016f76b..cf5b7518d 100644--- a/packages/web/src/components/overview/pulse-tab.tsx+++ b/packages/web/src/components/overview/pulse-tab.tsx@@ -4,8 +4,12 @@ import useSWR from "swr";import { CommitsMini } from "@repowise-dev/ui/dashboard/commits-mini";import { DecisionsTimeline } from "@repowise-dev/ui/dashboard/decisions-timeline";import { HotspotsMini } from "@repowise-dev/ui/dashboard/hotspots-mini";+import {+ CommitActivityCard,+ OverviewPanelPair,+} from "@repowise-dev/ui/dashboard/overview-grid";import { CommitCategorySparkline } from "@repowise-dev/ui/git/commit-category-sparkline";-import { Card, CardContent, CardHeader, CardTitle } from "@repowise-dev/ui/ui/card";+import { Card, CardContent } from "@repowise-dev/ui/ui/card";import { Skeleton } from "@repowise-dev/ui/ui/skeleton";import { getCommitsPage } from "@/lib/api/git";import type { Hotspot } from "@repowise-dev/types/git";@@ -38,7 +42,7 @@ export function PulseTab({ repoId, hotspots, hotspotTotal, decisions }: PulseTabreturn (<div className="space-y-4">- <div className="grid grid-cols-1 gap-4 md:grid-cols-2">+ <OverviewPanelPair>{isLoading ? (<Card><CardContent className="space-y-2 pt-4">@@ -51,26 +55,15 @@ export function PulseTab({ repoId, hotspots, hotspotTotal, decisions }: PulseTab<CommitsMini commits={commitsPage?.items ?? []} repoId={repoId} />)}<DecisionsTimeline decisions={decisions} repoId={repoId} />- </div>- <div className="grid grid-cols-1 gap-4 md:grid-cols-2">+ </OverviewPanelPair>+ <OverviewPanelPair><HotspotsMini hotspots={hotspots} repoId={repoId} total={hotspotTotal} />{hasCategories && (- <Card>- <CardHeader className="pb-2">- <CardTitle className="text-sm font-medium">Commit Activity</CardTitle>- </CardHeader>- <CardContent>- <CommitCategorySparkline categories={aggregatedCategories} />- <div className="flex flex-wrap items-center gap-x-4 gap-y-1 mt-2 text-[10px] text-[var(--color-text-tertiary)]">- <span className="flex items-center gap-1"><span className="inline-block h-2 w-2 rounded-sm" style={{ background: "var(--color-info)" }} /> Feature</span>- <span className="flex items-center gap-1"><span className="inline-block h-2 w-2 rounded-sm" style={{ background: "var(--color-error)" }} /> Fix</span>- <span className="flex items-center gap-1"><span className="inline-block h-2 w-2 rounded-sm" style={{ background: "var(--color-accent-secondary)" }} /> Refactor</span>- <span className="flex items-center gap-1"><span className="inline-block h-2 w-2 rounded-sm" style={{ background: "var(--color-accent-fill)" }} /> Dependency</span>- </div>- </CardContent>- </Card>+ <CommitActivityCard+ sparkline={<CommitCategorySparkline categories={aggregatedCategories} />}+ />)}- </div>+ </OverviewPanelPair></div>);}diff --git a/packages/web/src/components/overview/structure-tab.tsx b/packages/web/src/components/overview/structure-tab.tsxindex 3e05ce9fb..46accff8a 100644--- a/packages/web/src/components/overview/structure-tab.tsx+++ b/packages/web/src/components/overview/structure-tab.tsx@@ -4,9 +4,13 @@ import useSWR from "swr";import { ModuleOverviewGrid } from "@repowise-dev/ui/dashboard/module-overview-grid";import { OwnershipTreemap } from "@repowise-dev/ui/dashboard/ownership-treemap";import { ExecutionFlowsPanel } from "@repowise-dev/ui/dashboard/execution-flows-panel";+import {+ OverviewPanelPair,+ TitledPanel,+} from "@repowise-dev/ui/dashboard/overview-grid";import { BusFactorPanel } from "@repowise-dev/ui/git/bus-factor-panel";import { EmptyState } from "@repowise-dev/ui/shared";-import { Card, CardContent, CardHeader, CardTitle } from "@repowise-dev/ui/ui/card";+import { Card, CardContent } from "@repowise-dev/ui/ui/card";import { Skeleton } from "@repowise-dev/ui/ui/skeleton";import { CommunitySummaryGridWrapper } from "@/components/dashboard/community-summary-grid-wrapper";import { useCommunities, useExecutionFlows, useModuleGraph } from "@/lib/hooks/use-graph";@@ -72,7 +76,7 @@ export function StructureTab({ repoId }: StructureTabProps) {<CommunitySummaryGridWrapper communities={communities} repoId={repoId} />) : null}- <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">+ <OverviewPanelPair>{flowsLoading ? (<PanelSkeleton />) : flows && flows.flows.length > 0 ? (@@ -81,28 +85,18 @@ export function StructureTab({ repoId }: StructureTabProps) {{hotspotsLoading ? (<PanelSkeleton />) : hotspotsPage && hotspotsPage.items.length > 0 ? (- <Card>- <CardHeader className="pb-2">- <CardTitle className="text-sm font-medium">Bus Factor</CardTitle>- </CardHeader>- <CardContent>- <BusFactorPanel hotspots={hotspotsPage.items} />- </CardContent>- </Card>+ <TitledPanel title="Bus Factor">+ <BusFactorPanel hotspots={hotspotsPage.items} />+ </TitledPanel>) : null}- </div>+ </OverviewPanelPair>{ownershipLoading ? (<PanelSkeleton rows={8} />) : ownership && ownership.length > 0 ? (- <Card>- <CardHeader className="pb-2">- <CardTitle className="text-sm font-medium">Ownership Map</CardTitle>- </CardHeader>- <CardContent>- <OwnershipTreemap entries={ownership} />- </CardContent>- </Card>+ <TitledPanel title="Ownership Map">+ <OwnershipTreemap entries={ownership} />+ </TitledPanel>) : null}</div>);diff --git a/packages/web/src/components/repos/coordinator-health-panel.tsx b/packages/web/src/components/repos/coordinator-health-panel.tsxindex b9f9a334b..723c5446c 100644--- a/packages/web/src/components/repos/coordinator-health-panel.tsx+++ b/packages/web/src/components/repos/coordinator-health-panel.tsx@@ -11,9 +11,9 @@ interface Props {}const STATUS_BADGE: Record<CoordinatorHealth["status"], string> = {- ok: "bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400",- warning: "bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-400",- critical: "bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400",+ ok: "bg-[var(--color-success)]/10 text-[var(--color-success)]",+ warning: "bg-[var(--color-warning)]/10 text-[var(--color-warning)]",+ critical: "bg-[var(--color-error)]/10 text-[var(--color-error)]",};function StatRow({ label, value, help }: { label: string; value: string; help?: string }) {@@ -94,7 +94,7 @@ export function CoordinatorHealthPanel({ repoId, initial }: Props) {</p>)}{error && (- <p className="text-xs text-red-500">{error}</p>+ <p className="text-xs text-[var(--color-error)]">{error}</p>)}<Buttonvariant="outline"diff --git a/packages/web/src/components/repos/delete-repo-button.tsx b/packages/web/src/components/repos/delete-repo-button.tsxindex fc1c7ea76..59b687c35 100644--- a/packages/web/src/components/repos/delete-repo-button.tsx+++ b/packages/web/src/components/repos/delete-repo-button.tsx@@ -67,7 +67,7 @@ export function DeleteRepoButton({e.stopPropagation();setOpen(true);}}- className="opacity-0 group-hover:opacity-100 p-1 text-[var(--color-text-tertiary)] hover:text-red-400 transition-all"+ className="opacity-0 group-hover:opacity-100 p-1 text-[var(--color-text-tertiary)] hover:text-[var(--color-error)] transition-all"title="Delete repository"><Trash2 className="h-3.5 w-3.5" />diff --git a/packages/web/src/components/risk/dead-code-tab.tsx b/packages/web/src/components/risk/dead-code-tab.tsxindex c5e24506e..178eb3d1d 100644--- a/packages/web/src/components/risk/dead-code-tab.tsx+++ b/packages/web/src/components/risk/dead-code-tab.tsx@@ -6,15 +6,16 @@ import useSWR from "swr";import { toast } from "sonner";import { fileEntityPath } from "@repowise-dev/ui/shared/entity";import { Button } from "@repowise-dev/ui/ui/button";-import { Card, CardContent, CardHeader, CardTitle } from "@repowise-dev/ui/ui/card";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 "@/components/dead-code/findings-table";-import { getDeadCodeSummary, listDeadCode, analyzeDeadCode } from "@/lib/api/dead-code";+import { FindingsTable } from "@repowise-dev/ui/dead-code/findings-table";+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";export function DeadCodeTab({ repoId }: { repoId: string }) {const router = useRouter();@@ -27,10 +28,10 @@ export function DeadCodeTab({ repoId }: { repoId: string }) {{ revalidateOnFocus: false },);- const { data: findings } = useSWR<DeadCodeFindingResponse[]>(+ // 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`,- // Pull a wide slice so the leaderboard / pile / matrix have enough data- // to be representative without paging.() => listDeadCode(repoId, { limit: 500 }),{ revalidateOnFocus: false },);@@ -87,6 +88,48 @@ export function DeadCodeTab({ repoId }: { repoId: string }) {}};+ // 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;+ };+return (<div className="space-y-6"><div className="flex items-center justify-end">@@ -96,7 +139,7 @@ export function DeadCodeTab({ repoId }: { repoId: string }) {</div>{loadingSummary ? (- <div className="grid grid-cols-4 gap-3">+ <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" />))}@@ -112,6 +155,7 @@ export function DeadCodeTab({ repoId }: { repoId: string }) {</div>) : null}+ {/* Act now: the single "what do I delete" surface. */}{findings && safeFindings.length > 0 && (<SafeToDeletePilefindings={safeFindings}@@ -121,33 +165,45 @@ export function DeadCodeTab({ repoId }: { repoId: string }) {/>)}- <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">- <Card>- <CardHeader className="pb-2">- <CardTitle className="text-sm">Owner leaderboard</CardTitle>- <p className="text-xs text-[var(--color-text-tertiary)]">- Reclaimable lines per primary contributor — who has the most cleanup leverage.- </p>- </CardHeader>- <CardContent className="pt-0">- <OwnerLeaderboard findings={findingsList} safeOnly />- </CardContent>- </Card>-- <Card>- <CardHeader className="pb-2">- <CardTitle className="text-sm">Confidence × kind</CardTitle>- <p className="text-xs text-[var(--color-text-tertiary)]">- Where the findings cluster — start with high-confidence cells.- </p>- </CardHeader>- <CardContent className="pt-0">- <FindingsBreakdownGrid findings={findingsList} />- </CardContent>- </Card>- </div>+ {/* 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>+ )}- <FindingsTable repoId={repoId} />+ {/* 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></div>);}diff --git a/packages/web/src/components/risk/hotspots-tab.tsx b/packages/web/src/components/risk/hotspots-tab.tsxindex 3b794d559..794256bff 100644--- a/packages/web/src/components/risk/hotspots-tab.tsx+++ b/packages/web/src/components/risk/hotspots-tab.tsx@@ -1,58 +1,75 @@"use client";-import { useState } from "react";+import { useMemo, useState } from "react";import useSWR from "swr";import { useFileCardHost } from "@/components/shared/file-card-host";import { HotspotTopSymbolsHost } from "@/components/symbols/hotspot-top-symbols-host";import { SymbolDrawerWrapper } from "@/components/symbols/symbol-drawer-wrapper";-import type { HotspotResponse as HotspotRowType, Paginated, SymbolResponse } from "@/lib/api/types";-import type { FileCardData } from "@repowise-dev/ui/shared/file-card";+import type { Paginated, SymbolResponse } from "@/lib/api/types";+import { hotspotToFileCard } from "@repowise-dev/ui/shared/file-card";import { HotspotTable } from "@repowise-dev/ui/git/hotspot-table";import { HotspotTrendStrip } from "@repowise-dev/ui/git/hotspot-trend-strip";import { ChurnHistogram } from "@repowise-dev/ui/git/churn-histogram";import { CommitCategoryDonut } from "@repowise-dev/ui/git/commit-category-donut";import { RiskDistributionChart } from "@repowise-dev/ui/git/risk-distribution-chart";import { ChurnVsBusFactorScatter } from "@repowise-dev/ui/git/churn-vs-bus-factor-scatter";-import { ChurnComplexityQuadrant } from "@repowise-dev/ui/health/churn-complexity-quadrant";+import {+ CodeHealthMap,+ type CodeHealthOverlay,+} from "@repowise-dev/ui/health/code-health-map";import { Card, CardContent, CardHeader, CardTitle } from "@repowise-dev/ui/ui/card";import { Skeleton } from "@repowise-dev/ui/ui/skeleton";import { getHotspotsPage } from "@/lib/api/git";-import { getChurnComplexity } from "@/lib/api/code-health";-import type { ChurnComplexityResponse } from "@/lib/api/code-health";+import { getChurnComplexity, listHealthFiles } from "@/lib/api/code-health";+import type { ChurnComplexityResponse, HealthFilesResponse } from "@/lib/api/code-health";import type { HotspotResponse } from "@/lib/api/types";-type ChurnView = "complexity" | "bus-factor";-const PAGE_SIZE = 100;-function hotspotToFileCard(h: HotspotRowType): FileCardData {- return {- file_path: h.file_path,- git: {- churn_percentile: h.churn_percentile,- commit_count_90d: h.commit_count_90d,- lines_added_90d: h.lines_added_90d,- lines_deleted_90d: h.lines_deleted_90d,- bus_factor: h.bus_factor,- primary_owner: h.primary_owner,- is_hotspot: h.is_hotspot,- temporal_hotspot_score: h.temporal_hotspot_score,- },- };-}-export function HotspotsTab({ repoId }: { repoId: string }) {const { showFile, dialog } = useFileCardHost(repoId);const [pageLimit, setPageLimit] = useState(PAGE_SIZE);const [drawerSymbol, setDrawerSymbol] = useState<SymbolResponse | null>(null);- // Default to churn x complexity: complexity is more universally legible than- // bus factor, so it makes the friendlier first read of the danger zone.- const [churnView, setChurnView] = useState<ChurnView>("complexity");- const { data: churnComplexity } = useSWR<ChurnComplexityResponse>(- `health-churn-complexity:${repoId}`,- () => getChurnComplexity(repoId),- { revalidateOnFocus: false, keepPreviousData: true },+ // The galaxy map opens on the churn lens here — this is the hotspots surface,+ // so "what changes most" is the first read; the switcher still offers+ // health/coverage for cross-reference.+ const [overlay, setOverlay] = useState<CodeHealthOverlay>("churn");+ const { data: churnComplexity, isLoading: loadingChurn } =+ useSWR<ChurnComplexityResponse>(+ `health-churn-complexity:${repoId}`,+ () => getChurnComplexity(repoId),+ { revalidateOnFocus: false, keepPreviousData: true },+ );++ // Same payload + SWR key the triage page uses for its galaxy map, so the two+ // surfaces dedupe onto one request instead of double-fetching.+ const { data: mapFiles } = useSWR<HealthFilesResponse>(+ `code-health-map-files:${repoId}`,+ () => listHealthFiles(repoId, { limit: 2000, sort: "nloc", order: "desc" }),+ { revalidateOnFocus: false },);++ // The churn lens recolors by `churn_percentile`, which rides on the separate+ // churn request. Until it lands every node is neutral — flag that so the map+ // reads as "loading" rather than "no data".+ const overlayLoading = overlay === "churn" && loadingChurn && !churnComplexity;++ // Join churn percentiles onto the map files (by path) so the churn lens colors+ // real data; recomputes only when either source changes.+ const mapFilesWithChurn: HealthFilesResponse | undefined = useMemo(() => {+ if (!mapFiles) return undefined;+ if (!churnComplexity) return mapFiles;+ const byPath = new Map(+ churnComplexity.points.map((p) => [p.file_path, p.churn_percentile]),+ );+ return {+ ...mapFiles,+ files: mapFiles.files.map((file) => ({+ ...file,+ churn_percentile: byPath.get(file.file_path) ?? null,+ })),+ };+ }, [mapFiles, churnComplexity]);const {data: hotspotsPage,isLoading: loadingHotspots,@@ -115,6 +132,37 @@ export function HotspotsTab({ repoId }: { repoId: string }) {</div>)}+ {list.length > 0 && (+ <Card>+ <CardHeader className="pb-2">+ <CardTitle className="text-sm">Code health map</CardTitle>+ <p className="text-xs text-[var(--color-text-tertiary)]">+ Files clustered into module galaxies — dot size is NLOC, color is the+ chosen lens. On churn, the brightest nodes are your hottest files;+ switch lenses to cross-reference health or coverage. Click a file to+ inspect it.+ </p>+ </CardHeader>+ <CardContent className="pt-0">+ {!mapFilesWithChurn ? (+ <Skeleton className="h-[420px] w-full" />+ ) : (+ <CodeHealthMap+ files={mapFilesWithChurn.files}+ overlay={overlay}+ onOverlayChange={setOverlay}+ overlayLoading={overlayLoading}+ minHeight={420}+ onSelectFile={(path) => {+ const hit = list.find((h) => h.file_path === path);+ showFile(hit ? hotspotToFileCard(hit) : { file_path: path });+ }}+ />+ )}+ </CardContent>+ </Card>+ )}+{list.length > 0 && (<div className="grid grid-cols-1 gap-4 lg:grid-cols-2"><Card>@@ -131,62 +179,20 @@ export function HotspotsTab({ repoId }: { repoId: string }) {<Card><CardHeader className="pb-2">- <div className="flex items-center justify-between gap-2">- <CardTitle className="text-sm">- {churnView === "complexity" ? "Churn × complexity" : "Churn × bus factor"}- </CardTitle>- <div- className="inline-flex shrink-0 rounded-md border border-[var(--color-border-default)] p-0.5 text-xs"- role="tablist"- aria-label="Churn scatter view"- >- {(- [- ["complexity", "Complexity"],- ["bus-factor", "Bus factor"],- ] as [ChurnView, string][]- ).map(([value, label]) => (- <button- key={value}- type="button"- role="tab"- aria-selected={churnView === value}- onClick={() => setChurnView(value)}- className={`rounded px-2 py-0.5 transition-colors ${- churnView === value- ? "bg-[var(--color-bg-elevated)] text-[var(--color-text-primary)]"- : "text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)]"- }`}- >- {label}- </button>- ))}- </div>- </div>+ <CardTitle className="text-sm">Churn × bus factor</CardTitle><p className="text-xs text-[var(--color-text-tertiary)]">- {churnView === "complexity"- ? "Top-right is the refactor zone: files that change often AND are complex. Dot size is NLOC, color is health."- : "Top-right is the danger zone: high churn and a single owner. Bubble size reflects 90-day commit count."}+ Top-right is the danger zone: high churn and a single owner. Bubble+ size reflects 90-day commit count.</p></CardHeader><CardContent className="pt-0">- {churnView === "complexity" ? (- <ChurnComplexityQuadrant- points={churnComplexity?.points ?? []}- onSelect={(p) => {- const hit = list.find((h) => h.file_path === p.file_path);- showFile(hit ? hotspotToFileCard(hit) : { file_path: p.file_path });- }}- />- ) : (- <ChurnVsBusFactorScatter- hotspots={list}- onSelect={(path) => {- const hit = list.find((h) => h.file_path === path);- if (hit) showFile(hotspotToFileCard(hit));- }}- />- )}+ <ChurnVsBusFactorScatter+ hotspots={list}+ onSelect={(path) => {+ const hit = list.find((h) => h.file_path === path);+ if (hit) showFile(hotspotToFileCard(hit));+ }}+ /></CardContent></Card></div>diff --git a/packages/web/src/components/risk/impact-tab.tsx b/packages/web/src/components/risk/impact-tab.tsxindex 51c3f82e1..71a27b4f1 100644--- a/packages/web/src/components/risk/impact-tab.tsx+++ b/packages/web/src/components/risk/impact-tab.tsx@@ -1,11 +1,12 @@"use client";-import { useEffect, useRef, useState } from "react";+import { useState } from "react";import useSWR from "swr";-import { Plus, Flame, X } from "lucide-react";+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 { ReviewerSuggestions } from "@repowise-dev/ui/git/reviewer-suggestions";import type { BlastRadiusResponse } from "@repowise-dev/types/blast-radius";@@ -107,11 +108,11 @@ export function ImpactTab({ repoId }: { repoId: string }) {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-[11px] font-mono text-[var(--color-text-secondary)] hover:border-[var(--color-accent-primary)] hover:text-[var(--color-text-primary)] transition-colors"+ 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-orange-500" />+ <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>@@ -119,7 +120,15 @@ export function ImpactTab({ repoId }: { repoId: string }) {</div>)}- <FilePathPicker repoId={repoId} selected={selected} onAdd={addPaths} onRemove={removePath} />+ <FilePathPicker+ selected={selected}+ onAdd={addPaths}+ onRemove={removePath}+ onSearch={async (q) => {+ const results = await searchNodes(repoId, q, 8);+ return results.map((r) => r.node_id);+ }}+ /><div className="flex items-center gap-4 flex-wrap"><label className="flex items-center gap-2 text-xs text-[var(--color-text-secondary)]">@@ -150,6 +159,7 @@ export function ImpactTab({ repoId }: { repoId: string }) {{result && (<BlastRadiusResultsresult={result}+ changedFiles={selected}reviewersSlot={reviewers && reviewers.length > 0 ? (<ReviewerSuggestions@@ -163,174 +173,3 @@ export function ImpactTab({ repoId }: { repoId: string }) {</div>);}--/**- * Chips + typeahead input over the repo's file index (graph node search).- * Pasting a multi-line / comma-separated list adds every path at once.- */-function FilePathPicker({- repoId,- selected,- onAdd,- onRemove,-}: {- repoId: string;- selected: string[];- onAdd: (paths: string[]) => void;- onRemove: (path: string) => void;-}) {- const [query, setQuery] = useState("");- const [suggestions, setSuggestions] = useState<string[]>([]);- const [openList, setOpenList] = useState(false);- const [activeIndex, setActiveIndex] = useState(-1);- const containerRef = useRef<HTMLDivElement>(null);-- // Debounced typeahead over the graph node index.- useEffect(() => {- if (!query.trim()) {- setSuggestions([]);- setOpenList(false);- return;- }- let cancelled = false;- const t = window.setTimeout(async () => {- try {- const results = await searchNodes(repoId, query.trim(), 8);- if (cancelled) return;- const paths = results- .map((r) => r.node_id)- .filter((p) => !selected.includes(p));- setSuggestions(paths);- setOpenList(paths.length > 0);- setActiveIndex(-1);- } catch {- if (!cancelled) setSuggestions([]);- }- }, 200);- return () => {- cancelled = true;- window.clearTimeout(t);- };- }, [query, repoId, selected]);-- // Close the list when clicking outside.- useEffect(() => {- const handler = (e: MouseEvent) => {- if (containerRef.current && !containerRef.current.contains(e.target as Node)) {- setOpenList(false);- }- };- document.addEventListener("mousedown", handler);- return () => document.removeEventListener("mousedown", handler);- }, []);-- const commit = (path: string) => {- onAdd([path]);- setQuery("");- setSuggestions([]);- setOpenList(false);- };-- const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {- if (e.key === "ArrowDown" && suggestions.length > 0) {- e.preventDefault();- setOpenList(true);- setActiveIndex((i) => (i + 1) % suggestions.length);- } else if (e.key === "ArrowUp" && suggestions.length > 0) {- e.preventDefault();- setActiveIndex((i) => (i <= 0 ? suggestions.length - 1 : i - 1));- } else if (e.key === "Enter") {- e.preventDefault();- if (openList && activeIndex >= 0 && suggestions[activeIndex]) {- commit(suggestions[activeIndex]);- } else if (query.trim()) {- commit(query.trim());- }- } else if (e.key === "Escape") {- setOpenList(false);- } else if (e.key === "Backspace" && !query && selected.length > 0) {- onRemove(selected[selected.length - 1]!);- }- };-- const handlePaste = (e: React.ClipboardEvent<HTMLInputElement>) => {- const text = e.clipboardData.getData("text");- if (/[\n,]/.test(text)) {- e.preventDefault();- onAdd(text.split(/[\n,]+/));- setQuery("");- }- };-- return (- <div ref={containerRef} className="relative">- <div- className="flex flex-wrap items-center gap-1.5 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2 py-1.5 focus-within:ring-1 focus-within:ring-[var(--color-accent-primary)]"- onClick={() => containerRef.current?.querySelector("input")?.focus()}- >- {selected.map((p) => (- <span- key={p}- className="inline-flex items-center gap-1 rounded border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-1.5 py-0.5 text-[11px] font-mono text-[var(--color-text-primary)]"- title={p}- >- <span className="truncate max-w-[280px]">{p}</span>- <button- type="button"- onClick={(e) => {- e.stopPropagation();- onRemove(p);- }}- aria-label={`Remove ${p}`}- className="text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)]"- >- <X className="h-3 w-3" />- </button>- </span>- ))}- <input- value={query}- onChange={(e) => setQuery(e.target.value)}- onKeyDown={handleKeyDown}- onPaste={handlePaste}- onFocus={() => suggestions.length > 0 && setOpenList(true)}- placeholder={selected.length === 0 ? "src/auth/login.py — type to search, paste a list, Enter to add" : "Add another…"}- aria-label="Changed file paths"- role="combobox"- aria-expanded={openList}- aria-controls="impact-file-suggestions"- aria-autocomplete="list"- className="min-w-[180px] flex-1 bg-transparent px-1 py-0.5 text-xs font-mono text-[var(--color-text-primary)] placeholder:text-[var(--color-text-tertiary)] focus:outline-none"- />- </div>- {openList && suggestions.length > 0 ? (- <ul- id="impact-file-suggestions"- role="listbox"- className="absolute z-20 mt-1 w-full max-h-56 overflow-y-auto rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)] py-1 shadow-lg"- >- {suggestions.map((s, i) => (- <li key={s} role="option" aria-selected={i === activeIndex}>- <button- type="button"- onMouseDown={(e) => {- e.preventDefault();- commit(s);- }}- onMouseEnter={() => setActiveIndex(i)}- className={`block w-full truncate px-3 py-1.5 text-left text-xs font-mono ${- i === activeIndex- ? "bg-[var(--color-bg-elevated)] text-[var(--color-text-primary)]"- : "text-[var(--color-text-secondary)]"- }`}- title={s}- >- {s}- </button>- </li>- ))}- </ul>- ) : null}- </div>- );-}diff --git a/packages/web/src/components/risk/modules-tab.tsx b/packages/web/src/components/risk/modules-tab.tsxdeleted file mode 100644index 68e8c6cf2..000000000--- a/packages/web/src/components/risk/modules-tab.tsx+++ /dev/null@@ -1,87 +0,0 @@-"use client";--import { useMemo, useState } from "react";-import useSWRInfinite from "swr/infinite";-import { useRouter } from "next/navigation";-import { Folder } from "lucide-react";-import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@repowise-dev/ui/ui/select";-import { ModuleHealthList } from "@repowise-dev/ui/modules/module-health-list";-import { listModuleHealth, type ModuleHealthSortKey } from "@/lib/api/modules";-import type { ModuleHealthSummary, Paginated } from "@/lib/api/types";--const PAGE = 30;-const SORT_LABELS: Record<ModuleHealthSortKey, string> = {- health_score: "Lowest health first",- hotspot_count: "Most hotspots",- dead_code_lines: "Most dead code",- file_count: "Largest modules",-};--/**- * "Modules" tab on /risk — engineering-leader rollup of churn / ownership /- * docs / dead-code / decisions per top-level module.- */-export function ModulesTab({ repoId }: { repoId: string }) {- const router = useRouter();- const [sort, setSort] = useState<ModuleHealthSortKey>("health_score");-- const { data, isLoading, isValidating, size, setSize } = useSWRInfinite<- Paginated<ModuleHealthSummary>- >(- (pageIndex, previous) => {- if (previous && !previous.has_more) return null;- return `module-health:${repoId}:${sort}:${pageIndex}`;- },- (key) => {- const pageIndex = parseInt(key.split(":").pop()!, 10);- return listModuleHealth(repoId, {- sort,- limit: PAGE,- offset: pageIndex * PAGE,- });- },- { revalidateOnFocus: false, revalidateFirstPage: false },- );-- const items = useMemo(() => (data ? data.flatMap((p) => p.items) : []), [data]);- const total = data && data.length > 0 ? data[0].total : 0;- const hasMore = data ? data[data.length - 1].has_more : false;-- return (- <div className="space-y-3">- <div className="flex items-center justify-between">- <div className="flex items-center gap-2 text-sm text-[var(--color-text-secondary)]">- <Folder className="h-4 w-4" />- <span>- Health rollup across every top-level module — composite of churn, ownership,- docs, dead-code and decisions.- </span>- </div>- <Select value={sort} onValueChange={(v) => setSort(v as ModuleHealthSortKey)}>- <SelectTrigger className="w-[200px]">- <SelectValue />- </SelectTrigger>- <SelectContent>- {Object.entries(SORT_LABELS).map(([k, label]) => (- <SelectItem key={k} value={k}>- {label}- </SelectItem>- ))}- </SelectContent>- </Select>- </div>-- <ModuleHealthList- modules={items}- isLoading={isLoading}- total={total}- hasMore={hasMore}- loadingMore={isValidating && !isLoading}- onLoadMore={() => setSize(size + 1)}- onSelect={(m) =>- router.push(`/repos/${repoId}/modules/${encodeURIComponent(m.module_path)}`)- }- />- </div>- );-}diff --git a/packages/web/src/components/risk/risk-summary-strip.tsx b/packages/web/src/components/risk/risk-summary-strip.tsxdeleted file mode 100644index 197289f08..000000000--- a/packages/web/src/components/risk/risk-summary-strip.tsx+++ /dev/null@@ -1,90 +0,0 @@-"use client";--import useSWR from "swr";-import { Flame, Users, Trash2, Lightbulb, ShieldAlert } from "lucide-react";-import { StatCard } from "@repowise-dev/ui/shared/stat-card";-import { formatNumber } from "@repowise-dev/ui/lib/format";-import { getGitSummary, getOwnership } from "@/lib/api/git";-import { getDeadCodeSummary } from "@/lib/api/dead-code";-import { getDecisionHealth } from "@/lib/api/decisions";-import { listSecurityFindings } from "@/lib/api/security";--const RISK_BASE = (repoId: string) => `/repos/${repoId}/code-health`;--/**- * Always-visible 5-card strip atop /repos/[id]/risk. Pulls cached SWR data- * shared with the tab bodies, so switching tabs doesn't trigger refetches.- */-export function RiskSummaryStrip({ repoId }: { repoId: string }) {- const { data: gitSummary } = useSWR(`git-summary:${repoId}`, () => getGitSummary(repoId), {- revalidateOnFocus: false,- });- const { data: ownership } = useSWR(`ownership:${repoId}:module`, () =>- getOwnership(repoId, "module"),- );- const { data: deadCode } = useSWR(`dead-code-summary:${repoId}`, () =>- getDeadCodeSummary(repoId),- );- const { data: decisionHealth } = useSWR(- `decision-health:${repoId}`,- () => getDecisionHealth(repoId),- { revalidateOnFocus: false },- );- const { data: securityFindings } = useSWR(- `security-findings:${repoId}`,- // Pull a tight slice; we only need the count for the badge here.- () => listSecurityFindings(repoId, { limit: 200 }).catch(() => [] as Awaited<ReturnType<typeof listSecurityFindings>>),- { revalidateOnFocus: false },- );-- const siloCount = (ownership ?? []).filter((o) => o.is_silo).length;- const reclaimable = deadCode?.deletable_lines ?? 0;- const staleDecisions = decisionHealth?.stale_decisions?.length ?? 0;- const securityCritical = (securityFindings ?? []).filter(- (f) => f.severity === "high" || f.severity === "critical",- ).length;-- return (- <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-5">- <StatCard- label="Hotspots"- value={formatNumber(gitSummary?.hotspot_count ?? 0)}- description="high-churn files"- icon={<Flame className="h-4 w-4 text-orange-400" />}- href={`${RISK_BASE(repoId)}?tab=hotspots`}- />- <StatCard- label="Silos"- value={formatNumber(siloCount)}- description="single-owner modules"- icon={<Users className="h-4 w-4 text-amber-400" />}- href={`/repos/${repoId}/owners`}- />- <StatCard- label="Reclaimable"- value={formatNumber(reclaimable)}- description="lines safe to delete"- icon={<Trash2 className="h-4 w-4 text-rose-400" />}- href={`${RISK_BASE(repoId)}?tab=dead-code`}- />- <StatCard- label="Stale Decisions"- value={formatNumber(staleDecisions)}- description="needing review"- icon={<Lightbulb className="h-4 w-4 text-yellow-400" />}- href={`/repos/${repoId}/decisions`}- />- <StatCard- label="Security"- value={securityFindings ? formatNumber(securityCritical) : "—"}- description={- securityFindings- ? "critical / high findings"- : "scan not run"- }- icon={<ShieldAlert className="h-4 w-4 text-red-400" />}- href={`${RISK_BASE(repoId)}?tab=security`}- />- </div>- );-}diff --git a/packages/web/src/components/risk/routed-to-risk-banner.tsx b/packages/web/src/components/risk/routed-to-risk-banner.tsxdeleted file mode 100644index b6dab572b..000000000--- a/packages/web/src/components/risk/routed-to-risk-banner.tsx+++ /dev/null@@ -1,51 +0,0 @@-"use client";--import Link from "next/link";-import { ShieldAlert, ArrowRight } from "lucide-react";--interface RoutedToRiskBannerProps {- repoId: string;- /** Which Risk tab this old route now lives under. */- tab: "heatmap" | "hotspots" | "dead-code" | "impact";- /** Optional override for the human label (defaults to the tab id). */- tabLabel?: string;-}--const TAB_TITLE: Record<RoutedToRiskBannerProps["tab"], string> = {- heatmap: "Heatmap",- hotspots: "Hotspots",- "dead-code": "Dead code",- impact: "Impact analyzer",-};--/**- * Soft-consolidation banner: legacy /hotspots, /ownership, /dead-code,- * /blast-radius routes still resolve, but the banner nudges users toward- * the unified /repos/[id]/risk page where these now live as tabs. This- * keeps deep links + bookmarks working while the IA migration is rolled out.- */-export function RoutedToRiskBanner({ repoId, tab, tabLabel }: RoutedToRiskBannerProps) {- const target = `/repos/${repoId}/code-health?tab=${tab}`;- const label = tabLabel ?? TAB_TITLE[tab];- return (- <div className="flex flex-wrap items-center gap-2 rounded-lg border border-[var(--color-accent-primary)]/30 bg-[var(--color-accent-primary)]/8 px-3 py-2 text-xs text-[var(--color-text-secondary)]">- <ShieldAlert className="h-3.5 w-3.5 shrink-0 text-[var(--color-accent-primary)]" />- <span className="flex-1 min-w-0">- This view now lives under{" "}- <Link- href={target}- className="font-medium text-[var(--color-accent-primary)] hover:underline"- >- Risk → {label}- </Link>- . Existing bookmarks keep working.- </span>- <Link- href={target}- className="inline-flex shrink-0 items-center gap-1 rounded-md border border-[var(--color-accent-primary)]/40 bg-[var(--color-bg-elevated)] px-2 py-1 font-medium text-[var(--color-accent-primary)] transition hover:bg-[var(--color-accent-primary)]/10"- >- Open Risk <ArrowRight className="h-3 w-3" />- </Link>- </div>- );-}diff --git a/packages/web/src/components/risk/security-tab.tsx b/packages/web/src/components/risk/security-tab.tsxindex fc25308c6..34c69284c 100644--- a/packages/web/src/components/risk/security-tab.tsx+++ b/packages/web/src/components/risk/security-tab.tsx@@ -1,14 +1,14 @@"use client";-import { useMemo, useState } from "react";+import { useState } from "react";import useSWR from "swr";import { RotateCw } from "lucide-react";import { toast } from "sonner";-import { SeverityDistribution } from "@repowise-dev/ui/security/severity-distribution";import { SecurityFindingsTable } from "@repowise-dev/ui/security/findings-table";-import { FindingsByDirectory } from "@repowise-dev/ui/security/findings-by-directory";+import { SeverityDirectoryMatrix } from "@repowise-dev/ui/security/severity-directory-matrix";import { Button } from "@repowise-dev/ui/ui/button";import { Card, CardContent, CardHeader, CardTitle } from "@repowise-dev/ui/ui/card";+import { CollapsibleSection } from "@repowise-dev/ui/shared/collapsible-section";import { Skeleton } from "@repowise-dev/ui/ui/skeleton";import { listSecurityFindings, type SecurityFinding } from "@/lib/api/security";import { syncRepo } from "@/lib/api/repos";@@ -37,14 +37,6 @@ export function SecurityTab({ repoId }: { repoId: string }) {const { showFile, dialog } = useFileCardHost(repoId);- const counts = useMemo(() => {- const c: Record<string, number> = { high: 0, med: 0, low: 0 };- for (const f of findings ?? []) {- c[f.severity] = (c[f.severity] ?? 0) + 1;- }- return c;- }, [findings]);-const handleSelect = (f: SecurityFinding) => {const data: FileCardData = {file_path: f.file_path,@@ -73,10 +65,7 @@ export function SecurityTab({ repoId }: { repoId: string }) {</div>{isLoading ? (- <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">- <Skeleton className="h-40 w-full rounded-lg" />- <Skeleton className="h-40 w-full rounded-lg" />- </div>+ <Skeleton className="h-40 w-full rounded-lg" />) : error ? (<Card><CardHeader className="pb-2">@@ -88,11 +77,16 @@ export function SecurityTab({ repoId }: { repoId: string }) {</Card>) : (<>- <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">- <SeverityDistribution counts={counts} />- <FindingsByDirectory findings={findings ?? []} />- </div>- <SecurityFindingsTable findings={findings ?? []} onSelect={handleSelect} />+ {/* Single visual rollup — per-severity counts live in the table's+ filter pills below, not in a separate distribution card. */}+ <SeverityDirectoryMatrix findings={findings ?? []} />+ <CollapsibleSection+ title="All findings"+ hint={`${(findings ?? []).length} findings`}+ defaultOpen={false}+ >+ <SecurityFindingsTable findings={findings ?? []} onSelect={handleSelect} />+ </CollapsibleSection></>)}diff --git a/packages/web/src/components/search/search-result-card.tsx b/packages/web/src/components/search/search-result-card.tsxindex 96980b5cf..68c074bdc 100644--- a/packages/web/src/components/search/search-result-card.tsx+++ b/packages/web/src/components/search/search-result-card.tsx@@ -48,9 +48,9 @@ export function SearchResultCard({ result, query, repoId }: SearchResultCardPropclassName={cn("inline-flex items-center rounded border px-2 py-0.5 text-xs font-medium tabular-nums",result.score >= 0.8- ? "border-green-500/20 bg-green-500/10 text-green-500"+ ? "border-[var(--color-success)]/20 bg-[var(--color-success)]/10 text-[var(--color-success)]": result.score >= 0.5- ? "border-yellow-500/20 bg-yellow-500/10 text-yellow-500"+ ? "border-[var(--color-warning)]/20 bg-[var(--color-warning)]/10 text-[var(--color-warning)]": "border-[var(--color-border-default)] bg-transparent text-[var(--color-text-tertiary)]",)}>diff --git a/packages/web/src/components/settings/provider-section.tsx b/packages/web/src/components/settings/provider-section.tsxindex 16aa2fc17..266b24a4c 100644--- a/packages/web/src/components/settings/provider-section.tsx+++ b/packages/web/src/components/settings/provider-section.tsx@@ -219,10 +219,10 @@ export function ProviderSection() {{testStatus === "testing" ? "Testing…" : "Test connection"}</button>{testStatus === "ok" && (- <span className="text-sm text-green-600 dark:text-green-400">✓ Server healthy</span>+ <span className="text-sm text-[var(--color-success)]">✓ Server healthy</span>)}{testStatus === "error" && (- <span className="text-sm text-red-600 dark:text-red-400">+ <span className="text-sm text-[var(--color-error)]">✗ {testError || "Connection failed"}</span>)}diff --git a/packages/web/src/components/symbols/symbol-drawer-wrapper.tsx b/packages/web/src/components/symbols/symbol-drawer-wrapper.tsxindex 400d7cdc8..b8e7ddf8e 100644--- a/packages/web/src/components/symbols/symbol-drawer-wrapper.tsx+++ b/packages/web/src/components/symbols/symbol-drawer-wrapper.tsx@@ -1,9 +1,18 @@"use client";+import { useMemo } from "react";+import { useRouter } from "next/navigation";+import useSWR from "swr";import { SymbolDrawer } from "@repowise-dev/ui/symbols/symbol-drawer";-import { SymbolGraphPanelWrapper } from "./symbol-graph-panel-wrapper";-import { SymbolGitPanelWrapper } from "./symbol-git-panel-wrapper";+import {+ fileEntityPath,+ symbolEntityPath,+} from "@repowise-dev/ui/shared/entity";+import { useGraphMetrics, useCallersCallees } from "@/lib/hooks/use-graph";+import { getCoChanges, getGitMetadata } from "@/lib/api/git";+import { listDeadCode } from "@/lib/api/dead-code";import type { SymbolResponse } from "@/lib/api/types";+import type { SymbolDetailData } from "@repowise-dev/types/symbols";interface Props {symbol: SymbolResponse | null;@@ -11,13 +20,136 @@ interface Props {onClose: () => void;}+/**+ * Data-coupled adapter for the modal symbol surface. Fetches the graph+ * metrics, callers/callees, git metadata, co-changes, and dead-code feeds and+ * NORMALIZES them — together with the row's `SymbolResponse` — into the single+ * `SymbolDetailData` shape that `SymbolDetailBody` renders. This is the web+ * adapter referenced by the symbol-surface unification: the ui body stays pure.+ */export function SymbolDrawerWrapper({ symbol, repoId, onClose }: Props) {+ const router = useRouter();+ const nodeId = symbol ? `${symbol.file_path}::${symbol.name}` : null;+ const filePath = symbol?.file_path ?? null;++ const { metrics } = useGraphMetrics(repoId, nodeId);+ const { data: callData, isLoading: callsLoading } = useCallersCallees(repoId, nodeId);++ const { data: git } = useSWR(+ filePath ? `git-meta:${repoId}:${filePath}` : null,+ () =>+ getGitMetadata(repoId, filePath!).catch((err) => {+ if (err?.status === 404) return null;+ throw err;+ }),+ { revalidateOnFocus: false },+ );++ const { data: coChangePayload } = useSWR(+ git && filePath ? `co-changes:${repoId}:${filePath}` : null,+ () => getCoChanges(repoId, filePath!, 2),+ { revalidateOnFocus: false },+ );++ const { data: deadFindings } = useSWR(+ symbol ? `dead-code:${repoId}` : null,+ () => listDeadCode(repoId, { limit: 500 }),+ { revalidateOnFocus: false },+ );++ const overlappingDead = useMemo(() => {+ if (!deadFindings || !symbol) return [];+ return deadFindings.filter(+ (f) =>+ f.file_path === symbol.file_path &&+ f.symbol_name != null &&+ (f.symbol_name === symbol.name || f.symbol_name === symbol.qualified_name),+ );+ }, [deadFindings, symbol]);++ const data: SymbolDetailData | null = useMemo(() => {+ if (!symbol) return null;+ return {+ identity: {+ name: symbol.name,+ qualified_name: symbol.qualified_name,+ kind: symbol.kind,+ visibility: symbol.visibility,+ language: symbol.language,+ is_async: symbol.is_async,+ file_path: symbol.file_path,+ start_line: symbol.start_line,+ parent_name: symbol.parent_name,+ file_is_hotspot: symbol.file_is_hotspot ?? null,+ },+ signature: symbol.signature,+ docstring: symbol.docstring,+ importance_score: symbol.importance_score ?? null,+ complexity_estimate: symbol.complexity_estimate,+ graph: {+ in_degree: metrics?.in_degree ?? callData?.caller_count ?? 0,+ out_degree: metrics?.out_degree ?? callData?.callee_count ?? 0,+ callers: (callData?.callers ?? []).map((c) => ({+ symbol_id: c.symbol_id,+ name: c.name,+ file: c.file,+ edge_type: c.edge_type,+ confidence: c.confidence,+ })),+ callees: (callData?.callees ?? []).map((c) => ({+ symbol_id: c.symbol_id,+ name: c.name,+ file: c.file,+ edge_type: c.edge_type,+ confidence: c.confidence,+ })),+ pagerank_percentile: metrics?.pagerank_percentile ?? null,+ betweenness_percentile: metrics?.betweenness_percentile ?? null,+ community_label: metrics?.community_label ?? null,+ entry_point_score: metrics?.entry_point_score ?? null,+ },+ git: git+ ? {+ primary_owner_name: git.primary_owner_name,+ primary_owner_commit_pct: git.primary_owner_commit_pct,+ recent_owner_name: git.recent_owner_name,+ bus_factor: git.bus_factor,+ contributor_count: git.contributor_count,+ commit_count_90d: git.commit_count_90d,+ is_hotspot: git.is_hotspot,+ churn_percentile: git.churn_percentile,+ }+ : null,+ co_changes: (coChangePayload?.co_change_partners ?? []).map((p) => ({+ file_path: p.file_path,+ co_change_count: p.co_change_count,+ })),+ dead_code: overlappingDead.map((f) => ({+ id: f.id,+ kind: f.kind,+ reason: f.reason,+ lines: f.lines,+ safe_to_delete: f.safe_to_delete,+ })),+ file_context: { language: symbol.language },+ };+ }, [symbol, metrics, callData, git, coChangePayload, overlappingDead]);+return (<SymbolDrawer- symbol={symbol}+ data={data}onClose={onClose}- graphPanel={symbol ? <SymbolGraphPanelWrapper repoId={repoId} symbol={symbol} /> : null}- gitPanel={symbol ? <SymbolGitPanelWrapper repoId={repoId} symbol={symbol} /> : null}+ metricsLoading={callsLoading}+ symbolHref={(symId) => symbolEntityPath(`/repos/${repoId}`, symId)}+ fileHref={(p) => fileEntityPath(`/repos/${repoId}`, p)}+ {...(filePath+ ? {+ onOpenBlastRadius: () =>+ router.push(+ `/repos/${repoId}/code-health?tab=impact&file=${encodeURIComponent(filePath)}`,+ ),+ }+ : {})}/>);}diff --git a/packages/web/src/components/symbols/symbol-git-panel-wrapper.tsx b/packages/web/src/components/symbols/symbol-git-panel-wrapper.tsxdeleted file mode 100644index ed0fda617..000000000--- a/packages/web/src/components/symbols/symbol-git-panel-wrapper.tsx+++ /dev/null@@ -1,120 +0,0 @@-"use client";--import { useRouter } from "next/navigation";-import { useMemo } from "react";-import useSWR from "swr";-import { SymbolGitPanel } from "@repowise-dev/ui/symbols/symbol-git-panel";-import { getCoChanges, getGitMetadata } from "@/lib/api/git";-import { listDeadCode } from "@/lib/api/dead-code";-import { listDecisions } from "@/lib/api/decisions";-import type { SymbolResponse } from "@/lib/api/types";--interface Props {- symbol: SymbolResponse;- repoId: string;-}--/**- * Data-coupled wrapper around {@link SymbolGitPanel}. Fetches per-file- * git metadata, co-changes, and any dead-code findings whose line range- * overlaps the symbol — composed from existing endpoints so this panel- * is purely additive (no ingestion changes required).- */-export function SymbolGitPanelWrapper({ symbol, repoId }: Props) {- const router = useRouter();- const filePath = symbol.file_path;-- const { data: git, isLoading: gitLoading } = useSWR(- `git-meta:${repoId}:${filePath}`,- () =>- getGitMetadata(repoId, filePath).catch((err) => {- // 404 is expected for files outside the indexed history (vendored,- // generated, etc.) — fall back to null so the panel hides itself.- if (err?.status === 404) return null;- throw err;- }),- { revalidateOnFocus: false },- );-- const { data: coChangePayload } = useSWR(- git ? `co-changes:${repoId}:${filePath}` : null,- () => getCoChanges(repoId, filePath, 2),- { revalidateOnFocus: false },- );-- const { data: deadFindings } = useSWR(- `dead-code:${repoId}`,- () => listDeadCode(repoId, { limit: 500 }),- { revalidateOnFocus: false },- );-- // Decisions governing the module containing this file. Module-scope- // matches the existing decision `affected_modules_json` convention.- const modulePath = filePath.split("/", 2)[0];- const { data: decisions } = useSWR(- modulePath ? `decisions:${repoId}:${modulePath}` : null,- () => listDecisions(repoId, { module: modulePath, limit: 25 }),- { revalidateOnFocus: false },- );-- const overlappingDead = useMemo(() => {- if (!deadFindings) return [];- return deadFindings.filter((f) => {- if (f.file_path !== filePath) return false;- // The dead-code finding doesn't carry line ranges in this shape, so- // we conservatively match by file + symbol name when available.- if (!f.symbol_name) return false;- return (- f.symbol_name === symbol.name ||- f.symbol_name === symbol.qualified_name- );- });- }, [deadFindings, filePath, symbol.name, symbol.qualified_name]);-- return (- <SymbolGitPanel- filePath={filePath}- loading={gitLoading}- git={- git- ? {- primary_owner_name: git.primary_owner_name,- primary_owner_commit_pct: git.primary_owner_commit_pct,- recent_owner_name: git.recent_owner_name,- recent_owner_commit_pct: git.recent_owner_commit_pct,- bus_factor: git.bus_factor,- contributor_count: git.contributor_count,- commit_count_90d: git.commit_count_90d,- is_hotspot: git.is_hotspot,- churn_percentile: git.churn_percentile,- top_authors: git.top_authors,- }- : null- }- coChanges={coChangePayload?.co_change_partners ?? []}- deadCode={overlappingDead.map((f) => ({- id: f.id,- kind: f.kind,- reason: f.reason,- confidence: f.confidence,- lines: f.lines,- safe_to_delete: f.safe_to_delete,- }))}- governingDecisions={(decisions ?? []).map((d) => ({- id: d.id,- title: d.title,- status: d.status,- }))}- onSelectOwner={(name, email) => {- const key = email ?? `name:${name}`;- router.push(`/repos/${repoId}/owners/${encodeURIComponent(key)}`);- }}- onSelectDecision={(id) =>- router.push(`/repos/${repoId}/decisions/${encodeURIComponent(id)}`)- }- onOpenBlastRadius={() =>- router.push(`/repos/${repoId}/code-health?tab=impact&file=${encodeURIComponent(filePath)}`)- }- />- );-}diff --git a/packages/web/src/components/symbols/symbol-graph-panel-wrapper.tsx b/packages/web/src/components/symbols/symbol-graph-panel-wrapper.tsxdeleted file mode 100644index 903a81629..000000000--- a/packages/web/src/components/symbols/symbol-graph-panel-wrapper.tsx+++ /dev/null@@ -1,29 +0,0 @@-"use client";--import { SymbolGraphPanel } from "@repowise-dev/ui/symbols/symbol-graph-panel";-import { useGraphMetrics, useCallersCallees } from "@/lib/hooks/use-graph";-import type { SymbolResponse } from "@/lib/api/types";--interface Props {- repoId: string;- symbol: SymbolResponse;-}--export function SymbolGraphPanelWrapper({ repoId, symbol }: Props) {- const nodeId = `${symbol.file_path}::${symbol.name}`;- const { metrics, isLoading: metricsLoading } = useGraphMetrics(repoId, nodeId);- const { data: callData, isLoading: callsLoading } = useCallersCallees(repoId, nodeId);- const { data: heritageData } = useCallersCallees(repoId, nodeId, {- edge_types: "extends,implements",- });-- return (- <SymbolGraphPanel- metrics={metrics}- metricsLoading={metricsLoading}- callData={callData}- callsLoading={callsLoading}- heritageData={heritageData}- />- );-}diff --git a/packages/web/src/components/symbols/symbol-table-wrapper.tsx b/packages/web/src/components/symbols/symbol-table-wrapper.tsxindex 0baa255f9..dfc6ffc70 100644--- a/packages/web/src/components/symbols/symbol-table-wrapper.tsx+++ b/packages/web/src/components/symbols/symbol-table-wrapper.tsx@@ -5,7 +5,6 @@ import { useSearchParams } from "next/navigation";import { X } from "lucide-react";import useSWRInfinite from "swr/infinite";import { SymbolTable, type SymbolFilters } from "@repowise-dev/ui/symbols/symbol-table";-import { HotSymbolsBoard, type HotSymbol } from "@repowise-dev/ui/symbols/hot-symbols-board";import { SymbolDrawerWrapper } from "./symbol-drawer-wrapper";import { listSymbolsPage, type SymbolSortKey } from "@/lib/api/symbols";import { useDebounce } from "@/lib/hooks/use-debounce";@@ -77,25 +76,11 @@ export function SymbolTableWrapper({ repoId }: Props) {const total = data && data.length > 0 ? data[0].total : 0;const hasMore = data ? data[data.length - 1].has_more : false;- // Hot symbols board — uses the same server-ranked stream so it matches- // the table's order. We just take the top of the first page.- const hotSymbols: HotSymbol[] = useMemo(() => {- const firstPage = data && data.length > 0 ? data[0].items : [];- return firstPage- .filter((s) => (s.importance_score ?? 0) > 0)- .slice(0, 8)- .map((s) => ({- symbol: s,- score: s.importance_score ?? 0,- pagerank: s.file_pagerank ?? 0,- }));- }, [data]);-return (<div className="space-y-6">{fileFilter && (<div className="flex items-center gap-2">- <span className="inline-flex items-center gap-1.5 rounded-full border border-[var(--color-accent-primary)]/40 bg-[var(--color-accent-muted)] px-2.5 py-1 text-[11px] font-mono text-[var(--color-accent-primary)]">+ <span className="inline-flex items-center gap-1.5 rounded-full border border-[var(--color-accent-primary)]/40 bg-[var(--color-accent-muted)] px-2.5 py-1 text-xs font-mono text-[var(--color-accent-primary)]">{fileFilter}<buttontype="button"@@ -106,14 +91,11 @@ export function SymbolTableWrapper({ repoId }: Props) {<X className="h-3 w-3" /></button></span>- <span className="text-[11px] text-[var(--color-text-tertiary)]">+ <span className="text-xs text-[var(--color-text-tertiary)]">showing symbols in this file only</span></div>)}- {hotSymbols.length > 0 && (- <HotSymbolsBoard items={hotSymbols} onSelect={setSelected} />- )}<SymbolTableitems={items}repoId={repoId}diff --git a/packages/web/src/components/wiki/human-notes.tsx b/packages/web/src/components/wiki/human-notes.tsxindex cc321d6f6..cb21da771 100644--- a/packages/web/src/components/wiki/human-notes.tsx+++ b/packages/web/src/components/wiki/human-notes.tsx@@ -1,14 +1,12 @@"use client";-import { useState } from "react";import { toast } from "sonner";-import { Pencil, StickyNote, X } from "lucide-react";-import { Button } from "@repowise-dev/ui/ui/button";+import { HumanNotes as HumanNotesShell } from "@repowise-dev/ui/wiki/human-notes";import { updatePageNotes } from "@/lib/api/pages";/**- * Human-curated note pinned above a page's generated content, now editable- * in place. Notes survive regeneration server-side.+ * Web data wrapper around the presentational ``HumanNotes`` ui shell — owns the+ * persistence call and toast feedback. Notes survive regeneration server-side.*/export function HumanNotes({pageId,@@ -17,104 +15,21 @@ export function HumanNotes({pageId: string;initialNotes: string | null;}) {- const [notes, setNotes] = useState(initialNotes);- const [editing, setEditing] = useState(false);- const [draft, setDraft] = useState(initialNotes ?? "");- const [saving, setSaving] = useState(false);-- async function save() {- setSaving(true);- try {- const updated = await updatePageNotes(pageId, draft.trim() || null);- setNotes(updated.human_notes);- setDraft(updated.human_notes ?? "");- setEditing(false);- toast.success(updated.human_notes ? "Note saved" : "Note removed");- } catch (e) {- toast.error("Couldn't save note", {- description: e instanceof Error ? e.message : undefined,- });- } finally {- setSaving(false);- }- }-- if (!editing && !notes) {- return (- <button- onClick={() => setEditing(true)}- className="mb-5 inline-flex items-center gap-1.5 text-xs text-[var(--color-text-tertiary)] transition-colors hover:text-[var(--color-text-secondary)]"- >- <StickyNote className="h-3.5 w-3.5" />- Add a note for your team — it survives regeneration- </button>- );- }-return (- <div className="mb-5 rounded-lg border border-[var(--color-border-accent)] bg-[var(--color-accent-blue)]/5 px-4 py-3">- <div className="mb-1.5 flex items-center gap-1.5">- <StickyNote className="h-3.5 w-3.5 text-[var(--color-accent-blue)]" />- <span className="text-xs font-medium uppercase tracking-wider text-[var(--color-accent-blue)]">- Human Notes- </span>- {!editing && (- <button- onClick={() => setEditing(true)}- aria-label="Edit note"- className="ml-auto text-[var(--color-text-tertiary)] transition-colors hover:text-[var(--color-text-primary)]"- >- <Pencil className="h-3 w-3" />- </button>- )}- {editing && (- <button- onClick={() => {- setEditing(false);- setDraft(notes ?? "");- }}- aria-label="Cancel editing"- className="ml-auto text-[var(--color-text-tertiary)] transition-colors hover:text-[var(--color-text-primary)]"- >- <X className="h-3 w-3" />- </button>- )}- </div>- {editing ? (- <div className="space-y-2">- <textarea- value={draft}- onChange={(e) => setDraft(e.target.value)}- rows={4}- autoFocus- aria-label="Human note"- placeholder="Context the generated docs can't know — gotchas, history, plans…"- className="w-full resize-y rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-3 py-2 text-sm text-[var(--color-text-primary)] outline-none placeholder:text-[var(--color-text-tertiary)]"- />- <div className="flex items-center gap-2">- <Button size="sm" onClick={() => void save()} disabled={saving}>- {saving ? "Saving…" : "Save note"}- </Button>- {notes && (- <Button- size="sm"- variant="ghost"- disabled={saving}- onClick={() => {- setDraft("");- void save();- }}- >- Remove note- </Button>- )}- </div>- </div>- ) : (- <p className="whitespace-pre-wrap text-sm leading-relaxed text-[var(--color-text-secondary)]">- {notes}- </p>- )}- </div>+ <HumanNotesShell+ initialNotes={initialNotes}+ onSave={async (value) => {+ try {+ const updated = await updatePageNotes(pageId, value);+ toast.success(updated.human_notes ? "Note saved" : "Note removed");+ return updated.human_notes;+ } catch (e) {+ toast.error("Couldn't save note", {+ description: e instanceof Error ? e.message : undefined,+ });+ throw e;+ }+ }}+ />);}diff --git a/packages/web/src/components/wiki/wiki-renderer.tsx b/packages/web/src/components/wiki/wiki-renderer.tsxdeleted file mode 100644index bdfe20947..000000000--- a/packages/web/src/components/wiki/wiki-renderer.tsx+++ /dev/null@@ -1,66 +0,0 @@-import { MDXRemote } from "next-mdx-remote/rsc";-import { codeToHtml } from "shiki";-import { CodeBlock } from "@repowise-dev/ui/wiki/code-block";-import { MermaidDiagram } from "@repowise-dev/ui/wiki/mermaid-diagram";-import { wikiMdxComponents } from "@repowise-dev/ui/wiki/wiki-mdx-components";-import { preprocessWikiCodeBlocks } from "@repowise-dev/ui/wiki/wiki-mdx-preprocess";-import { WikiLink } from "@repowise-dev/ui/wiki/wiki-link";-import {- buildAnchorIndex,- type WikiLinkRef,-} from "@repowise-dev/ui/wiki/wiki-links-types";--interface Props {- content: string;- /** Pre-resolved wiki links from ``page.metadata.wiki_links``. */- wikiLinks?: WikiLinkRef[];- /** Repo ID required to build cross-page hrefs. */- repoId?: string;-}--export async function WikiRenderer({ content, wikiLinks, repoId }: Props) {- // Build the anchor → page_id index once per render; the preprocessor- // does an O(1) Map lookup per backtick match.- const index = buildAnchorIndex(wikiLinks ?? []);- const resolveWikiLink = repoId- ? (anchor: string) => index.get(anchor) ?? null- : undefined;- const buildWikiLinkUrl = (pageId: string) =>- `/repos/${repoId}/wiki/${encodeURIComponent(pageId)}`;-- const preprocessed = await preprocessWikiCodeBlocks(content, {- highlight: async (code, lang) =>- // Dual themes: tokens carry --shiki-light/--shiki-dark CSS vars and- // globals.css picks one per theme (see ".shiki span" rules there).- codeToHtml(code, {- lang: lang as Parameters<typeof codeToHtml>[1]["lang"],- themes: { light: "github-light", dark: "vesper" },- defaultColor: false,- }),- resolveWikiLink,- buildWikiLinkUrl,- });-- return (- <MDXRemote- source={preprocessed.source}- components={{- ...wikiMdxComponents,- ShikiBlock: ({ html, code, lang }: { html: string; code: string; lang: string }) => (- <CodeBlock html={html} code={code} language={lang} />- ),- MermaidBlock: ({ chart }: { chart: string }) => (- <MermaidDiagram chart={chart} />- ),- WikiLink,- }}- options={{- parseFrontmatter: false,- mdxOptions: {- remarkPlugins: [],- rehypePlugins: [],- },- }}- />- );-}diff --git a/packages/web/src/lib/api/decisions.ts b/packages/web/src/lib/api/decisions.tsindex 37903c4eb..a214969ab 100644--- a/packages/web/src/lib/api/decisions.ts+++ b/packages/web/src/lib/api/decisions.ts@@ -4,7 +4,6 @@ import type {DecisionEvidence,DecisionEvidenceResponse,DecisionGraph,- DecisionHealthResponse,DecisionLineageEntry,DecisionLineageResponse,DecisionRecordResponse,@@ -52,14 +51,6 @@ export async function patchDecision();}-export async function getDecisionHealth(- repoId: string,-): Promise<DecisionHealthResponse> {- return apiGet<DecisionHealthResponse>(- `/api/repos/${repoId}/decisions/health`,- );-}-export async function getDecisionEvidence(repoId: string,decisionId: string,diff --git a/packages/web/src/lib/api/types/dead-code.ts b/packages/web/src/lib/api/types/dead-code.tsindex 0263c730b..abea92e7e 100644--- a/packages/web/src/lib/api/types/dead-code.ts+++ b/packages/web/src/lib/api/types/dead-code.ts@@ -2,6 +2,8 @@// Dead Code// ---------------------------------------------------------------------------+import type { DeadCodeStatus } from "@repowise-dev/types/dead-code";+export interface DeadCodeFindingResponse {id: string;kind: string;@@ -18,12 +20,12 @@ export interface DeadCodeFindingResponse {/** Human-readable signals behind the finding (no-importers, age, risk). */evidence: string[];primary_owner: string | null;- status: string;+ status: DeadCodeStatus;note: string | null;}export interface DeadCodePatchRequest {- status: string;+ status: DeadCodeStatus;note?: string;}diff --git a/packages/web/src/lib/api/types/decisions.ts b/packages/web/src/lib/api/types/decisions.tsindex cbab43310..93de970a5 100644--- a/packages/web/src/lib/api/types/decisions.ts+++ b/packages/web/src/lib/api/types/decisions.ts@@ -120,16 +120,3 @@ export interface DecisionStatusUpdate {affected_modules?: string[];affected_files?: string[];}--export interface DecisionHealthResponse {- summary: {- active: number;- proposed: number;- deprecated: number;- superseded: number;- stale: number;- };- stale_decisions: DecisionRecordResponse[];- proposed_awaiting_review: DecisionRecordResponse[];- ungoverned_hotspots: string[];-}diff --git a/packages/web/src/lib/utils/health-score.ts b/packages/web/src/lib/utils/health-score.tsdeleted file mode 100644index bf06f6906..000000000--- a/packages/web/src/lib/utils/health-score.ts+++ /dev/null@@ -1,219 +0,0 @@-import type { HealthScoreComponent } from "@repowise-dev/ui/dashboard/health-score-ring";--export interface HealthScoreResult {- score: number;- components: HealthScoreComponent[];- /** True when the repo was indexed without generating wiki docs. */- indexOnly: boolean;- /** Human-readable note describing any reweighting (or undefined if none). */- note?: string;-}--/** Compute composite health score from available repo data */-export function computeHealthScore(params: {- docCoveragePct: number;- freshnessScore: number;- deadExportCount: number;- symbolCount: number;- hotspotCount: number;- totalFiles: number;- siloCount: number;- totalModules: number;-}): HealthScoreResult {- const {- docCoveragePct,- freshnessScore,- deadExportCount,- symbolCount,- hotspotCount,- totalFiles,- siloCount,- totalModules,- } = params;-- // Detect index-only mode: docs were never generated for this repo, so doc- // coverage and freshness are structurally zero. Penalizing them would punish- // users who explicitly opted into `repowise init --index-only`. We drop both- // components and renormalize the remaining weights.- const docsGenerated = docCoveragePct > 0 || freshnessScore > 0;-- // Doc coverage: 0-100, weight 25% (when applicable)- const docScore = Math.min(docCoveragePct, 100);-- // Freshness: 0-100, weight 25% (when applicable)- const freshScore = Math.min(freshnessScore * 100, 100);-- // Dead code: lower is better, weight 20%- const deadRatio = symbolCount > 0 ? deadExportCount / symbolCount : 0;- const deadScore = Math.max(0, (1 - deadRatio * 5) * 100);-- // Hotspot density: lower is better, weight 15%- const hotspotRatio = totalFiles > 0 ? hotspotCount / totalFiles : 0;- const hotspotScore = Math.max(0, (1 - hotspotRatio * 3) * 100);-- // Knowledge distribution: fewer silos is better, weight 15%- const siloRatio = totalModules > 0 ? siloCount / totalModules : 0;- const siloScore = Math.max(0, (1 - siloRatio * 2) * 100);-- const baseComponents: HealthScoreComponent[] = docsGenerated- ? [- {- key: "doc_coverage",- label: "Doc Coverage",- weight: 0.25,- score: Math.round(docScore),- detail: `${Math.round(docCoveragePct)}% of symbols documented`,- },- {- key: "freshness",- label: "Freshness",- weight: 0.25,- score: Math.round(freshScore),- detail: "Based on doc-to-code drift analysis",- },- {- key: "dead_code",- label: "Dead Code",- weight: 0.2,- score: Math.round(deadScore),- detail: `${deadExportCount} dead exports out of ${symbolCount} symbols`,- },- {- key: "hotspot_density",- label: "Hotspot Density",- weight: 0.15,- score: Math.round(hotspotScore),- detail: `${hotspotCount} hotspots across ${totalFiles} files`,- },- {- key: "knowledge_silos",- label: "Knowledge Silos",- weight: 0.15,- score: Math.round(siloScore),- detail: `${siloCount} silo${siloCount === 1 ? "" : "s"} out of ${totalModules} modules`,- },- ]- : [- // Index-only: redistribute the 0.25+0.25 doc weights across the- // remaining three components proportionally (0.20:0.15:0.15 → 0.40:0.30:0.30).- {- key: "dead_code",- label: "Dead Code",- weight: 0.4,- score: Math.round(deadScore),- detail: `${deadExportCount} dead exports out of ${symbolCount} symbols`,- },- {- key: "hotspot_density",- label: "Hotspot Density",- weight: 0.3,- score: Math.round(hotspotScore),- detail: `${hotspotCount} hotspots across ${totalFiles} files`,- },- {- key: "knowledge_silos",- label: "Knowledge Silos",- weight: 0.3,- score: Math.round(siloScore),- detail: `${siloCount} silo${siloCount === 1 ? "" : "s"} out of ${totalModules} modules`,- },- ];-- const composite = Math.round(- baseComponents.reduce((sum, c) => sum + c.score * c.weight, 0),- );-- return {- score: Math.max(0, Math.min(100, composite)),- components: baseComponents,- indexOnly: !docsGenerated,- note: docsGenerated- ? undefined- : "Docs haven't been generated for this repo (index-only). Doc Coverage and Freshness are excluded; remaining components are reweighted.",- };-}--/** Aggregate language distribution from graph nodes */-export function aggregateLanguages(- nodes: Array<{ language: string; node_type: string }>-): Record<string, number> {- const counts: Record<string, number> = {};- for (const n of nodes) {- if (n.node_type === "file" || !n.node_type) {- const lang = n.language?.toLowerCase() || "unknown";- counts[lang] = (counts[lang] || 0) + 1;- }- }- return counts;-}--export type { AttentionItem } from "@repowise-dev/ui/dashboard/attention-panel";-import type { AttentionItem } from "@repowise-dev/ui/dashboard/attention-panel";--/** Build attention items from existing API responses */-export function buildAttentionItems(params: {- staleDecisions: Array<{ id: string; title: string; staleness_score: number }>;- proposedDecisions: Array<{ id: string; title: string }>;- ungovernedHotspots: string[];- siloModules: Array<{ module_path: string; primary_owner: string | null }>;- deadCodeSafe: Array<{ id: string; file_path: string; symbol_name: string | null; lines: number }>;-}): AttentionItem[] {- const items: AttentionItem[] = [];-- for (const d of params.staleDecisions.slice(0, 3)) {- items.push({- id: `stale-${d.id}`,- type: "stale_decision",- title: d.title,- description: `Staleness score: ${Math.round(d.staleness_score * 100)}%`,- severity: d.staleness_score > 0.7 ? "high" : "medium",- });- }-- for (const h of params.ungovernedHotspots.slice(0, 3)) {- items.push({- id: `hotspot-${h}`,- type: "ungoverned_hotspot",- title: h.split("/").slice(-2).join("/"),- description: "High churn, no governing decision",- severity: "high",- });- }-- for (const s of params.siloModules.slice(0, 3)) {- items.push({- id: `silo-${s.module_path}`,- type: "knowledge_silo",- title: s.module_path,- description: `Single owner: ${s.primary_owner ?? "unknown"}`,- severity: "medium",- });- }-- const totalDeadLines = params.deadCodeSafe.reduce((sum, d) => sum + d.lines, 0);- if (params.deadCodeSafe.length > 0) {- items.push({- id: "dead-code-summary",- type: "dead_code",- title: `${params.deadCodeSafe.length} safe-to-delete findings`,- description: `${totalDeadLines} lines can be removed`,- severity: totalDeadLines > 500 ? "medium" : "low",- });- }-- for (const p of params.proposedDecisions.slice(0, 2)) {- items.push({- id: `proposed-${p.id}`,- type: "proposed_decision",- title: p.title,- description: "Awaiting review",- severity: "low",- });- }-- // Sort by severity- const order = { high: 0, medium: 1, low: 2 };- items.sort((a, b) => order[a.severity] - order[b.severity]);-- return items;-}