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
feat(files): port the file detail page onto the design language (#1621)
Raghav Chamadiya753349c4a0d2
diff --git a/packages/server/src/repowise/server/routers/files.py b/packages/server/src/repowise/server/routers/files.pyindex 9b42a408c..0f1b6a91f 100644--- a/packages/server/src/repowise/server/routers/files.py+++ b/packages/server/src/repowise/server/routers/files.py@@ -15,7 +15,7 @@ import jsonfrom typing import Anyfrom fastapi import APIRouter, Depends, HTTPException, Query-from sqlalchemy import select+from sqlalchemy import func, selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom repowise.core.analysis.health.signals import file_signals@@ -24,7 +24,12 @@ from repowise.core.ids import is_externalfrom repowise.core.ingestion.models import FILE_DEPENDENCY_EDGE_TYPESfrom repowise.core.persistence import crudfrom repowise.core.persistence.decision_graph import get_governing_decisions-from repowise.core.persistence.models import DeadCodeFinding, Page, WikiSymbol+from repowise.core.persistence.models import (+ DeadCodeFinding,+ GitFunctionBlame,+ Page,+ WikiSymbol,+)from repowise.server.deps import get_db_session, verify_api_keyfrom repowise.server.mcp_server._graph_utils import parse_community_metafrom repowise.server.routers.code_health import (@@ -221,8 +226,9 @@ async def file_detail("everything. 'slim' drops the four unbounded payloads — the wiki page ""body, the coverage line array, per-function blame, and each finding's ""'details' map — for a caller that renders the summary numbers only. "- "'coverage.covered_line_count' is present in both modes, so the "- "coverage headline survives the cut.",+ "'coverage.covered_line_count' and 'function_blame_count' are present "+ "in both modes, so a caller can still tell an empty block from a "+ "dropped one.",),session: AsyncSession = Depends(get_db_session),) -> dict:@@ -407,11 +413,29 @@ async def file_detail()).all()# Skipped outright under ``fields=slim`` — a query the caller cannot read.- blame_rows = (- []- if slim- else await crud.get_git_function_blames(session, repo_id, file_path=file_path)- )+ # The *count* still goes on the wire, for the same reason+ # ``covered_line_count`` does: a caller deciding whether the Health tab is+ # worth a round trip cannot tell an empty table from a dropped one, and+ # guessing either way is wrong for some file. One indexed COUNT against+ # ``(repository_id, file_path)``.+ blame_rows: list[Any] = []+ blame_count = 0+ if slim:+ blame_count = int(+ (+ await session.execute(+ select(func.count())+ .select_from(GitFunctionBlame)+ .where(+ GitFunctionBlame.repository_id == repo_id,+ GitFunctionBlame.file_path == file_path,+ )+ )+ ).scalar_one()+ )+ else:+ blame_rows = list(await crud.get_git_function_blames(session, repo_id, file_path=file_path))+ blame_count = len(blame_rows)# --- Governing decisions + dead code -------------------------------------governing = [@@ -453,6 +477,7 @@ async def file_detail("graph": graph,"symbols": [_symbol_slim(s) for s in symbol_rows],"function_blame": [_blame_to_dict(b) for b in blame_rows],+ "function_blame_count": blame_count,"governing_decisions": governing,"dead_code": dead_code,}diff --git a/packages/types/src/files.ts b/packages/types/src/files.tsindex 607ab9a7c..c1b707e20 100644--- a/packages/types/src/files.ts+++ b/packages/types/src/files.ts@@ -253,7 +253,16 @@ export interface FileDetailResponse {coverage: FileDetailCoverage | null;graph: FileDetailGraph | null;symbols: FileSymbolSlim[];+ /** Empty under `fields=slim`; read `function_blame_count` for the total. */function_blame: FunctionBlameRow[];+ /**+ * How many blame rows exist, in both modes. Optional so a frontend ahead of+ * its backend degrades rather than rendering `NaN` — the same contract+ * `coverage.covered_line_count` follows, and for the same reason: a caller+ * deciding whether a block is worth fetching cannot otherwise tell an empty+ * table from a dropped one.+ */+ function_blame_count?: number;governing_decisions: GoverningDecisionRef[];dead_code: FileDeadCodeFinding[];}diff --git a/packages/ui/COMPONENT_CONTRACTS.md b/packages/ui/COMPONENT_CONTRACTS.mdindex 0245dd2da..8a20ae255 100644--- a/packages/ui/COMPONENT_CONTRACTS.md+++ b/packages/ui/COMPONENT_CONTRACTS.md@@ -887,15 +887,48 @@ link to `/commits?commit=`). `SavingsMini` accepts the structural## `files/*` — File entity pageThe canonical "everything about this file" page used by-`/repos/[id]/files/<path>`. `FilePage` (client) assembles the header-(path, health badge, signal chips, governing decisions) plus Doc /-Health / History / Coverage / Graph tabs; per-tab components are-exported individually. Data arrives as one `FileDetailResponse`-(`@repowise-dev/types/files`); the host supplies `docSlot` (rendered-markdown), `coverageCodeHtml` (shiki output whose `.line` nodes carry-`data-covered` attributes), and `onFindingStatusChange` for triage.-`symbols/symbol-page` (`SymbolPage`) is the symbol-page sibling fed by-`SymbolDetailResponse`.+`/repos/[id]/files/<path>`. `symbols/symbol-page` (`SymbolPage`) is the+symbol-page sibling fed by `SymbolDetailResponse`.++**The page is four pieces, not one component, and the split is the+hydration boundary.** A host composes them; it does not hand a+`FileDetailResponse` to a client component.++| Piece | Where it runs | Job |+|---|---|---|+| `FilePageHeader` | server | Eyebrow, path as identity, the `PageLede` figure, the marker row, the `StatRibbon`. |+| `fileTabsFor(data)` | server | The tab row as `FileTabDef[]` — label, blurb, badge. `resolveFileTab` narrows a `?tab=` value against it. |+| `buildFilePanels({...})` | server | Renders the six pure tab bodies and returns them keyed by tab id. Takes `healthPanel` as an already-wrapped node. |+| `FilePage` | client | The shell: header slot, `ViewTabs`, active panel. Imports `ViewTabs` and nothing else from the slice. |++`FilePage` used to be `"use client"` and import all seven tab bodies, so+the whole slice plus a twice-serialised `FileDetailResponse` reached the+browser to render one tab. `file-health-tab` is now the only file in+`files/*` carrying `"use client"` — it owns triage state, two virtualised+lists and a measured trend. Because its triage callback and href builders+are functions, a host wraps it itself and passes the result in as+`healthPanel`; that wrapper is the page's only client boundary besides+the shell.++Two consequences a host must honour:++- **Key the shell on the file path.** Tab clicks are a shallow+ `history.replaceState`, so a soft navigation from one file page to+ another keeps React's state at the same tree position and strands the+ active tab out of sync with the URL. Every cross-file link in the tab+ bodies is a plain `<a>` today, which hides this; converting one to a+ router link without the key surfaces it.+- **`fields=slim` is the default fetch.** Only Documentation, Health and+ Coverage read the four unbounded blocks the aggregate can drop, so the+ route fetches slim unless the requested tab is one of those, and tells+ the shell through `refetchTabs` which tabs need a round trip on first+ click. A tab with nothing behind it is left out of that list rather+ than buying a trip to be shown the same empty state.++Bands come from `bandForScore` (`@repowise-dev/types/health`), never from+`scoreBadgeClass` — that is a four-step presentation ramp and this page+sits one click from the treemap and the health map, which both paint the+canonical three.### `dashboard/attention-panel` — `AttentionPanel`diff --git a/packages/ui/__tests__/files/file-decisions-tab.test.tsx b/packages/ui/__tests__/files/file-decisions-tab.test.tsxindex 035a2459b..15c826cff 100644--- a/packages/ui/__tests__/files/file-decisions-tab.test.tsx+++ b/packages/ui/__tests__/files/file-decisions-tab.test.tsx@@ -1,9 +1,17 @@-import { describe, it, expect, vi } from "vitest";+import { describe, it, expect, vi, beforeAll } from "vitest";import { render, screen, fireEvent } from "@testing-library/react";import { FileDecisionsTab } from "../../src/files/file-decisions-tab.js";import { FilePage } from "../../src/files/file-page.js";+import { FilePageHeader } from "../../src/files/file-page-header.js";+import { buildFilePanels } from "../../src/files/file-page-panels.js";+import { fileTabsFor, type FilePageTab } from "../../src/files/file-page-tabs.js";import type { FileDetailResponse, GoverningDecisionRef } from "@repowise-dev/types/files";+// jsdom has no scrollIntoView; `ViewTabs` keeps the active tab in view on mount.+beforeAll(() => {+ Element.prototype.scrollIntoView = vi.fn();+});+function makeDecision(id: string, title: string, status: string): GoverningDecisionRef {return { id, title, status };}@@ -57,50 +65,68 @@ describe("FileDecisionsTab", () => {});});-describe("FilePage - Governing Decisions Header & Tab", () => {- it("renders header summary and Decisions tab when decisions exist", () => {- const decisions = [+/** The page as the route composes it: panels rendered ahead of the shell, the+ * shell client-only. Written out here rather than hidden behind a helper so a+ * regression that puts a tab body back inside the client bundle shows up as a+ * test that no longer compiles. */+function renderPage(+ data: FileDetailResponse,+ extra: { initialTab?: FilePageTab; onTabChange?: (t: FilePageTab) => void } = {},+) {+ const tabs = fileTabsFor(data);+ const panels = buildFilePanels({+ data,+ linkPrefix: "/repos/r1",+ fileHref: (p) => `/repos/r1/files/${p}`,+ symbolHref: (s) => `/repos/r1/symbols/${s}`,+ });+ return render(+ <FilePage+ header={<FilePageHeader data={data} linkPrefix="/repos/r1" />}+ tabs={tabs}+ panels={panels}+ {...extra}+ />,+ );+}++describe("FilePage — the tab row", () => {+ it("badges the Decisions tab with its count when decisions exist", () => {+ const data = makeMockFileData([makeDecision("d1", "Keep branch names generic", "active"),makeDecision("d2", "Use TypeScript strictly", "active"),- ];- const data = makeMockFileData(decisions);+ ]);- render(<FilePage data={data} repoId="r1" />);+ renderPage(data);- expect(screen.getByText("Governed by")).toBeTruthy();- expect(screen.getByText("2 decisions")).toBeTruthy();expect(screen.getByRole("tab", { name: /decisions 2/i })).toBeTruthy();});- it("hides header summary line and Decisions tab when governing_decisions is empty", () => {- const data = makeMockFileData([]);-- render(<FilePage data={data} repoId="r1" />);+ it("drops the Decisions tab entirely when governing_decisions is empty", () => {+ renderPage(makeMockFileData([]));- expect(screen.queryByText("Governed by")).toBeNull();expect(screen.queryByRole("tab", { name: /decisions/i })).toBeNull();});- it("switches to Decisions tab when clicking header summary line", () => {- const decisions = [makeDecision("d1", "Single decision title", "active")];- const data = makeMockFileData(decisions);+ it("shows the decisions panel and reports the change when the tab is clicked", () => {+ const data = makeMockFileData([makeDecision("d1", "Single decision title", "active")]);const onTabChange = vi.fn();- render(<FilePage data={data} repoId="r1" onTabChange={onTabChange} />);-- const headerButton = screen.getByRole("button", { name: /governed by 1 decision/i });- fireEvent.click(headerButton);+ renderPage(data, { onTabChange });+ fireEvent.click(screen.getByRole("tab", { name: /decisions 1/i }));expect(onTabChange).toHaveBeenCalledWith("decisions");- expect(screen.getByRole("tab", { name: /decisions 1/i }).getAttribute("aria-selected")).toBe("true");+ expect(+ screen.getByRole("tab", { name: /decisions 1/i }).getAttribute("aria-selected"),+ ).toBe("true");expect(screen.getByText("Single decision title")).toBeTruthy();});it("falls back to overview if initialTab is decisions but governing_decisions is empty", () => {- const data = makeMockFileData([]);-- render(<FilePage data={data} repoId="r1" initialTab="decisions" />);+ renderPage(makeMockFileData([]), { initialTab: "decisions" });- expect(screen.getByRole("tab", { name: /overview/i }).getAttribute("aria-selected")).toBe("true");+ expect(screen.getByRole("tab", { name: /overview/i }).getAttribute("aria-selected")).toBe(+ "true",+ );});});diff --git a/packages/ui/__tests__/files/file-history-tab.test.tsx b/packages/ui/__tests__/files/file-history-tab.test.tsxindex 8dada7370..8e0ac71e8 100644--- a/packages/ui/__tests__/files/file-history-tab.test.tsx+++ b/packages/ui/__tests__/files/file-history-tab.test.tsx@@ -111,6 +111,6 @@ describe("FileHistoryTab file age", () => {describe("FileHistoryTab without git", () => {it("falls back to the empty state", () => {renderTab(null);- expect(screen.getByText("No git history")).toBeTruthy();+ expect(screen.getByText("No git history for this file")).toBeTruthy();});});diff --git a/packages/ui/__tests__/files/file-page-header.test.tsx b/packages/ui/__tests__/files/file-page-header.test.tsxnew file mode 100644index 000000000..2a2d71a38--- /dev/null+++ b/packages/ui/__tests__/files/file-page-header.test.tsx@@ -0,0 +1,125 @@+import { describe, it, expect } from "vitest";+import { render, screen } from "@testing-library/react";+import { FilePageHeader } from "../../src/files/file-page-header.js";+import { fileTabsFor } from "../../src/files/file-page-tabs.js";+import type { FileDetailResponse } from "@repowise-dev/types/files";++function makeData(overrides: Partial<FileDetailResponse> = {}): FileDetailResponse {+ return {+ file_path: "packages/ui/src/files/file-page.tsx",+ wiki_page: null,+ health: { metric: null, breakdown: null, findings: [], trend: null, signals: null },+ git: null,+ coverage: null,+ graph: null,+ symbols: [],+ function_blame: [],+ governing_decisions: [],+ dead_code: [],+ ...overrides,+ } as unknown as FileDetailResponse;+}++function metric(score: number) {+ return {+ file_path: "packages/ui/src/files/file-page.tsx",+ score,+ max_ccn: 4,+ max_nesting: 2,+ nloc: 245,+ has_test_file: true,+ line_coverage_pct: null,+ module: null,+ duplication_pct: null,+ };+}++describe("FilePageHeader health band", () => {+ it("bands a 6.9 as Warning, the way every other surface does", () => {+ // The trap this replaced: `scoreBadgeClass` is a four-step presentation+ // ramp that calls 6.9 "fair" and paints it caution, while the treemap and+ // the map that link here paint `bandForScore`. Same file, two readings.+ render(+ <FilePageHeader+ data={makeData({ health: { ...makeData().health, metric: metric(6.9) } })}+ linkPrefix="/repos/r1"+ />,+ );+ expect(screen.getByText("6.9")).toBeTruthy();+ expect(screen.getByText("Warning")).toBeTruthy();+ });++ it("bands an 8.0 as Healthy", () => {+ render(+ <FilePageHeader+ data={makeData({ health: { ...makeData().health, metric: metric(8.0) } })}+ linkPrefix="/repos/r1"+ />,+ );+ expect(screen.getByText("Healthy")).toBeTruthy();+ });++ it("renders the path without truncating it", () => {+ render(<FilePageHeader data={makeData()} linkPrefix="/repos/r1" />);+ const heading = screen.getByRole("heading", { level: 1 });+ expect(heading.textContent).toBe("packages/ui/src/files/file-page.tsx");+ });+});++describe("FilePageHeader marks", () => {+ it("renders no marker row for a file with nothing to report", () => {+ render(<FilePageHeader data={makeData()} linkPrefix="/repos/r1" />);+ expect(screen.queryByText("Hotspot")).toBeNull();+ expect(screen.queryByText("Entry point")).toBeNull();+ });++ it("names every marker rather than collapsing them into one dot", () => {+ // A priority cascade drawn as a single mark is silent data loss: a file+ // that is both an entry point and a hotspot must report both.+ render(+ <FilePageHeader+ data={makeData({+ graph: {+ language: "typescript",+ is_entry_point: true,+ is_test: false,+ symbol_count: 12,+ pagerank: 0.001,+ pagerank_percentile: 88,+ in_degree: 3,+ out_degree: 9,+ community_id: 1,+ community_label: null,+ dependents: [],+ dependencies: [],+ },+ git: { is_hotspot: true } as never,+ })}+ linkPrefix="/repos/r1"+ />,+ );+ expect(screen.getByText("Entry point")).toBeTruthy();+ expect(screen.getByText("Hotspot")).toBeTruthy();+ });+});++describe("fileTabsFor", () => {+ it("badges only what there is something to say about", () => {+ const tabs = fileTabsFor(makeData());+ expect(tabs.find((t) => t.id === "health")?.badge).toBeUndefined();+ expect(tabs.find((t) => t.id === "coverage")?.badge).toBeUndefined();+ expect(tabs.find((t) => t.id === "decisions")).toBeUndefined();+ });++ it("carries the finding count and coverage percentage as figures", () => {+ const base = makeData();+ const tabs = fileTabsFor(+ makeData({+ health: { ...base.health, findings: [{}, {}, {}] as never },+ coverage: { line_coverage_pct: 61.4 } as never,+ }),+ );+ expect(tabs.find((t) => t.id === "health")?.badge).toBe(3);+ expect(tabs.find((t) => t.id === "coverage")?.badge).toBe("61%");+ });+});diff --git a/packages/ui/src/files/file-coverage-tab.tsx b/packages/ui/src/files/file-coverage-tab.tsxindex c15483eed..d5538b698 100644--- a/packages/ui/src/files/file-coverage-tab.tsx+++ b/packages/ui/src/files/file-coverage-tab.tsx@@ -1,8 +1,10 @@import { Shield } from "lucide-react";import { EmptyState } from "../shared/empty-state";-import { coverageColor } from "../health/tokens";-import { formatRelativeTime } from "../lib/format";+import { PageLede } from "../shared/page-lede";+import { coverageBand } from "../health/tokens";+import { formatNumber, formatRelativeTime } from "../lib/format";import type { FileDetailCoverage } from "@repowise-dev/types/files";+import { FileSection, Fig } from "./file-section";interface FileCoverageTabProps {coverage: FileDetailCoverage | null;@@ -18,59 +20,112 @@ export function FileCoverageTab({ coverage, coverageCodeHtml }: FileCoverageTabPif (!coverage) {return (<EmptyState+ titleAs="h2"icon={<Shield className="h-8 w-8" />}- title="No coverage data"- description="Ingest a coverage report (repowise coverage add <report>) to see line-level coverage here."+ title="No coverage report ingested"+ description="Run `repowise coverage add <report>` with an lcov, cobertura or coverage.py file and line-level coverage appears here."/>);}const pct = coverage.line_coverage_pct;+ // `coverageBand().color` is a CSS custom-property reference. `coverageColor()`+ // returns a Tailwind *class* string, and this file used to put it straight+ // into `style={{ color }}` / `background:` — which is not a colour, so the+ // figure and the bar had been painting default ink the whole time.+ const band = coverageBand(pct);const coveredCount = coverage.covered_line_count ?? coverage.covered_lines.length;+ const uncovered = Math.max(0, coverage.total_coverable_lines - coveredCount);return (- <div className="space-y-4">- <div className="flex flex-wrap items-center gap-x-4 gap-y-2">- <span className="text-2xl font-semibold tabular-nums" style={{ color: coverageColor(pct) }}>- {pct.toFixed(1)}%- </span>- <span className="text-xs text-[var(--color-text-secondary)]">- {coveredCount.toLocaleString()} of {coverage.total_coverable_lines.toLocaleString()}{" "}- coverable lines hit- {coverage.branch_coverage_pct != null &&- ` · branches ${coverage.branch_coverage_pct.toFixed(1)}%`}- </span>- <span className="text-[10px] text-[var(--color-text-tertiary)] ml-auto">- {coverage.source_format}- {coverage.ingested_at && ` · ingested ${formatRelativeTime(coverage.ingested_at)}`}- {coverage.ingested_commit_sha && ` @ ${coverage.ingested_commit_sha.slice(0, 7)}`}- </span>- </div>- <div className="h-2 w-full overflow-hidden rounded-full bg-[var(--color-bg-inset)]">- <div- className="h-full rounded-full"- style={{ width: `${pct}%`, background: coverageColor(pct) }}- />- </div>+ <div>+ {/* `PageLede`, not a hand-rolled copy of it. Its docstring says it was+ extracted precisely because "three hand-rolled copies is how the+ 44 / 48 / 52 sizes drift apart", and a second band chip built out of+ `color-mix` by hand is the pill rule 9 kills. `CoverageLede` is the+ wrong shape here — it opens a whole *surface* and wants a+ `CoverageSummary` plus per-file rows to split. */}+ <PageLede+ label="Line coverage"+ value={`${pct.toFixed(1)}%`}+ valueColor={band.color}+ unit="of coverable lines"+ band={band}+ layout="beside"+ figureFooter={+ <div+ className="h-2 w-full overflow-hidden rounded-full bg-[var(--color-bg-inset)]"+ role="img"+ aria-label={`${pct.toFixed(1)}% of coverable lines covered`}+ >+ <div+ className="h-full rounded-full"+ style={{ width: `${Math.min(100, Math.max(0, pct))}%`, background: band.color }}+ />+ </div>+ }+ >+ <p>+ Tests reach{" "}+ <Fig>+ {formatNumber(coveredCount)} of {formatNumber(coverage.total_coverable_lines)}{" "}+ coverable lines+ </Fig>+ , leaving <Fig>{formatNumber(uncovered)}</Fig> with nothing executing them+ {coverage.branch_coverage_pct != null && (+ <>+ . Branch coverage is <Fig>{coverage.branch_coverage_pct.toFixed(1)}%</Fig>+ </>+ )}+ . This is read from your own test run, not inferred.+ </p>+ <p className="mt-2.5">+ Read from a{" "}+ <span className="font-mono text-[var(--color-text-primary)]">+ {coverage.source_format}+ </span>{" "}+ report+ {coverage.ingested_at && <> ingested {formatRelativeTime(coverage.ingested_at)}</>}+ {coverage.ingested_commit_sha && (+ <>+ {" "}+ at{" "}+ <span className="font-mono text-[var(--color-text-primary)]">+ {coverage.ingested_commit_sha.slice(0, 7)}+ </span>+ </>+ )}+ . Re-ingest after a test run to move these figures.+ </p>+ </PageLede>- {coverageCodeHtml ? (- <div className="coverage-code overflow-x-auto rounded-md border border-[var(--color-border-default)] text-xs leading-relaxed">- {/* Highlighted by the host through the shared shiki path; the- data-covered line attributes drive the gutter tint below. */}- <div dangerouslySetInnerHTML={{ __html: coverageCodeHtml }} />- <style>{`+ <FileSection+ title="Source"+ description={+ coverageCodeHtml+ ? "Every coverable line, tinted by whether the last report saw it run."+ : "The highlighted source appears here for files under the render cap once a coverage report has been ingested for them."+ }+ >+ {coverageCodeHtml ? (+ <div className="coverage-code overflow-x-auto border-y border-[var(--color-border-default)] text-xs leading-relaxed">+ {/* Highlighted by the host through the shared shiki path; the+ data-covered line attributes drive the gutter tint below. */}+ <div dangerouslySetInnerHTML={{ __html: coverageCodeHtml }} />+ <style>{`.coverage-code pre { margin: 0; padding: 0.75rem 0; background: transparent !important; }.coverage-code code { display: block; }.coverage-code .line { display: inline-block; width: 100%; padding: 0 0.75rem 0 0.5rem; border-left: 3px solid transparent; }.coverage-code .line[data-covered="y"] { border-left-color: var(--color-success); background: color-mix(in srgb, var(--color-success) 7%, transparent); }.coverage-code .line[data-covered="n"] { border-left-color: var(--color-error); background: color-mix(in srgb, var(--color-error) 8%, transparent); }`}</style>- </div>- ) : (- <p className="text-xs text-[var(--color-text-tertiary)]">- Source preview unavailable — coverage summary only.- </p>- )}+ </div>+ ) : (+ <p className="text-sm text-[var(--color-text-tertiary)]">+ Source preview unavailable for this file.+ </p>+ )}+ </FileSection></div>);}diff --git a/packages/ui/src/files/file-decisions-tab.tsx b/packages/ui/src/files/file-decisions-tab.tsxindex b4dd989f8..0cbd3abda 100644--- a/packages/ui/src/files/file-decisions-tab.tsx+++ b/packages/ui/src/files/file-decisions-tab.tsx@@ -1,18 +1,17 @@-"use client";-import * as React from "react";import { Scale } from "lucide-react";-import { Badge } from "../ui/badge";import { EmptyState } from "../shared/empty-state";-import { ResponsiveTable, type ResponsiveColumn } from "../shared/responsive-table";import { stripMarkdown } from "../lib/format";import type { GoverningDecisionRef } from "@repowise-dev/types/files";+import { FileSection } from "./file-section";-const STATUS_VARIANT: Record<string, "default" | "fresh" | "stale" | "outdated" | "outline" | "accent"> = {- active: "fresh",- proposed: "accent",- deprecated: "outdated",- superseded: "outline",+/** A decision's state, as a mono micro-label rather than a coloured pill.+ * Only `deprecated` and `superseded` take ink, because those are the two that+ * change how you should read the decision — rule 10, and rule 2 keeps the+ * band colours for health. */+const STATUS_INK: Record<string, string> = {+ deprecated: "text-[var(--color-text-tertiary)] line-through",+ superseded: "text-[var(--color-text-tertiary)] line-through",};export interface FileDecisionsTabProps {@@ -38,6 +37,7 @@ export function FileDecisionsTab({if (items.length === 0) {return (<EmptyState+ titleAs="h2"icon={<Scale className="h-8 w-8" />}title="No governing decisions"description="This file is not directly linked to any architectural governing decisions."@@ -45,53 +45,35 @@ export function FileDecisionsTab({);}- const columns: ResponsiveColumn<GoverningDecisionRef>[] = [- {- key: "title",- header: "Title",- priority: 1,- cellClassName: "min-w-[200px]",- render: (d) => (- <Link- href={`${linkPrefix}/decisions/${d.id}`}- className="font-medium text-[var(--color-text-primary)] hover:text-[var(--color-accent-primary)] hover:underline block truncate"- title={stripMarkdown(d.title)}- >- {stripMarkdown(d.title)}- </Link>- ),- },- {- key: "status",- header: "Status",- priority: 1,- render: (d) => (- <Badge variant={STATUS_VARIANT[d.status] ?? "outline"}>{d.status}</Badge>- ),- },- {- key: "action",- header: "",- priority: 2,- align: "right",- render: (d) => (- <Link- href={`${linkPrefix}/decisions/${d.id}`}- className="text-xs text-[var(--color-accent-primary)] hover:underline font-medium"- >- View decision →- </Link>- ),- },- ];-return (- <div className="space-y-4">- <ResponsiveTable- columns={columns}- rows={items}- rowKey={(d) => d.id}- />- </div>+ <FileSection+ first+ title="Governed by"+ description="Decisions recorded against this file. Open one to see what it settled and why."+ >+ {/* One verb per row — the whole row is the link, so there is no second+ "View decision →" control repeating it at the right edge. */}+ <ul className="divide-y divide-[var(--color-border-default)] border-y border-[var(--color-border-default)]">+ {items.map((d) => (+ <li key={d.id}>+ <Link+ href={`${linkPrefix}/decisions/${d.id}`}+ className="-mx-2 flex flex-wrap items-baseline gap-x-3 gap-y-1 rounded px-2 py-3 transition-colors hover:bg-[var(--color-bg-elevated)]"+ >+ <span className="min-w-0 flex-1 text-sm font-medium text-[var(--color-text-primary)]">+ {stripMarkdown(d.title)}+ </span>+ <span+ className={`shrink-0 font-mono text-[10px] uppercase tracking-[0.12em] ${+ STATUS_INK[d.status] ?? "text-[var(--color-text-tertiary)]"+ }`}+ >+ {d.status}+ </span>+ </Link>+ </li>+ ))}+ </ul>+ </FileSection>);}diff --git a/packages/ui/src/files/file-doc-tab.tsx b/packages/ui/src/files/file-doc-tab.tsxindex 51b2bfaf2..5d84cc016 100644--- a/packages/ui/src/files/file-doc-tab.tsx+++ b/packages/ui/src/files/file-doc-tab.tsx@@ -1,7 +1,6 @@import type { ReactNode } from "react";import { BookOpen } from "lucide-react";import { EmptyState } from "../shared/empty-state";-import { Badge } from "../ui/badge";import { formatRelativeTime } from "../lib/format";import type { FileWikiPageRef } from "@repowise-dev/types/files";@@ -13,62 +12,61 @@ interface FileDocTabProps {wikiHref?: string | undefined;}-const FRESHNESS_CLASS: Record<string, string> = {- fresh: "text-[var(--color-success)] border-[var(--color-success)]/30",- stale: "text-[var(--color-warning)] border-[var(--color-warning)]/30",- outdated: "text-[var(--color-error)] border-[var(--color-error)]/30",-};-export function FileDocTab({ wikiPage, docSlot, wikiHref }: FileDocTabProps) {if (!wikiPage) {return (<EmptyState+ titleAs="h2"icon={<BookOpen className="h-8 w-8" />}- title="This page didn't make the cut"- description="Not every file gets its own documentation page, and that's perfectly normal."+ title="No documentation page for this file"+ description="Repowise writes pages for the files that carry a repository's shape. Re-run the index with a wider page budget to bring this one in."/>);}return (- <div className="space-y-4">- <div className="flex flex-wrap items-center gap-2">- <Badge- variant="outline"- className={`text-[10px] h-5 ${FRESHNESS_CLASS[wikiPage.freshness_status] ?? ""}`}- >- {wikiPage.freshness_status}- </Badge>+ <div className="space-y-6">+ {/* The freshness marker lives in the header, where it sits beside the+ score and is on screen from whichever tab you arrive on. Repeating it+ here would be a badge on a row that already carries one. What is+ local to this tab is when the page was written and where to read it+ full-width. */}+ <div className="flex flex-wrap items-baseline gap-x-4 gap-y-1">{wikiPage.updated_at && (<span- className="text-xs text-[var(--color-text-tertiary)]"+ className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]"title={new Date(wikiPage.updated_at).toLocaleString()}>- updated {formatRelativeTime(wikiPage.updated_at)}+ Written {formatRelativeTime(wikiPage.updated_at)}</span>)}{wikiHref && (<ahref={wikiHref}- className="ml-auto text-xs text-[var(--color-accent-primary)] hover:underline"+ className="ml-auto text-sm font-medium text-[var(--color-accent-primary)] hover:underline">- Open in Docs →+ Open in Documentation <span aria-hidden>→</span></a>)}</div>+{wikiPage.human_notes && (- <div className="rounded-md border border-[var(--color-accent-primary)]/30 bg-[var(--color-bg-elevated)] p-3">- <p className="text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)] mb-1">+ <div className="border-l-2 border-[var(--color-accent-primary)] pl-4">+ <p className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">Team notes</p>- <p className="text-xs text-[var(--color-text-secondary)] whitespace-pre-wrap">+ <p className="mt-1.5 whitespace-pre-wrap text-sm leading-relaxed text-[var(--color-text-secondary)]">{wikiPage.human_notes}</p></div>)}- <article className="prose prose-invert max-w-none leading-relaxed overflow-hidden">- {docSlot}- </article>++ {/* No `prose` wrapper — rule 12. Tailwind Typography is banned on our+ markdown: every element the renderer emits is already themed through+ our tokens, `code::before/::after` prints literal backticks into the+ page, and `prose-invert` is a static class that cannot follow the+ theme. If the markdown needs a style, it gets styled in the renderer. */}+ <article className="max-w-none overflow-hidden">{docSlot}</article></div>);}diff --git a/packages/ui/src/files/file-graph-tab.tsx b/packages/ui/src/files/file-graph-tab.tsxindex d2d9bd459..f6bda4c91 100644--- a/packages/ui/src/files/file-graph-tab.tsx+++ b/packages/ui/src/files/file-graph-tab.tsx@@ -1,10 +1,9 @@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";import { isExternal, nodeKind } from "@repowise-dev/types";+import { FileSection, Fig } from "./file-section";interface FileGraphTabProps {graph: FileDetailGraph | null;@@ -17,132 +16,163 @@ interface FileGraphTabProps {}function NeighborList({- title,neighbors,fileHref,symbolHref,}: {- title: string;neighbors: FileGraphNeighbor[];fileHref: (path: string) => string;symbolHref: (symbolId: string) => string;}) {+ if (neighbors.length === 0) {+ return <p className="text-sm text-[var(--color-text-tertiary)]">None in the indexed graph.</p>;+ }+ return (+ <ul className="divide-y divide-[var(--color-border-default)] border-y border-[var(--color-border-default)]">+ {neighbors.map((n) => {+ const isExternalNode = isExternal(n.node_id);+ const isSymbol = !isExternalNode && nodeKind(n.node_id) === "symbol";+ const href = isSymbol ? symbolHref(n.node_id) : fileHref(n.node_id);+ const row = (+ <>+ <span+ className={`min-w-0 flex-1 truncate font-mono text-xs ${+ isExternalNode+ ? "text-[var(--color-text-tertiary)]"+ : "text-[var(--color-text-primary)]"+ }`}+ title={+ isExternalNode+ ? `${n.node_id} (external dependency, not part of this repo)`+ : n.node_id+ }+ >+ {truncatePath(n.node_id, 48)}+ </span>+ <span className="shrink-0 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">+ {n.edge_type}+ </span>+ </>+ );+ return (+ <li key={`${n.node_id}-${n.edge_type}`} className="py-2">+ {/* Rule 9: an external node has no page behind it, so it gets no+ hover ground and no href — plain tertiary mono instead. */}+ {isExternalNode ? (+ <div className="flex items-center gap-3">{row}</div>+ ) : (+ <a+ href={href}+ className="-mx-2 flex items-center gap-3 rounded px-2 transition-colors hover:bg-[var(--color-bg-elevated)]"+ >+ {row}+ </a>+ )}+ {n.imported_names.length > 0 && (+ <p+ className="mt-0.5 truncate font-mono text-[10px] text-[var(--color-text-tertiary)]"+ title={n.imported_names.join(", ")}+ >+ {n.imported_names.slice(0, 6).join(", ")}+ {n.imported_names.length > 6 && ` +${n.imported_names.length - 6}`}+ </p>+ )}+ </li>+ );+ })}+ </ul>+ );+}++/**+ * The bound, said out loud, and measured against what is actually drawn.+ *+ * The degree counts are a SQL `COUNT` over every edge; the lists beside them+ * are the server's ranked cut, 20 per direction. Printing the count over a+ * capped list with nothing on screen saying so is the silent-cap lie: the+ * reader is told 137 and can count 20. Renders nothing when the list is whole,+ * because then there is no bound to state.+ */+function shown(drawn: number, total: number) {+ if (drawn >= total) return null;return (- <Card>- <CardHeader className="pb-2">- <CardTitle className="text-sm font-medium">- {title}{" "}- <span className="text-[10px] font-normal text-[var(--color-text-tertiary)] tabular-nums">- {neighbors.length}- </span>- </CardTitle>- </CardHeader>- <CardContent>- {neighbors.length === 0 ? (- <p className="text-xs text-[var(--color-text-tertiary)]">None in the indexed graph.</p>- ) : (- <ul className="space-y-2">- {neighbors.map((n) => {- const isExternalNode = isExternal(n.node_id);- const isSymbol = !isExternalNode && nodeKind(n.node_id) === "symbol";- const href = isSymbol ? symbolHref(n.node_id) : fileHref(n.node_id);- const row = (- <>- <span- className={`font-mono text-xs truncate flex-1 min-w-0 ${- isExternalNode ? "text-[var(--color-text-tertiary)]" : "text-[var(--color-text-primary)]"- }`}- title={isExternalNode ? `${n.node_id} (external dependency, not part of this repo)` : n.node_id}- >- {truncatePath(n.node_id, 48)}- </span>- <span className="text-[10px] text-[var(--color-text-tertiary)] shrink-0">- {n.edge_type}- </span>- </>- );- return (- <li key={`${n.node_id}-${n.edge_type}`}>- {isExternalNode ? (- <div className="flex items-center gap-2 -mx-2 px-2 py-1 rounded">{row}</div>- ) : (- <a- href={href}- className="flex items-center gap-2 -mx-2 px-2 py-1 rounded hover:bg-[var(--color-bg-elevated)] transition-colors"- >- {row}- </a>- )}- {n.imported_names.length > 0 && (- <p- className="pl-1 text-[10px] text-[var(--color-text-tertiary)] truncate"- title={n.imported_names.join(", ")}- >- {n.imported_names.slice(0, 6).join(", ")}- {n.imported_names.length > 6 && ` +${n.imported_names.length - 6}`}- </p>- )}- </li>- );- })}- </ul>- )}- </CardContent>- </Card>+ <>+ {" "}+ — <Fig>{drawn}</Fig> of them below, the strongest edges first+ </>);}-export function FileGraphTab({ graph, filePath, linkPrefix, fileHref, symbolHref }: FileGraphTabProps) {+export function FileGraphTab({+ graph,+ filePath,+ linkPrefix,+ fileHref,+ symbolHref,+}: FileGraphTabProps) {if (!graph) {return (<EmptyState+ titleAs="h2"icon={<Network className="h-8 w-8" />}title="Not in the dependency graph"- description="This file isn't part of the indexed graph (it may be excluded or unparsed)."+ description="Files land in the graph once their imports are parsed. An excluded path or an unsupported language leaves this empty."/>);}+ const pct = Math.round(graph.pagerank_percentile);+ const community = graph.community_label ?? `community #${graph.community_id}`;+return (- <div className="space-y-4">- <StatGrid columns={4}>- <StatTile- label="PageRank"- value={`${Math.round(graph.pagerank_percentile)}th pct`}- hint={graph.pagerank.toFixed(6)}- />- <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">- <a- href={`${linkPrefix}/architecture?view=graph&node=${encodeURIComponent(filePath)}`}- className="text-[var(--color-accent-primary)] hover:underline"- >- Show in dependency graph →- </a>- <a- href={`${linkPrefix}/architecture?view=symbols&file=${encodeURIComponent(filePath)}`}- className="text-[var(--color-accent-primary)] hover:underline"- >- View symbols →- </a>- </div>- <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">- <NeighborList- title="Dependents"- neighbors={graph.dependents}- fileHref={fileHref}- symbolHref={symbolHref}- />- <NeighborList- title="Dependencies"- neighbors={graph.dependencies}- fileHref={fileHref}- symbolHref={symbolHref}- />- </div>+ <div>+ {/* Rule 14: one verb per section header, and the verb for this whole tab+ is "go to the graph". "View symbols" steers a different subject, so it+ sits on the section about what this file pulls in rather than being+ stacked beside the first one. */}+ <FileSection+ first+ title="Depended on by"+ description={+ <>+ <Fig>{graph.in_degree}</Fig> {graph.in_degree === 1 ? "file imports" : "files import"}{" "}+ this one+ {shown(graph.dependents.length, graph.in_degree)}. Its PageRank puts it in the{" "}+ <Fig>{pct}th</Fig> percentile of the repository, inside {community}.+ </>+ }+ action={+ <a+ href={`${linkPrefix}/architecture?view=graph&node=${encodeURIComponent(filePath)}`}+ className="text-sm font-medium text-[var(--color-accent-primary)] hover:underline"+ >+ Show in the dependency graph <span aria-hidden>→</span>+ </a>+ }+ >+ <NeighborList neighbors={graph.dependents} fileHref={fileHref} symbolHref={symbolHref} />+ </FileSection>++ <FileSection+ title="Depends on"+ description={+ <>+ <Fig>{graph.out_degree}</Fig> {graph.out_degree === 1 ? "edge" : "edges"} out+ {shown(graph.dependencies.length, graph.out_degree)}. Nodes outside the repository+ are listed but not linked — there is no page behind them.+ </>+ }+ action={+ <a+ href={`${linkPrefix}/architecture?view=symbols&file=${encodeURIComponent(filePath)}`}+ className="text-sm font-medium text-[var(--color-accent-primary)] hover:underline"+ >+ View symbols <span aria-hidden>→</span>+ </a>+ }+ >+ <NeighborList neighbors={graph.dependencies} fileHref={fileHref} symbolHref={symbolHref} />+ </FileSection></div>);}diff --git a/packages/ui/src/files/file-health-tab.tsx b/packages/ui/src/files/file-health-tab.tsxindex ed40f8ef8..a082a6143 100644--- a/packages/ui/src/files/file-health-tab.tsx+++ b/packages/ui/src/files/file-health-tab.tsx@@ -2,6 +2,7 @@import { useMemo, useState, type ReactNode } from "react";import { HeartPulse } from "lucide-react";+import { bandForScore, HEALTH_BAND_LABEL } from "@repowise-dev/types/health";import { EmptyState } from "../shared/empty-state";import { VirtualizedTable, useVirtualRows } from "../shared/virtualized-table";import { ScoreBreakdown, type ScoreBreakdownCategory } from "../health/score-breakdown";@@ -11,15 +12,17 @@ import {biomarkerLabel,biomarkerDimension,CATEGORY_LABEL,- DIMENSION_CHIP,DIMENSION_LABEL,type BiomarkerDimension,} from "../health/biomarker-glossary";-import { scoreBadgeClass, type Severity } from "../health/tokens";+import { healthBandTextColor, type Severity } from "../health/tokens";import { FileTrendChart } from "../health/file-trend-chart";import { FileSignalsPanel } from "../health/file-signals-panel";-import type { FileDetailHealth, FunctionBlameRow } from "@repowise-dev/types/files";+import { StatRibbon, type RibbonStat } from "../stats/stat-ribbon";import { SeverityMark } from "../health/severity-mark";+import { formatNumber } from "../lib/format";+import type { FileDetailHealth, FunctionBlameRow } from "@repowise-dev/types/files";+import { FileSection, Fig } from "./file-section";export type FindingStatus = "open" | "acknowledged" | "resolved" | "false_positive";@@ -53,6 +56,12 @@ function medianAgeDays(medianAuthorTime: number | null): number | null {return Math.max(0, Math.round((Date.now() / 1000 - medianAuthorTime) / 86400));}+/**+ * The one tab body that is genuinely interactive — finding triage, two+ * virtualised lists and a measured trend — and therefore the only one that+ * carries `"use client"`. Every other panel renders on the server and crosses+ * the boundary as markup rather than as data plus a bundle.+ */export function FileHealthTab({health,functionBlame,@@ -88,12 +97,16 @@ export function FileHealthTab({[functionBlame],);- if (!metric && findings.length === 0) {+ // `functionBlame` is part of the test: a file git tracks but the parser never+ // scored has blame rows and no metric, and the early return dropped the+ // churn table on the floor for it.+ if (!metric && findings.length === 0 && functionBlame.length === 0) {return (<EmptyState+ titleAs="h2"icon={<HeartPulse className="h-8 w-8" />}title="No health data"- description="Index this repo to score this file. Health signals land with the first index."+ description="Scores, biomarkers and the per-function churn table land with the first index of this repository."/>);}@@ -109,72 +122,94 @@ export function FileHealthTab({}};+ const pillars: RibbonStat[] = [];+ if (metric) {+ // Defect risk is deliberately absent: the header's lede carries it at 44px+ // with its band, on screen from whichever tab you arrive on. Repeating it+ // here at a quarter the size is the same number twice.+ if (metric.maintainability_score != null) {+ pillars.push({+ label: "Maintainability",+ value: metric.maintainability_score.toFixed(1),+ valueColor: healthBandTextColor(bandForScore(metric.maintainability_score)),+ sub: HEALTH_BAND_LABEL[bandForScore(metric.maintainability_score)],+ });+ }+ if (metric.performance_score != null) {+ pillars.push({+ label: "Performance",+ value: metric.performance_score.toFixed(1),+ valueColor: healthBandTextColor(bandForScore(metric.performance_score)),+ sub: HEALTH_BAND_LABEL[bandForScore(metric.performance_score)],+ });+ }+ pillars.push({ label: "Max CCN", value: formatNumber(metric.max_ccn) });+ pillars.push({ label: "Max nesting", value: formatNumber(metric.max_nesting) });+ if (metric.duplication_pct != null) {+ pillars.push({ label: "Duplication", value: `${metric.duplication_pct.toFixed(0)}%` });+ }+ }+return (- <div className="space-y-5">+ <div>{metric && (- <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">- <Stat- label="Defect risk"- value={- <span- className={`inline-flex items-baseline rounded px-2 py-0.5 font-bold tabular-nums ${scoreBadgeClass(metric.score)}`}- >- {metric.score.toFixed(1)}- <span className="ml-0.5 text-[10px] font-normal opacity-70">/10</span>- </span>- }- />- <Stat label="Maintainability" value={<DimScore score={metric.maintainability_score} />} />- <Stat label="Performance" value={<DimScore score={metric.performance_score} />} />- <Stat label="Max CCN" value={<Num v={metric.max_ccn} />} />- <Stat label="Max nesting" value={<Num v={metric.max_nesting} />} />- <Stat label="NLOC" value={<Num v={metric.nloc} />} />- <Stat label="Tests" value={<span className="text-xs">{metric.has_test_file ? "Paired" : "None"}</span>} />- <Stat- label="Coverage"- value={- <span className="text-xs tabular-nums">- {metric.line_coverage_pct == null ? "—" : `${metric.line_coverage_pct.toFixed(0)}%`}- </span>- }- />- <Stat- label="Duplication"- value={- <span className="text-xs tabular-nums">- {metric.duplication_pct == null ? "—" : `${metric.duplication_pct.toFixed(0)}%`}- </span>- }- />- <Stat label="Module" value={<span className="text-xs">{metric.module ?? "—"}</span>} />- </div>+ <FileSection+ first+ title="The three signals"+ description={+ <>+ Defect risk is the calibrated number in the header. Maintainability and performance+ are co-equal signals rather than a blend of it, and they are banded the same way —+ healthy at 8 and above, alert below 4.{" "}+ {metric.has_test_file+ ? "This file has a paired test file."+ : "No paired test file was found for it."}+ {metric.module && (+ <>+ {" "}+ It sits in <Fig>{metric.module}</Fig>.+ </>+ )}+ </>+ }+ >+ {pillars.length > 0 && <StatRibbon stats={pillars} />}+ {trend && trend.points.length >= 2 && <FileTrendChart trend={trend} />}+ </FileSection>)}- {trend && trend.points.length >= 2 && <FileTrendChart trend={trend} />}-- <FileSignalsPanel signals={signals} />-- {breakdown && (- <section className="space-y-2">- <h3 className="text-xs font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">- Why this score?- </h3>- <ScoreBreakdown- score={breakdown.score}- totalDeduction={breakdown.total_deduction}- categories={breakdown.categories as ScoreBreakdownCategory[]}- />- </section>+ {(breakdown || signals) && (+ <FileSection+ first={!metric}+ title="Why this score"+ description="Every deduction that separates this file from a clean 10, and the repository-level signals that fed them."+ >+ {breakdown && (+ <ScoreBreakdown+ score={breakdown.score}+ totalDeduction={breakdown.total_deduction}+ categories={breakdown.categories as ScoreBreakdownCategory[]}+ />+ )}+ <FileSignalsPanel signals={signals} />+ </FileSection>)}{findings.length > 0 && (- <section className="space-y-2">- <h3 className="text-xs font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">- Findings ({findings.length})- </h3>+ <FileSection+ first={!metric && !breakdown && !signals}+ title="Findings"+ description={+ <>+ <Fig>{formatNumber(findings.length)}</Fig> open{" "}+ {findings.length === 1 ? "biomarker" : "biomarkers"}, worst first. The figure on the+ right of each row is what it costs the score.+ </>+ }+ ><ulref={findingsVirtual.scrollRef}- className="space-y-2 overflow-auto"+ className="divide-y divide-[var(--color-border-default)] overflow-auto border-y border-[var(--color-border-default)]"style={{ maxHeight: 600 }}>{findingsVirtual.paddingTop > 0 && (@@ -190,45 +225,52 @@ export function FileHealthTab({key={f.id}ref={findingsVirtual.measureElement}data-index={vr.index}- className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3 space-y-1"+ className="space-y-1.5 py-3">- <div className="flex items-center gap-2 flex-wrap">+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1"><SeverityMark severity={f.severity as Severity} />- <span className="text-xs font-semibold text-[var(--color-text-primary)]">+ <span className="text-sm font-semibold text-[var(--color-text-primary)]">{biomarkerLabel(f.biomarker_type)}</span>- <span className="text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">- {CATEGORY_LABEL[info.category]}+ {/* Category and pillar are machine-produced labels, so they+ are mono micro-labels rather than two tinted chips —+ rule 9, nothing here responds to a click. */}+ <span className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">+ {CATEGORY_LABEL[info.category]} · {DIMENSION_LABEL[findingDimension(f)]}</span>- <DimensionChip dimension={findingDimension(f)} />{f.function_name && (- <span className="text-xs font-mono text-[var(--color-text-tertiary)]">+ <span className="font-mono text-xs text-[var(--color-text-tertiary)]">{f.function_name}{f.line_start ? `:${f.line_start}` : ""}</span>)}- <span className="ml-auto text-xs tabular-nums text-[var(--color-error)]">- −{f.health_impact.toFixed(2)}+ <span className="ml-auto font-mono text-xs tabular-nums text-[var(--color-text-secondary)]">+ −{f.health_impact.toFixed(2)}</span></div>- <p className="text-xs text-[var(--color-text-secondary)]">{f.reason}</p>+ <p className="text-sm leading-relaxed text-[var(--color-text-secondary)]">+ {f.reason}+ </p><BiomarkerDetailsbiomarkerType={f.biomarker_type}details={f.details as BiomarkerDetailsRecord | null}onPartnerHref={partnerHref}/>{onFindingStatusChange && (- <div className="flex items-center gap-1.5 pt-1">+ // One control, four states — a segmented selector for a+ // single field, not rule 14's pile of independent verbs+ // (which mixed "change this record" with "navigate away").+ <div className="flex flex-wrap items-center gap-1 pt-1">{STATUS_OPTIONS.map((opt) => (<buttonkey={opt.value}type="button"disabled={savingId === f.id || status === opt.value}onClick={() => setStatus(f.id, opt.value)}- className={`rounded border px-1.5 py-0.5 text-[10px] transition-colors ${+ className={`rounded px-2 py-0.5 text-xs font-medium transition-colors ${status === opt.value- ? "border-[var(--color-accent-primary)] text-[var(--color-accent-primary)]"- : "border-[var(--color-border-default)] text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)] hover:border-[var(--color-border-hover)]"+ ? "bg-[var(--color-accent-muted)] text-[var(--color-accent-primary)]"+ : "text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)]"}`}>{opt.label}@@ -243,28 +285,33 @@ export function FileHealthTab({<li aria-hidden style={{ height: findingsVirtual.paddingBottom }} />)}</ul>- </section>+ </FileSection>)}{functionBlame.length > 0 && (- <section className="space-y-2">- <h3 className="text-xs font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">- Functions by churn- </h3>+ <FileSection+ first={!metric && !breakdown && !signals && findings.length === 0}+ title="Functions by churn"+ description={+ <>+ How often each function in this file has been modified, and who owns the lines.+ Median age is how long the current lines have been standing.+ </>+ }+ ><VirtualizedTablerows={blameRows}rowKey={(b) => b.row.symbol_id}estimateRowHeight={BLAME_ROW_ESTIMATE}- className="overflow-x-auto overflow-hidden border border-[var(--color-border-default)]"- tableClassName="text-xs"- headerClassName="bg-[var(--color-bg-surface)]"+ className="overflow-x-auto overflow-hidden border-y border-[var(--color-border-default)]"+ tableClassName="text-sm"header={- <tr className="border-b border-[var(--color-border-default)] text-left text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">- <th className="px-3 py-2 font-medium">Function</th>- <th className="px-3 py-2 font-medium text-right">Mods</th>- <th className="px-3 py-2 font-medium text-right">Recent</th>- <th className="px-3 py-2 font-medium text-right">Median age</th>- <th className="px-3 py-2 font-medium">Owner</th>+ <tr className="border-b border-[var(--color-border-default)] text-left font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">+ <th className="px-3 py-2 font-normal">Function</th>+ <th className="px-3 py-2 text-right font-normal">Mods</th>+ <th className="px-3 py-2 text-right font-normal">Recent</th>+ <th className="px-3 py-2 text-right font-normal">Median age</th>+ <th className="px-3 py-2 font-normal">Owner</th></tr>}renderRow={({ row: b, age, name }, index, measureRef) => (@@ -302,42 +349,12 @@ export function FileHealthTab({</tr>)}/>- </section>+ </FileSection>)}</div>);}-function Stat({ label, value }: { label: string; value: React.ReactNode }) {- 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>- <div className="text-[var(--color-text-primary)]">{value}</div>- </div>- );-}--function Num({ v }: { v: number }) {- return <span className="text-base font-semibold tabular-nums">{v}</span>;-}--/** A per-dimension pillar score badge, or "—" when the pillar is unmeasured. */-function DimScore({ score }: { score?: number | null | undefined }) {- if (score == null) {- return <span className="text-xs text-[var(--color-text-tertiary)]">—</span>;- }- return (- <span- className={`inline-flex items-baseline rounded px-2 py-0.5 font-bold tabular-nums ${scoreBadgeClass(score)}`}- >- {score.toFixed(1)}- <span className="ml-0.5 text-[10px] font-normal opacity-70">/10</span>- </span>- );-}-/** A finding's home pillar, preferring the server value over the glossary. */function findingDimension(f: { dimension?: string; biomarker_type: string }): BiomarkerDimension {if (@@ -349,14 +366,3 @@ function findingDimension(f: { dimension?: string; biomarker_type: string }): Bi}return biomarkerDimension(f.biomarker_type);}--function DimensionChip({ dimension }: { dimension: BiomarkerDimension }) {- return (- <span- className={`inline-flex items-center rounded px-1.5 py-px text-[10px] font-medium ${DIMENSION_CHIP[dimension]}`}- title={`${DIMENSION_LABEL[dimension]} pillar`}- >- {DIMENSION_LABEL[dimension]}- </span>- );-}diff --git a/packages/ui/src/files/file-history-tab.tsx b/packages/ui/src/files/file-history-tab.tsxindex 95c0ff466..98896e506 100644--- a/packages/ui/src/files/file-history-tab.tsx+++ b/packages/ui/src/files/file-history-tab.tsx@@ -1,16 +1,19 @@-import { GitBranch, Bot } from "lucide-react";+import { GitBranch } 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 { ChangeHistoryCard } from "../git/change-history-card";-import { FixHistoryBadge } from "../git/fix-history-badge";-import { StatGrid, StatTile } from "../shared/stat-grid";-import { Badge } from "../ui/badge";-import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";+import { StatRibbon, type RibbonStat } from "../stats/stat-ribbon";import { summarizeFixHistory } from "../lib/fix-history";-import { formatAgeDays, formatRelativeTime, truncatePath } from "../lib/format";+import { formatAgeDays, formatNumber, formatRelativeTime, truncatePath } from "../lib/format";import type { FileDetailGit } from "@repowise-dev/types/files";+import { FileSection, Fig } from "./file-section";+import { FileMark } from "./file-marks";++/** Matches `FixHistoryBadge`'s default tooltip — same claim, same wording. */+const FIX_HISTORY_TITLE =+ "Bug-fix commits that touched this file in the trailing defect window.";interface FileHistoryTabProps {git: FileDetailGit | null;@@ -23,9 +26,10 @@ export function FileHistoryTab({ git, linkPrefix, partnerHref }: FileHistoryTabPif (!git) {return (<EmptyState+ titleAs="h2"icon={<GitBranch className="h-8 w-8" />}- title="No git history"- description="Git metadata appears once the repository's history is indexed."+ title="No git history for this file"+ description="Commits, authors and co-change partners land the first time the repository's history is indexed."/>);}@@ -33,9 +37,9 @@ export function FileHistoryTab({ git, linkPrefix, partnerHref }: FileHistoryTabPconst hasCategories = Object.values(git.commit_categories ?? {}).some((v) => v > 0);const agentPct =git.agent.agent_authored_pct != null ? Math.round(git.agent.agent_authored_pct * 100) : null;- // Same helper the wiki sidebar uses, so one file's fix history reads- // identically on both surfaces. Null means no counted fixes: render nothing.- const fix = summarizeFixHistory(git.prior_defect_count, git.last_fix_at, git.bug_magnet);+ // Same helper the wiki sidebar uses, so one file's history reads identically+ // on both surfaces. Null means nothing counted: render nothing.+ const summary = summarizeFixHistory(git.prior_defect_count, git.last_fix_at, git.bug_magnet);// A file whose git indexing never completed lands with zeroes across the// board, and `formatAgeDays(0)` reads "< 1 day". Anchor the age to having// at least one commit so an unindexed file is not called brand new.@@ -43,168 +47,181 @@ export function FileHistoryTab({ git, linkPrefix, partnerHref }: FileHistoryTabPconst age =commits > 0 && Number.isFinite(git.age_days) ? formatAgeDays(git.age_days as number) : null;+ const stats: RibbonStat[] = [+ {+ label: "Commits",+ value: formatNumber(commits),+ ...(age ? { sub: `over ${age}` } : {}),+ },+ { label: "Last 90 days", value: formatNumber(git.commit_count_90d) },+ { label: "Contributors", value: formatNumber(git.contributor_count) },+ { label: "Bus factor", value: formatNumber(git.bus_factor) },+ ];+ if (git.churn_percentile != null) {+ stats.push({ label: "Churn", value: `${Math.round(git.churn_percentile)}th pct` });+ }+return (- <div className="space-y-4">- {(fix || git.is_stable) && (- <div className="flex flex-wrap items-center gap-2">- {git.is_stable && <Badge variant="fresh">Stable</Badge>}- <FixHistoryBadge- count={git.prior_defect_count ?? null}- lastFixAt={git.last_fix_at ?? null}- bugMagnet={git.bug_magnet ?? false}- />- </div>- )}+ <div>+ <FileSection+ first+ title="Change rhythm"+ description={+ <>+ Mined from the full git history Repowise indexed. Churn is a percentile against every+ other file in the repository, and bus factor is how many people would have to leave+ before nobody knew this file.+ </>+ }+ >+ {/* `FixHistoryBadge` renders the same summary as a bordered, tinted+ `Badge`. Beside a `FileMark` — which is what the header row above+ uses for exactly this job — that is two vocabularies for "one thing+ worth knowing about this file", and the bordered one is the pill+ rule 9 kills. `summarizeFixHistory` is the shared copy rule, so+ reading it directly keeps the wording identical to the badge's+ everywhere the badge still ships. */}+ {(summary || git.is_stable) && (+ <div className="flex flex-wrap items-center gap-x-5 gap-y-2">+ {git.is_stable && (+ <FileMark title="No recent commits — this file has settled.">Stable</FileMark>+ )}+ {summary && (+ <FileMark title={FIX_HISTORY_TITLE}>+ {summary.magnet ? `Bug magnet · ${summary.label}` : summary.label}+ </FileMark>+ )}+ </div>+ )}- <StatGrid columns={4}>- <StatTile- label="Commits (total)"- value={commits}- {...(age ? { hint: `over ${age}` } : {})}- />- <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>+ <StatRibbon stats={stats} />- {/* Self-contained: returns null when there is nothing to say, so an- entropy-less, never-fixed, never-renamed file loses no space to it. */}- <ChangeHistoryCard- changeEntropyPct={git.change_entropy_pct ?? null}- priorDefectCount={git.prior_defect_count ?? null}- lastFixAt={git.last_fix_at ?? null}- originalPath={git.original_path ?? null}- commitCountCapped={git.commit_count_capped ?? false}- className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3"- />+ {/* Self-contained: returns null when there is nothing to say, so an+ entropy-less, never-renamed file loses no space to it. No border+ box around it — the section's own rhythm is the grouping. */}+ <ChangeHistoryCard+ changeEntropyPct={git.change_entropy_pct ?? null}+ priorDefectCount={git.prior_defect_count ?? null}+ lastFixAt={git.last_fix_at ?? null}+ originalPath={git.original_path ?? null}+ commitCountCapped={git.commit_count_capped ?? false}+ />- <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">- <Card>- <CardHeader className="pb-2">- <CardTitle className="text-sm font-medium">Significant commits</CardTitle>- </CardHeader>- <CardContent>- {git.significant_commits.length === 0 ? (- <p className="text-xs text-[var(--color-text-tertiary)]">- No significant commits recorded.- </p>- ) : (- <ul className="space-y-1.5">- {git.significant_commits.slice(0, 8).map((c) => (- <li key={c.sha}>- <a- href={`${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-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">- {c.message}- </span>- <span className="text-[10px] text-[var(--color-text-tertiary)] shrink-0">- {c.date ? formatRelativeTime(c.date) : ""}- </span>- </a>- </li>- ))}- </ul>- )}- </CardContent>- </Card>+ {hasCategories && <CommitCategorySparkline categories={git.commit_categories} />}+ </FileSection>- <div className="space-y-4">- {hasCategories && (- <Card>- <CardHeader className="pb-2">- <CardTitle className="text-sm font-medium">Commit mix</CardTitle>- </CardHeader>- <CardContent>- <CommitCategorySparkline categories={git.commit_categories} />- </CardContent>- </Card>- )}- <Card>- <CardHeader className="pb-2">- <CardTitle className="text-sm font-medium flex items-center gap-2">- <Bot className="h-4 w-4 text-[var(--color-text-secondary)]" />- Agent share- </CardTitle>- </CardHeader>- <CardContent>- {git.agent.agent_commit_count === 0 ? (- <p className="text-xs text-[var(--color-text-tertiary)]">- No agent-attributed commits on this file.- </p>- ) : (- <div className="space-y-2">- <p className="text-xs text-[var(--color-text-secondary)]">- <span className="text-base font-semibold tabular-nums text-[var(--color-text-primary)]">- {git.agent.agent_commit_count}- </span>{" "}- agent commit{git.agent.agent_commit_count === 1 ? "" : "s"}- {agentPct != null && ` · ${agentPct}% of indexed history`}- </p>- {Object.keys(git.agent.tier_counts).length > 0 && (- <AgentTierBar tierCounts={git.agent.tier_counts} />- )}- </div>- )}- </CardContent>- </Card>- </div>- </div>+ {git.significant_commits.length > 0 && (+ <FileSection+ title="Significant commits"+ description="The commits that moved this file the most, largest first."+ >+ <ul className="divide-y divide-[var(--color-border-default)] border-y border-[var(--color-border-default)]">+ {git.significant_commits.slice(0, 8).map((c) => (+ <li key={c.sha}>+ <a+ href={`${linkPrefix}/commits?commit=${c.sha}`}+ className="-mx-2 flex items-baseline gap-3 rounded px-2 py-2.5 transition-colors hover:bg-[var(--color-bg-elevated)]"+ >+ <span className="shrink-0 font-mono text-[11px] tabular-nums text-[var(--color-text-tertiary)]">+ {c.sha.slice(0, 8)}+ </span>+ <span className="min-w-0 flex-1 truncate text-sm text-[var(--color-text-primary)]">+ {c.message}+ </span>+ <span className="shrink-0 font-mono text-[10px] text-[var(--color-text-tertiary)]">+ {c.date ? formatRelativeTime(c.date) : ""}+ </span>+ </a>+ </li>+ ))}+ </ul>+ </FileSection>+ )}- <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">- <Card>- <CardHeader className="pb-2">- <CardTitle className="text-sm font-medium">Top authors</CardTitle>- </CardHeader>- <CardContent>+ <FileSection+ title="Who writes it"+ description={+ <>+ Commit share by author across the indexed history+ {git.agent.agent_commit_count > 0 && (+ <>+ , and how much of it came from a coding agent —{" "}+ <Fig>{formatNumber(git.agent.agent_commit_count)}</Fig>{" "}+ {git.agent.agent_commit_count === 1 ? "commit" : "commits"}+ {agentPct != null && <> ({agentPct}%)</>}+ </>+ )}+ .+ </>+ }+ >+ <div className="grid grid-cols-1 gap-x-10 gap-y-8 lg:grid-cols-2">+ <div className="min-w-0">{git.top_authors.length === 0 ? (- <p className="text-xs text-[var(--color-text-tertiary)]">No author data.</p>+ <p className="text-sm text-[var(--color-text-tertiary)]">+ Author attribution lands with the next index.+ </p>) : (<OwnershipDonut- slices={git.top_authors.map((a) => ({- name: a.name,- value: a.commit_count,- }))}+ slices={git.top_authors.map((a) => ({ name: a.name, value: a.commit_count }))}/>)}- </CardContent>- </Card>-- <Card>- <CardHeader className="pb-2">- <CardTitle className="text-sm font-medium">Changes together with</CardTitle>- </CardHeader>- <CardContent>- {git.co_change_partners.length === 0 ? (- <p className="text-xs text-[var(--color-text-tertiary)]">- No co-change partners detected.+ </div>+ <div className="min-w-0">+ <p className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">+ Agent share+ </p>+ {git.agent.agent_commit_count === 0 ? (+ <p className="mt-2 text-sm text-[var(--color-text-tertiary)]">+ No agent-attributed commits on this file.</p>) : (- <ul className="space-y-2">- {git.co_change_partners.slice(0, 8).map((p) => (- <li key={p.file_path}>- <a- href={partnerHref(p.file_path)}- 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="font-mono text-xs text-[var(--color-text-primary)] truncate" title={p.file_path}>- {truncatePath(p.file_path, 44)}- </span>- <span className="text-xs tabular-nums text-[var(--color-text-tertiary)] shrink-0">- ×{p.co_change_count}- </span>- </a>- </li>- ))}- </ul>+ Object.keys(git.agent.tier_counts).length > 0 && (+ <div className="mt-3">+ <AgentTierBar tierCounts={git.agent.tier_counts} />+ </div>+ ))}- </CardContent>- </Card>- </div>+ </div>+ </div>+ </FileSection>++ <FileSection+ title="Changes together with"+ description={+ git.co_change_partners.length > 0 ? (+ <>+ Files that land in the same commit as this one. The count is how many commits touched+ both — a partner you did not expect is usually a coupling nobody wrote down.+ </>+ ) : (+ "Files that repeatedly land in the same commit as this one appear here once the history has enough commits to be sure."+ )+ }+ >+ {git.co_change_partners.length > 0 && (+ <ul className="divide-y divide-[var(--color-border-default)] border-y border-[var(--color-border-default)]">+ {git.co_change_partners.slice(0, 8).map((p) => (+ <li key={p.file_path}>+ <a+ href={partnerHref(p.file_path)}+ className="-mx-2 flex items-baseline justify-between gap-3 rounded px-2 py-2.5 transition-colors hover:bg-[var(--color-bg-elevated)]"+ >+ <span+ className="min-w-0 truncate font-mono text-xs text-[var(--color-text-primary)]"+ title={p.file_path}+ >+ {truncatePath(p.file_path, 44)}+ </span>+ <span className="shrink-0 font-mono text-[11px] tabular-nums text-[var(--color-text-tertiary)]">+ {p.co_change_count}×+ </span>+ </a>+ </li>+ ))}+ </ul>+ )}+ </FileSection></div>);}diff --git a/packages/ui/src/files/file-marks.tsx b/packages/ui/src/files/file-marks.tsxnew file mode 100644index 000000000..c209631e7--- /dev/null+++ b/packages/ui/src/files/file-marks.tsx@@ -0,0 +1,83 @@+import * as React from "react";+import type { FileDetailResponse } from "@repowise-dev/types/files";+import { formatLOC } from "../lib/format";++/**+ * One thing worth knowing about a file, as a dot plus a word.+ *+ * The shape is `SeverityMark`'s and so is the reasoning: a tinted ground, a+ * border and coloured text are three ways of saying one thing, and four of them+ * across a header tile into stripes that outweigh the path they belong to. The+ * word stays, because colour is not the name of a state.+ *+ * The hue is deliberately **not** the health ramp. The score sits forty pixels+ * above these, painted on `bandForScore`, and rule 19 is exactly the case where+ * a second mark reaches for green/amber/red and teaches the reader a rule that+ * makes them confidently wrong about the first. Health owns the band colours+ * here; a role mark is one accent hue meaning "there is something here", and+ * the word carries which thing.+ */+export function FileMark({+ children,+ title,+}: {+ children: React.ReactNode;+ title?: string | undefined;+}) {+ return (+ <span+ className="inline-flex shrink-0 items-center gap-1.5 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-accent-primary)]"+ {...(title ? { title } : {})}+ >+ <span+ className="h-1.5 w-1.5 shrink-0 rounded-full bg-[var(--color-accent-primary)]"+ aria-hidden+ />+ {children}+ </span>+ );+}++/**+ * The header's marker row. Renders **nothing** for a file with nothing to+ * report — rule 10, the same convention `FreshnessDot` and `StubDot` follow, so+ * a quiet header is a healthy file rather than a header that failed to load.+ */+export function FileMarks({ data }: { data: FileDetailResponse }) {+ const deadLines = data.dead_code.reduce((s, f) => s + f.lines, 0);+ const freshness = data.wiki_page?.freshness_status;+ const docStale = freshness === "stale" || freshness === "outdated";++ const marks: React.ReactNode[] = [];+ if (data.graph?.is_entry_point) {+ marks.push(+ <FileMark key="entry" title="Something outside the repository calls into this file.">+ Entry point+ </FileMark>,+ );+ }+ if (data.git?.is_hotspot) {+ marks.push(+ <FileMark key="hotspot" title="High churn against high complexity, from full git history.">+ Hotspot+ </FileMark>,+ );+ }+ if (data.dead_code.length > 0) {+ marks.push(+ <FileMark key="dead" title="Symbols the dead-code pass found no reachable caller for.">+ {data.dead_code.length} unreachable · {formatLOC(deadLines)} lines+ </FileMark>,+ );+ }+ if (docStale) {+ marks.push(+ <FileMark key="doc" title="The file has changed since its documentation page was written.">+ Doc {freshness}+ </FileMark>,+ );+ }++ if (marks.length === 0) return null;+ return <div className="flex flex-wrap items-center gap-x-5 gap-y-2">{marks}</div>;+}diff --git a/packages/ui/src/files/file-overview-tab.tsx b/packages/ui/src/files/file-overview-tab.tsxindex 5128eb163..1e380e1b2 100644--- a/packages/ui/src/files/file-overview-tab.tsx+++ b/packages/ui/src/files/file-overview-tab.tsx@@ -1,12 +1,10 @@-import { ArrowRight, Bug, Code2, Network } from "lucide-react";+import { FileQuestion } from "lucide-react";import type { FileDetailResponse } from "@repowise-dev/types/files";import { isExternal, nodeKind } from "@repowise-dev/types";-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";+import { EmptyState } from "../shared/empty-state";+import { formatLOC, truncatePath } from "../lib/format";import { SYMBOL_FIX_TITLE } from "../git/fix-history-badge";+import { FileSection, Fig } from "./file-section";interface FileOverviewTabProps {data: FileDetailResponse;@@ -17,12 +15,16 @@ interface FileOverviewTabProps {}/**- * 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).+ * The default file tab: the symbols worth knowing about, an inline dependency+ * snapshot, and anything the dead-code pass could not reach — so an+ * undocumented file is never empty (the old default landed on an empty+ * "No documentation yet" Doc tab).+ *+ * The headline figures are **not** here. They moved into the header's+ * `StatRibbon`, which is on screen whichever tab is open; a four-tile grid+ * repeating them under the tab row was the same five numbers twice.*/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);// Keyed on the row's own symbol_id, not a rebuilt `${path}::${name}`: some// extractors mint ids from the qualified name, and those would never match.@@ -40,11 +42,10 @@ export function FileOverviewTab({ data, symbolHref, fileHref }: FileOverviewTabP// Two full sorts of every symbol in the file to pick eight chips. Left// unmemoized deliberately: `useMemo` would make this a client component, and- // this is one of the five tab bodies that are pure and hookless today —- // which is what lets the hydration boundary move down to `file-health-tab`- // alone. Radix mounts only the active tab, and the redundant tab-change- // effect and the refetch-on-click are both gone, so the sorts now run once- // per mount rather than on every parent render.+ // this is one of the six tab bodies that are pure and hookless — which is+ // what lets the hydration boundary sit at `file-health-tab` alone. Only the+ // active panel is rendered, and it is rendered on the server, so the sorts+ // run once per request rather than on every parent render.//// Complexity picks the list, as it always has: biasing the whole sort on a// "was fixed" boolean would evict the file's most complex symbol in favour@@ -66,131 +67,192 @@ export function FileOverviewTab({ data, symbolHref, fileHref }: FileOverviewTabP}}- 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>+ const hasNeighbors =+ !!data.graph && (data.graph.dependents.length > 0 || data.graph.dependencies.length > 0);- {/* ── Key symbols ── */}+ if (keySymbols.length === 0 && !hasNeighbors && data.dead_code.length === 0) {+ return (+ <EmptyState+ titleAs="h2"+ icon={<FileQuestion className="h-8 w-8" />}+ title="Nothing extracted from this file yet"+ description="Symbols and dependency edges land with the next index. A file with none is usually data, config or a language Repowise does not parse."+ />+ );+ }++ return (+ <div>{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">+ <FileSection+ first+ title="Key symbols"+ description={+ <>+ {keySymbols.length < data.symbols.length ? (+ <>+ The <Fig>{keySymbols.length}</Fig> most complex of{" "}+ <Fig>{data.symbols.length}</Fig> extracted symbols+ </>+ ) : (+ <>+ All <Fig>{data.symbols.length}</Fig> extracted{" "}+ {data.symbols.length === 1 ? "symbol" : "symbols"}, ordered by complexity+ </>+ )}+ {perSymbolSignal+ ? ", each carrying the number of prior bug fixes that touched it."+ : "."}+ </>+ }+ >+ <div className="flex flex-wrap gap-1.5">{keySymbols.map((s) => {const fixes = fixesIn(s.symbol_id);return (<akey={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)]"+ className="inline-flex items-center gap-1.5 rounded border border-[var(--color-border-default)] px-2 py-1 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>{fixes > 0 && (<span- className="inline-flex items-center gap-0.5 text-[10px] tabular-nums text-[var(--color-error)]"+ className="tabular-nums text-[10px] text-[var(--color-error)]"title={SYMBOL_FIX_TITLE}>- <Bug className="h-2.5 w-2.5" />- {fixes}+ {fixes} {fixes === 1 ? "fix" : "fixes"}</span>)}</a>);})}- </CardContent>- </Card>+ </div>+ </FileSection>)}- {/* ── 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 isExternalNode = isExternal(n.node_id);- const isSymbol = !isExternalNode && nodeKind(n.node_id) === "symbol";- if (isExternalNode) {- return (- <p- key={`out-${n.node_id}`}- className="block truncate font-mono text-xs text-[var(--color-text-tertiary)]"- title={`${n.node_id} (external dependency, not part of this repo)`}- >- {truncatePath(n.node_id, 30)}- </p>- );- }- 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 && hasNeighbors && (+ <FileSection+ first={keySymbols.length === 0}+ title="Nearest neighbours"+ description={+ <>+ <Fig>{data.graph.in_degree}</Fig>{" "}+ {data.graph.in_degree === 1 ? "file imports" : "files import"} this one and it+ imports <Fig>{data.graph.out_degree}</Fig>. Five of each are below, and the+ Dependencies tab widens that to twenty — the aggregate ranks and cuts the edge+ list server-side, so neither view is the whole graph. The dependency canvas is.+ </>+ }+ >+ <div className="grid grid-cols-1 gap-x-10 gap-y-6 sm:grid-cols-2">+ <NeighborColumn+ label="Depended on by"+ nodes={data.graph.dependents.slice(0, 5).map((n) => n.node_id)}+ fileHref={fileHref}+ symbolHref={symbolHref}+ />+ <NeighborColumn+ label="Depends on"+ nodes={data.graph.dependencies.slice(0, 5).map((n) => n.node_id)}+ fileHref={fileHref}+ symbolHref={symbolHref}+ />+ </div>+ </FileSection>)}- {data.graph?.is_entry_point && (- <Badge variant="outline" className="text-[10px] text-[var(--color-info)] border-[var(--color-info)]/30">- Entry point- </Badge>+ {data.dead_code.length > 0 && (+ <FileSection+ first={keySymbols.length === 0 && !hasNeighbors}+ title="Unreachable"+ description={+ <>+ <Fig>{data.dead_code.length}</Fig>{" "}+ {data.dead_code.length === 1 ? "symbol" : "symbols"} totalling{" "}+ <Fig>{formatLOC(deadLines)}</Fig> lines that the dead-code pass found no+ reachable caller for. Confidence is per finding; check the reason before+ deleting.+ </>+ }+ >+ <ul className="divide-y divide-[var(--color-border-default)] border-y border-[var(--color-border-default)]">+ {data.dead_code.map((f) => (+ <li key={f.id} className="flex flex-wrap items-baseline gap-x-3 gap-y-1 py-2.5">+ <span className="font-mono text-xs text-[var(--color-text-primary)]">+ {f.symbol_name ?? f.kind}+ </span>+ <span className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">+ {f.kind}+ </span>+ {/* Drops to its own line below `sm`. Sharing a 390px row with+ the name, the kind and the confidence squeezed the reason+ into a four-word column. */}+ <span className="order-last min-w-0 basis-full text-xs text-[var(--color-text-secondary)] sm:order-none sm:basis-0 sm:flex-1">+ {f.reason}+ </span>+ <span className="shrink-0 font-mono text-[10px] tabular-nums text-[var(--color-text-tertiary)]">+ {Math.round(f.confidence * 100)}% · {f.lines} ln+ </span>+ </li>+ ))}+ </ul>+ </FileSection>)}</div>);}++/** One side of the neighbour snapshot. External nodes render as plain mono with+ * no ground and no href — rule 9, following them goes nowhere. */+function NeighborColumn({+ label,+ nodes,+ fileHref,+ symbolHref,+}: {+ label: string;+ nodes: string[];+ fileHref: (path: string) => string;+ symbolHref: (id: string) => string;+}) {+ return (+ <div className="min-w-0">+ <p className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">+ {label}+ </p>+ <ul className="mt-2 space-y-1.5">+ {nodes.length === 0 && (+ <li className="text-xs text-[var(--color-text-tertiary)]">None in the indexed graph.</li>+ )}+ {nodes.map((id) => {+ const external = isExternal(id);+ const symbol = !external && nodeKind(id) === "symbol";+ if (external) {+ return (+ <li+ key={id}+ className="truncate font-mono text-xs text-[var(--color-text-tertiary)]"+ title={`${id} (external dependency, not part of this repo)`}+ >+ {truncatePath(id, 40)}+ </li>+ );+ }+ return (+ <li key={id} className="min-w-0">+ <a+ href={symbol ? symbolHref(id) : fileHref(id)}+ className="block truncate font-mono text-xs text-[var(--color-text-secondary)] hover:text-[var(--color-accent-primary)]"+ title={id}+ >+ {truncatePath(id, 40)}+ </a>+ </li>+ );+ })}+ </ul>+ </div>+ );+}diff --git a/packages/ui/src/files/file-page-header.tsx b/packages/ui/src/files/file-page-header.tsxnew file mode 100644index 000000000..76ae9ea73--- /dev/null+++ b/packages/ui/src/files/file-page-header.tsx@@ -0,0 +1,169 @@+import * as React from "react";+import { bandForScore, HEALTH_BAND_LABEL } from "@repowise-dev/types/health";+import type { FileDetailResponse } from "@repowise-dev/types/files";+import { PageLede } from "../shared/page-lede";+import { StatRibbon, type RibbonStat } from "../stats/stat-ribbon";+import { healthBandInk, coverageTextColor } from "../health/tokens";+import { formatLOC, formatNumber } from "../lib/format";+import { FileMarks } from "./file-marks";++export interface FilePageHeaderProps {+ data: FileDetailResponse;+ /** Route prefix for the repo, e.g. `/repos/:id`. */+ linkPrefix: string;+ LinkComponent?: React.ElementType | undefined;+}++/**+ * The file page's opening: the house micro-label eyebrow, the path as identity,+ * and a `PageLede`-shaped figure carrying the defect score with its canonical+ * band.+ *+ * This is a **server** component and stays one. It was `EntityHeader` before,+ * whose eyebrow ran `text-xs font-semibold uppercase tracking-wider` against+ * the house `font-mono text-[10px] uppercase tracking-[0.12em]`, and whose+ * identity ran `text-lg` against `RepoIdentityHeader`'s `text-xl sm:text-2xl` —+ * a different face and two different sizes from every other surface.+ *+ * The score is banded by `bandForScore`, not `scoreBadgeClass`. The latter is a+ * four-step presentation ramp whose own docstring says it is not a labelling+ * scheme, and it disagrees with the bands the Files index, the treemap and the+ * health map all paint: a 6.9 read one way here and another 200px away on the+ * map that links to this page.+ */+export function FilePageHeader({ data, linkPrefix, LinkComponent }: FilePageHeaderProps) {+ const A = LinkComponent ?? "a";+ const score = data.health.metric?.score;+ const dir = data.file_path.slice(0, data.file_path.lastIndexOf("/") + 1);+ const name = data.file_path.slice(dir.length);++ return (+ <header className="flex flex-col gap-6">+ <div>+ <p className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">+ File+ </p>+ {/* `break-all`, never an ellipsis: a path is the identity of this page+ and rule 6 puts no truncation in the primary column. The directory+ is set quieter than the leaf so a deep path still reads as one+ thing you can find your place in. */}+ <h1 className="mt-2 font-mono text-xl font-semibold tracking-tight text-[var(--color-text-primary)] break-all sm:text-2xl">+ {dir && <span className="font-normal text-[var(--color-text-tertiary)]">{dir}</span>}+ {name}+ </h1>+ </div>++ {score != null ? (+ <PageLede+ label="Defect risk"+ value={score.toFixed(1)}+ valueColor={healthBandInk(bandForScore(score))}+ unit="out of 10"+ band={{+ label: HEALTH_BAND_LABEL[bandForScore(score)],+ color: healthBandInk(bandForScore(score)),+ }}+ layout="beside"+ >+ <FileProse data={data} linkPrefix={linkPrefix} LinkComponent={A} />+ </PageLede>+ ) : (+ <div className="max-w-[62ch] text-[13px] leading-relaxed text-[var(--color-text-secondary)] [text-wrap:pretty]">+ <FileProse data={data} linkPrefix={linkPrefix} LinkComponent={A} />+ </div>+ )}++ <FileMarks data={data} />++ <StatRibbon stats={headerStats(data)} {...(LinkComponent ? { LinkComponent } : {})} />+ </header>+ );+}++/** The sentences that make the figure mean something. Rule 4: the prose is+ * load-bearing here, not decoration. */+function FileProse({+ data,+ linkPrefix,+ LinkComponent,+}: {+ data: FileDetailResponse;+ linkPrefix: string;+ LinkComponent: React.ElementType;+}) {+ const A = LinkComponent;+ const findings = data.health.findings.length;+ const deduction = data.health.breakdown?.total_deduction;+ const owner = data.git?.primary_owner;+ const ownerPct = data.git?.primary_owner_commit_pct;+ const commits = data.git?.commit_count_total ?? 0;++ return (+ <>+ <p>{fileSummary(data)}</p>+ {findings > 0 && (+ <p className="mt-3">+ {findings === 1 ? "One open finding deducts" : `${formatNumber(findings)} open findings deduct`}+ {deduction != null ? ` ${deduction.toFixed(2)}` : ""} from the score, which is+ calibrated against this file’s complexity, static biomarkers and prior fix+ history.+ </p>+ )}+ {owner && (+ <p className="mt-3">+ Mostly written by{" "}+ <A+ href={`${linkPrefix}/owners/${encodeURIComponent(owner)}`}+ className="text-[var(--color-accent-primary)] hover:underline"+ >+ {owner}+ </A>+ {ownerPct != null && ` (${Math.round(ownerPct * 100)}% of commits)`}+ {commits > 0 && `, across ${formatNumber(commits)} commit${commits === 1 ? "" : "s"}`}.+ </p>+ )}+ </>+ );+}++/** The headline figures, as a hairline `<dl>` rather than four bordered tiles.+ * Only figures the payload actually carries — an unmeasured cell is dropped,+ * not printed as an em dash. */+function headerStats(data: FileDetailResponse): RibbonStat[] {+ const stats: RibbonStat[] = [];+ const nloc = data.health.metric?.nloc;+ // `data.symbols.length`, not `graph.symbol_count`: the latter is a column on+ // the graph node and the former is the extracted-symbol table, and they can+ // disagree — which read as "Symbols 12" here over "All 9 extracted symbols"+ // one section below. This page can enumerate the second one, so it counts it.+ const symbols = data.symbols.length;+ const coveragePct = data.coverage?.line_coverage_pct ?? data.health.metric?.line_coverage_pct;++ if (nloc != null) stats.push({ label: "Lines", value: formatLOC(nloc) });+ if (symbols > 0) stats.push({ label: "Symbols", value: formatNumber(symbols) });+ if (data.graph) {+ stats.push({ label: "Depended on by", value: formatNumber(data.graph.in_degree) });+ stats.push({ label: "Depends on", value: formatNumber(data.graph.out_degree) });+ }+ if (coveragePct != null) {+ stats.push({+ label: "Coverage",+ value: `${coveragePct.toFixed(0)}%`,+ valueColor: coverageTextColor(coveragePct),+ });+ }+ return stats;+}++/** Synthesised "what is this" one-liner for a file — wiki summary or fallback. */+export function fileSummary(data: FileDetailResponse): string {+ const wiki = data.wiki_page?.summary?.trim();+ if (wiki) return wiki;+ const lang = data.graph?.language;+ const symbols = 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/file-page-panels.tsx b/packages/ui/src/files/file-page-panels.tsxnew file mode 100644index 000000000..71260fd67--- /dev/null+++ b/packages/ui/src/files/file-page-panels.tsx@@ -0,0 +1,87 @@+import type { ElementType, ReactNode } from "react";+import type { FileDetailResponse } from "@repowise-dev/types/files";+import { FileOverviewTab } from "./file-overview-tab";+import { FileDocTab } from "./file-doc-tab";+import { FileHistoryTab } from "./file-history-tab";+import { FileDecisionsTab } from "./file-decisions-tab";+import { FileCoverageTab } from "./file-coverage-tab";+import { FileGraphTab } from "./file-graph-tab";+import type { FilePageTab } from "./file-page-tabs";++export interface BuildFilePanelsOptions {+ data: FileDetailResponse;+ /** Route prefix for the repo, e.g. `/repos/:id`. */+ linkPrefix: string;+ /** Build a file-page href. */+ fileHref: (path: string) => string;+ /** Build a symbol-page href. */+ symbolHref: (symbolId: string) => string;+ /** Server-rendered wiki content for the Doc tab. */+ docSlot?: ReactNode;+ /** Shiki HTML with per-line `data-covered` attributes (Coverage tab). */+ coverageCodeHtml?: string | undefined;+ /** Deep link into the docs reading surface. */+ wikiHref?: string | undefined;+ /**+ * The Health panel. It is the one tab body that is genuinely interactive, so+ * the host supplies it already wrapped in whatever client component owns the+ * triage callback — a function cannot cross a server boundary as a prop.+ */+ healthPanel?: ReactNode;+ LinkComponent?: ElementType | undefined;+}++/**+ * Render the six pure tab bodies **on the server** and hand them to the client+ * shell as markup.+ *+ * This is where the hydration boundary moved to. `FilePage` used to be a client+ * component that imported all seven bodies, so the whole slice — donut,+ * sparkline, tier bar, treemap helpers, seven icon sets — shipped to the+ * browser along with a `FileDetailResponse` serialised twice (into the flight+ * payload and inlined into the HTML), on a page that renders one tab. Only+ * `FileHealthTab` needs hydrating now.+ *+ * A plain function rather than a component because the shell addresses panels+ * individually; components cannot return a record. It must be called from a+ * server component.+ */+export function buildFilePanels({+ data,+ linkPrefix,+ fileHref,+ symbolHref,+ docSlot,+ coverageCodeHtml,+ wikiHref,+ healthPanel,+ LinkComponent,+}: BuildFilePanelsOptions): Partial<Record<FilePageTab, ReactNode>> {+ return {+ overview: <FileOverviewTab data={data} symbolHref={symbolHref} fileHref={fileHref} />,+ doc: <FileDocTab wikiPage={data.wiki_page} docSlot={docSlot} wikiHref={wikiHref} />,+ health: healthPanel,+ history: (+ <FileHistoryTab git={data.git} linkPrefix={linkPrefix} partnerHref={fileHref} />+ ),+ decisions: (+ <FileDecisionsTab+ decisions={data.governing_decisions ?? []}+ linkPrefix={linkPrefix}+ {...(LinkComponent ? { LinkComponent } : {})}+ />+ ),+ graph: (+ <FileGraphTab+ graph={data.graph}+ filePath={data.file_path}+ linkPrefix={linkPrefix}+ fileHref={fileHref}+ symbolHref={symbolHref}+ />+ ),+ coverage: (+ <FileCoverageTab coverage={data.coverage} coverageCodeHtml={coverageCodeHtml} />+ ),+ };+}diff --git a/packages/ui/src/files/file-page-tabs.ts b/packages/ui/src/files/file-page-tabs.tsindex 32378c0af..2ab3edb99 100644--- a/packages/ui/src/files/file-page-tabs.ts+++ b/packages/ui/src/files/file-page-tabs.ts@@ -1,7 +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.- * Order is the rendered tab order: Overview first so undocumented files are- * never empty; Coverage last (often empty). */+/** Tab ids for the file entity page, their copy, and the badge rules.+ *+ * Lives outside the client component so server components can validate+ * `?tab=` values, build the tab row and render the panels without importing+ * client code. Order is the rendered tab order: Overview first so undocumented+ * files are never empty; Coverage last (often empty).+ */++import type { FileDetailResponse } from "@repowise-dev/types/files";+export const FILE_PAGE_TABS = ["overview","doc",@@ -12,3 +18,96 @@ export const FILE_PAGE_TABS = ["coverage",] as const;export type FilePageTab = (typeof FILE_PAGE_TABS)[number];++/** Tab names. "Documentation" rather than "Doc" per the fixed vocabulary —+ * name things the way a person would. "Dependencies" rather than "Graph"+ * because the tab is the file's neighbourhood in the dependency graph, not a+ * canvas; the lists inside it are "Depended on by" / "Depends on" so the tab+ * name and a column heading never read as the same thing. */+export const FILE_TAB_LABEL: Record<FilePageTab, string> = {+ overview: "Overview",+ doc: "Documentation",+ health: "Health",+ history: "History",+ decisions: "Decisions",+ graph: "Dependencies",+ coverage: "Coverage",+};++/**+ * The sentence under the tab row. Says what the tab measures rather than+ * repeating its own name, which the tab row already carries.+ *+ * Each one has to stay true above the panel's *empty* state, because it renders+ * either way. "The documentation page Repowise wrote for this file" sitting+ * directly on top of "No documentation page for this file" asserts the thing+ * exists and is then contradicted a line later, so these are all phrased as+ * what the tab is for rather than as a claim that the data landed.+ */+export const FILE_TAB_BLURB: Record<FilePageTab, string> = {+ overview: "The shape of the file: what it holds, what it touches, and what needs attention.",+ doc: "What Repowise has written about this file.",+ health: "Defect risk, the biomarkers deducted from it, and how each function churns.",+ history: "What git knows about this file — how often it changes, who changes it, and what moves with it.",+ decisions: "Architectural decisions recorded against this file.",+ graph: "Where this file sits in the indexed dependency graph.",+ coverage: "Line coverage, once a test report has been ingested for this repository.",+};++export interface FileTabDef {+ id: FilePageTab;+ label: string;+ /** How much is behind the tab, so a clean one says so before it is clicked. */+ badge?: number | string;+ blurb: string;+}++/**+ * The tab row for a file.+ *+ * Every badge here is already in the aggregate, so none of them costs a call —+ * the Code Health rule is "only show the ones you can afford", and these are+ * free. They are also only rendered where there is something to say: a file+ * with no findings and no coverage carries no figures, per rule 10.+ *+ * Decisions is the one tab that disappears. A file governed by nothing has an+ * empty tab that can never fill from this page, where every other tab either+ * has data or explains how to get it.+ */+export function fileTabsFor(data: FileDetailResponse): FileTabDef[] {+ const findings = data.health.findings.length;+ const decisions = data.governing_decisions?.length ?? 0;+ // Same fallback the header's stat ribbon uses. Reading only `coverage` here+ // left a file whose percentage rides on the health metric showing "Coverage+ // 61%" in the ribbon above an unbadged Coverage tab — one number, two+ // sources, which is rule 20's second corollary.+ const coveragePct = data.coverage?.line_coverage_pct ?? data.health.metric?.line_coverage_pct;++ return FILE_PAGE_TABS.filter((id) => id !== "decisions" || decisions > 0).map((id) => {+ const badge =+ id === "health" && findings > 0+ ? findings+ : id === "decisions" && decisions > 0+ ? decisions+ : id === "coverage" && coveragePct != null+ ? `${Math.round(coveragePct)}%`+ : undefined;+ return {+ id,+ label: FILE_TAB_LABEL[id],+ blurb: FILE_TAB_BLURB[id],+ ...(badge !== undefined ? { badge } : {}),+ };+ });+}++/** The tab a `?tab=` value resolves to, given what this file actually has.+ * A deep link to Decisions on an ungoverned file lands on Overview rather+ * than on a tab that is not in the row. */+export function resolveFileTab(+ requested: string | undefined,+ tabs: FileTabDef[],+): FilePageTab {+ const match = tabs.find((t) => t.id === requested);+ return match ? match.id : "overview";+}diff --git a/packages/ui/src/files/file-page.tsx b/packages/ui/src/files/file-page.tsxindex a66216f4b..430d0dc74 100644--- a/packages/ui/src/files/file-page.tsx+++ b/packages/ui/src/files/file-page.tsx@@ -1,245 +1,81 @@"use client";import { useState, type ReactNode } from "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";-import { FileDecisionsTab } from "./file-decisions-tab";-import { FileCoverageTab } from "./file-coverage-tab";-import { FileGraphTab } from "./file-graph-tab";-import type { FileDetailResponse } from "@repowise-dev/types/files";-import { FILE_PAGE_TABS, type FilePageTab } from "./file-page-tabs";+import { ViewTabs } from "../shared/view-tabs";+import { FILE_PAGE_TABS, type FilePageTab, type FileTabDef } from "./file-page-tabs";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). */- coverageCodeHtml?: string;- /** Deep link into the docs reading surface. */- wikiHref?: string;- initialTab?: FilePageTab;- onTabChange?: (tab: FilePageTab) => void;- onFindingStatusChange?: (findingId: string, status: FindingStatus) => Promise<void> | void;+ /**+ * The server-rendered header. A `ReactNode` rather than `data`, because the+ * header is a server component and this shell is the client boundary — see+ * `buildFilePanels`.+ */+ header?: ReactNode;+ /** The tab row, from `fileTabsFor(data)` on the server. */+ tabs: FileTabDef[];+ /** Server-rendered tab bodies, keyed by tab id. */+ panels: Partial<Record<FilePageTab, ReactNode>>;+ initialTab?: FilePageTab | undefined;+ onTabChange?: ((tab: FilePageTab) => void) | undefined;}/**- * 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 /- * Decisions / Graph / Coverage tabs. Overview leads so undocumented files are never empty.+ * The file page's shell: the header, the one underline tab row, and the active+ * panel.+ *+ * It is deliberately thin. Everything with a figure or a table in it renders on+ * the server and arrives here as markup, so the only JavaScript this page ships+ * for six of its seven tabs is the tab row itself.+ *+ * `initialTab` seeds the state and nothing more. The effect that re-applied it+ * on every change fired a redundant second state update on top of the one+ * `handleTabChange` had just done, and only ever mattered because the host+ * re-rendered the server tree on a tab click. It no longer does — which is also+ * why a caller that turns its cross-file links into soft navigations must key+ * this component on the file path: React would otherwise preserve this state at+ * the same tree position and strand the active tab out of sync with the URL.*/-export function FilePage({- data,- repoId,- linkPrefix,- breadcrumb,- LinkComponent,- docSlot,- coverageCodeHtml,- wikiHref,- initialTab,- onTabChange,- onFindingStatusChange,-}: FilePageProps) {- const prefix = linkPrefix ?? `/repos/${repoId}`;- const score = data.health.metric?.score;- const language = data.graph?.language;- const owner = data.git?.primary_owner ?? null;- const deadLines = data.dead_code.reduce((s, f) => s + f.lines, 0);- const fileHref = (p: string) => fileEntityPath(prefix, p);- const symbolHref = (s: string) => symbolEntityPath(prefix, s);-- const decisions = data.governing_decisions ?? [];- const hasDecisions = decisions.length > 0;-- const rawTab: FilePageTab =- initialTab && FILE_PAGE_TABS.includes(initialTab) ? initialTab : "overview";- const defaultTab: FilePageTab =- rawTab === "decisions" && !hasDecisions ? "overview" : rawTab;-- // `defaultTab` seeds the state and nothing more. The effect that re-applied- // it on every change fired a redundant second state update on top of the one- // `handleTabChange` had just done, and only ever mattered because the host- // re-rendered the server tree on a tab click. It no longer does.- const [activeTab, setActiveTab] = useState<FilePageTab>(defaultTab);+export function FilePage({ header, tabs, panels, initialTab, onTabChange }: FilePageProps) {+ const seed: FilePageTab =+ initialTab && tabs.some((t) => t.id === initialTab) ? initialTab : "overview";+ const [activeTab, setActiveTab] = useState<FilePageTab>(seed);const handleTabChange = (tab: FilePageTab) => {setActiveTab(tab);onTabChange?.(tab);};- return (- <div className="space-y-4">- <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 ? (- <span- className={`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>- ) : 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 ? (- <a- href={`${prefix}/owners/${encodeURIComponent(owner)}`}- 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>- ) : undefined- }- decisions={- hasDecisions ? (- <button- type="button"- onClick={() => handleTabChange("decisions")}- className="inline-flex items-center gap-1.5 text-xs text-[var(--color-text-secondary)] hover:text-[var(--color-accent-primary)] hover:underline cursor-pointer focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[var(--color-accent-primary)] rounded"- >- <span className="text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">- Governed by- </span>- <span className="font-medium text-[var(--color-text-primary)]">- {decisions.length} {decisions.length === 1 ? "decision" : "decisions"}- </span>- </button>- ) : undefined- }- {...(LinkComponent ? { LinkComponent } : {})}- />+ const active = tabs.find((t) => t.id === activeTab) ?? tabs[0];- {/* ── Tabs ── */}- <Tabs value={activeTab} onValueChange={(v) => handleTabChange(v as FilePageTab)}>- <TabsList className="flex-wrap">- <TabsTrigger value="overview">Overview</TabsTrigger>- <TabsTrigger value="doc">Doc</TabsTrigger>- <TabsTrigger value="health">- Health- {data.health.findings.length > 0 && (- <span className="ml-1 text-[10px] tabular-nums opacity-70">- {data.health.findings.length}- </span>- )}- </TabsTrigger>- <TabsTrigger value="history">History</TabsTrigger>- {hasDecisions && (- <TabsTrigger value="decisions">- Decisions- <span className="ml-1 text-[10px] tabular-nums opacity-70">- {decisions.length}- </span>- </TabsTrigger>+ return (+ <div className="flex flex-col gap-8">+ {header}+ <ViewTabs+ tabs={tabs.map((t) => ({+ id: t.id,+ label: t.label,+ ...(t.badge !== undefined ? { badge: t.badge } : {}),+ }))}+ value={activeTab}+ onValueChange={(id) => handleTabChange(id as FilePageTab)}+ >+ <div className="space-y-6">+ {active && (+ <p className="max-w-[75ch] text-sm leading-relaxed text-[var(--color-text-secondary)] [text-wrap:pretty]">+ {active.blurb}+ </p>)}- <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>- <TabsContent value="health" className="mt-4">- <FileHealthTab- health={data.health}- functionBlame={data.function_blame}- onFindingStatusChange={onFindingStatusChange}- partnerHref={fileHref}- symbolHref={symbolHref}- />- </TabsContent>- <TabsContent value="history" className="mt-4">- <FileHistoryTab git={data.git} linkPrefix={prefix} partnerHref={fileHref} />- </TabsContent>- {hasDecisions && (- <TabsContent value="decisions" className="mt-4">- <FileDecisionsTab- decisions={decisions}- linkPrefix={prefix}- {...(LinkComponent ? { LinkComponent } : {})}- />- </TabsContent>- )}- <TabsContent value="graph" className="mt-4">- <FileGraphTab- graph={data.graph}- filePath={data.file_path}- linkPrefix={prefix}- fileHref={fileHref}- symbolHref={symbolHref}- />- </TabsContent>- <TabsContent value="coverage" className="mt-4">- <FileCoverageTab coverage={data.coverage} coverageCodeHtml={coverageCodeHtml} />- </TabsContent>- </Tabs>+ {panels[activeTab]}+ </div>+ </ViewTabs></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"}` : ""- }.`;+/** Narrow a `?tab=` string to a tab this page actually renders. Exported for+ * server components that need it before the shell mounts. */+export function asFilePageTab(value: string | undefined): FilePageTab | undefined {+ return value && (FILE_PAGE_TABS as readonly string[]).includes(value)+ ? (value as FilePageTab)+ : undefined;}diff --git a/packages/ui/src/files/file-section.tsx b/packages/ui/src/files/file-section.tsxnew file mode 100644index 000000000..4a8be8733--- /dev/null+++ b/packages/ui/src/files/file-section.tsx@@ -0,0 +1,64 @@+import * as React from "react";+import { cn } from "../lib/cn";++export interface FileSectionProps {+ title: string;+ /** What the figures in it mean. Not the section's own name again. */+ description?: React.ReactNode;+ action?: React.ReactNode;+ /**+ * The first section inside a tab panel. The tab row already draws a hairline+ * directly above it, so a second one 12 units down is a rule where the+ * layout already has one.+ */+ first?: boolean;+ className?: string;+ children: React.ReactNode;+}++/**+ * The grouping device for everything inside a file tab: a hairline and vertical+ * rhythm, not a bordered box. Rule 1 — a card means "a discrete object you can+ * act on", and a table of function churn is not that.+ *+ * The measurements are `files-index.tsx`'s heavier variant (`mt-12` / `pt-8`,+ * `text-lg` heading) rather than `OverviewSection`'s, deliberately: the two+ * Files surfaces link into each other constantly and a reader moving between+ * them should not cross a type-scale change to do it.+ */+export function FileSection({+ title,+ description,+ action,+ first = false,+ className,+ children,+}: FileSectionProps) {+ return (+ <section+ className={cn(+ "space-y-3",+ !first && "mt-12 border-t border-[var(--color-border-default)] pt-8",+ className,+ )}+ >+ <div className="flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1">+ <h2 className="text-lg font-semibold text-[var(--color-text-primary)]">{title}</h2>+ {action}+ </div>+ {description && (+ <p className="max-w-[75ch] text-sm leading-relaxed text-[var(--color-text-secondary)] [text-wrap:pretty]">+ {description}+ </p>+ )}+ {children}+ </section>+ );+}++/** A figure inside a section's sentence. Matches `files-index`'s `Fig` so the+ * two surfaces emphasise numbers the same way. No `tabular-nums`: it is not in+ * a column and cannot change in place, which is where that rule applies. */+export function Fig({ children }: { children: React.ReactNode }) {+ return <span className="font-medium text-[var(--color-text-primary)]">{children}</span>;+}diff --git a/packages/ui/src/files/files-index.tsx b/packages/ui/src/files/files-index.tsxindex c787e6a11..18b47d2db 100644--- a/packages/ui/src/files/files-index.tsx+++ b/packages/ui/src/files/files-index.tsx@@ -1,6 +1,6 @@"use client";-import { useMemo, useState, type ReactNode } from "react";+import { useMemo, useState } from "react";import { Search } from "lucide-react";import type { FileLanguageCount, FileRow } from "@repowise-dev/types/files";import { bandForScore } from "@repowise-dev/types/health";@@ -8,6 +8,10 @@ import { cn } from "../lib/cn";import { formatLOC, formatNumber } from "../lib/format";import { FilesTreemap, type TreemapColor, type TreemapSize } from "./files-treemap";import { FilesTable, type SortKey } from "./files-table";+// One `Fig`, shared with the file detail page. The two Files surfaces are meant+// to emphasise a figure identically, and two identical local copies is how that+// stops being true without anyone noticing.+import { Fig } from "./file-section";interface FilesIndexProps {files: FileRow[];@@ -87,12 +91,6 @@ function Segmented<T extends string>({);}-/** A figure inside the lede sentence. No `tabular-nums`: it is not in a column- * and cannot change in place, which is where that rule applies. */-function Fig({ children }: { children: ReactNode }) {- return <span className="font-medium text-[var(--color-text-primary)]">{children}</span>;-}-export function FilesIndex({ files, languages, fileHref }: FilesIndexProps) {const [query, setQuery] = useState("");const [sortKey, setSortKey] = useState<SortKey>("dependents");diff --git a/packages/ui/src/files/index.ts b/packages/ui/src/files/index.tsindex ffc05a307..d5fd96b8e 100644--- a/packages/ui/src/files/index.ts+++ b/packages/ui/src/files/index.ts@@ -1,5 +1,9 @@export * from "./file-page";export * from "./file-page-tabs";+export * from "./file-page-header";+export * from "./file-page-panels";+export * from "./file-section";+export * from "./file-marks";export * from "./file-overview-tab";export * from "./file-doc-tab";export * from "./file-health-tab";diff --git a/packages/ui/src/health/tokens.ts b/packages/ui/src/health/tokens.tsindex b420208be..0a4ebb54b 100644--- a/packages/ui/src/health/tokens.ts+++ b/packages/ui/src/health/tokens.ts@@ -66,16 +66,25 @@ export function scoreBand(score: number): ScoreBand {}/* Color classes for the 3 canonical health bands (Alert/Warning/Healthy).- * Literal strings so Tailwind's static scanner keeps them. */+ * Literal strings so Tailwind's static scanner keeps them.+ *+ * These MUST use the same tokens as `HEALTH_BAND_INK` below. They did not:+ * the Warning band read `--color-caution` here and `--color-warning` there,+ * so a 6.9 was one amber as a label and a different amber as a fill —+ * the treemap tile and the file page's score, or the zoom map's dot and its+ * detail panel, describing one file in one viewport. Two marks on one object+ * may not disagree about a colour they both derive from `bandForScore`.+ * `--color-caution` stays where it belongs: the four-step severity/presentation+ * ramp below, which is not a band. */const HEALTH_BAND_TEXT: Record<HealthBand, string> = {alert: "text-[var(--color-error)]",- warning: "text-[var(--color-caution)]",+ warning: "text-[var(--color-warning)]",healthy: "text-[var(--color-success)]",};const HEALTH_BAND_BADGE_SOFT: Record<HealthBand, string> = {alert: "bg-[var(--color-error)]/15 text-[var(--color-error)]",- warning: "bg-[var(--color-caution)]/15 text-[var(--color-caution)]",+ warning: "bg-[var(--color-warning)]/15 text-[var(--color-warning)]",healthy: "bg-[var(--color-success)]/15 text-[var(--color-success)]",};diff --git a/packages/ui/src/shared/empty-state.tsx b/packages/ui/src/shared/empty-state.tsxindex 31a57b653..fa27001e0 100644--- a/packages/ui/src/shared/empty-state.tsx+++ b/packages/ui/src/shared/empty-state.tsx@@ -11,9 +11,23 @@ interface EmptyStateProps {onClick: () => void;};className?: string;+ /**+ * Heading level for the title. Defaults to `h3`, which is right where the+ * empty state stands in for a section inside one. Pass `h2` where it *is*+ * the whole panel — the file page's tab bodies do, and without it the page+ * runs `h1` (the path) straight to `h3` with nothing between.+ */+ titleAs?: "h2" | "h3";}-export function EmptyState({ icon, title, description, action, className }: EmptyStateProps) {+export function EmptyState({+ icon,+ title,+ description,+ action,+ className,+ titleAs: Heading = "h3",+}: EmptyStateProps) {return (<divclassName={cn(@@ -27,7 +41,9 @@ export function EmptyState({ icon, title, description, action, className }: Empt</div>)}<div className="space-y-1">- <h3 className="text-sm font-semibold text-[var(--color-text-primary)]">{title}</h3>+ <Heading className="text-sm font-semibold text-[var(--color-text-primary)]">+ {title}+ </Heading>{description && (<p className="text-sm text-[var(--color-text-secondary)]">{description}</p>)}diff --git a/packages/web/src/app/repos/[id]/files/[...path]/loading.tsx b/packages/web/src/app/repos/[id]/files/[...path]/loading.tsxindex 18ce2146f..7464e1a65 100644--- a/packages/web/src/app/repos/[id]/files/[...path]/loading.tsx+++ b/packages/web/src/app/repos/[id]/files/[...path]/loading.tsx@@ -1,16 +1,37 @@import { Skeleton } from "@repowise-dev/ui/ui/skeleton";+/**+ * Shapes match the real header: eyebrow, path, the lede's 44px figure beside+ * its prose column, the hairline stat ribbon, then the tab row and one panel.+ * The old version drew a row of pills the page no longer has and no figure at+ * all, so content landing reflowed everything — which reads as slower than+ * showing nothing.+ */export default function FilePageLoading() {return (- <div className="p-4 sm:p-6 max-w-[1200px] space-y-4">- <Skeleton className="h-6 w-2/3" />- <div className="flex gap-2">- <Skeleton className="h-6 w-14" />- <Skeleton className="h-6 w-20" />- <Skeleton className="h-6 w-24" />+ <div className="mx-auto flex w-full max-w-[1280px] flex-col p-[var(--page-pad)]">+ <div className="flex flex-col gap-8">+ <div className="flex flex-col gap-6">+ <div>+ <Skeleton className="h-3 w-8" />+ <Skeleton className="mt-2 h-7 w-2/3" />+ </div>+ <div className="flex flex-col gap-5 lg:flex-row lg:items-start lg:gap-12">+ <div className="lg:w-[220px]">+ <Skeleton className="h-3 w-20" />+ <Skeleton className="mt-2.5 h-11 w-28" />+ </div>+ <div className="flex-1 space-y-2">+ <Skeleton className="h-4 w-full max-w-[62ch]" />+ <Skeleton className="h-4 w-5/6 max-w-[62ch]" />+ <Skeleton className="h-4 w-3/4 max-w-[62ch]" />+ </div>+ </div>+ <Skeleton className="h-[74px] w-full" />+ </div>+ <Skeleton className="h-9 w-full max-w-lg" />+ <Skeleton className="h-96 w-full" /></div>- <Skeleton className="h-9 w-96" />- <Skeleton className="h-96 w-full" /></div>);}diff --git a/packages/web/src/app/repos/[id]/files/[...path]/page.tsx b/packages/web/src/app/repos/[id]/files/[...path]/page.tsxindex b06dd4c61..6ea80c8ee 100644--- a/packages/web/src/app/repos/[id]/files/[...path]/page.tsx+++ b/packages/web/src/app/repos/[id]/files/[...path]/page.tsx@@ -1,10 +1,20 @@import type { Metadata } from "next";import { notFound } from "next/navigation";+import Link from "next/link";import { bundledLanguages, getSingletonHighlighter, type BundledLanguage } from "shiki";import { getFileContent, getFileDetail } from "@/lib/api/files";import { WikiMarkdown } from "@repowise-dev/ui/wiki/wiki-markdown";+import { fileEntityPath, symbolEntityPath } from "@repowise-dev/ui/shared/entity";+import {+ asFilePageTab,+ buildFilePanels,+ fileTabsFor,+ FilePageHeader,+ resolveFileTab,+ type FilePageTab,+} from "@repowise-dev/ui/files";import { FilePageHost } from "@/components/files/file-page-host";-import { FILE_PAGE_TABS, type FilePageTab } from "@repowise-dev/ui/files";+import { FileHealthPanel } from "@/components/files/file-health-panel";import type { FileDetailResponse } from "@repowise-dev/types/files";/** Matches the sibling routes (`decisions`, the repo root, the four workspace@@ -20,6 +30,14 @@ interface Props {searchParams: Promise<{ tab?: string }>;}+/**+ * The three tabs whose bodies read one of the four unbounded blocks the+ * aggregate can drop (`fields=slim`): the wiki body, the covered-line array,+ * per-function blame and per-finding `details`. Landing on any other tab does+ * not need them, and the four together are most of the payload.+ */+const HEAVY_TABS: readonly FilePageTab[] = ["doc", "health", "coverage"];+export async function generateMetadata({ params }: Props): Promise<Metadata> {const { path } = await params;const filePath = path.map(decodeURIComponent).join("/");@@ -85,23 +103,25 @@ export default async function FileEntityPage({ params, searchParams }: Props) {const { id, path } = await params;const { tab } = await searchParams;const filePath = path.map(decodeURIComponent).join("/");+ const prefix = `/repos/${id}`;- const initialTab =- tab && (FILE_PAGE_TABS as readonly string[]).includes(tab)- ? (tab as FilePageTab)- : undefined;+ const requested = asFilePageTab(tab);+ // Only a landing on one of the heavy tabs pays for the heavy blocks. The+ // aggregate's `fields=slim` skips the blame query outright and empties the+ // other three, and the host round-trips on the first click into a tab this+ // render could not produce a body for.+ const wantsFull = requested !== undefined && HEAVY_TABS.includes(requested);- // Only the Coverage tab renders highlighted source, and reading the file off- // disk costs three DB queries of its own inside `/file-content`. Fetched- // beside the aggregate rather than after it: the highlight needs `detail`,- // but the source bytes do not.- const wantsCoverage = initialTab === "coverage";let detail: FileDetailResponse;let source: string | undefined;try {+ // Only the Coverage tab renders highlighted source, and reading the file+ // off disk costs three DB queries of its own inside `/file-content`.+ // Fetched beside the aggregate rather than after it: the highlight needs+ // `detail`, but the source bytes do not.[detail, source] = await Promise.all([- getFileDetail(id, filePath),- wantsCoverage+ getFileDetail(id, filePath, { fields: wantsFull ? "full" : "slim" }),+ requested === "coverage"? getFileContent(id, filePath).catch(() => undefined): Promise.resolve(undefined),]);@@ -111,40 +131,72 @@ export default async function FileEntityPage({ params, searchParams }: Props) {const coverageCodeHtml = await renderCoverageCode(source, detail);- const docSlot = detail.wiki_page ? (- <WikiMarkdown content={detail.wiki_page.content} />- ) : undefined;- const wikiHref = detail.wiki_page- ? `/repos/${id}/docs?page=${encodeURIComponent(detail.wiki_page.id)}`- : undefined;-- // `FilePageHost` is a client component taking `data` whole, so everything in- // it is serialized into the RSC flight payload *and* inlined into the HTML —- // downloaded twice. These two blocks were consumed above, on the server, and- // are read by nothing in the client tree: the wiki body became `docSlot`,- // and the coverage line array became `coverageCodeHtml` plus a count.- const clientData: FileDetailResponse = {- ...detail,- wiki_page: detail.wiki_page ? { ...detail.wiki_page, content: "" } : null,- coverage: detail.coverage- ? {- ...detail.coverage,- covered_line_count:- detail.coverage.covered_line_count ?? detail.coverage.covered_lines.length,- covered_lines: [],- }- : null,- };+ const tabs = fileTabsFor(detail);+ const initialTab = resolveFileTab(requested, tabs);++ // Which tabs this render could not produce a usable body for. A tab with+ // nothing behind it is left out: clicking Documentation on a file that has+ // no page would otherwise buy a round trip to be shown the same empty state.+ const refetchTabs: FilePageTab[] = [];+ if (!wantsFull) {+ if (detail.wiki_page) refetchTabs.push("doc");+ // `function_blame_count` is why this reads the count rather than the array:+ // slim drops the rows, so an empty array and a dropped one are the same+ // shape on the wire, and guessing either way is wrong for some file.+ const blame = detail.function_blame_count ?? detail.function_blame.length;+ if (detail.health.metric || detail.health.findings.length > 0 || blame > 0) {+ refetchTabs.push("health");+ }+ }+ const covered = detail.coverage;+ const highlightPossible =+ !!covered && (covered.covered_line_count ?? covered.covered_lines.length) > 0;+ // Gated on not already being here. Land on `?tab=coverage` for a file over+ // the highlight size cap and `coverageCodeHtml` is undefined for good — so+ // without this, every click on the tab you are already on re-ran the whole+ // aggregate to produce byte-identical output, which is the Phase 1 bug.+ if (highlightPossible && !coverageCodeHtml && requested !== "coverage") {+ refetchTabs.push("coverage");+ }++ const panels = buildFilePanels({+ data: detail,+ linkPrefix: prefix,+ fileHref: (p) => fileEntityPath(prefix, p),+ symbolHref: (s) => symbolEntityPath(prefix, s),+ ...(detail.wiki_page?.content+ ? { docSlot: <WikiMarkdown content={detail.wiki_page.content} /> }+ : {}),+ coverageCodeHtml,+ ...(detail.wiki_page+ ? { wikiHref: `${prefix}/docs?page=${encodeURIComponent(detail.wiki_page.id)}` }+ : {}),+ healthPanel: (+ <FileHealthPanel+ repoId={id}+ health={detail.health}+ functionBlame={detail.function_blame}+ />+ ),+ LinkComponent: Link,+ });return (- <div className="p-4 sm:p-6 max-w-[1200px]">+ // The Overview's wrapper verbatim: centred, `--page-pad`, 1280. The page+ // was `max-w-[1200px] p-4 sm:p-6` and left-anchored, so at 2048 it left a+ // 770px hole down the right while every ported sibling centred.+ <div className="mx-auto flex w-full max-w-[1280px] flex-col p-[var(--page-pad)]"><FilePageHost- repoId={id}- data={clientData}- docSlot={docSlot}- coverageCodeHtml={coverageCodeHtml}- wikiHref={wikiHref}+ // Keyed on the path so a soft navigation between two file pages+ // remounts the shell. Without it React preserves the tab state at the+ // same tree position and the active tab strands out of sync with the+ // URL the new page was rendered for.+ key={detail.file_path}+ header={<FilePageHeader data={detail} linkPrefix={prefix} LinkComponent={Link} />}+ tabs={tabs}+ panels={panels}initialTab={initialTab}+ refetchTabs={refetchTabs}/></div>);diff --git a/packages/web/src/components/files/file-health-panel.tsx b/packages/web/src/components/files/file-health-panel.tsxnew file mode 100644index 000000000..c62b327db--- /dev/null+++ b/packages/web/src/components/files/file-health-panel.tsx@@ -0,0 +1,46 @@+"use client";++import { toast } from "sonner";+import { FileHealthTab, type FindingStatus } from "@repowise-dev/ui/files";+import { fileEntityPath, symbolEntityPath } from "@repowise-dev/ui/shared/entity";+import { updateFindingStatus } from "@/lib/api/code-health";+import type { FileDetailHealth, FunctionBlameRow } from "@repowise-dev/types/files";++interface FileHealthPanelProps {+ repoId: string;+ health: FileDetailHealth;+ functionBlame: FunctionBlameRow[];+}++/**+ * The one client wrapper the file page needs.+ *+ * `FileHealthTab` is the single tab body that hydrates, and the only reason it+ * cannot be handed straight to `buildFilePanels` from the server page is that+ * its triage callback and its two href builders are functions, which do not+ * cross a server boundary as props. Wrapping it here keeps that boundary at one+ * component instead of at the top of the page.+ */+export function FileHealthPanel({ repoId, health, functionBlame }: FileHealthPanelProps) {+ const prefix = `/repos/${repoId}`;++ const onFindingStatusChange = async (findingId: string, status: FindingStatus) => {+ try {+ await updateFindingStatus(repoId, findingId, status);+ toast.success(`Finding marked ${status.replace("_", " ")}`);+ } catch (err) {+ toast.error("Couldn't update finding status");+ throw err;+ }+ };++ return (+ <FileHealthTab+ health={health}+ functionBlame={functionBlame}+ onFindingStatusChange={onFindingStatusChange}+ partnerHref={(p) => fileEntityPath(prefix, p)}+ symbolHref={(s) => symbolEntityPath(prefix, s)}+ />+ );+}diff --git a/packages/web/src/components/files/file-page-host.tsx b/packages/web/src/components/files/file-page-host.tsxindex 42bc0ecd2..ab17b14a1 100644--- a/packages/web/src/components/files/file-page-host.tsx+++ b/packages/web/src/components/files/file-page-host.tsx@@ -1,31 +1,30 @@"use client";import type { ReactNode } from "react";-import Link from "next/link";import { usePathname, useRouter, useSearchParams } from "next/navigation";-import { toast } from "sonner";-import { FilePage, type FilePageTab, type FindingStatus } from "@repowise-dev/ui/files";-import { updateFindingStatus } from "@/lib/api/code-health";-import type { FileDetailResponse } from "@repowise-dev/types/files";+import { FilePage, type FilePageTab, type FileTabDef } from "@repowise-dev/ui/files";interface FilePageHostProps {- repoId: string;- data: FileDetailResponse;- docSlot?: ReactNode;- coverageCodeHtml?: string;- wikiHref?: string;- initialTab?: FilePageTab;+ header: ReactNode;+ tabs: FileTabDef[];+ panels: Partial<Record<FilePageTab, ReactNode>>;+ initialTab?: FilePageTab | undefined;+ /**+ * Tabs whose body the current server render could not produce, so clicking+ * one has to go back for it. Empty when the page was fetched in full.+ */+ refetchTabs?: FilePageTab[];}-/** Client host for the file entity page: wires finding triage to the API- * (with toasts) and keeps the active tab in the URL for deep links. */+/** Client host for the file entity page: keeps the active tab in the URL for+ * deep links without re-running the aggregate for the tabs that do not need+ * it. Everything it renders arrived as server markup. */export function FilePageHost({- repoId,- data,- docSlot,- coverageCodeHtml,- wikiHref,+ header,+ tabs,+ panels,initialTab,+ refetchTabs = [],}: FilePageHostProps) {const router = useRouter();const pathname = usePathname();@@ -34,16 +33,6 @@ export function FilePageHost({// packages/ui/README.md rules out for the shared components this hosts.const searchParams = useSearchParams();- // Whether a server round trip could produce highlighted source at all. The- // server declines to highlight when there is no coverage row and when the- // covered-line set is empty, and both of those are visible from here — so a- // click on Coverage for an un-ingested file must not pay for the aggregate- // to be told "no" again. The two cases it cannot see (source over the size- // cap, `/file-content` failing) are rare and cost one trip.- const covered = data.coverage;- const highlightPossible =- !!covered && (covered.covered_line_count ?? covered.covered_lines.length) > 0;-const onTabChange = (tab: FilePageTab) => {const sp = new URLSearchParams(searchParams.toString());if (tab === "overview") sp.delete("tab");@@ -51,47 +40,27 @@ export function FilePageHost({const qs = sp.toString();const url = qs ? `${pathname}?${qs}` : pathname;- // Coverage is the one tab whose body is server-rendered (shiki-highlighted- // source), so it is the one tab that can still need the round trip. Every- // other tab reads data already in `data`, and `router.replace` re-ran the- // whole ~18-query aggregate plus the highlight to hand back a payload- // identical to the one on screen. A shallow history entry keeps the tab- // deep-linkable and reloadable without refetching anything.- if (tab === "coverage" && highlightPossible && !coverageCodeHtml) {+ // The three heavy tabs — Documentation, Health and Coverage — are the only+ // ones whose bodies read a payload the slim fetch drops. When the page was+ // served slim, the first click into one of them needs the round trip that+ // produces it; every other tab reads data already on screen, and+ // `router.replace` re-ran the whole aggregate to hand back a payload+ // identical to the one being displayed. A shallow history entry keeps the+ // tab deep-linkable and reloadable without refetching anything.+ if (refetchTabs.includes(tab)) {router.replace(url, { scroll: false });return;}window.history.replaceState(null, "", url);};- const onFindingStatusChange = async (findingId: string, status: FindingStatus) => {- try {- await updateFindingStatus(repoId, findingId, status);- toast.success(`Finding marked ${status.replace("_", " ")}`);- } catch (err) {- toast.error("Couldn't update finding status");- throw err;- }- };-- 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 (<FilePage- data={data}- repoId={repoId}- LinkComponent={Link}- breadcrumb={[- ...(dir ? [{ label: dir }] : []),- { label: fileName },- ]}- docSlot={docSlot}- coverageCodeHtml={coverageCodeHtml}- wikiHref={wikiHref}+ header={header}+ tabs={tabs}+ panels={panels}initialTab={initialTab}onTabChange={onTabChange}- onFindingStatusChange={onFindingStatusChange}/>);}