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(dead-code): one figure, one list, one table (#3309)
Raghav Chamadiyab0e760fd48d3
diff --git a/packages/ui/COMPONENT_CONTRACTS.md b/packages/ui/COMPONENT_CONTRACTS.mdindex ff2032c24..0d27f413f 100644--- a/packages/ui/COMPONENT_CONTRACTS.md+++ b/packages/ui/COMPONENT_CONTRACTS.md@@ -195,17 +195,17 @@ Filter unions:## `dead-code/dead-code-view` - `DeadCodeView`-The whole Dead Code page: summary tiles, the safe-to-delete pile, the-"where it clusters" rollups, and the drill-down findings table. Owns the+The whole Dead Code page: a lede (reclaimable lines and one posture+sentence), the safe-to-delete list, and the findings table. Owns theoptimistic patch + undo toast, bulk resolve, the AI cleanup prompt modal,-Re-analyze, and the status filter that switches which slice the table shows.+Re-analyze, and the status control that switches which slice the table shows.| Prop | Type | Required | Notes ||------|------|----------|-------|| `adapter` | `DeadCodeAdapter` | yes | Everything host-specific: fetching, mutation, links, navigation. |Behaviour worth knowing:-- Two fetches. The open slice feeds the pile, the rollups and the table;+- Two fetches. The open slice feeds the list and the table;a second, conditional fetch backs the status filter when it is not "open".Both are capped at 500 rows. The open slice has a repo-wide total tocompare against, so its hint says "Showing N of M"; a non-open status has@@ -215,7 +215,10 @@ Behaviour worth knowing:repository. A failed refresh over rows already in hand keeps the table andputs the card above it.- Optimistic row state lives here, not in the table, so resolving a row moves- the pile and the rollups with it and undo can put it back.+ the list with it and undo can put it back.+- Zero open findings: with `summary.analyzed_at` set, the lede reads "0 lines"+ with a positive all-clear and no sections; without it, a neutral "Not+ analysed yet" with a run button. Never green without a recorded run.---@@ -232,6 +235,7 @@ adding a required member is a breaking change for every consumer.| `listFindings` | `(opts?: { limit?: number; status?: DeadCodeStatus }) => Promise<DeadCodeFinding[]>` | yes | `status` defaults to `"open"` server-side. || `analyze` | `() => Promise<{ job_id?: string } \| void>` | yes | Returning a `job_id` lets the view wait and refresh itself. || `waitForAnalysis` | `(jobId: string) => Promise<void>` | no | Without it the view cannot know when to refetch, and says so in its toast. |+| `analyzeDisabledReason` | `string` | no | Renders Re-analyze disabled with this sentence beside it. || `patchFinding` | `(id: string, patch: DeadCodePatchInput) => Promise<DeadCodeFinding>` | yes | Must return the updated finding; the view stores it as the optimistic override. || `fileHref` | `(path: string) => string` | yes | Makes the path a link and the row clickable. || `graphHref` | `(path: string) => string` | no | Omit and the per-row Graph action disappears, which keeps app routes out of this package. |@@ -241,14 +245,14 @@ adding a required member is a breaking change for every consumer.## `dead-code/findings-table` - `FindingsTable`-The drill-down table: kind tabs driven by the data, a search box, sortable-columns, the confidence slider, a cleanup-ready switch, bulk resolve, and-per-row status actions. Built on `shared/responsive-table` with+The findings table: kind tabs driven by the data, a search box, sortable+columns, one confidence control (All / High only), bulk resolve, and per-row+status actions. Built on `shared/responsive-table` with`stacked="sm"` and windowed rows.| Prop | Type | Required | Notes ||------|------|----------|-------|-| `findings` | `DeadCodeFinding[]` | yes | One status slice; the table filters it by kind / confidence / safety client-side. |+| `findings` | `DeadCodeFinding[]` | yes | One status slice; the table filters it by kind / confidence / search client-side. || `onPatch` | `(id, { status }) => Promise<DeadCodeFinding>` | yes | Host owns the API call and the undo toast. || `onBulkResolve` | `(ids: string[]) => Promise<string[]>` | no | Must return the ids that actually resolved, not the ids it was given. The table reconciles against that, never against position. || `fileHref` | `(path: string) => string` | no | |@@ -258,8 +262,8 @@ per-row status actions. Built on `shared/responsive-table` with| `status` | `DeadCodeStatus` | no | Which slice is on screen. Defaults to `"open"`; bulk resolve only appears there. || `isLoading` | `boolean` | no | Shows a skeleton instead of an empty state during the first fetch. |-Selection is always intersected with the rows currently visible, so raising-the confidence slider after selecting cannot resolve rows the user can no+Selection is always intersected with the rows currently visible, so narrowing+the confidence filter after selecting cannot resolve rows the user can nolonger see.---@@ -267,7 +271,8 @@ longer see.## `dead-code/finding-cells` - cell renderers`FindingIdentity`, `FindingConfidence`, `FindingSafety` and-`FindingRowActions` back the table's columns. `FindingRowActions` is separate+`FindingRowActions` back the table's columns. `FindingSafety` renders nothing+on a deletion-ready row and "Review first" plus the reason on the rest. `FindingRowActions` is separatebecause it owns per-row pending/confirm state that a plain `render(row)`closure cannot hold; it offers resolve/ack/FP on an open finding and Reopenon anything already actioned. `DEAD_CODE_STATUS_LABELS` is the shared label@@ -285,49 +290,6 @@ findings with the AI cleanup CTA.| `findings` | `SafeToDeletePileFinding[]` | yes | Caller passes the safe slice; structural subset of `DeadCodeFinding`. || `onPropose` | `(ids: string[]) => void` | no | Opens the AI prompt modal; omit and the CTA disappears. || `onSelect` | `(finding: DeadCodeFinding) => void` | no | Row click. |-| `reclaimableLines` | `number` | no | The repo-wide total. Pass it only when the findings are not a capped slice, otherwise it sits next to counts describing a different population. |-------## `dead-code/owner-leaderboard` - `OwnerLeaderboard`--Inline bar chart of dead-code lines per primary contributor. No charting-dependency.--| Prop | Type | Required | Notes |-|------|------|----------|-------|-| `findings` | `OwnerLeaderboardFinding[]` | yes | Structural subset of `DeadCodeFinding`. |-| `topN` | `number` | no | Default 8. |-| `safeOnly` | `boolean` | no | Count only cleanup-ready findings. |-| `onSelect` | `(owner: string) => void` | no | Turns each bar into a button. |-| `className` | `string` | no | |-------## `dead-code/findings-breakdown-grid` - `FindingsBreakdownGrid`--Confidence-tier by kind heat matrix. Its own `<table>` is deliberate:-this is a matrix, not a list, so `ResponsiveTable` is the wrong primitive.-Tier boundaries come from `DEAD_CODE_CONFIDENCE` in-`@repowise-dev/types/dead-code`, which mirrors the engine's-`SAFE_CONFIDENCE_THRESHOLD`. The low row renders only when something is in-it, since the list endpoint floors at the medium boundary.--| Prop | Type | Required | Notes |-|------|------|----------|-------|-| `findings` | `FindingsBreakdownItem[]` | yes | Needs only `kind` and `confidence`. |-| `className` | `string` | no | |-------## `dead-code/summary-bar` - `SummaryBar`--Four-tile summary header for a dead-code report: total findings, candidate-lines, breakdown by kind, breakdown by confidence band.--| Prop | Type | Required | Notes |-|------|------|----------|-------|-| `summary` | `DeadCodeSummary` (`@repowise-dev/types/dead-code`) | yes | Caller fetches the rollup. |---diff --git a/packages/ui/__tests__/dead-code/dead-code-lede.test.tsx b/packages/ui/__tests__/dead-code/dead-code-lede.test.tsxindex 3e557ca34..5ca622f20 100644--- a/packages/ui/__tests__/dead-code/dead-code-lede.test.tsx+++ b/packages/ui/__tests__/dead-code/dead-code-lede.test.tsx@@ -9,6 +9,7 @@ const SUMMARY: DeadCodeSummary = {deletable_lines: 4321,total_lines: 91234,by_kind: { unreachable_file: 12, unused_export: 88, zombie_package: 42 },+ analyzed_at: new Date(Date.now() - 2 * 86_400_000).toISOString(),};describe("DeadCodeLede", () => {@@ -18,43 +19,44 @@ describe("DeadCodeLede", () => {expect(screen.getByText("lines")).toBeInTheDocument();});- it("names every kind in prose rather than as separate tiles", () => {+ it("says the posture in one sentence, with when it was measured", () => {render(<DeadCodeLede summary={SUMMARY} />);const prose = screen.getByText(/have no reachable caller/);- expect(prose.textContent).toContain("88 unused exports");- expect(prose.textContent).toContain("42 zombie packages");- expect(prose.textContent).toContain("12 unreachable files");+ expect(prose.textContent).toBe(+ "142 findings across 91,234 lines have no reachable caller. Analysed 2d ago.",+ );});- it("splits confidence across the ribbon and the bar", () => {+ it("carries no stat ribbon or confidence bar repeating the sentence", () => {render(<DeadCodeLede summary={SUMMARY} />);- // High stands alone; medium and low are the one "verify this" bucket.- expect(screen.getByText("89")).toBeInTheDocument();- expect(screen.getByText("53")).toBeInTheDocument();- expect(screen.getByLabelText("89 high confidence")).toBeInTheDocument();+ expect(screen.queryByText("High confidence")).not.toBeInTheDocument();+ expect(screen.queryByLabelText("89 high confidence")).not.toBeInTheDocument();+ // The methodology sits behind the label's info tip instead of in prose.+ expect(screen.getByRole("button", { name: "What Reclaimable means" })).toBeInTheDocument();});- it("reports the deletable share of the flagged lines, not of the repo", () => {- render(<DeadCodeLede summary={SUMMARY} />);- // 4,321 of the 91,234 lines sitting inside a finding.- expect(screen.getByText("5%")).toBeInTheDocument();- expect(screen.getByText("91,234")).toBeInTheDocument();+ it("drops the time rather than inventing one when the run is unknown", () => {+ render(<DeadCodeLede summary={{ ...SUMMARY, analyzed_at: null }} />);+ expect(screen.getByText(/have no reachable caller/).textContent).not.toMatch(/Analysed/);});- it("says a clean repository is a result, not an absence", () => {+ it("agrees in number for a single finding", () => {render(<DeadCodeLede- summary={{- total_findings: 0,- confidence_summary: { high: 0, medium: 0, low: 0 },- deletable_lines: 0,- total_lines: 0,- by_kind: {},- }}+ summary={{ ...SUMMARY, total_findings: 1, total_lines: 12, deletable_lines: 1, analyzed_at: null }}/>,);- expect(- screen.getByText(/Nothing in this repository is currently flagged/),- ).toBeInTheDocument();+ expect(screen.getByText(/no reachable caller/).textContent).toBe(+ "1 finding across 12 lines has no reachable caller.",+ );+ });++ it("shows flagged lines, not a zero, when nothing is deletion-ready", () => {+ render(<DeadCodeLede summary={{ ...SUMMARY, total_findings: 47, total_lines: 1669, deletable_lines: 0 }} />);+ expect(screen.getByText("1,669")).toBeInTheDocument();+ expect(screen.getByText(/have no reachable caller/).textContent).toBe(+ "47 findings have no reachable caller. None is deletion-ready yet, so review them before deleting. Analysed 2d ago.",+ );+ expect(screen.getByRole("button", { name: "What Flagged means" })).toBeInTheDocument();});});diff --git a/packages/ui/__tests__/dead-code/dead-code-view.test.tsx b/packages/ui/__tests__/dead-code/dead-code-view.test.tsxindex 9a2f25df3..2ab0491de 100644--- a/packages/ui/__tests__/dead-code/dead-code-view.test.tsx+++ b/packages/ui/__tests__/dead-code/dead-code-view.test.tsx@@ -9,7 +9,7 @@ import type {DeadCodeSummary,} from "@repowise-dev/types/dead-code";-// jsdom has no layout engine → stub ResizeObserver so the Radix slider mounts.+// jsdom has no layout engine → stub ResizeObserver for the Radix primitives.class RO {observe() {}unobserve() {}@@ -34,8 +34,7 @@ vi.mock("sonner", () => ({* lets CSS pick one; jsdom applies no CSS, so a row control matches in both.* These scope row queries to the table.*- * By caption, not by role alone: the cluster rollups above it are no longer- * behind a disclosure, so the page now carries more than one <table>.+ * By caption, so a second <table> elsewhere on the page cannot match.*/const FINDINGS_TABLE = { name: "Dead code findings" };const rowButton = (name: string) =>@@ -55,6 +54,16 @@ const SUMMARY: DeadCodeSummary = {deletable_lines: 120,total_lines: 9000,by_kind: { unreachable_file: 2, unused_export: 1, zombie_package: 0 },+ analyzed_at: "2026-10-08T12:00:00Z",+};++const CLEAN: DeadCodeSummary = {+ total_findings: 0,+ confidence_summary: { high: 0, medium: 0, low: 0 },+ deletable_lines: 0,+ total_lines: 0,+ by_kind: {},+ analyzed_at: "2026-10-08T12:00:00Z",};const FINDINGS: DeadCodeFinding[] = [@@ -157,7 +166,7 @@ describe("DeadCodeView", () => {// The lede's figure, then the safe pile's own sentence.expect(await screen.findByText("Propose cleanup")).toBeInTheDocument();- expect(screen.getByText(/come back high confidence/)).toBeInTheDocument();+ expect(screen.getByText(/with no runtime-load risk/)).toBeInTheDocument();// The safe slice (not the unsafe bootstrap file) drives the pile preview.expect(screen.getAllByText(/legacy\.ts/).length).toBeGreaterThan(0);});@@ -220,9 +229,7 @@ describe("DeadCodeView", () => {// With no open findings the page still has to offer the way back in, not// just the "no dead code found" state.- fireEvent.change(await screen.findByLabelText("Status"), {- target: { value: "acknowledged" },- });+ fireEvent.click(await screen.findByRole("radio", { name: "Acknowledged" }));await waitFor(() =>expect(listFindings).toHaveBeenCalledWith(@@ -244,7 +251,7 @@ describe("DeadCodeView", () => {// ...and it has to arrive in the open slice. The open payload predates the// reopen and does not contain it, so without merging the override in, the// finding is open on the server and invisible in the UI until a reload.- fireEvent.change(screen.getByLabelText("Status"), { target: { value: "open" } });+ fireEvent.click(screen.getByRole("radio", { name: "Open" }));expect(screen.queryByText("No dead code found")).not.toBeInTheDocument();expect(await findRowButton("Resolve src/old/legacy.ts")).toBeInTheDocument();@@ -292,6 +299,7 @@ describe("DeadCodeView", () => {).not.toBeInTheDocument(),);expect(screen.queryByText("No dead code found")).not.toBeInTheDocument();+ expect(screen.getByText("Every finding is resolved or set aside")).toBeInTheDocument();const undo = lastUndoAction();await undo.onClick();@@ -313,7 +321,7 @@ describe("DeadCodeView", () => {),});renderView(<DeadCodeView adapter={adapter} />);- await screen.findByText(/come back high confidence/);+ await screen.findByText(/with no runtime-load risk/);const listCallsBefore = (adapter.listFindings as ReturnType<typeof vi.fn>).mock.calls.length;fireEvent.click(await screen.findByRole("button", { name: "Re-analyze" }));@@ -389,4 +397,77 @@ describe("DeadCodeView", () => {expect(rowButton("Resolve src/old/legacy.ts")).toBeInTheDocument(),);});++ it("calls a recorded zero clean, with no table or sections under it", async () => {+ renderView(+ <DeadCodeView+ adapter={makeAdapter({+ getSummary: vi.fn(async () => CLEAN),+ listFindings: vi.fn(async () => []),+ })}+ />,+ );++ const clean = await screen.findByText("No dead code found");+ expect(clean.closest("[data-tone]")).toHaveAttribute("data-tone", "positive");+ expect(screen.getByText("0")).toBeInTheDocument();+ expect(screen.queryByText("All findings")).not.toBeInTheDocument();+ expect(screen.queryByText("Safe to delete")).not.toBeInTheDocument();+ });++ it("reviews past findings from the clean state", async () => {+ const listFindings = vi.fn(async () => [] as DeadCodeFinding[]);+ renderView(+ <DeadCodeView+ adapter={makeAdapter({ getSummary: vi.fn(async () => CLEAN), listFindings })}+ />,+ );++ fireEvent.click(await screen.findByRole("button", { name: "Review past findings" }));++ expect(await screen.findByText("All findings")).toBeInTheDocument();+ await waitFor(() =>+ expect(listFindings).toHaveBeenCalledWith(expect.objectContaining({ status: "resolved" })),+ );+ });++ it("never calls an unrecorded zero clean", async () => {+ const adapter = makeAdapter({+ getSummary: vi.fn(async () => ({ ...CLEAN, analyzed_at: null })),+ listFindings: vi.fn(async () => []),+ });+ renderView(<DeadCodeView adapter={adapter} />);++ expect(await screen.findByText("Not analysed yet")).toBeInTheDocument();+ expect(screen.queryByText("No dead code found")).not.toBeInTheDocument();+ expect(document.querySelector('[data-tone="positive"]')).toBeNull();++ fireEvent.click(screen.getByRole("button", { name: "Run analysis" }));+ await waitFor(() => expect(adapter.analyze).toHaveBeenCalledTimes(1));+ });++ it("renders Re-analyze disabled with the host's reason beside it", async () => {+ const adapter = makeAdapter({ analyzeDisabledReason: "This snapshot is read-only." });+ renderView(<DeadCodeView adapter={adapter} />);++ const button = await screen.findByRole("button", { name: "Re-analyze" });+ expect(button).toBeDisabled();+ expect(button).toHaveAccessibleDescription("This snapshot is read-only.");+ expect(screen.getByText("This snapshot is read-only.")).toBeVisible();+ });++ it("switches the table's slice from the segmented status control", async () => {+ const listFindings = vi.fn(async () => FINDINGS);+ renderView(<DeadCodeView adapter={makeAdapter({ listFindings })} />);++ expect(await screen.findByRole("radio", { name: "Open" })).toHaveAttribute("aria-checked", "true");+ expect(screen.queryByRole("combobox")).not.toBeInTheDocument();++ fireEvent.click(screen.getByRole("radio", { name: "False positive" }));+ await waitFor(() =>+ expect(listFindings).toHaveBeenCalledWith(+ expect.objectContaining({ status: "false_positive" }),+ ),+ );+ });});diff --git a/packages/ui/__tests__/dead-code/findings-table.test.tsx b/packages/ui/__tests__/dead-code/findings-table.test.tsxindex 39805c08f..92617cfb5 100644--- a/packages/ui/__tests__/dead-code/findings-table.test.tsx+++ b/packages/ui/__tests__/dead-code/findings-table.test.tsx@@ -3,7 +3,7 @@ import { render, screen, fireEvent, waitFor, within } from "@testing-library/reaimport { FindingsTable } from "../../src/dead-code/findings-table.js";import type { DeadCodeFinding } from "@repowise-dev/types/dead-code";-// jsdom has no layout engine → stub ResizeObserver so the Radix slider mounts.+// jsdom has no layout engine → stub ResizeObserver for the Radix primitives.class RO {observe() {}unobserve() {}@@ -77,38 +77,43 @@ describe("FindingsTable kind bucketing", () => {// The regression this guards: a fixed three-kind allowlist silently dropped// unused_internal findings that every other surface was counting.- expect(screen.getByRole("tab", { name: /Unreachable Files/ })).toBeInTheDocument();- expect(screen.getByRole("tab", { name: /Unused Internals/ })).toBeInTheDocument();- expect(screen.getByRole("tab", { name: /Some Future Kind/ })).toBeInTheDocument();+ expect(screen.getByRole("tab", { name: /Unreachable files/ })).toBeInTheDocument();+ expect(screen.getByRole("tab", { name: /Unused internals/ })).toBeInTheDocument();+ expect(screen.getByRole("tab", { name: /Some future kind/ })).toBeInTheDocument();});it("shows no tab for a kind that is absent from the data", () => {renderTable([finding({ id: "a", kind: "unreachable_file" })]);- expect(screen.queryByRole("tab", { name: /Zombie Packages/ })).not.toBeInTheDocument();+ expect(screen.queryByRole("tab", { name: /Zombie packages/ })).not.toBeInTheDocument();});it("renders an empty state rather than tabs when there are no findings", () => {renderTable([]);- expect(screen.getByText("No findings")).toBeInTheDocument();+ expect(screen.getByText("No open findings")).toBeInTheDocument();expect(screen.queryByRole("tab")).not.toBeInTheDocument();});+ it("words an empty review slice for its status", () => {+ renderTable([], { status: "acknowledged" });++ expect(screen.getByText("No acknowledged findings")).toBeInTheDocument();+ });+it("tab counts follow the confidence filter while the tab itself stays put", async () => {renderTable([finding({ id: "a", kind: "unreachable_file", confidence: 1 }),finding({ id: "b", kind: "unreachable_file", confidence: 0.45 }),]);- expect(screen.getByRole("tab", { name: /Unreachable Files 2/ })).toBeInTheDocument();+ expect(screen.getByRole("tab", { name: /Unreachable files 2/ })).toBeInTheDocument();- const slider = screen.getByLabelText("Minimum confidence");- for (let i = 0; i < 12; i++) fireEvent.keyDown(slider, { key: "ArrowRight" });+ fireEvent.click(screen.getByRole("radio", { name: "High only" }));// The count drops, but the tab does not disappear from under the pointer.await waitFor(() =>- expect(screen.getByRole("tab", { name: /Unreachable Files 1/ })).toBeInTheDocument(),+ expect(screen.getByRole("tab", { name: /Unreachable files 1/ })).toBeInTheDocument(),);});});@@ -126,8 +131,7 @@ describe("FindingsTable selection", () => {);// Push the low-confidence row out of view first, then select all.- const slider = screen.getByLabelText("Minimum confidence");- for (let i = 0; i < 12; i++) fireEvent.keyDown(slider, { key: "ArrowRight" });+ fireEvent.click(screen.getByRole("radio", { name: "High only" }));await waitFor(() =>expect(screen.queryByLabelText("Select finding src/hidden.ts")).not.toBeInTheDocument(),);@@ -151,11 +155,10 @@ describe("FindingsTable selection", () => {fireEvent.click(screen.getByLabelText("Select all findings"));expect(screen.getByRole("button", { name: "Resolve 2 selected" })).toBeInTheDocument();- // Raise the floor past the second finding: it leaves the table, so it must- // leave the selection too — otherwise "Resolve N selected" resolves rows- // the user can no longer see.- const slider = screen.getByLabelText("Minimum confidence");- for (let i = 0; i < 12; i++) fireEvent.keyDown(slider, { key: "ArrowRight" });+ // Narrow to high confidence: the second finding leaves the table, so it+ // must leave the selection too, otherwise "Resolve N selected" resolves+ // rows the user can no longer see.+ fireEvent.click(screen.getByRole("radio", { name: "High only" }));await waitFor(() =>expect(screen.getByRole("button", { name: "Resolve 1 selected" })).toBeInTheDocument(),@@ -177,7 +180,7 @@ describe("FindingsTable selection", () => {expect(screen.getByRole("button", { name: "Resolve 1 selected" })).toBeInTheDocument();// Radix activates a tab on mousedown, not click.- fireEvent.mouseDown(screen.getByRole("tab", { name: /Unused Exports/ }));+ fireEvent.mouseDown(screen.getByRole("tab", { name: /Unused exports/ }));expect(screen.queryByRole("button", { name: /Resolve \d+ selected/ })).not.toBeInTheDocument();});@@ -236,6 +239,7 @@ describe("FindingsTable sort and search", () => {target: { value: "nothing matches this" },});expect(screen.queryByRole("table")).not.toBeInTheDocument();+ expect(screen.getByText("1 finding hidden by the current filters")).toBeInTheDocument();// Without this the user is left staring at an empty state with no hint// that their own filter, not the repository, is why.@@ -345,3 +349,28 @@ describe("FindingsTable row actions", () => {expect(String(toastError.mock.calls[0]?.[0])).toMatch(/Couldn't update finding/);});});++describe("FindingsTable colour jobs", () => {+ it("shows confidence as a neutral percent, never in alarm colours", () => {+ renderTable([finding({ id: "a", confidence: 0.95 })]);++ const pct = inTable().getByText("95%");+ expect(pct.className).not.toMatch(/color-error|color-warning|color-success/);+ });++ it("keeps the row's Resolve verb neutral", () => {+ renderTable([finding({ id: "a" })]);++ const resolve = inTable().getByRole("button", { name: "Resolve src/a.ts" });+ expect(resolve.className).not.toMatch(/color-success/);+ });++ it("grounds a selected row on the neutral selected token, not the accent", () => {+ renderTable([finding({ id: "a" })]);++ fireEvent.click(inTable().getByLabelText("Select finding src/a.ts"));+ const row = inTable().getByRole("row", { name: /src\/a\.ts/ });+ expect(row.className).toMatch(/color-bg-selected/);+ expect(row.className).not.toMatch(/accent-muted/);+ });+});diff --git a/packages/ui/__tests__/dead-code/risk-factor-labels.test.tsx b/packages/ui/__tests__/dead-code/risk-factor-labels.test.tsxindex 6ed10cc34..a01a49220 100644--- a/packages/ui/__tests__/dead-code/risk-factor-labels.test.tsx+++ b/packages/ui/__tests__/dead-code/risk-factor-labels.test.tsx@@ -2,11 +2,11 @@* Risk factors reach a reader as English, not as API slugs.** Both surfaces that render `risk_factors` used to `join(", ")` the raw tags,- * so the badge tooltip and the agent prompt said "config, asset" where the+ * so the row marker and the agent prompt said "config, asset" where the* engine's own evidence line says "configuration, runtime-loaded web asset".** The two were uncovered in different ways, which is worth keeping straight.- * The tooltip was *executed* with a real factor — `dead-code-view`'s fixture+ * The marker was *executed* with a real factor — `dead-code-view`'s fixture* gives one finding `risk_factors: ["bootstrap"]` and the table renders it —* but nothing asserted on the text. The prompt branch was never executed at* all: the only prompt test seeds from `safeFindings`, which filters on@@ -40,11 +40,35 @@ function finding(over: Partial<DeadCodeFinding>): DeadCodeFinding {}describe("risk-factor labels", () => {- it("renders the badge tooltip with labels, not slugs", () => {+ it("names the risk factors as visible text, with labels, not slugs", () => {render(<FindingSafety finding={finding({ risk_factors: ["asset", "config"] })} />);- const badge = screen.getByTitle(/Runtime-load risk/);- expect(badge.getAttribute("title")).toContain("runtime-loaded web asset, configuration");- expect(badge.getAttribute("title")).not.toContain("asset, config)");+ const marker = screen.getByText(/may load at runtime/);+ expect(marker.textContent).toContain("runtime-loaded web asset, configuration");+ expect(marker.textContent).not.toContain("asset, config)");+ expect(screen.getByText("Review first")).toBeInTheDocument();+ });++ it("marks nothing on a deletion-ready row", () => {+ const { container } = render(+ <FindingSafety finding={finding({ safe_to_delete: true, confidence: 0.9 })} />,+ );+ expect(container).toBeEmptyDOMElement();+ });++ it("marks only deletion-ready rows when they are the exception", () => {+ const { rerender, container } = render(+ <FindingSafety mark="safe" finding={finding({ safe_to_delete: true, confidence: 0.9 })} />,+ );+ expect(screen.getByText("Deletion-ready")).toBeInTheDocument();+ rerender(<FindingSafety mark="safe" finding={finding({})} />);+ expect(container).toBeEmptyDOMElement();+ rerender(<FindingSafety mark="safe" finding={finding({ risk_factors: ["config"] })} />);+ expect(container.textContent).toBe("may load at runtime (configuration)");+ });++ it("says just Review first when no risk factor is known", () => {+ const { container } = render(<FindingSafety finding={finding({})} />);+ expect(container.textContent).toBe("Review first");});it("labels the risk factors in the dead-code agent prompt", () => {@@ -56,6 +80,6 @@ describe("risk-factor labels", () => {it("falls back to the raw tag for a factor the label map has not learned", () => {render(<FindingSafety finding={finding({ risk_factors: ["telemetry"] })} />);- expect(screen.getByTitle(/Runtime-load risk/).getAttribute("title")).toContain("telemetry");+ expect(screen.getByText(/may load at runtime/).textContent).toContain("telemetry");});});diff --git a/packages/ui/src/dead-code/dead-code-adapter.ts b/packages/ui/src/dead-code/dead-code-adapter.tsindex 59c2a8250..f49a03618 100644--- a/packages/ui/src/dead-code/dead-code-adapter.ts+++ b/packages/ui/src/dead-code/dead-code-adapter.ts@@ -8,8 +8,8 @@ import type {/*** App-injected data + navigation for the shared {@link DeadCodeView}.*- * The view owns the composition — the safe-to-delete pile, the cluster- * rollups, the drill-down table, the optimistic patch/undo toast, bulk+ * The view owns the composition — the lede, the safe-to-delete list, the+ * findings table, the optimistic patch/undo toast, bulk* resolve, the "Propose cleanup" agent brief, and Re-analyze. The host* supplies *how* to fetch/mutate and *where* file links go, so web and hosted* render the same view from one source.@@ -43,6 +43,11 @@ export interface DeadCodeAdapter {* fails. Optional: without it the view cannot know when to refetch.*/waitForAnalysis?(jobId: string): Promise<void>;+ /**+ * When set, Re-analyze renders disabled with this sentence beside it, for a+ * host that cannot run a pass right now (a read-only snapshot, a plan limit).+ */+ analyzeDisabledReason?: string;patchFinding(findingId: string,patch: DeadCodePatchInput,diff --git a/packages/ui/src/dead-code/dead-code-lede.tsx b/packages/ui/src/dead-code/dead-code-lede.tsxindex 007adb1c8..aa403a574 100644--- a/packages/ui/src/dead-code/dead-code-lede.tsx+++ b/packages/ui/src/dead-code/dead-code-lede.tsx@@ -1,226 +1,81 @@/**- * The Dead Code tab's opening read.+ * The Dead Code tab's opening read: one figure (reclaimable lines) and one+ * sentence saying what it is a share of and when it was measured.*- * It replaces four `MetricCard`s in a grid, two of which held a stacked- * label-and-count list inside the value slot. That is a table wearing a card:- * seven figures at near-identical weight behind four uppercase labels, with- * nothing leading and nothing saying what any of it means. A count of findings- * is also the wrong figure to lead with, because the question this tab answers- * is "what can I delete", and the answer is measured in lines.- *- * The kind breakdown moved into prose. Four kinds as four tiles read as four- * equal problems; as a sentence they read as what they are, one pile sorted by- * how it was found.+ * Earlier versions added three paragraphs, a confidence bar and a five-stat+ * ribbon under the figure; every one of them restated the same three numbers.+ * The confidence methodology lives on the label's info tip instead.*/import type { ReactNode } from "react";-import { DEAD_CODE_CONFIDENCE, type DeadCodeSummary } from "@repowise-dev/types/dead-code";+import type { DeadCodeSummary } from "@repowise-dev/types/dead-code";import { PageLede } from "../shared/page-lede";-import { StatRibbon, type RibbonStat } from "../stats/stat-ribbon";-import { formatNumber } from "../lib/format";+import { formatDateTime, formatNumber, formatRelativeTimeOrNull } from "../lib/format";export interface DeadCodeLedeProps {summary: DeadCodeSummary;- /**- * Findings in the slice on screen. Passed so the lede can say when the- * server-wide totals and the list below describe different populations,- * rather than letting a capped page read as the whole repository.- */- shownCount?: number;- truncated?: boolean;/** Rendered under the prose. The tab's one action. */action?: ReactNode;+ /** Replaces the posture sentence, e.g. with the all-clear state. */+ children?: ReactNode;}-/** How a finding was reached, in the words a person would use. */-const KIND_LABELS: Record<string, string> = {- unreachable_file: "unreachable file",- unused_export: "unused export",- unused_internal: "unused internal symbol",- zombie_package: "zombie package",-};--function kindPhrase(kind: string, count: number): string {- const label = KIND_LABELS[kind] ?? kind.replace(/_/g, " ");- return `${formatNumber(count)} ${label}${count === 1 ? "" : "s"}`;-}+const CONFIDENCE_HINT =+ "Deletion-ready means high confidence and outside the config, bootstrap and environment paths we never delete from unreviewed. Confidence is a statement about the language, not a hedge: a Python entry point registered by name or a TypeScript symbol re-exported through a barrel file is invisible to a call-graph walk.";-/** "a, b and c" — an Oxford-comma-free list, built rather than interpolated so- * a repo with one kind does not read "1 unused export and". */-function joinPhrases(parts: string[]): string {- if (parts.length <= 1) return parts[0] ?? "";- return `${parts.slice(0, -1).join(", ")} and ${parts[parts.length - 1]}`;+function plural(n: number, word: string): string {+ return `${formatNumber(n)} ${word}${n === 1 ? "" : "s"}`;}-export function DeadCodeLede({- summary,- shownCount,- truncated = false,- action,-}: DeadCodeLedeProps) {- const kinds = Object.entries(summary.by_kind)- .filter(([, count]) => count > 0)- .sort((a, b) => b[1] - a[1]);- const confidence = summary.confidence_summary;- const high = confidence.high ?? 0;- const medium = confidence.medium ?? 0;- const low = confidence.low ?? 0;- const graded = high + medium + low;- const flagged = summary.total_lines;- const share =- flagged > 0 ? Math.round((summary.deletable_lines / flagged) * 100) : null;-- const stats: RibbonStat[] = [- {- label: "Findings",- value: formatNumber(summary.total_findings),- ...(truncated && shownCount != null- ? { sub: `${formatNumber(shownCount)} on this page` }- : {}),- },- {- label: "Lines flagged",- value: formatNumber(flagged),- sub: "across every finding",- hint: "Every line inside a dead-code finding, whether or not we would delete it unreviewed.",- },- {- label: "High confidence",- value: formatNumber(high),- valueColor: high > 0 ? "text-[var(--color-success)]" : undefined,- sub: `confidence ${DEAD_CODE_CONFIDENCE.HIGH} or better`,- hint: "No dynamic reference, no re-export, no entry point that we can see.",- },- {- label: "Needs a look",- value: formatNumber(medium + low),- sub: "verify before deleting",- hint: "Reachable only through something static analysis cannot follow: a dynamic import, a plugin registry, a framework hook.",- },- {- label: "Deletion-ready",- value: share == null ? "" : `${share}%`,- sub: "of the flagged lines",- hint: "High confidence and outside the config, bootstrap and environment paths we never auto-delete from.",- },- ];-+/** "Analysed 2d ago." with the exact time on hover, or nothing when unknown. */+export function AnalysedAt({ at }: { at: string | null | undefined }) {+ const relative = formatRelativeTimeOrNull(at, "");+ if (!at || !relative) return null;return (- <div className="flex flex-col gap-6">- <PageLede- label="Reclaimable"- value={formatNumber(summary.deletable_lines)}- unit="lines"- layout="beside"- {...(action ? { action } : {})}- figureFooter={- graded > 0 ? (- <ConfidenceSplit high={high} medium={medium} low={low} />- ) : undefined- }- >- {summary.total_findings === 0 ? (- <p>- Nothing in this repository is currently flagged as unreachable, unused or- zombie. That is a real result rather than an absence: the analysis walked- the import graph, the export surface and the package manifests and found- no symbol it could reach from no entry point. Re-run it after a large- refactor, when whole call paths tend to go quiet at once.- </p>- ) : (- <>- <p>- <strong className="font-semibold text-[var(--color-text-primary)]">- {formatNumber(summary.total_findings)} findings- </strong>{" "}- covering{" "}- <strong className="font-semibold text-[var(--color-text-primary)]">- {formatNumber(flagged)} lines- </strong>{" "}- have no reachable caller. They are{" "}- {joinPhrases(kinds.map(([kind, count]) => kindPhrase(kind, count)))},- found by walking the import graph and the export surface rather than by- matching names.- </p>-- <p className="mt-2.5">- Of those,{" "}- <strong className="font-semibold text-[var(--color-text-primary)]">- {formatNumber(summary.deletable_lines)} lines- </strong>{" "}- are deletion-ready: high confidence, and outside the config, bootstrap- and environment paths we never delete from unreviewed- {share != null ? `, which is ${share}% of what is flagged` : ""}. That- is the number the cleanup brief is seeded from.- </p>-- <p className="mt-2.5">- Confidence is not a hedge on the finding, it is a statement about the- language. A Python entry point registered by string name and a- TypeScript symbol re-exported through a barrel file are both invisible- to a call-graph walk, and calling either one dead would be wrong.- </p>- </>- )}- </PageLede>-- <StatRibbon stats={stats} />- </div>+ <>+ {" "}+ <time dateTime={at} title={formatDateTime(at)}>+ Analysed {relative}.+ </time>+ </>);}-/**- * The one second read belonging to the number itself: how much of the pile you- * can act on now. Stepped down from the accent rather than reaching for three- * new hues, because confidence is an ordered scale, not three categories.- */-function ConfidenceSplit({- high,- medium,- low,-}: {- high: number;- medium: number;- low: number;-}) {- const total = high + medium + low;- const segments = [- { key: "high", label: "high", count: high, bar: "bg-[var(--color-accent-primary)]" },- {- key: "medium",- label: "medium",- count: medium,- bar: "bg-[color-mix(in_srgb,var(--color-accent-primary)_45%,var(--color-bg-inset))]",- },- {- key: "low",- label: "low",- count: low,- bar: "bg-[color-mix(in_srgb,var(--color-accent-primary)_18%,var(--color-bg-inset))]",- },- ].filter((s) => s.count > 0);+export function DeadCodeLede({ summary, action, children }: DeadCodeLedeProps) {+ const findings = summary.total_findings;+ const strong = "font-semibold text-[var(--color-text-primary)]";+ const ready = summary.deletable_lines > 0;return (- <div className="space-y-1.5">- <div className="flex h-1.5 w-full overflow-hidden rounded-full bg-[var(--color-bg-inset)]">- {segments.map((s) => (- <div- key={s.key}- className={s.bar}- style={{ width: `${(s.count / total) * 100}%` }}- aria-label={`${s.count} ${s.label} confidence`}- />- ))}- </div>- <div className="flex flex-wrap gap-x-3 gap-y-0.5 text-xs text-[var(--color-text-tertiary)]">- {segments.map((s) => (- <span key={s.key} className="inline-flex items-center gap-1 tabular-nums">- <span className={`inline-block h-1.5 w-1.5 rounded-full ${s.bar}`} />- {formatNumber(s.count)} {s.label}- </span>- ))}- </div>- </div>+ <PageLede+ label={findings > 0 && !ready ? "Flagged" : "Reclaimable"}+ labelHint={CONFIDENCE_HINT}+ value={formatNumber(findings > 0 && !ready ? summary.total_lines : summary.deletable_lines)}+ unit="lines"+ layout="beside"+ {...(action ? { action } : {})}+ >+ {children ?? (+ <p>+ {findings === 0 ? (+ "No open findings remain."+ ) : ready ? (+ <>+ <strong className={strong}>{plural(findings, "finding")}</strong> across{" "}+ <strong className={strong}>{plural(summary.total_lines, "line")}</strong>{" "}+ {findings === 1 ? "has" : "have"} no reachable caller.+ </>+ ) : (+ <>+ <strong className={strong}>{plural(findings, "finding")}</strong>{" "}+ {findings === 1 ? "has" : "have"} no reachable caller. None is deletion-ready yet,+ so review {findings === 1 ? "it" : "them"} before deleting.+ </>+ )}+ <AnalysedAt at={summary.analyzed_at} />+ </p>+ )}+ </PageLede>);}diff --git a/packages/ui/src/dead-code/dead-code-view.tsx b/packages/ui/src/dead-code/dead-code-view.tsxindex f3021749e..017a8535c 100644--- a/packages/ui/src/dead-code/dead-code-view.tsx+++ b/packages/ui/src/dead-code/dead-code-view.tsx@@ -3,25 +3,23 @@/*** Dead Code view, on the section design language.*- * The shape is: a lede that leads with the reclaimable line count and says in- * prose what confidence means, then the safe-to-delete pile, the optional- * cluster rollups, and the full drill-down table. Carries the optimistic row- * patch + Undo toast, bulk resolve, the "Propose cleanup" agent brief, and+ * Three things, top to bottom: a lede with the reclaimable line count and one+ * posture sentence, the safe-to-delete list, and the full findings table with+ * its status control in the section header. Carries the optimistic row patch+ * + Undo toast, bulk resolve, the "Propose cleanup" agent brief, and* Re-analyze.*- * What it replaces: four `MetricCard`s in a grid (two of them holding a stacked- * count list inside the value slot), a red gradient hero card that repeated the- * headline figure, and a floating chrome row carrying a status dropdown and a- * button above all of it. The controls now sit in the header of the section- * they operate on, which is also why the status filter can live there safely:- * a section header renders whether or not the table underneath it does.+ * Owner and confidence-by-kind rollups used to sit between the list and the+ * table. They cut the same findings two more ways without changing what to do+ * next, so the page no longer carries them; the table sorts by owner and+ * filters by kind and confidence when that question comes up.** Presentation + orchestration only: the host injects data fetching,* mutations, links, and navigation through a {@link DeadCodeAdapter}, so web* and hosted render the same view from one source.*/-import { useMemo, useState } from "react";+import { useId, useMemo, useState } from "react";import useSWR from "swr";import { toast } from "sonner";import type {@@ -30,24 +28,22 @@ import type {DeadCodeSummary,} from "@repowise-dev/types/dead-code";-import { Trash2 } from "lucide-react";-import { Button } from "../ui/button";import { Skeleton } from "../ui/skeleton";import { ApiError } from "../shared/api-error";import { EmptyState } from "../shared/empty-state";+import { Segmented } from "../shared/segmented";import { OverviewSection } from "../overview/section";import { AiPromptModal } from "../health/ai-prompt-modal";import { buildDeadCodeAiPrompt } from "../health/ai-prompt-builder";-import { DeadCodeLede } from "./dead-code-lede";+import { AnalysedAt, DeadCodeLede } from "./dead-code-lede";import { SafeToDeletePile } from "./safe-to-delete-pile";-import { OwnerLeaderboard } from "./owner-leaderboard";-import { FindingsBreakdownGrid } from "./findings-breakdown-grid";import { FindingsTable } from "./findings-table";import { DEAD_CODE_STATUS_LABELS } from "./finding-cells";import type { DeadCodeAdapter } from "./dead-code-adapter";import { toFriendlyMessage } from "../lib/errors";+import { formatNumber } from "../lib/format";/*** Server ceiling for one findings page (`limit` is clamped to 500 server-side).@@ -56,8 +52,10 @@ import { toFriendlyMessage } from "../lib/errors";*/const FINDINGS_LIMIT = 500;-/** Order of the status filter; "open" first because it is the working list. */-const STATUS_ORDER: DeadCodeStatus[] = ["open", "acknowledged", "resolved", "false_positive"];+/** Order of the status control; "open" first because it is the working list. */+const STATUS_OPTIONS = (["open", "acknowledged", "resolved", "false_positive"] as const).map(+ (value) => ({ value, label: DEAD_CODE_STATUS_LABELS[value] }),+);/** The one failure card both fetches use, so a broken load never reads as "clean". */function RetryCard({@@ -69,18 +67,20 @@ function RetryCard({error: unknown;onRetry: () => void;}) {- return <ApiError title={title} message={toFriendlyMessage(error)} onRetry={onRetry} />;+ return (+ <ApiError title={title} message={toFriendlyMessage(error)} onRetry={onRetry} size="compact" />+ );}export function DeadCodeView({ adapter }: { adapter: DeadCodeAdapter }) {const [analyzing, setAnalyzing] = useState(false);const [promptIds, setPromptIds] = useState<string[] | null>(null);- /** Which slice the drill-down table shows; everything above it stays open-only. */+ /** Which slice the findings table shows; the lede and the list stay open-only. */const [statusFilter, setStatusFilter] = useState<DeadCodeStatus>("open");- // Optimistic row state lives here, not in the table: the pile, the cluster- // rollups and the table all read one slice, so resolving a row (or undoing- // it) moves every surface together.+ // Optimistic row state lives here, not in the table: the list and the table+ // read one slice, so resolving a row (or undoing it) moves both together.const [overrides, setOverrides] = useState<Record<string, DeadCodeFinding>>({});+ const reasonId = useId();const {data: summary,@@ -93,8 +93,8 @@ export function DeadCodeView({ adapter }: { adapter: DeadCodeAdapter }) {{ revalidateOnFocus: false },);- // Single findings fetch feeds the pile, the cluster views, AND the drill-down- // table (which filters this slice client-side) — no second fetch.+ // Single findings fetch feeds the list AND the table (which filters this+ // slice client-side); no second fetch.const {data: findings,isLoading: loadingFindings,@@ -107,8 +107,8 @@ export function DeadCodeView({ adapter }: { adapter: DeadCodeAdapter }) {);// Reviewing an already-actioned finding is a second, narrower question than- // "what can I delete", so it gets its own fetch and leaves the pile, the- // rollups and the summary reading the open slice they have always read.+ // "what can I delete", so it gets its own fetch and leaves the list and the+ // summary reading the open slice.const {data: reviewFindings,isLoading: loadingReview,@@ -130,8 +130,8 @@ export function DeadCodeView({ adapter }: { adapter: DeadCodeAdapter }) {const findingsList = useMemo(() => {const inPayload = new Set(fetched.map((f) => f.id));// A finding reopened from the review list is not in the open payload, but- // it is open now and belongs in the pile and the rollups. Refetching- // instead would race the optimistic override that is masking it.+ // it is open now and belongs in the list. Refetching instead would race the+ // optimistic override that is masking it.const reopened = Object.values(overrides).filter((f) => !inPayload.has(f.id));return [...fetched.map((f) => overrides[f.id] ?? f), ...reopened].filter((f) => f.status === "open",@@ -142,7 +142,7 @@ export function DeadCodeView({ adapter }: { adapter: DeadCodeAdapter }) {[findingsList],);- // What the drill-down table renders. Same override + status treatment as the+ // What the findings table renders. Same override + status treatment as the// open slice, so reopening a row drops it out of the review list immediately.const tableFindings = useMemo(() => {if (statusFilter === "open") return findingsList;@@ -158,12 +158,23 @@ export function DeadCodeView({ adapter }: { adapter: DeadCodeAdapter }) {// for a non-open status, so the hint can only say the count is a first page.const reviewTruncated = (reviewFindings?.length ?? 0) >= FINDINGS_LIMIT;+ // Nothing open, per the summary and the payload. Keyed off the fetched+ // payload, not the locally filtered list: resolving the last row must not+ // swap the sections out, or undo would restore it into a remounted page.+ const clean =+ statusFilter === "open" &&+ !findingsError &&+ fetched.length === 0 &&+ (summary?.total_findings ?? 0) === 0 &&+ (findings !== undefined || summary !== undefined);+ // Only a recorded run can call a zero clean; an unknown one is "not yet".+ const analyzed = Boolean(summary?.analyzed_at);+// "Propose cleanup" opens the shared AI-prompt modal seeded with the safe- // pile — same agent-flavor picker (incl. repowise MCP) and copy affordance as- // every other AI action in the dashboard.+ // list, with the same agent picker as every other AI action in the dashboard.const handlePropose = (findingIds: string[]) => setPromptIds(findingIds);- // Seeded from both slices: the pile's CTA names open findings even while the+ // Seeded from both slices: the list's CTA names open findings even while the// table is showing a review slice, and an empty modal is worse than none.const promptFindings = useMemo(() => {if (!promptIds) return [];@@ -176,9 +187,9 @@ export function DeadCodeView({ adapter }: { adapter: DeadCodeAdapter }) {}, [promptIds, findingsList, tableFindings]);const handleAnalyze = async () => {- // Guard here rather than on each button: the empty-state action cannot- // disable itself, and two clicks would race a second job into a 409.- if (analyzing) return;+ // Guard here rather than on each button: two clicks would race a second+ // job into a 409.+ if (analyzing || adapter.analyzeDisabledReason) return;setAnalyzing(true);let jobId: string | undefined;try {@@ -186,8 +197,8 @@ export function DeadCodeView({ adapter }: { adapter: DeadCodeAdapter }) {jobId = started?.job_id;toast.success(jobId && adapter.waitForAnalysis- ? "Analysis started — this page refreshes when it finishes."- : "Analysis started — results will appear shortly.",+ ? "Analysis started. This page refreshes when it finishes."+ : "Analysis started. Results will appear shortly.",);} catch (err) {// 409 is the one failure with a specific remedy: wait for the other job.@@ -231,8 +242,8 @@ export function DeadCodeView({ adapter }: { adapter: DeadCodeAdapter }) {const previousStatus: DeadCodeStatus = finding?.status ?? "open";const updated = await adapter.patchFinding(id, patch);setOverrides((prev) => ({ ...prev, [id]: updated }));- // The tiles are server-derived counts of the open slice; without this they- // drift by one on every row action and quietly disagree with the table.+ // The lede is a server-derived count of the open slice; without this it+ // drifts by one on every row action and quietly disagrees with the table.void mutateSummary();toast.success(`Finding ${patch.status.replace(/_/g, " ")}`, {action: {@@ -264,7 +275,7 @@ export function DeadCodeView({ adapter }: { adapter: DeadCodeAdapter }) {// continue; report partial below}}- // Reflect only the rows the server confirmed — never a positional guess.+ // Reflect only the rows the server confirmed, never a positional guess.if (succeededIds.length > 0) {const confirmed = new Set(succeededIds);setOverrides((prev) => {@@ -287,33 +298,80 @@ export function DeadCodeView({ adapter }: { adapter: DeadCodeAdapter }) {return succeededIds;};- // The tab's one action, placed under the lede prose. It is the same element- // wherever the lede cannot render, so a failed summary still leaves a way to- // re-run the pass.- const reanalyze = (- <Button size="sm" variant="outline" onClick={handleAnalyze} disabled={analyzing}>- {analyzing ? "Analyzing…" : "Re-analyze"}- </Button>+ // The tab's one action. The same element renders wherever the lede cannot,+ // so a failed summary still leaves a way to re-run the pass. A host that+ // cannot run one says why beside the disabled button, not after a click.+ const disabledReason = adapter.analyzeDisabledReason;+ const analyzeAction = (label: string) => (+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1">+ <Button+ size="sm"+ variant="outline"+ className="h-8"+ onClick={handleAnalyze}+ disabled={analyzing || Boolean(disabledReason)}+ {...(disabledReason ? { "aria-describedby": reasonId } : {})}+ >+ {analyzing ? "Analyzing…" : label}+ </Button>+ {disabledReason && (+ <span id={reasonId} className="text-xs text-[var(--color-text-tertiary)]">+ {disabledReason}+ </span>+ )}+ </div>);+ const openCount = findingsList.length;+ const sectionDescription = tableLoading+ ? "Loading…"+ : statusFilter !== "open"+ ? `${reviewTruncated ? "The first " : ""}${formatNumber(tableFindings.length)} ${DEAD_CODE_STATUS_LABELS[statusFilter].toLowerCase()} finding${tableFindings.length === 1 ? "" : "s"}. Reopen one to put it back on the open list.`+ : truncated && summary+ ? `Showing the first ${formatNumber(openCount)} of ${formatNumber(summary.total_findings)} open findings. Every action can be undone for six seconds.`+ : "Resolve, acknowledge or mark a false positive. Every action can be undone for six seconds.";+return (<div className="flex flex-col gap-6 sm:gap-8">{loadingSummary ? (// Shapes and widths match the lede, so nothing reflows when it lands.- <div className="flex flex-col gap-6">- <div className="flex flex-col gap-5 lg:flex-row lg:gap-12">- <Skeleton className="h-[92px] w-full rounded-lg lg:w-[220px]" />- <Skeleton className="h-[92px] w-full max-w-[62ch] rounded-lg" />- </div>- <Skeleton className="h-[74px] w-full" />+ <div className="flex flex-col gap-5 lg:flex-row lg:gap-12">+ <Skeleton className="h-[72px] w-full rounded-lg lg:w-[220px]" />+ <Skeleton className="h-[72px] w-full max-w-[62ch] rounded-lg" /></div>) : summary ? (- <DeadCodeLede- summary={summary}- shownCount={findingsList.length}- truncated={truncated}- action={reanalyze}- />+ clean && !analyzed ? (+ // A zero with no recorded run is "not yet", never an all-clear.+ <EmptyState+ title="Not analysed yet"+ description="Dead-code analysis has not run for this repository. Run it to find unreachable files, unused exports and zombie packages."+ >+ {analyzeAction("Run analysis")}+ </EmptyState>+ ) : (+ <DeadCodeLede summary={summary} action={analyzeAction("Re-analyze")}>+ {clean ? (+ <EmptyState+ tone="positive"+ className="items-start px-0 py-0 text-left"+ title="No dead code found"+ description={+ <>+ No unreachable files, unused exports or zombie packages across this+ repository.+ <AnalysedAt at={summary.analyzed_at} />+ </>+ }+ // Resolved and set-aside findings stay reviewable from here,+ // since the clean page carries no table to switch.+ secondaryAction={{+ label: "Review past findings",+ onClick: () => setStatusFilter("resolved"),+ }}+ />+ ) : undefined}+ </DeadCodeLede>+ )) : summaryError ? (<div className="flex flex-col gap-3"><RetryCard@@ -321,140 +379,81 @@ export function DeadCodeView({ adapter }: { adapter: DeadCodeAdapter }) {error={summaryError}onRetry={() => void mutateSummary()}/>- <div>{reanalyze}</div>+ {analyzeAction("Re-analyze")}</div>) : null}- {/* Act now: the single "what do I delete" surface. */}- {findings && safeFindings.length > 0 && (+ {!clean && findings && safeFindings.length > 0 && (<SafeToDeletePilefindings={safeFindings}onPropose={handlePropose}onSelect={(f) => adapter.navigate(adapter.fileHref(f.file_path))}- // The summary total covers the whole repo; the file and finding- // counts beside it come from a capped slice. Only pass it when the- // two describe the same population.- {...(summary && !truncated ? { reclaimableLines: summary.deletable_lines } : {})}/>)}- {/* Where it clusters. No longer behind a disclosure: the accordion existed- because this sat among six boxes of equal weight and something had to- give, and a hairline plus vertical rhythm now does that job without- hiding a rollup the reader has to guess at. */}- {findingsList.length > 0 && (+ {/* The status control lives in this header rather than among the table's+ own filters because the table swaps out for empty and error states,+ and a control living inside it would go with them. */}+ {!clean && (<OverviewSection- title="Where it clusters"- description="The same findings cut two ways: by the person who last owned the code, and by how sure we are against how it was found."+ title="All findings"+ description={sectionDescription}+ action={+ <Segmented<DeadCodeStatus>+ label="Status"+ value={statusFilter}+ onChange={setStatusFilter}+ options={STATUS_OPTIONS}+ />+ }>- <div className="grid grid-cols-1 gap-6 lg:grid-cols-2">- <div className="flex flex-col gap-2">- <p className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">- Reclaimable lines by owner- </p>- <OwnerLeaderboard findings={findingsList} safeOnly />- </div>- <div className="flex flex-col gap-2">- <p className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">- Confidence against kind- </p>- <FindingsBreakdownGrid findings={findingsList} />- </div>- </div>+ {/* A failure with nothing to show has to be the whole story: a table+ or an empty state underneath it would restate the failure as+ "clean". */}+ {tableError && tableFindings.length === 0 && !tableLoading ? (+ <RetryCard+ title="Couldn't load findings"+ error={tableError}+ onRetry={retryTable}+ />+ ) : tableLoading && tableFindings.length === 0 ? (+ <Skeleton className="h-40 w-full rounded-lg" />+ ) : statusFilter === "open" && openCount === 0 && fetched.length > 0 && !truncated ? (+ // Every row in the payload was actioned on this page. The section+ // stays mounted so Undo can put a row straight back.+ <EmptyState+ tone="positive"+ title="Every finding is resolved or set aside"+ description="Switch the status above to review or reopen one."+ />+ ) : (+ <>+ {/* A failed refresh over data we already hold: say so, but keep+ the rows. Replacing a working table with an error card loses+ the user's place over a transient blip. */}+ {tableError && (+ <RetryCard+ title="Couldn't refresh findings"+ error={tableError}+ onRetry={retryTable}+ />+ )}+ <FindingsTable+ findings={tableFindings}+ onPatch={handlePatch}+ onBulkResolve={handleBulkResolve}+ onGeneratePrompt={handlePropose}+ fileHref={(p) => adapter.fileHref(p)}+ onNavigate={(href) => adapter.navigate(href)}+ {...(adapter.graphHref ? { graphHref: (p: string) => adapter.graphHref!(p) } : {})}+ status={statusFilter}+ isLoading={tableLoading}+ />+ </>+ )}</OverviewSection>)}- {/* The drill-down. Its contents route off the slice actually on screen,- not the open fetch: a failed open fetch used to blank the table even- when the user had switched the filter to a slice that loaded fine.-- The status control lives in this header rather than among the table's- own filters because a clean repository swaps the table out for an- empty state, and a control living inside it would go with it. The- header renders either way. */}- <OverviewSection- title="All findings"- description={- tableLoading- ? "Loading…"- : statusFilter !== "open"- ? `${reviewTruncated ? `The first ${tableFindings.length}` : tableFindings.length} ${DEAD_CODE_STATUS_LABELS[statusFilter].toLowerCase()} finding${tableFindings.length === 1 ? "" : "s"}. Reopen one to put it back in the working list.`- : truncated && summary- ? `Showing ${findingsList.length} of ${summary.total_findings} open findings. Resolve, acknowledge or flag a false positive; every action is undoable for six seconds.`- : `${findingsList.length} open finding${findingsList.length === 1 ? "" : "s"}. Resolve, acknowledge or flag a false positive; every action is undoable for six seconds.`- }- action={- <div className="flex items-center gap-2">- <label- htmlFor="finding-status"- className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]"- >- Status- </label>- <select- id="finding-status"- value={statusFilter}- onChange={(e) => setStatusFilter(e.target.value as DeadCodeStatus)}- className="h-8 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-2 text-xs text-[var(--color-text-secondary)]"- >- {STATUS_ORDER.map((s) => (- <option key={s} value={s}>- {DEAD_CODE_STATUS_LABELS[s]}- </option>- ))}- </select>- </div>- }- >- {/* A failure with nothing to show has to be the whole story: a table or- an empty state underneath it would restate the failure as "clean". */}- {tableError && tableFindings.length === 0 && !tableLoading ? (- <RetryCard- title="Couldn't load findings"- error={tableError}- onRetry={retryTable}- />- ) : tableLoading && tableFindings.length === 0 ? (- <Skeleton className="h-40 w-full rounded-lg" />- ) : /* A clean repository gets said out loud. Keyed off the fetched- payload, not the locally filtered list: resolving the last row must- not swap the table out, because undoing it would then bring the row- back into a section that had remounted. Only for the open slice:- swapping the table out while reviewing acknowledged findings would- strand the user there. */- statusFilter === "open" && fetched.length === 0 && findingsList.length === 0 ? (- <EmptyState- icon={<Trash2 className="h-6 w-6" />}- title="No dead code found"- description="Nothing in this repository is currently flagged as unreachable, unused or zombie. Re-run the analysis after a large refactor, when whole call paths tend to go quiet at once."- />- ) : (- <>- {/* A failed refresh over data we already hold: say so, but keep the- rows. Replacing a working table with an error card loses the- user's place over a transient blip. */}- {tableError && (- <RetryCard- title="Couldn't refresh findings"- error={tableError}- onRetry={retryTable}- />- )}- <FindingsTable- findings={tableFindings}- onPatch={handlePatch}- onBulkResolve={handleBulkResolve}- onGeneratePrompt={handlePropose}- fileHref={(p) => adapter.fileHref(p)}- onNavigate={(href) => adapter.navigate(href)}- {...(adapter.graphHref ? { graphHref: (p: string) => adapter.graphHref!(p) } : {})}- status={statusFilter}- isLoading={tableLoading}- />- </>- )}- </OverviewSection>-<AiPromptModalopen={promptIds !== null}onOpenChange={(o) => !o && setPromptIds(null)}@@ -476,7 +475,7 @@ export function DeadCodeView({ adapter }: { adapter: DeadCodeAdapter }) {: null}title="AI cleanup prompt"- description="A ready-to-paste prompt that has your AI agent verify and remove this dead-code pile safely, in reviewable commits."+ description="A ready-to-paste prompt that has your AI agent verify and remove these findings safely, in reviewable commits."/></div>);diff --git a/packages/ui/src/dead-code/finding-cells.tsx b/packages/ui/src/dead-code/finding-cells.tsxindex e8f23f1a3..33a3a4bcc 100644--- a/packages/ui/src/dead-code/finding-cells.tsx+++ b/packages/ui/src/dead-code/finding-cells.tsx@@ -5,14 +5,12 @@ import type * as React from "react";import { CircleSlash, Eye, GitBranch, MoreHorizontal, Sparkles } from "lucide-react";import { toast } from "sonner";import { Button } from "../ui/button";-import { Badge } from "../ui/badge";import { ConfirmDialog } from "../ui/confirm-dialog";import { Popover, PopoverContent, PopoverTrigger } from "../ui/popover";import { formatConfidence } from "../lib/format";import { toFriendlyMessage } from "../lib/errors";import { cn } from "../lib/cn";import {- deadCodeConfidenceTier,deadCodeRiskFactorLabel,type DeadCodeFinding,type DeadCodeStatus,@@ -72,14 +70,15 @@ export interface FindingIdentityProps {href?: string | undefined;/** Client-side navigation, so a plain click does not trigger a full page load. */onNavigate?: ((href: string) => void) | undefined;+ /** Which safety group is the exception in the current list. */+ mark?: "safe" | "review" | undefined;}/**- * File path (linked when the host can route), symbol name, and the detector's- * reason. The reason was already being fed to the AI prompt builder, so the- * model saw the justification and the human did not.+ * File path (linked when the host can route), symbol name, the detector's+ * reason, and the safety marker for whichever group is the exception.*/-export function FindingIdentity({ finding, href, onNavigate }: FindingIdentityProps) {+export function FindingIdentity({ finding, href, onNavigate, mark }: FindingIdentityProps) {const onLinkClick = (e: MouseEvent<HTMLAnchorElement>) => {e.stopPropagation();if (!href || !onNavigate) return;@@ -119,49 +118,72 @@ export function FindingIdentity({ finding, href, onNavigate }: FindingIdentityPr)}{finding.reason && (<span- className="mt-0.5 block truncate text-2xs text-[var(--color-text-tertiary)]"+ className="mt-0.5 block truncate text-xs text-[var(--color-text-tertiary)]"title={finding.reason}>{finding.reason}</span>)}+ <FindingSafety finding={finding} mark={mark ?? "review"} /></div>);}-/** Confidence, coloured on the shared tier boundaries rather than local ones. */+/**+ * Confidence as a neutral mono percent. Dead code is not an alarm, so the+ * figure carries no red or amber; the tier is what the filter and the+ * "Review first" marker act on.+ */export function FindingConfidence({ finding }: { finding: DeadCodeFinding }) {- const tier = deadCodeConfidenceTier(finding.confidence);return (- <span- className={cn(- "font-medium tabular-nums text-xs",- tier === "high"- ? "text-[var(--color-error)]"- : tier === "medium"- ? "text-[var(--color-warning)]"- : "text-[var(--color-text-secondary)]",- )}- >+ <span className="font-mono text-xs tabular-nums text-[var(--color-text-secondary)]">{formatConfidence(finding.confidence)}</span>);}-/** "Candidate" vs "Review", with the risk factors behind the tooltip. */-export function FindingSafety({ finding }: { finding: DeadCodeFinding }) {- if (finding.safe_to_delete) return <Badge variant="fresh">Candidate</Badge>;+/**+ * Marks the exception, not the default. When deletion-ready rows are the+ * minority they carry the dot; otherwise the rows needing review do, with+ * their risk factors when the engine named any.+ */+export function FindingSafety({+ finding,+ mark = "review",+}: {+ finding: DeadCodeFinding;+ /** Which group is the exception in the current list. */+ mark?: "safe" | "review";+}) {+ const factors = finding.risk_factors ?? [];+ const risk =+ factors.length > 0+ ? `may load at runtime (${factors.map(deadCodeRiskFactorLabel).join(", ")})`+ : null;+ if (mark === "safe") {+ if (!finding.safe_to_delete) {+ return risk ? (+ <span className="mt-0.5 block text-xs text-[var(--color-text-tertiary)]">{risk}</span>+ ) : null;+ }+ return <SafetyMark label="Deletion-ready" />;+ }+ if (finding.safe_to_delete) return null;+ return <SafetyMark label="Review first" detail={risk} />;+}++function SafetyMark({ label, detail }: { label: string; detail?: string | null }) {return (- <Badge- variant="default"- title={- finding.risk_factors && finding.risk_factors.length > 0- ? `Runtime-load risk (${finding.risk_factors.map(deadCodeRiskFactorLabel).join(", ")}) - verify it isn't loaded outside static imports before deleting`- : "Lower confidence - verify before deleting"- }- >- Review- </Badge>+ <span className="mt-0.5 flex min-w-0 items-baseline gap-1.5 text-xs text-[var(--color-text-tertiary)]">+ <span+ aria-hidden+ className="inline-block h-1.5 w-1.5 shrink-0 translate-y-[-1px] rounded-full bg-[var(--color-text-tertiary)]"+ />+ <span className="min-w-0">+ <span className="font-medium text-[var(--color-text-secondary)]">{label}</span>+ {detail ? ` · ${detail}` : null}+ </span>+ </span>);}@@ -256,7 +278,7 @@ export function FindingRowActions({variant="ghost"disabled={pending}onClick={() => setConfirmStatus("resolved")}- className="h-6 px-2 text-xs text-[var(--color-success)] hover:text-[var(--color-success)]"+ className="h-8 px-2 text-xs"aria-label={`Resolve ${finding.file_path}`}>Resolve@@ -267,7 +289,7 @@ export function FindingRowActions({variant="ghost"disabled={pending}onClick={() => setConfirmStatus("open")}- className="h-6 px-2 text-xs"+ className="h-8 px-2 text-xs"aria-label={`Reopen ${finding.file_path}`}>Reopen@@ -279,7 +301,7 @@ export function FindingRowActions({<Buttonsize="sm"variant="ghost"- className="h-6 w-6 px-0 text-[var(--color-text-tertiary)]"+ className="h-8 w-8 px-0 text-[var(--color-text-tertiary)]"aria-label={`More actions for ${finding.file_path}`}><MoreHorizontal className="h-3.5 w-3.5" />diff --git a/packages/ui/src/dead-code/findings-breakdown-grid.tsx b/packages/ui/src/dead-code/findings-breakdown-grid.tsxdeleted file mode 100644index beaefd02d..000000000--- a/packages/ui/src/dead-code/findings-breakdown-grid.tsx+++ /dev/null@@ -1,140 +0,0 @@-"use client";--import * as React from "react";-import {- DEAD_CODE_CONFIDENCE,- deadCodeConfidenceTier,-} from "@repowise-dev/types/dead-code";-import { EmptyState } from "../shared/empty-state";-import { cn } from "../lib/cn";--export interface FindingsBreakdownItem {- kind: string;- confidence: number;-}--interface FindingsBreakdownGridProps {- findings: FindingsBreakdownItem[];- className?: string;-}--/** Rows of the matrix, on the shared boundaries rather than a local guess. */-const CONFIDENCE_TIERS = [- { id: "high", label: `High (≥${DEAD_CODE_CONFIDENCE.HIGH})` },- {- id: "medium",- label: `Medium (${DEAD_CODE_CONFIDENCE.MEDIUM}–${DEAD_CODE_CONFIDENCE.HIGH})`,- },- { id: "low", label: `Low (<${DEAD_CODE_CONFIDENCE.MEDIUM})` },-] as const;--const KIND_LABELS: Record<string, string> = {- unreachable_file: "Unreachable file",- unused_export: "Unused export",- unused_internal: "Unused internal",- zombie_package: "Zombie package",-};--/**- * Confidence-tier × kind matrix for dead-code findings — surfaces where the- * concentration is so reviewers know whether to start with high-confidence- * file removals or low-confidence symbol pruning.- */-export function FindingsBreakdownGrid({ findings, className }: FindingsBreakdownGridProps) {- const { kinds, counts, max, tiers } = React.useMemo(() => {- const kindSet = new Set<string>();- const counts: Record<string, Record<string, number>> = {};- let max = 0;- for (const f of findings) {- const tier = deadCodeConfidenceTier(f.confidence);- const kind = f.kind ?? "unknown";- kindSet.add(kind);- counts[tier] ??= {};- counts[tier][kind] = (counts[tier][kind] ?? 0) + 1;- if (counts[tier][kind] > max) max = counts[tier][kind];- }- const ordered = Array.from(kindSet).sort();- // The list endpoint floors at MEDIUM, so the low row is normally an empty- // band across the whole matrix. Show it only when something is in it.- const tiers = CONFIDENCE_TIERS.filter(- (t) => t.id !== "low" || Object.keys(counts["low"] ?? {}).length > 0,- );- return { kinds: ordered, counts, max, tiers };- }, [findings]);-- if (kinds.length === 0) {- return (- <EmptyState- title="No findings yet"- description="Nothing to break down until an analysis has produced dead-code findings."- {...(className ? { className } : {})}- />- );- }-- return (- <div- className={cn(- "overflow-hidden rounded-md border border-[var(--color-border-default)]",- className,- )}- >- <table className="w-full border-collapse text-xs">- <thead>- <tr className="bg-[var(--color-bg-elevated)]">- <th className="px-3 py-2 text-left font-medium text-[var(--color-text-tertiary)]">- Confidence- </th>- {kinds.map((k) => (- <th- key={k}- className="px-2 py-2 text-right font-medium text-[var(--color-text-tertiary)]"- >- {KIND_LABELS[k] ?? k}- </th>- ))}- </tr>- </thead>- <tbody>- {tiers.map((tier) => (- <tr key={tier.id} className="border-t border-[var(--color-border-default)]">- <td className="px-3 py-2 text-[var(--color-text-secondary)]">{tier.label}</td>- {kinds.map((k) => {- const c = counts[tier.id]?.[k] ?? 0;- const intensity = max > 0 ? c / max : 0;- // Heat scales the fill alpha; the hue comes from the token for- // each tier (error → warning → muted) via color-mix.- const tierToken =- tier.id === "high"- ? "var(--color-error)"- : tier.id === "medium"- ? "var(--color-warning)"- : "var(--color-text-tertiary)";- const alphaPct =- tier.id === "high"- ? Math.round((0.12 + intensity * 0.55) * 100)- : tier.id === "medium"- ? Math.round((0.1 + intensity * 0.5) * 100)- : Math.round((0.08 + intensity * 0.4) * 100);- const bg =- c === 0- ? "transparent"- : `color-mix(in srgb, ${tierToken} ${alphaPct}%, transparent)`;- return (- <td- key={k}- className="px-2 py-2 text-right tabular-nums"- style={{ backgroundColor: bg }}- title={`${c} ${KIND_LABELS[k] ?? k} at ${tier.label}`}- >- {c || ""}- </td>- );- })}- </tr>- ))}- </tbody>- </table>- </div>- );-}diff --git a/packages/ui/src/dead-code/findings-table.tsx b/packages/ui/src/dead-code/findings-table.tsxindex 9b041bbf0..00b2ff5f3 100644--- a/packages/ui/src/dead-code/findings-table.tsx+++ b/packages/ui/src/dead-code/findings-table.tsx@@ -3,25 +3,18 @@import { useMemo, useState } from "react";import { Search } from "lucide-react";import { toast } from "sonner";-import { Tabs, TabsList, TabsTrigger, TabsContent } from "../ui/tabs";+import { Tabs, ScrollableTabsList, TabsTrigger, TabsContent } from "../ui/tabs";import { Button } from "../ui/button";import { Input } from "../ui/input";-import { Slider } from "../ui/slider";-import { Switch } from "../ui/switch";+import { Segmented } from "../shared/segmented";import { TableSkeleton } from "../shared/loading-skeletons";import { ConfirmDialog } from "../ui/confirm-dialog";import { EmptyState } from "../shared/empty-state";import { ResponsiveTable, type ResponsiveColumn } from "../shared/responsive-table";import { toFriendlyMessage } from "../lib/errors";import { AiPromptButton } from "../health/ai-prompt-button";-import { formatDateTime, formatRelativeTimeOrNull } from "../lib/format";-import {- FindingIdentity,- FindingConfidence,- FindingSafety,- FindingRowActions,- DEAD_CODE_STATUS_LABELS,-} from "./finding-cells";+import { formatDateTime, formatNumber, formatRelativeTimeOrNull } from "../lib/format";+import { FindingIdentity, FindingConfidence, FindingRowActions } from "./finding-cells";import {DEAD_CODE_CONFIDENCE,type DeadCodeFinding,@@ -35,25 +28,41 @@ import {* card and the breakdown grid were counting all along.*/const KIND_LABELS: Record<string, string> = {- unreachable_file: "Unreachable Files",- unused_export: "Unused Exports",- unused_internal: "Unused Internals",- zombie_package: "Zombie Packages",+ unreachable_file: "Unreachable files",+ unused_export: "Unused exports",+ unused_internal: "Unused internals",+ zombie_package: "Zombie packages",};const KIND_ORDER = Object.keys(KIND_LABELS);-/** "unused_internal" -> "Unused Internals" for kinds we have no name for. */+/** "some_future_kind" -> "Some future kind" for kinds we have no name for. */function labelForKind(kind: string): string {const known = KIND_LABELS[kind];if (known) return known;- return kind- .split(/[_\-\s]+/)- .filter(Boolean)- .map((w) => w.charAt(0).toUpperCase() + w.slice(1))- .join(" ");+ const words = kind.split(/[_\-\s]+/).filter(Boolean).join(" ");+ return words.charAt(0).toUpperCase() + words.slice(1);}+/** Copy for a status slice with nothing in it. Neutral: an empty review list is not news. */+const EMPTY_STATUS_COPY: Record<DeadCodeStatus, { title: string; description: string }> = {+ open: { title: "No open findings", description: "Nothing is waiting for review." },+ acknowledged: {+ title: "No acknowledged findings",+ description: "Acknowledge a finding to keep it on record without it counting as open.",+ },+ resolved: {+ title: "No resolved findings",+ description: "Findings you resolve land here, where you can reopen them.",+ },+ false_positive: {+ title: "No findings marked as false positive",+ description: "Mark a finding as a false positive to take it off the open list.",+ },+};++type ConfidenceScope = "all" | "high";+type SortKey = "path" | "confidence" | "owner" | "lines" | "last_commit_at";/** Sort value per column; strings compare with localeCompare, numbers subtract. */@@ -100,8 +109,8 @@ export interface FindingsTableProps {/*** Canonical interactive dead-code table: kind tabs, a search box, sortable- * columns, a confidence slider (the single confidence control for the spine),- * cleanup-ready filter, bulk resolve, and per-row status actions.+ * columns, one confidence control (all or high only), bulk resolve, and+ * per-row status actions.** Built on the shared `ResponsiveTable` so it collapses to stacked cards on* small screens and windows its rows — the fetch is capped at 500, which is@@ -122,10 +131,9 @@ export function FindingsTable({isLoading,}: FindingsTableProps) {const [activeTab, setActiveTab] = useState<string | null>(null);- // The slider floor is the server's own `min_confidence` default (0.4, derived from- // RISK_CAP_CONFIDENCE in risk_factors.py): nothing below it is ever fetched.- const [minConfidence, setMinConfidence] = useState<number>(DEAD_CODE_CONFIDENCE.MEDIUM);- const [safeOnly, setSafeOnly] = useState(false);+ // "High" is the deletion-ready floor (SAFE_CONFIDENCE_THRESHOLD); "all" is+ // whatever the server sent, which already stops at its own 0.4 floor.+ const [scope, setScope] = useState<ConfidenceScope>("all");const [query, setQuery] = useState("");const [sortKey, setSortKey] = useState<SortKey>("confidence");const [sortOrder, setSortOrder] = useState<"asc" | "desc">("desc");@@ -134,7 +142,7 @@ export function FindingsTable({const [bulkConfirmOpen, setBulkConfirmOpen] = useState(false);// Tabs come from the unfiltered slice so the set stays put while the- // confidence slider empties a bucket, instead of tabs appearing and+ // confidence filter empties a bucket, instead of tabs appearing and// vanishing under the pointer.const tabs = useMemo(() => {const present = new Set(findings.map((f) => f.kind));@@ -148,8 +156,7 @@ export function FindingsTable({const buckets: Record<string, DeadCodeFinding[]> = {};for (const t of tabs) buckets[t.value] = [];for (const f of findings) {- if (f.confidence < minConfidence) continue;- if (safeOnly && !f.safe_to_delete) continue;+ if (scope === "high" && f.confidence < DEAD_CODE_CONFIDENCE.HIGH) continue;if (needle &&!f.file_path.toLowerCase().includes(needle) &&@@ -162,7 +169,7 @@ export function FindingsTable({buckets[f.kind]?.push(f);}return buckets;- }, [findings, tabs, minConfidence, safeOnly, query]);+ }, [findings, tabs, scope, query]);// The active tab can disappear when the slice changes (a refetch, a resolved// last row); fall back to the first tab rather than rendering nothing.@@ -197,8 +204,8 @@ export function FindingsTable({setSortOrder(key === "path" || key === "owner" ? "asc" : "desc");};- // Selection is scoped to what is on screen. Without this, raising the- // confidence slider after selecting rows would resolve findings the user can+ // Selection is scoped to what is on screen. Without this, narrowing the+ // confidence filter after selecting rows would resolve findings the user can// no longer see.const visibleSelected = useMemo(() => {const visible = new Set(current.map((f) => f.id));@@ -222,12 +229,21 @@ export function FindingsTable({};const resetFilters = () => {- setMinConfidence(DEAD_CODE_CONFIDENCE.MEDIUM);- setSafeOnly(false);+ setScope("all");setQuery("");};- const filtersActive = minConfidence > DEAD_CODE_CONFIDENCE.MEDIUM || safeOnly || query.trim() !== "";+ // Mark whichever safety group is the minority, so the mark stays an exception.+ const safeMark = useMemo(+ () => (findings.filter((f) => f.safe_to_delete).length * 2 < findings.length ? "safe" : "review"),+ [findings],+ );++ // Rows in the active tab that the filters are hiding, for the filtered state.+ const hiddenInTab = useMemo(+ () => (effectiveTab ? findings.filter((f) => f.kind === effectiveTab).length : 0),+ [findings, effectiveTab],+ );const resolveSelected = async () => {if (!onBulkResolve) return;@@ -294,6 +310,7 @@ export function FindingsTable({finding={f}href={fileHref?.(f.file_path)}onNavigate={onNavigate}+ mark={safeMark}/>),mobileRender: (f) => (@@ -303,6 +320,7 @@ export function FindingsTable({finding={f}href={fileHref?.(f.file_path)}onNavigate={onNavigate}+ mark={safeMark}/></span>),@@ -313,6 +331,7 @@ export function FindingsTable({mobileLabel: "Confidence",sortable: true,headerClassName: "w-24",+ align: "right",render: (f) => <FindingConfidence finding={f} />,},{@@ -338,14 +357,14 @@ export function FindingsTable({headerClassName: "w-28",render: (f) => (<span- className="block text-xs tabular-nums text-[var(--color-text-tertiary)]"+ className="block font-mono text-xs tabular-nums text-[var(--color-text-tertiary)]"title={f.last_commit_at ? formatDateTime(f.last_commit_at) : undefined}>{formatRelativeTimeOrNull(f.last_commit_at)}{/* Recent churn is why a finding scores low; saying so makes theconfidence number legible instead of arbitrary. */}{f.commit_count_90d ? (- <span className="block text-2xs text-[var(--color-text-tertiary)]">+ <span className="block text-xs text-[var(--color-text-tertiary)]">{f.commit_count_90d} commit{f.commit_count_90d === 1 ? "" : "s"}/90d</span>) : null}@@ -360,19 +379,11 @@ export function FindingsTable({align: "right",headerClassName: "w-16",render: (f) => (- <span className="text-xs tabular-nums text-[var(--color-text-tertiary)]">{f.lines ?? "—"}</span>+ <span className="font-mono text-xs tabular-nums text-[var(--color-text-secondary)]">+ {f.lines == null ? "—" : formatNumber(f.lines)}+ </span>),},- {- key: "safety",- header: "Safety",- mobileLabel: "Safety",- // The badge's tooltip is the only place risk_factors surface, so keep- // it on tablet widths where the old markup showed it.- priority: 2,- headerClassName: "w-20",- render: (f) => <FindingSafety finding={f} />,- },{key: "actions",header: <span className="sr-only">Actions</span>,@@ -405,6 +416,7 @@ export function FindingsTable({onGeneratePrompt,onPatch,current,+ safeMark,]);const openFile =@@ -414,39 +426,35 @@ export function FindingsTable({return (<div className="space-y-4">- {/* Controls — the confidence slider is the only confidence axis. */}- <div className="flex flex-wrap items-center gap-4">- <div className="relative">+ <div className="flex flex-wrap items-center gap-x-4 gap-y-3">+ <div className="relative w-full sm:w-72"><Search className="absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-[var(--color-text-tertiary)]" /><Inputvalue={query}onChange={(e) => setQuery(e.target.value)}placeholder="Search path, symbol, owner, reason…"aria-label="Search findings"- className="h-8 w-full pl-8 text-xs sm:w-72"+ className="h-8 w-full pl-8 text-xs"/></div><div className="flex items-center gap-2">- {/* A live value readout, not a <label>: the thing it describes is a- Radix span with role="slider", which htmlFor cannot reach. The- accessible name rides on the thumb's aria-label instead. */}- <span className="text-xs text-[var(--color-text-secondary)]">- Min confidence: {Math.round(minConfidence * 100)}%+ <span aria-hidden className="text-xs text-[var(--color-text-secondary)]">+ Confidence</span>- <Slider- min={DEAD_CODE_CONFIDENCE.MEDIUM}- max={1}- step={0.05}- value={[minConfidence]}- onValueChange={([v]) => setMinConfidence(v ?? DEAD_CODE_CONFIDENCE.MEDIUM)}- aria-label="Minimum confidence"- className="w-28"+ <Segmented<ConfidenceScope>+ label="Confidence"+ value={scope}+ onChange={setScope}+ options={[+ { value: "all", label: "All" },+ {+ value: "high",+ label: "High only",+ hint: `${Math.round(DEAD_CODE_CONFIDENCE.HIGH * 100)}% or higher, the deletion-ready floor`,+ },+ ]}/></div>- <label className="flex cursor-pointer select-none items-center gap-1.5 text-xs text-[var(--color-text-secondary)]">- <Switch checked={safeOnly} onCheckedChange={setSafeOnly} />- Cleanup-ready only- </label>{/* Bulk resolve only makes sense on findings that are still open. */}{onBulkResolve && status === "open" && selectedCount > 0 && (@@ -455,7 +463,7 @@ export function FindingsTable({variant="outline"disabled={bulkPending}onClick={() => setBulkConfirmOpen(true)}- className="text-[var(--color-success)] border-[var(--color-success)]/30 hover:bg-[var(--color-success)]/10"+ className="h-8">{bulkPending ? "Resolving…" : `Resolve ${selectedCount} selected`}</Button>@@ -481,10 +489,7 @@ export function FindingsTable({{isLoading && findings.length === 0 ? (<TableSkeleton className="mt-2" />) : tabs.length === 0 ? (- <EmptyState- title="No findings"- description={`No ${DEAD_CODE_STATUS_LABELS[status].toLowerCase()} dead-code findings for this repository.`}- />+ <EmptyState {...EMPTY_STATUS_COPY[status]} />) : (<Tabs// Non-null in this branch: tabs is non-empty, so effectiveTab resolved.@@ -496,18 +501,18 @@ export function FindingsTable({setSelected(new Set());}}>- <TabsList>+ <ScrollableTabsList>{tabs.map((t) => (<TabsTrigger key={t.value} value={t.value}>{t.label}{(byKind[t.value]?.length ?? 0) > 0 && (- <span className="ml-1.5 text-xs text-[var(--color-text-tertiary)]">- {byKind[t.value]?.length}+ <span className="ml-1.5 font-mono text-xs tabular-nums text-[var(--color-text-tertiary)]">+ {formatNumber(byKind[t.value]?.length ?? 0)}</span>)}</TabsTrigger>))}- </TabsList>+ </ScrollableTabsList>{/* One content panel for the active tab only. Rendering a panel per taband filling each with the *active* tab's rows happened to work@@ -526,20 +531,18 @@ export function FindingsTable({virtualize={{ estimateRowHeight: 56, estimateCardHeight: 96 }}// The hover class the primitive applies is a different Tailwind// variant, so it survives the merge and would blank the selected- // tint the moment the pointer lands on a selected row.+ // ground the moment the pointer lands on a selected row.rowClassName={(f) =>selected.has(f.id)- ? "bg-[var(--color-accent-muted)] hover:bg-[var(--color-accent-muted)]"+ ? "bg-[var(--color-bg-selected)] hover:bg-[var(--color-bg-selected-hover)]": undefined}{...(openFile ? { onRowClick: openFile } : {})}empty={<EmptyState- title="No findings"- description="No findings in this category with the current filters."- {...(filtersActive- ? { action: { label: "Reset filters", onClick: resetFilters } }- : {})}+ tone="filtered"+ title={`${formatNumber(hiddenInTab)} finding${hiddenInTab === 1 ? "" : "s"} hidden by the current filters`}+ action={{ label: "Reset filters", onClick: resetFilters }}/>}/>diff --git a/packages/ui/src/dead-code/index.ts b/packages/ui/src/dead-code/index.tsindex b9bf5370b..43456474c 100644--- a/packages/ui/src/dead-code/index.ts+++ b/packages/ui/src/dead-code/index.ts@@ -1,7 +1,5 @@export * from "./dead-code-lede";export * from "./safe-to-delete-pile";-export * from "./owner-leaderboard";-export * from "./findings-breakdown-grid";export * from "./findings-table";export * from "./finding-cells";export * from "./dead-code-adapter";diff --git a/packages/ui/src/dead-code/owner-leaderboard.tsx b/packages/ui/src/dead-code/owner-leaderboard.tsxdeleted file mode 100644index 8af8d0371..000000000--- a/packages/ui/src/dead-code/owner-leaderboard.tsx+++ /dev/null@@ -1,98 +0,0 @@-"use client";--import * as React from "react";-import { EmptyState } from "../shared/empty-state";-import { cn } from "../lib/cn";--export interface OwnerLeaderboardFinding {- primary_owner: string | null;- lines: number | null;- safe_to_delete?: boolean;-}--interface OwnerLeaderboardProps {- findings: OwnerLeaderboardFinding[];- /** Maximum bars to render. Default 8. */- topN?: number;- /** Only count safe_to_delete findings. */- safeOnly?: boolean;- className?: string;- onSelect?: (owner: string) => void;-}--/**- * Bar chart of dead-code lines owned per primary contributor — shows who has- * the most cleanup leverage. Renders inline (no recharts dep) so the chart- * stays cheap and resilient to data shape.- */-export function OwnerLeaderboard({- findings,- topN = 8,- safeOnly = false,- className,- onSelect,-}: OwnerLeaderboardProps) {- const tallies = React.useMemo(() => {- const map = new Map<string, { lines: number; count: number }>();- for (const f of findings) {- if (safeOnly && !f.safe_to_delete) continue;- const owner = f.primary_owner?.trim() || "Unowned";- const prev = map.get(owner) ?? { lines: 0, count: 0 };- prev.lines += f.lines ?? 0;- prev.count += 1;- map.set(owner, prev);- }- return Array.from(map.entries())- .map(([owner, v]) => ({ owner, ...v }))- .sort((a, b) => b.lines - a.lines)- .slice(0, topN);- }, [findings, safeOnly, topN]);-- const max = tallies[0]?.lines ?? 0;-- if (tallies.length === 0) {- return (- <EmptyState- title="No owner attribution yet"- description="Run the analysis to attribute dead code to its primary contributors."- {...(className ? { className } : {})}- />- );- }-- return (- <ul className={cn("space-y-2", className)}>- {tallies.map((t) => {- const widthPct = max > 0 ? Math.max((t.lines / max) * 100, 4) : 0;- const Tag = onSelect ? "button" : "div";- return (- <li key={t.owner}>- <Tag- type={onSelect ? "button" : undefined}- onClick={onSelect ? () => onSelect(t.owner) : undefined}- className={cn(- "block w-full text-left",- onSelect && "transition hover:opacity-90",- )}- >- <div className="flex items-baseline justify-between gap-3 text-xs">- <span className="truncate text-[var(--color-text-secondary)]" title={t.owner}>- {t.owner}- </span>- <span className="shrink-0 font-mono tabular-nums text-[var(--color-text-tertiary)]">- {t.lines.toLocaleString()} lines · {t.count}- </span>- </div>- <div className="mt-1 h-1.5 w-full overflow-hidden rounded-full bg-[var(--color-bg-elevated)]">- <div- className="h-full rounded-full bg-[var(--color-error)]/60 transition-[width] duration-300"- style={{ width: `${widthPct}%` }}- />- </div>- </Tag>- </li>- );- })}- </ul>- );-}diff --git a/packages/ui/src/dead-code/safe-to-delete-pile.tsx b/packages/ui/src/dead-code/safe-to-delete-pile.tsxindex b3c3eb2c8..00b367ac5 100644--- a/packages/ui/src/dead-code/safe-to-delete-pile.tsx+++ b/packages/ui/src/dead-code/safe-to-delete-pile.tsx@@ -5,6 +5,7 @@ import { ArrowRight } from "lucide-react";import { AiPromptButton } from "../health/ai-prompt-button";import { OverviewSection } from "../overview/section";import { cn } from "../lib/cn";+import { formatNumber } from "../lib/format";export interface SafeToDeletePileFinding {id: string;@@ -16,8 +17,6 @@ export interface SafeToDeletePileFinding {interface SafeToDeletePileProps {findings: SafeToDeletePileFinding[];- /** Total lines reclaimable across all safe findings (may differ if filtered). */- reclaimableLines?: number;/** Optional CTA — invoked with the list of finding ids. */onPropose?: (findingIds: string[]) => void;/**@@ -29,27 +28,17 @@ interface SafeToDeletePileProps {}/**- * The "what do I delete" list: files carrying high-confidence findings, biggest- * pile first.- *- * It used to be a red gradient card with a trash icon in a tinted tile and the- * reclaimable line count set at 3xl. The lede above now leads with that same- * figure, so repeating it here at near-hero size gave the page two headlines- * that agree, and the red ground made a list of file paths read as a warning- * about the files rather than an offer to remove them. Rule 9: the loudest- * thing on screen should be the thing that responds, and what responds here is- * the row and the prompt button.+ * The "what do I delete" list: files carrying deletion-ready findings, biggest+ * pile first, on quiet hairline rows. The reclaimable line total is the lede's+ * figure, so this section does not repeat it; what responds here is the row+ * and the prompt button.*/export function SafeToDeletePile({findings,- reclaimableLines,onPropose,onSelect,className,}: SafeToDeletePileProps) {- const lines =- reclaimableLines ??- findings.reduce((sum, f) => sum + (f.lines ?? 0), 0);const files = new Set(findings.map((f) => f.file_path)).size;// Roll findings up by file so the preview list shows distinct files@@ -89,7 +78,7 @@ export function SafeToDeletePile({return (<OverviewSectiontitle="Safe to delete"- description={`${lines.toLocaleString()} lines across ${files.toLocaleString()} file${files === 1 ? "" : "s"} (${findings.length.toLocaleString()} finding${findings.length === 1 ? "" : "s"}) come back high confidence, with no caller we can find. Read the diff before you delete, then hand the rest to an agent.`}+ description={`${formatNumber(findings.length)} high-confidence finding${findings.length === 1 ? "" : "s"} in ${formatNumber(files)} file${files === 1 ? "" : "s"}, with no runtime-load risk. Read the diff before you delete.`}{...(className ? { className } : {})}action={onPropose && findings.length > 0 ? (@@ -116,7 +105,7 @@ export function SafeToDeletePile({type={onSelect ? "button" : undefined}onClick={onSelect ? () => onSelect(g.representative) : undefined}className={cn(- "flex w-full items-center justify-between gap-3 py-2.5 text-left text-xs",+ "flex min-h-9 w-full items-center justify-between gap-3 py-2 text-left text-xs",onSelect && "hover:bg-[var(--color-bg-elevated)]",)}>@@ -127,12 +116,12 @@ export function SafeToDeletePile({{g.file_path}{g.finding_count > 1 && (<span className="ml-1.5 text-[var(--color-text-tertiary)]">- ({g.finding_count} findings)+ ({formatNumber(g.finding_count)} findings)</span>)}</span><span className="shrink-0 font-mono tabular-nums text-[var(--color-text-tertiary)]">- {g.lines.toLocaleString()} lines+ {formatNumber(g.lines)} lines{onSelect && <ArrowRight className="ml-1 inline h-3 w-3" />}</span></Tag>@@ -143,7 +132,7 @@ export function SafeToDeletePile({)}{moreFiles > 0 && (<p className="text-xs text-[var(--color-text-tertiary)]">- {moreFiles.toLocaleString()} more file{moreFiles === 1 ? "" : "s"} in the+ {formatNumber(moreFiles)} more file{moreFiles === 1 ? "" : "s"} in thefindings table below.</p>)}diff --git a/packages/web/src/components/risk/dead-code-tab.tsx b/packages/web/src/components/risk/dead-code-tab.tsxindex 47f77f689..c4bfe9e42 100644--- a/packages/web/src/components/risk/dead-code-tab.tsx+++ b/packages/web/src/components/risk/dead-code-tab.tsx@@ -2,9 +2,9 @@/*** Dead Code host — binds the shared {@link DeadCodeView} to web's `/api`- * client and `/repos/:id` routing. The composition (safe-to-delete pile,- * cluster rollups, drill-down table, patch/undo, bulk resolve, Propose- * cleanup, Re-analyze) lives in `@repowise-dev/ui/dead-code`; this file only+ * client and `/repos/:id` routing. The composition (lede, safe-to-delete+ * list, findings table, patch/undo, bulk resolve, Propose cleanup,+ * Re-analyze) lives in `@repowise-dev/ui/dead-code`; this file only* injects the app-specific pieces so web and hosted render the same view.*/