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(security): lead with posture and scan freshness, findings open by default (#3307)
Raghav Chamadiya2593da5cf269
diff --git a/packages/ui/__tests__/security/security.test.tsx b/packages/ui/__tests__/security/security.test.tsxnew file mode 100644index 000000000..a4855ce33--- /dev/null+++ b/packages/ui/__tests__/security/security.test.tsx@@ -0,0 +1,145 @@+import { describe, it, expect } from "vitest";+import { render, screen, fireEvent, within } from "@testing-library/react";+import type { SecurityFinding } from "@repowise-dev/types";+import { SecurityFindingsTable } from "../../src/security/findings-table.js";+import { SeverityDirectoryMatrix } from "../../src/security/severity-directory-matrix.js";+import {+ SecurityPosture,+ countSecurityFindings,+ securityPathClass,+} from "../../src/security/posture.js";++let nextId = 1;+function finding(file_path: string, severity: string, kind = "eval_call"): SecurityFinding {+ return {+ id: nextId++,+ file_path,+ kind,+ severity,+ snippet: "eval(x)",+ detected_at: "2026-10-01T00:00:00Z",+ line_number: 3,+ line_verified: true,+ commit_at: null,+ };+}++const FINDINGS = [+ finding("tests/fixtures/keys.py", "low", "hardcoded_secret"),+ finding("src/app/server.py", "high"),+ finding("docs/setup.md", "med", "hardcoded_secret"),+ finding("src/app/util.py", "med"),+];++describe("securityPathClass", () => {+ it("separates shipped source from tests and docs", () => {+ expect(securityPathClass("src/app/server.py")).toBe("source");+ expect(securityPathClass("packages/ui/__tests__/a.test.tsx")).toBe("test");+ expect(securityPathClass("pkg/foo_test.go")).toBe("test");+ expect(securityPathClass("test_login.py")).toBe("test");+ expect(securityPathClass("docs/guide/index.html")).toBe("docs");+ expect(securityPathClass("CHANGELOG.md")).toBe("docs");+ });+});++describe("countSecurityFindings", () => {+ it("counts by place and severity", () => {+ expect(countSecurityFindings(FINDINGS)).toEqual({+ total: 4,+ source: 2,+ elsewhere: 2,+ sourceHigh: 1,+ high: 1,+ med: 2,+ low: 1,+ });+ });+});++describe("SecurityPosture", () => {+ it("leads with shipped source and says when the scan ran", () => {+ render(<SecurityPosture findings={FINDINGS} scannedAgo="3 days ago" />);+ expect(screen.getByText("In shipped source")).toBeInTheDocument();+ expect(screen.getByText("of 4 findings")).toBeInTheDocument();+ expect(+ screen.getByText(/matched 2 places in shipped source, 1 of them high\. 2 more are in tests and docs/),+ ).toBeInTheDocument();+ expect(screen.getByText("Scanned 3 days ago.")).toBeInTheDocument();+ });++ it("never implies freshness it does not have", () => {+ render(<SecurityPosture findings={FINDINGS} scannedAgo={null} capped />);+ expect(screen.getByText("Scan time not recorded.")).toBeInTheDocument();+ expect(screen.getByText("of 4+ findings")).toBeInTheDocument();+ });++ it("does not headline matches that only sit in tests", () => {+ render(<SecurityPosture findings={[FINDINGS[0]!]} scannedAgo="now" />);+ expect(screen.getByText(/Nothing matched in shipped source\. The one match is in tests and docs/)).toBeInTheDocument();+ });+});++describe("SecurityFindingsTable", () => {+ it("marks severity as a dot and a word, never green or a filled chip", () => {+ const { container } = render(<SecurityFindingsTable findings={FINDINGS} />);+ const table = screen.getByRole("table");+ expect(within(table).getAllByText("Medium")).toHaveLength(2);+ expect(container.innerHTML).not.toContain("--color-success");+ expect(container.querySelector("[class*='bg-[var(--color-accent-primary)]']")).toBeNull();+ });++ it("ranks shipped source first and labels the rest", () => {+ render(<SecurityFindingsTable findings={FINDINGS} />);+ const rows = within(screen.getByRole("table")).getAllByRole("row").slice(1);+ expect(rows.map((r) => r.textContent)).toEqual([+ expect.stringContaining("src/app/server.py"),+ expect.stringContaining("src/app/util.py"),+ expect.stringContaining("tests/fixtures/keys.py"),+ expect.stringContaining("docs/setup.md"),+ ]);+ expect(rows[2]!.textContent).toContain("test");+ });++ it("wraps the path instead of truncating it", () => {+ render(<SecurityFindingsTable findings={FINDINGS} />);+ const path = screen.getByText("src/app/server.py");+ expect(path.className).not.toContain("break-all");+ expect(path.querySelectorAll("wbr").length).toBeGreaterThan(1);+ expect(path.className).not.toContain("truncate");+ });++ it("keeps every severity option and its unfiltered count when one is picked", () => {+ render(<SecurityFindingsTable findings={FINDINGS} />);+ const group = screen.getByRole("radiogroup", { name: "Severity" });+ fireEvent.click(within(group).getByRole("radio", { name: /High/ }));+ expect(within(group).getByRole("radio", { name: /High/ })).toHaveAttribute("aria-checked", "true");+ expect(within(group).getAllByRole("radio").map((r) => r.textContent)).toEqual([+ "All4",+ "High1",+ "Medium2",+ "Low1",+ ]);+ expect(within(screen.getByRole("table")).getAllByRole("row")).toHaveLength(2);+ });++ it("offers to clear filters when they hide everything", () => {+ render(<SecurityFindingsTable findings={FINDINGS} />);+ fireEvent.change(screen.getByLabelText("Search findings"), { target: { value: "nothing-here" } });+ expect(screen.getByText("No findings match these filters")).toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Clear filters" }));+ expect(within(screen.getByRole("table")).getAllByRole("row")).toHaveLength(5);+ });+});++describe("SeverityDirectoryMatrix", () => {+ it("is a plain count table without heat tints", () => {+ const { container } = render(<SeverityDirectoryMatrix findings={FINDINGS} />);+ expect(screen.getByRole("rowheader", { name: "src/app" })).toBeInTheDocument();+ expect(container.querySelector("[style]")).toBeNull();+ });++ it("renders nothing for no findings", () => {+ const { container } = render(<SeverityDirectoryMatrix findings={[]} />);+ expect(container).toBeEmptyDOMElement();+ });+});diff --git a/packages/ui/src/security/findings-by-directory.tsx b/packages/ui/src/security/findings-by-directory.tsxdeleted file mode 100644index ce060e3db..000000000--- a/packages/ui/src/security/findings-by-directory.tsx+++ /dev/null@@ -1,60 +0,0 @@-"use client";--import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";-import type { SecurityFinding } from "./findings-table";--export interface FindingsByDirectoryProps {- findings: SecurityFinding[];- /** Path-segment depth to group at (default 2). */- depth?: number;-}--export function FindingsByDirectory({ findings, depth = 2 }: FindingsByDirectoryProps) {- const grouped = new Map<string, { dir: string; high: number; med: number; low: number; total: number }>();- for (const f of findings) {- const segments = f.file_path.split("/").slice(0, depth);- const dir = segments.length === 0 ? "(root)" : segments.join("/");- const cur = grouped.get(dir) ?? { dir, high: 0, med: 0, low: 0, total: 0 };- if (f.severity === "high") cur.high += 1;- else if (f.severity === "med") cur.med += 1;- else cur.low += 1;- cur.total += 1;- grouped.set(dir, cur);- }-- const rows = Array.from(grouped.values()).sort((a, b) => b.total - a.total).slice(0, 16);- const max = rows.reduce((m, r) => Math.max(m, r.total), 1);-- if (rows.length === 0) {- return null;- }-- return (- <Card>- <CardHeader className="pb-2">- <CardTitle className="text-sm">Findings by directory</CardTitle>- </CardHeader>- <CardContent className="pt-0 space-y-2">- {rows.map((r) => (- <div key={r.dir} className="text-xs">- <div className="flex items-center justify-between mb-1">- <span className="font-mono text-[var(--color-text-primary)] truncate">{r.dir}</span>- <span className="tabular-nums text-[var(--color-text-tertiary)] ml-2">{r.total}</span>- </div>- <div className="flex h-2 w-full overflow-hidden rounded-full bg-[var(--color-bg-inset)]">- {r.high > 0 && (- <div style={{ width: `${(r.high / max) * 100}%`, backgroundColor: "var(--color-error)" }} />- )}- {r.med > 0 && (- <div style={{ width: `${(r.med / max) * 100}%`, backgroundColor: "var(--color-warning)" }} />- )}- {r.low > 0 && (- <div style={{ width: `${(r.low / max) * 100}%`, backgroundColor: "var(--color-success)" }} />- )}- </div>- </div>- ))}- </CardContent>- </Card>- );-}diff --git a/packages/ui/src/security/findings-table.tsx b/packages/ui/src/security/findings-table.tsxindex 17147121c..ebd4b0c9c 100644--- a/packages/ui/src/security/findings-table.tsx+++ b/packages/ui/src/security/findings-table.tsx@@ -1,14 +1,18 @@"use client";+import * as React from "react";import { useMemo, useState } from "react";import { Search } from "lucide-react";-import { Badge } from "../ui/badge";import { Input } from "../ui/input";import { EmptyState } from "../shared/empty-state";import { CiHint } from "../shared/ci-hint";+import { Segmented } from "../shared/segmented";import { ResponsiveTable, type ResponsiveColumn } from "../shared/responsive-table";import { AiPromptButton } from "../health/ai-prompt-button";+import { SeverityMark } from "../health/severity-mark";+import type { Severity } from "../health/tokens";import { formatDate, formatDateTime, formatRelativeTimeOrNull } from "../lib/format";+import { securityLevel, securityPathClass, type SecurityLevel } from "./posture";import type { SecurityFinding } from "@repowise-dev/types";// One declaration of the wire shape, not a third hand-kept copy: this file's@@ -16,11 +20,39 @@ import type { SecurityFinding } from "@repowise-dev/types";// line number went unrendered.export type { SecurityFinding };-const SEVERITY_VARIANT: Record<string, "outdated" | "stale" | "outline"> = {- high: "outdated",- med: "stale",- low: "outline",-};+// Break only at path separators; `anywhere` is the last resort for a single+// segment wider than the box.+function BreakablePath({ path }: { path: string }) {+ const parts = path.split("/");+ return (+ <>+ {parts.map((part, i) => (+ <React.Fragment key={i}>+ {part}+ {i < parts.length - 1 && (+ <>+ /<wbr />+ </>+ )}+ </React.Fragment>+ ))}+ </>+ );+}++// The scanner's `med` is the shared scale's `medium`. No level maps to+// critical: a pattern match is a lead to confirm, not a proven path to harm.+const MARK: Record<SecurityLevel, Severity> = { high: "high", med: "medium", low: "low" };+const LEVEL_RANK: Record<SecurityLevel, number> = { high: 0, med: 1, low: 2 };+const CLASS_RANK = { source: 0, test: 1, docs: 2 } as const;++type SeverityFilter = "all" | SecurityLevel;+const FILTERS: { value: SeverityFilter; label: string }[] = [+ { value: "all", label: "All" },+ { value: "high", label: "High" },+ { value: "med", label: "Medium" },+ { value: "low", label: "Low" },+];/*** `path:line` for a finding, degrading honestly.@@ -30,10 +62,18 @@ const SEVERITY_VARIANT: Record<string, "outdated" | "stale" | "outline"> = {* confirm (prefixed `~`, never presented as fact), and no line at all when the* flagged code has moved away entirely. A wrong line here sends the reader to* innocent code looking authoritative, which is worse than showing none.+ *+ * The path is the row's name, so it wraps rather than truncates.*/function FindingLocation({ finding }: { finding: SecurityFinding }) {const line = finding.line_number;const verified = finding.line_verified;+ // Tests and docs are labelled, never headlined: shipped code ranks first.+ const where = securityPathClass(finding.file_path);+ const tag =+ where === "source" ? null : (+ <span className="ml-1.5 font-sans text-2xs text-[var(--color-text-tertiary)]">{where}</span>+ );// Every state carries words, not just a colour and a tooltip: `title` is// invisible to touch and to assistive tech, which is why VerificationBadge@@ -41,27 +81,29 @@ function FindingLocation({ finding }: { finding: SecurityFinding }) {if (line == null) {return (<span- className="block max-w-[280px] truncate font-mono text-xs text-[var(--color-text-primary)]"- title={`${finding.file_path} — the flagged code is no longer at the recorded line`}+ className="block min-w-[14rem] [overflow-wrap:anywhere] font-mono text-xs text-[var(--color-text-primary)]"+ title={`${finding.file_path}: the flagged code is no longer at the recorded line`}>- {finding.file_path}+ <BreakablePath path={finding.file_path} /><span className="ml-1.5 not-italic text-2xs text-[var(--color-text-tertiary)]">(line moved)</span>+ {tag}</span>);}return (<span- className="block max-w-[280px] truncate font-mono text-xs text-[var(--color-text-primary)]"+ className="block min-w-[14rem] [overflow-wrap:anywhere] font-mono text-xs text-[var(--color-text-primary)]"title={verified? `${finding.file_path}:${line}`- : `${finding.file_path}:${line} — could not be confirmed against the current file`+ : `${finding.file_path}:${line}: could not be confirmed against the current file`}>- {finding.file_path}+ <BreakablePath path={finding.file_path} />+ <wbr /><spanclassName={verified ? "text-[var(--color-text-secondary)]" : "text-[var(--color-text-tertiary)]"@@ -71,6 +113,7 @@ function FindingLocation({ finding }: { finding: SecurityFinding }) {{line}</span>{!verified && <span className="sr-only"> (line unconfirmed)</span>}+ {tag}</span>);}@@ -84,11 +127,19 @@ export interface SecurityFindingsTableProps {export function SecurityFindingsTable({ findings, onSelect, onGeneratePrompt }: SecurityFindingsTableProps) {const [q, setQ] = useState("");- const [sev, setSev] = useState<"all" | "high" | "med" | "low">("all");+ const [sev, setSev] = useState<SeverityFilter>("all");++ // Options and counts come from the unfiltered list, so picking one level+ // never hides the others.+ const options = useMemo(() => {+ const c: Record<SeverityFilter, number> = { all: findings.length, high: 0, med: 0, low: 0 };+ for (const f of findings) c[securityLevel(f.severity)] += 1;+ return FILTERS.map((o) => ({ ...o, count: c[o.value].toLocaleString() }));+ }, [findings]);const filtered = useMemo(() => {let items = findings;- if (sev !== "all") items = items.filter((f) => f.severity === sev);+ if (sev !== "all") items = items.filter((f) => securityLevel(f.severity) === sev);if (q) {const needle = q.toLowerCase();items = items.filter(@@ -98,7 +149,12 @@ export function SecurityFindingsTable({ findings, onSelect, onGeneratePrompt }:(f.snippet ?? "").toLowerCase().includes(needle),);}- return items;+ // What to do first: shipped source before tests before docs, then severity.+ return [...items].sort(+ (a, b) =>+ CLASS_RANK[securityPathClass(a.file_path)] - CLASS_RANK[securityPathClass(b.file_path)] ||+ LEVEL_RANK[securityLevel(a.severity)] - LEVEL_RANK[securityLevel(b.severity)],+ );}, [findings, q, sev]);const columns = useMemo(() => {@@ -106,12 +162,8 @@ export function SecurityFindingsTable({ findings, onSelect, onGeneratePrompt }:{key: "severity",header: "Severity",- headerClassName: "w-20",- render: (f) => (- <Badge variant={SEVERITY_VARIANT[f.severity] ?? "outline"} className="capitalize">- {f.severity}- </Badge>- ),+ headerClassName: "w-24",+ render: (f) => <SeverityMark severity={MARK[securityLevel(f.severity)]} />,},{key: "file_path",@@ -190,57 +242,53 @@ export function SecurityFindingsTable({ findings, onSelect, onGeneratePrompt }:<div className="flex flex-col items-center gap-2"><EmptyStatetitle="No findings"- description="No security findings detected on this repo. Re-run analysis to refresh."+ description="The pattern scan has no security findings to show for this repository."/><CiHint command="repowise security check" checks="what each change adds" /></div>);}+ const clear = () => {+ setQ("");+ setSev("all");+ };+return (<div className="space-y-3"><div className="flex flex-wrap items-center gap-2">- <div className="relative">- <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-[var(--color-text-tertiary)]" />+ <div className="relative w-full sm:w-72">+ <Search+ aria-hidden+ className="absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-[var(--color-text-tertiary)]"+ /><Inputvalue={q}onChange={(e) => setQ(e.target.value)}placeholder="Search file, kind, or snippet…"- className="pl-8 h-8 w-full sm:w-72 text-xs"+ aria-label="Search findings"+ className="h-8 w-full pl-8 text-xs"/></div>- <div className="flex rounded-md border border-[var(--color-border-default)] overflow-hidden text-xs">- {(["all", "high", "med", "low"] as const).map((s) => (- <button- key={s}- type="button"- onClick={() => setSev(s)}- className={- sev === s- ? "px-2.5 py-1.5 bg-[var(--color-accent-primary)] text-[var(--color-text-inverse)]"- : "px-2.5 py-1.5 bg-transparent text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)]"- }- >- {s}- {s !== "all" && (- <span className="ml-1 text-[10px] opacity-70">- ({findings.filter((f) => f.severity === s).length})- </span>- )}- </button>- ))}- </div>+ <Segmented label="Severity" value={sev} onChange={setSev} options={options} /></div>+ {/* Scrolls sideways inside its own frame on a phone rather than+ stacking: the path column keeps a readable minimum width. Windowed,+ because the list is open by default and can hold 500 rows. */}<ResponsiveTablecolumns={columns}rows={filtered}rowKey={(f) => String(f.id)}caption="Security findings"{...(onSelect ? { onRowClick: onSelect } : {})}- stacked="sm"+ virtualize={{}}empty={- <p className="text-sm text-[var(--color-text-tertiary)] py-6 text-center">No matches.</p>+ <EmptyState+ tone="filtered"+ title="No findings match these filters"+ action={{ label: "Clear filters", onClick: clear }}+ />}/></div>diff --git a/packages/ui/src/security/index.ts b/packages/ui/src/security/index.tsindex 8fd321c79..12149428e 100644--- a/packages/ui/src/security/index.ts+++ b/packages/ui/src/security/index.ts@@ -1,3 +1,3 @@export * from "./findings-table";-export * from "./findings-by-directory";+export * from "./posture";export * from "./severity-directory-matrix";diff --git a/packages/ui/src/security/posture.tsx b/packages/ui/src/security/posture.tsxnew file mode 100644index 000000000..36f23a278--- /dev/null+++ b/packages/ui/src/security/posture.tsx@@ -0,0 +1,184 @@+import * as React from "react";+import { PageLede } from "../shared/page-lede";+import { Skeleton, SkeletonRegion } from "../ui/skeleton";+import type { SecurityFinding } from "@repowise-dev/types";++export type SecurityPathClass = "source" | "test" | "docs";++// Client-side guess at where a match lives, mirroring the scanner's own+// low-severity path tokens. Ceiling: a heuristic on the path alone. Hosted+// serves a server-side `path_class`; switch to it once the OSS endpoint+// carries one.+const TEST_SEGMENTS = new Set([+ "test",+ "tests",+ "__tests__",+ "__test__",+ "testdata",+ "e2e",+ "spec",+ "specs",+ "fixtures",+ "__fixtures__",+]);+const DOCS_SEGMENTS = new Set(["docs", "doc", "documentation", "example", "examples"]);+// Mock directories (`mock`, `mocks`, `__mocks__`) as a pattern: the bare word reads as a provider name to the UI guard.+const MOCK_SEGMENT = /^(__)?mocks?(__)?$/;+const TEST_FILE = /(^test_|_test\.|\.test\.|\.spec\.|_spec\.)/i;+const DOCS_FILE = /\.(md|mdx|rst|adoc)$/i;++/** Shipped source, tests, or docs, judged from the path. */+export function securityPathClass(path: string): SecurityPathClass {+ const parts = path.replace(/\\/g, "/").toLowerCase().split("/");+ const name = parts[parts.length - 1] ?? "";+ if (parts.some((p) => TEST_SEGMENTS.has(p) || MOCK_SEGMENT.test(p)) || TEST_FILE.test(name)) return "test";+ if (parts.some((p) => DOCS_SEGMENTS.has(p)) || DOCS_FILE.test(name)) return "docs";+ return "source";+}++/** The scanner's three severities; anything unrecognised counts as low. */+export type SecurityLevel = "high" | "med" | "low";++export function securityLevel(severity: string): SecurityLevel {+ return severity === "high" || severity === "med" ? severity : "low";+}++export interface SecurityPostureCounts {+ total: number;+ /** Matches in shipped source. */+ source: number;+ /** Matches in tests and docs. */+ elsewhere: number;+ sourceHigh: number;+ high: number;+ med: number;+ low: number;+}++export function countSecurityFindings(findings: SecurityFinding[]): SecurityPostureCounts {+ const c: SecurityPostureCounts = {+ total: findings.length,+ source: 0,+ elsewhere: 0,+ sourceHigh: 0,+ high: 0,+ med: 0,+ low: 0,+ };+ for (const f of findings) {+ const level = securityLevel(f.severity);+ c[level] += 1;+ if (securityPathClass(f.file_path) === "source") {+ c.source += 1;+ if (level === "high") c.sourceHigh += 1;+ } else {+ c.elsewhere += 1;+ }+ }+ return c;+}++export interface SecurityPostureLabels {+ figure: string;+ figureHint: string;+ /** Unit beside the figure. `capped` means the total is a floor. */+ unit: (total: number, capped: boolean) => string;+ sentence: (counts: SecurityPostureCounts) => string;+ /** Receives a relative time, e.g. "3 days ago". */+ scanned: (when: string) => string;+ scanTimeUnknown: string;+}++const n = (v: number) => v.toLocaleString();+const plural = (v: number, one: string, many: string) => `${n(v)} ${v === 1 ? one : many}`;++export const DEFAULT_SECURITY_POSTURE_LABELS: SecurityPostureLabels = {+ figure: "In shipped source",+ figureHint:+ "Pattern matches outside test, spec, fixture, mock, example and docs paths. These are the ones to confirm first.",+ unit: (total, capped) => `of ${n(total)}${capped ? "+" : ""} ${total === 1 ? "finding" : "findings"}`,+ sentence: (c) => {+ if (c.source === 0) {+ return `Nothing matched in shipped source. ${+ c.elsewhere === 1 ? "The one match is" : `All ${n(c.elsewhere)} matches are`+ } in tests and docs, listed so you can confirm they are fixtures.`;+ }+ const lead = `The pattern scan for secrets and dangerous calls matched ${plural(+ c.source,+ "place",+ "places",+ )} in shipped source, ${n(c.sourceHigh)} of them high.`;+ if (c.elsewhere === 0) return lead;+ return `${lead} ${n(c.elsewhere)} more ${c.elsewhere === 1 ? "is" : "are"} in tests and docs, listed after shipped code.`;+ },+ scanned: (when) => `Scanned ${when}.`,+ scanTimeUnknown: "Scan time not recorded.",+};++export interface SecurityPostureProps {+ findings: SecurityFinding[];+ /** Relative scan time ("3 days ago"), or null when the server has none. */+ scannedAgo: string | null;+ /** True when the list was cut at the request limit, so counts are a floor. */+ capped?: boolean;+ labels?: Partial<SecurityPostureLabels>;+}++/**+ * The security page's lede: the figure to act on (matches in shipped source),+ * the sentence that scopes it, and when the scan ran.+ * Never coloured: a pattern match is a lead to confirm, not a live path to+ * harm.+ */+export function SecurityPosture({ findings, scannedAgo, capped = false, labels }: SecurityPostureProps) {+ const l = { ...DEFAULT_SECURITY_POSTURE_LABELS, ...labels };+ const c = React.useMemo(() => countSecurityFindings(findings), [findings]);++ return (+ <PageLede+ label={l.figure}+ labelHint={l.figureHint}+ value={n(c.source)}+ unit={l.unit(c.total, capped)}+ layout="beside"+ >+ {/* One paragraph so the scan line stays under the sentence when the+ lede flows into columns. */}+ <p>+ {l.sentence(c)}+ <span className="mt-2 block text-xs text-[var(--color-text-tertiary)]">+ {scannedAgo ? l.scanned(scannedAgo) : l.scanTimeUnknown}+ </span>+ </p>+ </PageLede>+ );+}++/** Loading silhouette in the shape of the posture plus the findings list. */+export function SecurityPostureSkeleton({ label = "Loading security findings" }: { label?: string }) {+ return (+ <SkeletonRegion label={label} className="space-y-6">+ <div className="flex flex-col gap-5 lg:flex-row lg:gap-12">+ <div className="space-y-3 lg:w-[220px]">+ <Skeleton className="h-3 w-28" />+ <Skeleton className="h-11 w-20" />+ </div>+ <div className="w-full max-w-[62ch] space-y-2">+ <Skeleton className="h-4 w-full" />+ <Skeleton className="h-4 w-4/5" />+ <Skeleton className="h-3 w-32" />+ </div>+ </div>+ <div className="space-y-3 border-t border-[var(--color-border-default)] pt-6 sm:pt-8">+ <Skeleton className="h-5 w-32" />+ <div className="flex flex-wrap gap-2">+ <Skeleton className="h-8 w-full sm:w-72" />+ <Skeleton className="h-8 w-56" />+ </div>+ {Array.from({ length: 6 }, (_, i) => (+ <Skeleton key={i} className="h-9 w-full" />+ ))}+ </div>+ </SkeletonRegion>+ );+}diff --git a/packages/ui/src/security/severity-directory-matrix.tsx b/packages/ui/src/security/severity-directory-matrix.tsxindex 235bd3c85..55d92c176 100644--- a/packages/ui/src/security/severity-directory-matrix.tsx+++ b/packages/ui/src/security/severity-directory-matrix.tsx@@ -3,6 +3,7 @@import * as React from "react";import { cn } from "../lib/cn";import type { SecurityFinding } from "./findings-table";+import { securityLevel, type SecurityLevel } from "./posture";export interface SeverityDirectoryMatrixProps {findings: SecurityFinding[];@@ -13,22 +14,17 @@ export interface SeverityDirectoryMatrixProps {className?: string;}-const SEVERITY_ORDER = ["high", "med", "low"] as const;-const SEVERITY_LABEL: Record<string, string> = {+const SEVERITY_ORDER: SecurityLevel[] = ["high", "med", "low"];+const SEVERITY_LABEL: Record<SecurityLevel, string> = {high: "High",med: "Medium",low: "Low",};-const SEVERITY_TOKEN: Record<string, string> = {- high: "var(--color-error)",- med: "var(--color-warning)",- low: "var(--color-text-tertiary)",-};/**- * Severity × directory heat matrix — where the security findings concentrate,- * so reviewers know which area to triage first. Mirrors the dead-code- * confidence × kind grid idiom; intensity rides on a token via color-mix.+ * Where the security findings concentrate: a plain count table of directory+ * by severity, highest total first. Counts only, no cell tints: a heat ground+ * made a directory of fixtures look like the page's emergency.*/export function SeverityDirectoryMatrix({findings,@@ -36,91 +32,72 @@ export function SeverityDirectoryMatrix({maxRows = 14,className,}: SeverityDirectoryMatrixProps) {- const { rows, max } = React.useMemo(() => {- const byDir = new Map<string, { dir: string; counts: Record<string, number>; total: number }>();- let max = 0;+ const rows = React.useMemo(() => {+ const byDir = new Map<string, { dir: string; counts: Record<SecurityLevel, number>; total: number }>();for (const f of findings) {const segments = f.file_path.split("/").slice(0, depth);const dir = segments.length === 0 ? "(root)" : segments.join("/");- const sev = SEVERITY_ORDER.includes(f.severity as (typeof SEVERITY_ORDER)[number])- ? f.severity- : "low";- const cur = byDir.get(dir) ?? { dir, counts: {}, total: 0 };- cur.counts[sev] = (cur.counts[sev] ?? 0) + 1;+ const cur = byDir.get(dir) ?? { dir, counts: { high: 0, med: 0, low: 0 }, total: 0 };+ cur.counts[securityLevel(f.severity)] += 1;cur.total += 1;- if (cur.counts[sev] > max) max = cur.counts[sev];byDir.set(dir, cur);}- const ordered = Array.from(byDir.values())+ return Array.from(byDir.values()).sort((a, b) => b.total - a.total).slice(0, maxRows);- return { rows: ordered, max };}, [findings, depth, maxRows]);- if (rows.length === 0) {- return (- <div- className={cn(- "rounded-md border border-dashed border-[var(--color-border-default)] p-4 text-center text-xs text-[var(--color-text-tertiary)]",- className,- )}- >- No findings yet.- </div>- );- }+ if (rows.length === 0) return null;return (<divclassName={cn(- "overflow-hidden rounded-md border border-[var(--color-border-default)]",+ "overflow-x-auto rounded-md border border-[var(--color-border-default)]",className,)}><table className="w-full border-collapse text-xs"><thead>- <tr className="bg-[var(--color-bg-elevated)]">- <th className="px-3 py-2 text-left font-medium text-[var(--color-text-tertiary)]">+ <tr className="text-2xs uppercase tracking-wider text-[var(--color-text-tertiary)]">+ <th scope="col" className="px-3 py-2 text-left font-medium">Directory</th>{SEVERITY_ORDER.map((s) => (- <th- key={s}- className="px-2 py-2 text-right font-medium text-[var(--color-text-tertiary)]"- >+ <th key={s} scope="col" className="px-3 py-2 text-right font-medium">{SEVERITY_LABEL[s]}</th>))}+ <th scope="col" className="px-3 py-2 text-right font-medium">+ Total+ </th></tr></thead><tbody>{rows.map((r) => (- <tr key={r.dir} className="border-t border-[var(--color-border-default)]">- <td- className="max-w-[260px] truncate px-3 py-2 font-mono text-[var(--color-text-secondary)]"- title={r.dir}+ <tr key={r.dir} className="border-t border-[var(--color-table-divider)]">+ <th+ scope="row"+ className="min-w-[10rem] break-all px-3 py-2 text-left font-mono font-normal text-[var(--color-text-secondary)]">{r.dir}- </td>+ </th>{SEVERITY_ORDER.map((s) => {- const c = r.counts[s] ?? 0;- const intensity = max > 0 ? c / max : 0;- const alphaPct = Math.round((0.1 + intensity * 0.55) * 100);- const bg =- c === 0- ? "transparent"- : `color-mix(in srgb, ${SEVERITY_TOKEN[s]} ${alphaPct}%, transparent)`;+ const c = r.counts[s];return (<tdkey={s}- className="px-2 py-2 text-right tabular-nums"- style={{ backgroundColor: bg }}- title={`${c} ${SEVERITY_LABEL[s]} in ${r.dir}`}+ className={cn(+ "px-3 py-2 text-right font-mono tabular-nums",+ c ? "text-[var(--color-text-primary)]" : "text-[var(--color-text-tertiary)]",+ )}>- {c || ""}+ {c}</td>);})}+ <td className="px-3 py-2 text-right font-mono tabular-nums text-[var(--color-text-secondary)]">+ {r.total}+ </td></tr>))}</tbody>diff --git a/packages/web/messages/en.json b/packages/web/messages/en.jsonindex 5e84bf3d3..3445984a2 100644--- a/packages/web/messages/en.json+++ b/packages/web/messages/en.json@@ -803,6 +803,26 @@}},"risk": {+ "posture": {+ "figure": "In shipped source",+ "figureHint": "Pattern matches outside test, spec, fixture, mock, example and docs paths. These are the ones to confirm first.",+ "unit": "of {count, plural, one {# finding} other {# findings}}",+ "unitCapped": "of {total}+ findings",+ "sentenceSource": "The pattern scan for secrets and dangerous calls matched {count, plural, one {# place} other {# places}} in shipped source, {high} of them high.",+ "sentenceElsewhere": "{count, plural, one {# more is} other {# more are}} in tests and docs, listed after shipped code.",+ "sentenceNoSource": "Nothing matched in shipped source. {count, plural, one {The one match is} other {All # matches are}} in tests and docs, listed so you can confirm they are fixtures.",+ "scanned": "Scanned {when}.",+ "scanTimeUnknown": "Scan time not recorded.",+ "loading": "Loading security findings",+ "retry": "Retry",+ "clearTitle": "No security findings",+ "clearBody": "The pattern scan for secrets and dangerous calls matched nothing in source, tests or docs. Scanned {when}.",+ "notScannedTitle": "Not scanned yet",+ "notScannedBody": "The pattern scan for secrets and dangerous calls runs when the repository syncs. Start one with Re-scan, or run repowise update in the repository.",+ "capped": "Showing the first {count} findings. The counts on this page cover those {count}.",+ "byDirectory": "By directory",+ "byDirectoryBody": "Where the matches concentrate, busiest directories first."+ },"analysisTimeout": "Analysis is taking longer than expected. Reload to see the results.","syncStarted": "Sync started — findings refresh when it completes","syncFailed": "Couldn't start a sync",diff --git a/packages/web/messages/zh-CN.json b/packages/web/messages/zh-CN.jsonindex 135cd258e..7fef0e95d 100644--- a/packages/web/messages/zh-CN.json+++ b/packages/web/messages/zh-CN.json@@ -803,6 +803,26 @@}},"risk": {+ "posture": {+ "figure": "交付代码中",+ "figureHint": "位于 test、spec、fixture、mock、example 和 docs 路径之外的模式匹配。应优先确认这些。",+ "unit": "共 {count} 条发现项",+ "unitCapped": "共 {total}+ 条发现项",+ "sentenceSource": "密钥与危险调用的模式扫描在交付代码中匹配到 {count} 处,其中 {high} 处为高。",+ "sentenceElsewhere": "另有 {count} 处位于测试和文档中,排在交付代码之后。",+ "sentenceNoSource": "交付代码中没有匹配。全部 {count} 处匹配都位于测试和文档中,列出以便确认它们是测试夹具。",+ "scanned": "扫描于{when}。",+ "scanTimeUnknown": "未记录扫描时间。",+ "loading": "正在加载安全发现项",+ "retry": "重试",+ "clearTitle": "没有安全发现项",+ "clearBody": "密钥与危险调用的模式扫描在源码、测试和文档中均未匹配到任何内容。扫描于{when}。",+ "notScannedTitle": "尚未扫描",+ "notScannedBody": "密钥与危险调用的模式扫描会在仓库同步时运行。点击「重新扫描」启动一次,或在仓库中运行 repowise update。",+ "capped": "仅显示前 {count} 条发现项。本页的计数只涵盖这 {count} 条。",+ "byDirectory": "按目录",+ "byDirectoryBody": "匹配集中的位置,按数量从多到少排列。"+ },"analysisTimeout": "分析耗时超出预期。请重新加载以查看结果。","syncStarted": "同步已开始 —— 完成后发现项会刷新","syncFailed": "无法启动同步",diff --git a/packages/web/src/components/risk/security-tab.tsx b/packages/web/src/components/risk/security-tab.tsxindex 6e3266a15..7a7466c45 100644--- a/packages/web/src/components/risk/security-tab.tsx+++ b/packages/web/src/components/risk/security-tab.tsx@@ -1,28 +1,54 @@"use client";-import { useState } from "react";+import { useMemo, useState, type ReactNode } from "react";import useSWR from "swr";import { RotateCw } from "lucide-react";import { toast } from "sonner";import { SecurityFindingsTable } from "@repowise-dev/ui/security/findings-table";import { SeverityDirectoryMatrix } from "@repowise-dev/ui/security/severity-directory-matrix";+import {+ SecurityPosture,+ SecurityPostureSkeleton,+ type SecurityPostureLabels,+} from "@repowise-dev/ui/security/posture";import { AiPromptModal, buildSecurityAiPrompt, fileChatContext } from "@repowise-dev/ui/health";import { Button } from "@repowise-dev/ui/ui/button";-import { Card, CardContent, CardHeader, CardTitle } from "@repowise-dev/ui/ui/card";-import { CollapsibleSection } from "@repowise-dev/ui/shared/collapsible-section";-import { Skeleton } from "@repowise-dev/ui/ui/skeleton";-import { listSecurityFindings, type SecurityFinding } from "@/lib/api/security";+import { OverviewSection } from "@repowise-dev/ui/overview/section";+import { EmptyState } from "@repowise-dev/ui/shared/empty-state";+import { ApiError } from "@repowise-dev/ui/shared/api-error";+import { formatRelativeTime } from "@repowise-dev/ui/lib/format";+import {+ getSecuritySummary,+ listSecurityFindings,+ type SecurityFinding,+ type SecuritySummary,+} from "@/lib/api/security";import { syncRepo } from "@/lib/api/repos";import { useFileCardHost } from "@/components/shared/file-card-host";import type { FileCardData } from "@repowise-dev/ui/shared/file-card";import { toFriendlyMessage } from "@repowise-dev/ui/lib/errors";import { useTranslations } from "next-intl";+/** Request limit for the findings list; at the limit the page says so. */+const LIMIT = 500;+export function SecurityTab({ repoId }: { repoId: string }) {const t = useTranslations("risk");- const { data: findings, isLoading, error } = useSWR<SecurityFinding[]>(+ const {+ data: findings,+ isLoading,+ error,+ mutate,+ } = useSWR<SecurityFinding[]>(`security:${repoId}`,- () => listSecurityFindings(repoId, { limit: 500 }),+ () => listSecurityFindings(repoId, { limit: LIMIT }),+ { revalidateOnFocus: false },+ );+ // An older server has no summary route; that reads as "scan time unknown",+ // never as an all-clear, so a failure here must not fail the page.+ const { data: summary, isLoading: summaryLoading } = useSWR<SecuritySummary | null>(+ `security-summary:${repoId}`,+ () => getSecuritySummary(repoId).catch(() => null),{ revalidateOnFocus: false },);const [rescanning, setRescanning] = useState(false);@@ -56,12 +82,82 @@ export function SecurityTab({ repoId }: { repoId: string }) {showFile(data);};+ const labels = useMemo<SecurityPostureLabels>(+ () => ({+ figure: t("posture.figure"),+ figureHint: t("posture.figureHint"),+ unit: (total, capped) =>+ capped ? t("posture.unitCapped", { total }) : t("posture.unit", { count: total }),+ sentence: (c) =>+ c.source === 0+ ? t("posture.sentenceNoSource", { count: c.elsewhere })+ : [+ t("posture.sentenceSource", { count: c.source, high: c.sourceHigh }),+ c.elsewhere ? t("posture.sentenceElsewhere", { count: c.elsewhere }) : "",+ ]+ .filter(Boolean)+ .join(" "),+ scanned: (when) => t("posture.scanned", { when }),+ scanTimeUnknown: t("posture.scanTimeUnknown"),+ }),+ [t],+ );++ const scannedAt = summary?.scanned_at ?? null;+ const scannedAgo = scannedAt ? formatRelativeTime(scannedAt) : null;+ const list = findings ?? [];+ const capped = list.length >= LIMIT;++ let body: ReactNode;+ if (isLoading || summaryLoading) {+ body = <SecurityPostureSkeleton label={t("posture.loading")} />;+ } else if (error) {+ body = (+ <ApiError+ title={t("loadFailed")}+ message={t("loadFailedBody")}+ retryLabel={t("posture.retry")}+ onRetry={() => void mutate()}+ />+ );+ } else if (list.length === 0) {+ // Green only when the scan is known to have run; an unknown scan time+ // with nothing listed is "not scanned yet", not good news.+ body = scannedAgo ? (+ <EmptyState+ tone="positive"+ title={t("posture.clearTitle")}+ description={t("posture.clearBody", { when: scannedAgo })}+ />+ ) : (+ <EmptyState title={t("posture.notScannedTitle")} description={t("posture.notScannedBody")} />+ );+ } else {+ body = (+ <>+ <SecurityPosture findings={list} scannedAgo={scannedAgo} capped={capped} labels={labels} />+ <OverviewSection title={t("allFindings")} description={t("description")}>+ <SecurityFindingsTable+ findings={list}+ onSelect={handleSelect}+ onGeneratePrompt={setPromptFinding}+ />+ {capped && (+ <p className="text-xs text-[var(--color-text-tertiary)]">+ {t("posture.capped", { count: LIMIT })}+ </p>+ )}+ </OverviewSection>+ <OverviewSection title={t("posture.byDirectory")} description={t("posture.byDirectoryBody")}>+ <SeverityDirectoryMatrix findings={list} />+ </OverviewSection>+ </>+ );+ }+return (<div className="space-y-6">- <div className="flex flex-wrap items-center gap-2">- <p className="text-sm text-[var(--color-text-secondary)] mr-auto">- {t("description")}- </p>+ <div className="flex flex-wrap items-center justify-end gap-2"><Button size="sm" variant="outline" onClick={handleRescan} disabled={rescanning}><RotateCwclassName={`h-3.5 w-3.5 mr-1.5 ${rescanning ? "motion-safe:animate-spin" : ""}`}@@ -70,35 +166,7 @@ export function SecurityTab({ repoId }: { repoId: string }) {</Button></div>- {isLoading ? (- <Skeleton className="h-40 w-full rounded-lg" />- ) : error ? (- <Card>- <CardHeader className="pb-2">- <CardTitle className="text-sm">{t("loadFailed")}</CardTitle>- </CardHeader>- <CardContent className="pt-0 text-xs text-[var(--color-text-secondary)]">- {t("loadFailedBody")}- </CardContent>- </Card>- ) : (- <>- {/* Single visual rollup — per-severity counts live in the table's- filter pills below, not in a separate distribution card. */}- <SeverityDirectoryMatrix findings={findings ?? []} />- <CollapsibleSection- title={t("allFindings")}- hint={t("findingsCount", { count: (findings ?? []).length })}- defaultOpen={false}- >- <SecurityFindingsTable- findings={findings ?? []}- onSelect={handleSelect}- onGeneratePrompt={setPromptFinding}- />- </CollapsibleSection>- </>- )}+ {body}<AiPromptModalopen={promptFinding !== null}