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(health): make the Coverage tab a Tests tab that answers without a report (#1758)
Raghav Chamadiyaa06bebcf9dce
diff --git a/packages/api-client/src/code-health.ts b/packages/api-client/src/code-health.tsindex 29f915724..c1ca20adb 100644--- a/packages/api-client/src/code-health.ts+++ b/packages/api-client/src/code-health.ts@@ -10,6 +10,7 @@ import type {HealthFilesResponse,HealthFinding,HealthCoverageResponse,+ TestsReachingFile,HealthFileBreakdownResponse,HealthOverviewResponse,HealthTrendResponse,@@ -104,7 +105,12 @@ export async function updateFindingStatus(export async function getHealthCoverage(repoId: string,- opts?: { file_path?: string; limit?: number; module_limit?: number },+ opts?: {+ file_path?: string;+ limit?: number;+ module_limit?: number;+ include_inferred?: boolean;+ },): Promise<HealthCoverageResponse> {return apiGet<HealthCoverageResponse>(`/api/repos/${repoId}/health/coverage`,@@ -112,6 +118,16 @@ export async function getHealthCoverage();}+export async function getTestsReaching(+ repoId: string,+ filePath: string,+): Promise<TestsReachingFile> {+ return apiGet<TestsReachingFile>(+ `/api/repos/${repoId}/health/tests-reaching`,+ { file_path: filePath },+ );+}+export async function getRefactoringTargets(repoId: string,opts?: RefactoringQuery,diff --git a/packages/server/src/repowise/server/routers/code_health/coverage_routes.py b/packages/server/src/repowise/server/routers/code_health/coverage_routes.pyindex bb5ab30f3..4210f9c68 100644--- a/packages/server/src/repowise/server/routers/code_health/coverage_routes.py+++ b/packages/server/src/repowise/server/routers/code_health/coverage_routes.py@@ -56,6 +56,7 @@ async def health_coverage(file_path: str | None = Query(None),limit: int = Query(500, ge=1, le=5000),module_limit: int = Query(1000, ge=0, le=5000),+ include_inferred: bool = Query(True),session: AsyncSession = Depends(get_db_session),) -> dict:"""Coverage summary + per-file rows.@@ -73,6 +74,14 @@ async def health_coverage(``modules_total`` is always the full count, so a trimmed rollup can never beread as the whole repo. ``module_limit=0`` returns none of them, for callersthat want the summary and nothing else.++ ``include_inferred=false`` declines the graph-inferred fallback. It is not a+ third cap: the fallback costs a read of every call edge in the repository+ plus every health metric, which is the right price for the tab and the wrong+ one for the tab *badge*, whose whole point is that it asks for one file row+ and no modules. A declined response omits ``basis`` rather than reporting+ ``"none"`` - the graph was not consulted, which is not the same as the graph+ having nothing to say."""repo = await crud.get_repository(session, repo_id)if repo is None:@@ -88,6 +97,13 @@ async def health_coverage(if not all_rows:# No report was ever ingested. The graph can still answer "does a test# reach this", so answer that instead of an empty measured shape.+ if not include_inferred:+ return {+ "summary": _empty_summary(),+ "files": [],+ "modules": [],+ "modules_total": 0,+ }return await _inferred_coverage(session, repo_id, limit)summary = await crud.get_coverage_summary(session, repo_id, rows=all_rows)if summary.get("ingested_at") is not None:diff --git a/packages/types/src/health.ts b/packages/types/src/health.tsindex c2cc5ab78..a948bdf22 100644--- a/packages/types/src/health.ts+++ b/packages/types/src/health.ts@@ -607,9 +607,11 @@ export interface HealthCoverageResponse {*/modules_total?: number;/**- * Which signal answered. Optional because the hosted backend does not send it- * yet; absent reads as `measured`, which is what every caller assumed before- * this field existed.+ * Which signal answered, when the response determined one. Absent means it did+ * not: an older backend that predates the field, or a caller that passed+ * `include_inferred=false` and so never consulted the graph. That is why a+ * declined response omits it rather than reporting `"none"` — not consulted+ * and nothing to say are different states.*/basis?: CoverageBasis;/**diff --git a/packages/ui/__tests__/health/inferred-tests.test.tsx b/packages/ui/__tests__/health/inferred-tests.test.tsxnew file mode 100644index 000000000..e90b80b77--- /dev/null+++ b/packages/ui/__tests__/health/inferred-tests.test.tsx@@ -0,0 +1,263 @@+/**+ * The Tests tab on the inferred basis.+ *+ * These are mostly *negative* assertions, and deliberately so. The graph-inferred+ * test map over-claims by construction and carries no line attribution, so the+ * failure mode this tab has to be protected from is not "renders wrong" but+ * "renders convincingly as a measurement": a percentage, a progress bar, or a+ * health-band colour on data that has no band. Each of those is one convenience+ * change away at any time, so each is asserted directly.+ */++import { describe, it, expect, vi } from "vitest";+import { render, screen, waitFor } from "@testing-library/react";+import type {+ HealthCoverageResponse,+ InferredTestMap,+ ReachedFileRow,+ TestsReachingFile,+} from "@repowise-dev/types/health";++import { RiskCoverageScatter } from "../../src/health/risk-coverage-scatter.js";+import { InferredTestsView } from "../../src/health/inferred-tests-view.js";+import { TestsReachingList } from "../../src/health/tests-reaching-list.js";++function row(+ partial: Partial<ReachedFileRow> & { file_path: string },+): ReachedFileRow {+ return { reached: false, health_score: 5, nloc: 100, ...partial };+}++function response(map: Partial<InferredTestMap> = {}): HealthCoverageResponse {+ const files = map.files ?? [+ row({ file_path: "src/a.py", reached: true, health_score: 8 }),+ row({ file_path: "src/b.py", reached: false, health_score: 3 }),+ ];+ return {+ basis: "inferred",+ summary: {+ file_count: 0,+ covered_lines: 0,+ total_lines: 0,+ line_coverage_pct: null,+ branch_coverage_pct: null,+ source_format: null,+ ingested_at: null,+ ingested_commit_sha: null,+ },+ files: [],+ modules: [],+ modules_total: 0,+ inferred: {+ files,+ files_total: files.length,+ files_reached: files.filter((f) => f.reached).length,+ files_not_reached: files.filter((f) => !f.reached).length,+ test_file_count: 12,+ ...map,+ },+ };+}++describe("RiskCoverageScatter, inferred basis", () => {+ const points = [+ { file_path: "src/a.py", health_score: 8, line_coverage_pct: null, nloc: 50, reached: true },+ { file_path: "src/b.py", health_score: 3, line_coverage_pct: null, nloc: 90, reached: false },+ ];++ it("names the two columns instead of a percentage axis", () => {+ render(<RiskCoverageScatter basis="inferred" points={points} />);++ expect(screen.getByText("no test reaches it")).toBeInTheDocument();+ expect(screen.getByText("a test reaches it")).toBeInTheDocument();+ // The measured axis ticks must not survive the collapse: a "%" anywhere on+ // this chart is the claim the basis is not allowed to make.+ expect(screen.queryByText("50%")).not.toBeInTheDocument();+ expect(screen.queryByText("100%")).not.toBeInTheDocument();+ });++ it("keeps the measured axis when no basis is passed", () => {+ render(<RiskCoverageScatter points={[{ ...points[0]!, line_coverage_pct: 80 }]} />);++ expect(screen.getByText("100%")).toBeInTheDocument();+ expect(screen.queryByText("a test reaches it")).not.toBeInTheDocument();+ });++ it("paints the dots by column in the sunset pair, never the health ramp", () => {+ // Health is already the Y axis, so a health-banded dot would re-say its own+ // position and leave nothing carrying the split. It would also paint a+ // static reading in the colours reserved for measured health bands.+ const { container } = render(+ <RiskCoverageScatter basis="inferred" points={points} />,+ );+ const fillOf = (path: string) =>+ container.querySelector(`circle[data-file="${path}"]`)?.getAttribute("fill");++ expect(fillOf("src/a.py")).toBe("var(--color-accent-fill)");+ expect(fillOf("src/b.py")).toBe("var(--color-accent-secondary)");+ // src/b.py scores 3, which on the measured chart would be the error band.+ expect(container.innerHTML).not.toContain("--color-error");+ expect(container.innerHTML).not.toContain("--color-success");+ });++ it("separates the columns and keeps each file's position stable across renders", () => {+ // The jitter is seeded off the path precisely so a re-render does not move+ // the field. Random jitter would pass a single-render test and fail a user.+ const { container, rerender } = render(+ <RiskCoverageScatter basis="inferred" points={points} />,+ );+ const cxOf = (path: string) =>+ Number(+ container.querySelector(`circle[data-file="${path}"]`)?.getAttribute("cx"),+ );++ const firstA = cxOf("src/a.py");+ const firstB = cxOf("src/b.py");+ expect(firstA).toBeGreaterThan(firstB);++ rerender(<RiskCoverageScatter basis="inferred" points={[...points]} />);++ expect(cxOf("src/a.py")).toBe(firstA);+ expect(cxOf("src/b.py")).toBe(firstB);+ });+});++describe("InferredTestsView", () => {+ it("leads with the count of risky files nothing reaches", () => {+ render(+ <InferredTestsView+ data={response()}+ untestedFindings={[]}+ onOpenFile={vi.fn()}+ />,+ );++ expect(screen.getByText("Files nothing tests")).toBeInTheDocument();+ // src/b.py alone: unreached and under the at-risk score. src/a.py is+ // reached, and an unreached file scoring well is not the headline. The+ // singular unit is the assertion — it can only render from a count of one.+ expect(screen.getByText("risky file")).toBeInTheDocument();+ });++ it("renders no percentage and no progress bar anywhere", () => {+ const { container } = render(+ <InferredTestsView+ data={response()}+ untestedFindings={[]}+ onOpenFile={vi.fn()}+ />,+ );++ expect(container.textContent).not.toMatch(/\d+(\.\d+)?%/);+ // A bar is a percentage drawn. The measured tab renders one per row; this+ // one must not, whatever it is styled from.+ expect(container.querySelector('[role="progressbar"]')).toBeNull();+ expect(container.querySelector(".rounded-full")).toBeNull();+ });++ it("states the split as two counts against the repository total", () => {+ render(+ <InferredTestsView+ data={response()}+ untestedFindings={[]}+ onOpenFile={vi.fn()}+ />,+ );++ // Both sides named, and the denominator is files rather than lines: there+ // is no line-level evidence behind this basis to count.+ expect(screen.getByText("1 of 2 files")).toBeInTheDocument();+ expect(screen.getByText(/Nothing reaches the other 1/)).toBeInTheDocument();+ });++ it("says the ranking was trimmed rather than letting it read as the repo", () => {+ const data = response({ files_total: 900 });+ render(+ <InferredTestsView data={data} untestedFindings={[]} onOpenFile={vi.fn()} />,+ );++ expect(screen.getByText(/of 900 files, capped/)).toBeInTheDocument();+ });++ it("frames a report as added resolution, not as a prerequisite", () => {+ render(+ <InferredTestsView+ data={response()}+ untestedFindings={[]}+ onOpenFile={vi.fn()}+ />,+ );++ expect(screen.getByText(/Sharpen this with a coverage report/)).toBeInTheDocument();+ expect(screen.getByText(/needs no setup/)).toBeInTheDocument();+ // The old dead-end line, which stopped being true once the graph answered.+ expect(screen.queryByText(/Nothing is inferred/)).not.toBeInTheDocument();+ });+});++describe("TestsReachingList", () => {+ const answer = (partial: Partial<TestsReachingFile> = {}): TestsReachingFile => ({+ file_path: "src/a.py",+ basis: "inferred",+ reached: true,+ tests: ["tests/test_a.py", "tests/test_b.py"],+ via: "call-graph",+ ...partial,+ });++ it("states the relationship and names the tests", async () => {+ render(+ <TestsReachingList+ filePath="src/a.py"+ cacheKey="k1"+ fetcher={async () => answer()}+ />,+ );++ await waitFor(() =>+ expect(screen.getByText("2 test files")).toBeInTheDocument(),+ );+ expect(screen.getByText("tests/test_a.py")).toBeInTheDocument();+ expect(screen.getByText(/run into this file/)).toBeInTheDocument();+ });++ it("says an import-only answer is the weaker claim", async () => {+ render(+ <TestsReachingList+ filePath="src/a.py"+ cacheKey="k2"+ fetcher={async () => answer({ via: "import-graph" })}+ />,+ );++ await waitFor(() =>+ expect(screen.getByText(/import this file/)).toBeInTheDocument(),+ );+ expect(screen.getByText(/without necessarily running any of it/)).toBeInTheDocument();+ });++ it("names the static limits when nothing reaches the file", async () => {+ render(+ <TestsReachingList+ filePath="src/lonely.py"+ cacheKey="k3"+ fetcher={async () => answer({ reached: false, tests: [], via: null })}+ />,+ );++ await waitFor(() =>+ expect(screen.getByText(/No test in the repository calls into this file/)).toBeInTheDocument(),+ );+ // The caveat is the point: a framework hook is invisible to a static walk,+ // and claiming "untested" without saying so would overstate the evidence.+ expect(screen.getByText(/framework hook/)).toBeInTheDocument();+ });++ it("renders nothing when the host has not wired the endpoint", () => {+ const { container } = render(+ <TestsReachingList filePath="src/a.py" cacheKey="k4" />,+ );++ expect(container).toBeEmptyDOMElement();+ });+});diff --git a/packages/ui/src/files/file-coverage-tab.tsx b/packages/ui/src/files/file-coverage-tab.tsxindex d5538b698..3d596beab 100644--- a/packages/ui/src/files/file-coverage-tab.tsx+++ b/packages/ui/src/files/file-coverage-tab.tsx@@ -1,5 +1,4 @@-import { Shield } from "lucide-react";-import { EmptyState } from "../shared/empty-state";+import type { ReactNode } from "react";import { PageLede } from "../shared/page-lede";import { coverageBand } from "../health/tokens";import { formatNumber, formatRelativeTime } from "../lib/format";@@ -14,17 +13,43 @@ interface FileCoverageTabProps {* When absent we fall back to a summary-only view.*/coverageCodeHtml?: string | undefined;+ /**+ * The graph-inferred "which tests reach this file" block, supplied by the host+ * already wrapped. A node rather than a fetcher because the tab bodies are+ * server components; see `buildFilePanels`.+ */+ testsPanel?: ReactNode | undefined;}-export function FileCoverageTab({ coverage, coverageCodeHtml }: FileCoverageTabProps) {+export function FileCoverageTab({+ coverage,+ coverageCodeHtml,+ testsPanel,+}: FileCoverageTabProps) {+ // Rendered on both bases. Without a report it is the whole answer; with one it+ // adds what a coverage report structurally cannot give at file level - the+ // names of the tests, rather than how much of the file ran.+ const reaching = testsPanel ?? null;+if (!coverage) {+ // Not a dead end any more. No report was ingested, and the dependency graph+ // can still name the tests that reach this file, with no setup at all.return (- <EmptyState- titleAs="h2"- icon={<Shield className="h-8 w-8" />}- title="No coverage report ingested"- description="Run `repowise coverage add <report>` with an lcov, cobertura or coverage.py file and line-level coverage appears here."- />+ <div className="flex flex-col gap-6">+ {reaching}+ <FileSection+ title="Line-level coverage"+ description="What a report would add here: which lines of this file your tests actually executed, rather than which tests can reach it."+ >+ <p className="max-w-[62ch] text-[13px] leading-relaxed text-[var(--color-text-secondary)] [text-wrap:pretty]">+ Run your suite with coverage on and hand us the report with{" "}+ <span className="font-mono text-[var(--color-text-primary)]">+ repowise coverage add <report>+ </span>+ . LCOV, Cobertura and coverage.py output all work.+ </p>+ </FileSection>+ </div>);}@@ -77,7 +102,8 @@ export function FileCoverageTab({ coverage, coverageCodeHtml }: FileCoverageTabP. Branch coverage is <Fig>{coverage.branch_coverage_pct.toFixed(1)}%</Fig></>)}- . This is read from your own test run, not inferred.+ . These are the lines your own test run executed, so this figure is+ line-level and exact.</p><p className="mt-2.5">Read from a{" "}@@ -99,6 +125,8 @@ export function FileCoverageTab({ coverage, coverageCodeHtml }: FileCoverageTabP</p></PageLede>+ {reaching ? <div className="mt-6">{reaching}</div> : null}+<FileSectiontitle="Source"description={diff --git a/packages/ui/src/files/file-page-header.tsx b/packages/ui/src/files/file-page-header.tsxindex 6f3581cc9..e9b149257 100644--- a/packages/ui/src/files/file-page-header.tsx+++ b/packages/ui/src/files/file-page-header.tsx@@ -183,7 +183,7 @@ function headerStats(data: FileDetailResponse): RibbonStat[] {}if (coveragePct != null) {stats.push({- label: "Coverage",+ label: "Tests",value: `${coveragePct.toFixed(0)}%`,valueColor: coverageTextColor(coveragePct),});diff --git a/packages/ui/src/files/file-page-panels.tsx b/packages/ui/src/files/file-page-panels.tsxindex 5739c77fb..6597a1330 100644--- a/packages/ui/src/files/file-page-panels.tsx+++ b/packages/ui/src/files/file-page-panels.tsx@@ -26,6 +26,12 @@ export interface BuildFilePanelsOptions {* triage callback — a function cannot cross a server boundary as a prop.*/healthPanel?: ReactNode;+ /**+ * The graph-inferred test list for the Tests tab. Supplied already wrapped by+ * the host for the same reason as `healthPanel`: it fetches on the client, and+ * a fetcher function cannot cross the server boundary as a prop.+ */+ testsPanel?: ReactNode;/*** Router link, forwarded to every tab body that renders one.*@@ -62,6 +68,7 @@ export function buildFilePanels({docSlot,coverageCodeHtml,healthPanel,+ testsPanel,LinkComponent,}: BuildFilePanelsOptions): Partial<Record<FilePageTab, ReactNode>> {const link = LinkComponent ? { LinkComponent } : {};@@ -102,7 +109,11 @@ export function buildFilePanels({/>),coverage: (- <FileCoverageTab coverage={data.coverage} coverageCodeHtml={coverageCodeHtml} />+ <FileCoverageTab+ coverage={data.coverage}+ coverageCodeHtml={coverageCodeHtml}+ testsPanel={testsPanel}+ />),};}diff --git a/packages/ui/src/files/file-page-tabs.ts b/packages/ui/src/files/file-page-tabs.tsindex 2ab3edb99..5593d6ff8 100644--- a/packages/ui/src/files/file-page-tabs.ts+++ b/packages/ui/src/files/file-page-tabs.ts@@ -31,7 +31,7 @@ export const FILE_TAB_LABEL: Record<FilePageTab, string> = {history: "History",decisions: "Decisions",graph: "Dependencies",- coverage: "Coverage",+ coverage: "Tests",};/**@@ -51,7 +51,8 @@ export const FILE_TAB_BLURB: Record<FilePageTab, string> = {history: "What git knows about this file — how often it changes, who changes it, and what moves with it.",decisions: "Architectural decisions recorded against this file.",graph: "Where this file sits in the indexed dependency graph.",- coverage: "Line coverage, once a test report has been ingested for this repository.",+ coverage:+ "Which tests reach this file, read from the dependency graph, plus the lines they executed once a coverage report has been ingested.",};export interface FileTabDef {diff --git a/packages/ui/src/health/code-health-adapter.ts b/packages/ui/src/health/code-health-adapter.tsindex e743d0900..94fc02f6f 100644--- a/packages/ui/src/health/code-health-adapter.ts+++ b/packages/ui/src/health/code-health-adapter.ts@@ -7,6 +7,7 @@ import type {HealthOverviewResponse,RefactoringQuery,RefactoringTargetsResponse,+ TestsReachingFile,} from "@repowise-dev/types/health";/** Subset of the findings list query the shared views need. */@@ -58,8 +59,18 @@ export interface CodeHealthAdapter {file_path?: string;limit?: number;module_limit?: number;+ /** False declines the graph-inferred fallback. For cheap summary reads. */+ include_inferred?: boolean;}): Promise<HealthCoverageResponse>;+ /**+ * Which tests reach one file, per the dependency graph. Optional: a host that+ * has not wired it yet renders no test list rather than an error, which is+ * the same degradation the response types use for a frontend ahead of its+ * backend.+ */+ getTestsReaching?(filePath: string): Promise<TestsReachingFile>;+/** Build an href to a file detail page. */fileHref(path: string): string;/** Build an href to a symbol detail page, or `undefined` if not linkable. */diff --git a/packages/ui/src/health/coverage-lede.tsx b/packages/ui/src/health/coverage-lede.tsxindex d6a104a9f..580b1d86b 100644--- a/packages/ui/src/health/coverage-lede.tsx+++ b/packages/ui/src/health/coverage-lede.tsx@@ -120,9 +120,10 @@ export function CoverageLede({</strong>{" "}across {formatNumber(summary.file_count)} instrumented files{moduleCount > 0 ? ` in ${formatNumber(moduleCount)} directories` : ""}.- {band ? ` We rate that ${band.label.toLowerCase()}.` : ""} Coverage is read- from your own test run, not inferred: nothing here is a guess about which- lines a test would have touched.+ {band ? ` We rate that ${band.label.toLowerCase()}.` : ""} These are the+ lines your own test run executed, so every figure on this tab is+ line-level and exact. Without a report we can still name which tests+ reach which files, but not how much of a file they run.</p><p className="mt-2.5">diff --git a/packages/ui/src/health/coverage-view.tsx b/packages/ui/src/health/coverage-view.tsxindex e7043d818..edceeb432 100644--- a/packages/ui/src/health/coverage-view.tsx+++ b/packages/ui/src/health/coverage-view.tsx@@ -42,6 +42,7 @@ import {type UntestedHotspotEntry,} from "./untested-hotspot-warning";import { RiskCoverageScatter } from "./risk-coverage-scatter";+import { InferredTestsView } from "./inferred-tests-view";import {buildCoverageAiPrompt,type CoverageFilePromptInput,@@ -81,6 +82,16 @@ export function CoverageView({ adapter }: { adapter: CodeHealthAdapter }) {title="Couldn't load coverage data"description="The coverage endpoint returned an error. Try refreshing, or re-run the health pass."/>+ ) : data?.basis === "inferred" && data.inferred ? (+ // No report was ever ingested, and the graph can answer anyway. This+ // branch never renders a measured field: the two bases are separate+ // objects in the payload precisely so one cannot leak into the other's+ // code path.+ <InferredTestsView+ data={data}+ untestedFindings={untestedFindings ?? []}+ onOpenFile={openFilePage}+ />) : !data || data.summary.file_count === 0 ? (<NoCoverageState />) : (@@ -447,21 +458,28 @@ function CoverageBody({}/**- * Says what will fill the page, not that something is missing. The two commands- * are the whole setup, so they are the content rather than a footnote under a- * dashed placeholder box.+ * The last resort: no report, and the graph had nothing to say either — an+ * unindexed repository, or one with no test files at all. When the graph *can*+ * answer, `InferredTestsView` renders instead and the reader never reaches here.+ *+ * It used to be the only thing behind "no coverage", and it claimed "Nothing is+ * inferred: we read the lines your tests really executed" — which stopped being+ * true once the graph could answer, and turned a solved question into a wall.+ * What is left is the honest version: this is genuinely unknown, and here is+ * what would fill it.*/function NoCoverageState() {return (<div className="flex max-w-[62ch] flex-col gap-3"><h2 className="text-base font-semibold text-[var(--color-text-primary)]">- No coverage report ingested yet+ Nothing here can say whether your code is tested</h2><p className="text-[13px] leading-relaxed text-[var(--color-text-secondary)] [text-wrap:pretty]">- Run your test suite with coverage on and hand us the report. This tab then- plots every file by health against coverage, names the files where a gap- actually costs something, and rolls the numbers up per directory. Nothing is- inferred: we read the lines your tests really executed.+ No coverage report has been ingested, and the dependency graph found no+ test files to trace either. Either would fill this tab: a report gives the+ lines your tests executed, and the graph alone can name which tests reach+ which files with no setup at all. Run your suite with coverage on and hand+ us the report.</p><pre className="w-fit overflow-x-auto rounded-md bg-[var(--color-bg-inset)] px-3 py-2 font-mono text-xs text-[var(--color-text-primary)]">pytest --cov --cov-report=lcov{"\n"}diff --git a/packages/ui/src/health/health-file-drawer.tsx b/packages/ui/src/health/health-file-drawer.tsxindex b58a4d580..2c6cc3036 100644--- a/packages/ui/src/health/health-file-drawer.tsx+++ b/packages/ui/src/health/health-file-drawer.tsx@@ -690,6 +690,10 @@ function MetricGrid({ metric }: { metric: HealthDrawerMetric }) {},{ label: "Performance", value: <PillarScore v={metric.performance_score ?? null} /> },{+ // Stays "Coverage" while the tab is renamed to "Tests": this cell is the+ // measured percentage, and a "Tests" cell already sits four rows down+ // carrying the paired-file flag. Two cells named the same thing in one+ // grid is the vocabulary failure the rename exists to avoid.label: "Coverage",value: (<PlainValue>diff --git a/packages/ui/src/health/health-tabs.tsx b/packages/ui/src/health/health-tabs.tsxindex c7ab91a46..99c2d7539 100644--- a/packages/ui/src/health/health-tabs.tsx+++ b/packages/ui/src/health/health-tabs.tsx@@ -25,7 +25,7 @@ export interface HealthTabsProps {const TABS: { key: HealthTabKey; label: string; suffix: string; Icon: React.ComponentType<{ className?: string }> }[] = [{ key: "overview", label: "Overview", suffix: "", Icon: HeartPulse },{ key: "trend", label: "Trend", suffix: "/trend", Icon: TrendingUp },- { key: "coverage", label: "Coverage", suffix: "/coverage", Icon: TestTubeDiagonal },+ { key: "coverage", label: "Tests", suffix: "/coverage", Icon: TestTubeDiagonal },{ key: "refactoring", label: "Refactoring", suffix: "/refactoring-targets", Icon: Wrench },];diff --git a/packages/ui/src/health/index.ts b/packages/ui/src/health/index.tsindex c085ca62f..d666db655 100644--- a/packages/ui/src/health/index.ts+++ b/packages/ui/src/health/index.ts@@ -42,4 +42,6 @@ export * from "./code-health-adapter";export * from "./triage-view";export * from "./findings-view";export * from "./coverage-view";+export * from "./inferred-tests-view";+export * from "./tests-reaching-list";export * from "./trend-view";diff --git a/packages/ui/src/health/inferred-tests-view.tsx b/packages/ui/src/health/inferred-tests-view.tsxnew file mode 100644index 000000000..c5feabf0f--- /dev/null+++ b/packages/ui/src/health/inferred-tests-view.tsx@@ -0,0 +1,265 @@+"use client";++/**+ * The Tests tab on the inferred basis: what the dependency graph knows about+ * which files a test reaches, when no coverage report was ever ingested.+ *+ * This replaces a dead end. The tab used to answer "no coverage report" with+ * setup instructions and the line "Nothing is inferred: we read the lines your+ * tests really executed", which stopped being true the moment the graph could+ * answer the question, and read as the product apologising for something it had+ * just fixed.+ *+ * Three rules run through every figure here, all inherited from the core and+ * none of them negotiable:+ *+ * **No percentage, and no bar.** Reaching is a file-level fact with no line+ * attribution behind it, so a ratio built from it would be a coverage figure the+ * data cannot support. Counts only. That is also why the hero is a small+ * integer rather than "1,074 of 2,185 files reached", which begs for a bar and a+ * bar is a percentage.+ *+ * **No health-band colour on inferred data.** Green, amber and red are reserved+ * for health readouts where they carry a band. Painting "nothing reaches this"+ * red would make a static reading look like a measurement.+ *+ * **A relationship, not a score.** The strongest thing this tab can say is+ * "these six tests run this file", and it says that. The moment it becomes a+ * number on a scale we have rebuilt the confusion both core changes spent all+ * their care avoiding.+ */++import { useMemo, useState } from "react";+import type {+ HealthCoverageResponse,+ HealthFinding,+ InferredTestMap,+} from "@repowise-dev/types/health";++import { OverviewSection } from "../overview/section";+import { PageLede } from "../shared/page-lede";+import { ResponsiveTable, type ResponsiveColumn } from "../shared/responsive-table";+import { ResultsFooter } from "../shared/results-footer";+import { formatNumber } from "../lib/format";++import { RiskCoverageScatter } from "./risk-coverage-scatter";+import { scoreBadgeClass } from "./tokens";++/** Below this, a file nothing reaches is worth leading with. */+const AT_RISK_SCORE = 6;++export function InferredTestsView({+ data,+ untestedFindings,+ onOpenFile,+}: {+ data: HealthCoverageResponse;+ untestedFindings: HealthFinding[];+ onOpenFile: (path: string) => void;+}) {+ const map = data.inferred as InferredTestMap;+ const PAGE = 25;+ const [visible, setVisible] = useState(PAGE);++ const points = useMemo(+ () =>+ map.files+ .filter((f) => f.health_score != null)+ .map((f) => ({+ file_path: f.file_path,+ health_score: f.health_score!,+ line_coverage_pct: null,+ nloc: f.nloc ?? 0,+ reached: f.reached,+ })),+ [map.files],+ );++ // The hero. Scoped to what is actionable rather than to the whole repo: a+ // small integer cannot be misread as coverage, and "files nothing tests" on+ // its own would be a number nobody can act on in one sitting.+ //+ // Prefers the biomarker, which weighs churn and dependents, and falls back to+ // the plain score cut when the health pass has not run.+ const atRisk = useMemo(() => {+ const unreached = new Set(+ map.files.filter((f) => !f.reached).map((f) => f.file_path),+ );+ const flagged = untestedFindings.filter((f) => unreached.has(f.file_path));+ if (flagged.length > 0) return flagged.map((f) => f.file_path);+ return map.files+ .filter(+ (f) => !f.reached && f.health_score != null && f.health_score < AT_RISK_SCORE,+ )+ .map((f) => f.file_path);+ }, [map.files, untestedFindings]);++ const ranked = useMemo(() => {+ const rank = new Map(atRisk.map((p, i) => [p, i]));+ return map.files+ .filter((f) => !f.reached)+ .sort((a, b) => {+ const ra = rank.get(a.file_path);+ const rb = rank.get(b.file_path);+ if (ra != null && rb != null) return ra - rb;+ if (ra != null) return -1;+ if (rb != null) return 1;+ return (a.health_score ?? 10) - (b.health_score ?? 10);+ });+ }, [map.files, atRisk]);++ const trimmed = map.files_total > map.files.length;++ const columns: ResponsiveColumn<(typeof ranked)[number]>[] = [+ {+ key: "file_path",+ header: "File",+ priority: 1,+ render: (f) => (+ <span+ className="block truncate font-mono text-xs text-[var(--color-text-primary)]"+ title={f.file_path}+ >+ {f.file_path}+ </span>+ ),+ },+ {+ key: "nloc",+ header: "Lines",+ priority: 3,+ align: "right",+ render: (f) => (+ <span className="tabular-nums text-[var(--color-text-tertiary)]">+ {f.nloc ?? "—"}+ </span>+ ),+ },+ {+ key: "health_score",+ header: "Health",+ priority: 2,+ align: "right",+ render: (f) =>+ f.health_score == null ? (+ <span className="text-[var(--color-text-tertiary)]">—</span>+ ) : (+ <span+ className={`inline-block rounded px-1.5 py-0.5 text-xs font-semibold ${scoreBadgeClass(f.health_score)}`}+ >+ {f.health_score.toFixed(1)}+ </span>+ ),+ },+ ];++ return (+ <div className="flex flex-col gap-6 sm:gap-8">+ <PageLede+ label="Files nothing tests"+ value={formatNumber(atRisk.length)}+ unit={atRisk.length === 1 ? "risky file" : "risky files"}+ layout="beside"+ >+ <p>+ No coverage report has been ingested, so this reads the dependency+ graph instead: a file is <strong className="font-semibold text-[var(--color-text-primary)]">reached</strong>{" "}+ when some test's calls run into code defined in it. Your{" "}+ {formatNumber(map.test_file_count)} test files reach{" "}+ <strong className="font-semibold text-[var(--color-text-primary)]">+ {formatNumber(map.files_reached)} of {formatNumber(map.files_total)} files+ </strong>+ . Nothing reaches the other {formatNumber(map.files_not_reached)}.+ </p>++ <p className="mt-2.5">+ The figure beside this is the part worth acting on: files nothing+ reaches that we also score as weak. Reaching is not executing, so treat+ it as a floor rather than a measurement. A call edge says control{" "}+ <em>can</em> flow into the file, which makes “something tests+ this” safe to trust and “this much is tested”+ something it cannot tell you.+ </p>+ </PageLede>++ <OverviewSection+ title="Health against tests"+ description="Every file placed by its defect-risk score, split by whether any test reaches it, sized by lines of code. There is no percentage axis here because there is no line-level evidence to build one from. The left column is the page: weak code nothing runs. Click a file to open it."+ >+ <RiskCoverageScatter+ basis="inferred"+ points={points}+ onSelect={(p) => onOpenFile(p.file_path)}+ />+ </OverviewSection>++ <OverviewSection+ title="Nothing reaches these"+ description="Worst health first, and the files the untested-hotspot marker flagged lead the list because churn and dependents make a gap there cost more. Open a file to see what the graph does and does not know about it."+ >+ <div className="border-t border-[var(--color-border-default)]">+ <ResponsiveTable+ columns={columns}+ rows={ranked.slice(0, visible)}+ rowKey={(f) => f.file_path}+ onRowClick={(f) => onOpenFile(f.file_path)}+ stacked="sm"+ bare+ />+ {ranked.length > 0 ? (+ <ResultsFooter+ shown={Math.min(visible, ranked.length)}+ total={ranked.length}+ hasMore={visible < ranked.length}+ onLoadMore={() => setVisible((v) => v + PAGE)}+ noun="files"+ />+ ) : null}+ </div>+ {trimmed ? (+ <p className="text-xs text-[var(--color-text-tertiary)]">+ Ranked over {formatNumber(map.files.length)} of{" "}+ {formatNumber(map.files_total)} files, capped so one tab does not pull+ the whole repository. The counts above are the repository's.+ </p>+ ) : null}+ </OverviewSection>++ <AddResolutionSection />+ </div>+ );+}++/**+ * The report as added resolution, not as the price of entry.+ *+ * The old copy sat under "No coverage report ingested yet" and read as a wall.+ * It is the same two commands; what changed is that the reader now arrives here+ * having already been answered, so the argument is what a report buys rather+ * than what its absence costs. The X axis spreading from two positions into a+ * continuum is the most honest one-line version of that.+ */+function AddResolutionSection() {+ return (+ <OverviewSection+ title="Sharpen this with a coverage report"+ description="Everything above is read from the dependency graph and needs no setup. A report adds what the graph structurally cannot see: which lines actually ran."+ >+ <div className="flex max-w-[62ch] flex-col gap-3 border-t border-[var(--color-border-default)] pt-4">+ <p className="text-[13px] leading-relaxed text-[var(--color-text-secondary)] [text-wrap:pretty]">+ Hand us a report and the two columns above become a continuous axis,+ every file moves to its own coverage figure, and the untested-hotspot+ list narrows from “nothing calls this” to the exact lines no+ test executed. Reaching becomes measuring.+ </p>+ <pre className="w-fit overflow-x-auto rounded-md bg-[var(--color-bg-inset)] px-3 py-2 font-mono text-xs text-[var(--color-text-primary)]">+ pytest --cov --cov-report=lcov{"\n"}+ repowise coverage add coverage.lcov+ </pre>+ <p className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">+ LCOV · Cobertura · Clover+ </p>+ </div>+ </OverviewSection>+ );+}diff --git a/packages/ui/src/health/risk-coverage-scatter.tsx b/packages/ui/src/health/risk-coverage-scatter.tsxindex 4dbee2200..0e2241e72 100644--- a/packages/ui/src/health/risk-coverage-scatter.tsx+++ b/packages/ui/src/health/risk-coverage-scatter.tsx@@ -1,31 +1,53 @@"use client";import { useEffect, useMemo, useRef, useState } from "react";+import type { CoverageBasis } from "@repowise-dev/types/health";export interface RiskCoveragePoint {file_path: string;health_score: number;+ /** Measured basis only. */line_coverage_pct: number | null;nloc: number;+ /** Inferred basis only: does any test reach this file. */+ reached?: boolean;}export interface RiskCoverageScatterProps {points: RiskCoveragePoint[];onSelect?: (point: RiskCoveragePoint) => void;height?: number;+ /**+ * Which signal the points carry. `measured` plots line coverage on a 0-100+ * X axis; `inferred` collapses X to two positions. Defaults to `measured`,+ * which is what every existing caller passes nothing for.+ */+ basis?: CoverageBasis;}/**- * Health × coverage quadrant plot. Y axis is the defect-risk score (0 to 10,- * higher is better), X axis is line coverage (0 to 100), and dot radius encodes- * lines of code.+ * Health × tests. Y is the defect-risk score (0 to 10, higher is better) and+ * dot radius encodes lines of code on both bases. What X means depends on which+ * signal answered, and that is the whole design.+ *+ * On the **measured** basis X is line coverage, 0 to 100, and the plot reads as+ * four quadrants:** - Top right (healthy, covered): Sweet spot* - Top left (healthy, uncovered): Risky, needs tests* - Bottom right (weak, covered): Tested but messy* - Bottom left (weak, uncovered): Critical hotspot*- * Three things here are deliberate rather than incidental:+ * On the **inferred** basis there is no percentage to plot — reaching is a+ * file-level fact with no line attribution — so X collapses to two positions:+ * nothing reaches this file, or something does. That is deliberate rather than+ * a degraded fallback. The chart's own resolution is the honest statement about+ * the evidence behind it: two columns read as coarser than a measurement+ * without a disclaimer nobody reads, ingesting a report becomes "the axis gains+ * focus" rather than a prerequisite, and a gradient that is never drawn cannot+ * be misread as one.+ *+ * Four things here are deliberate rather than incidental:** The SVG sizes to its container instead of scaling a fixed 640-unit viewBox.* Inside a full-width section that box was being scaled by ~2.4, so every 10px@@ -40,17 +62,25 @@ export interface RiskCoverageScatterProps {* No `<title>` child per dot. That is a second DOM node per file for a native* tooltip that fires on its own delay and fights the hover card below. The path* rides on `data-file` instead, which is also a stable handle for tests.+ *+ * The inferred columns are beeswarmed, and the jitter is **seeded off the file+ * path** rather than random. X carries one bit there, so horizontal space is+ * otherwise dead and a thousand files stack into two vertical lines that hide+ * the mass. Random jitter would move every dot on each re-render, which is the+ * same class of problem the memo boundary above exists for.*/export function RiskCoverageScatter({points,onSelect,height = 340,+ basis = "measured",}: RiskCoverageScatterProps) {const containerRef = useRef<HTMLDivElement | null>(null);// Seeded rather than zero so the first paint is a plausible chart instead of// an empty box that reflows a frame later.const [width, setWidth] = useState(900);const [hovered, setHovered] = useState<number | null>(null);+ const inferred = basis === "inferred";useEffect(() => {const el = containerRef.current;@@ -65,10 +95,12 @@ export function RiskCoverageScatter({const data = useMemo(() =>- points.filter(- (p) => p.line_coverage_pct != null && Number.isFinite(p.health_score),+ points.filter((p) =>+ inferred+ ? p.reached != null && Number.isFinite(p.health_score)+ : p.line_coverage_pct != null && Number.isFinite(p.health_score),),- [points],+ [points, inferred],);const geom = useMemo(() => {@@ -84,6 +116,17 @@ export function RiskCoverageScatter({const xScale = (pct: number) => padL + (pct / 100) * plotW;const yScale = (score: number) => padT + ((10 - score) / 10) * plotH;const radius = (nloc: number) => 2 + Math.min(7, Math.sqrt(nloc / maxNloc) * 7);+ // Column centres and the half-width the swarm may spread into. Kept clear+ // of the divider so the two clouds never touch and the split stays legible+ // at any container width.+ const colLeft = padL + plotW * 0.25;+ const colRight = padL + plotW * 0.75;+ const swarm = plotW * 0.17;+ const xOf = (p: RiskCoveragePoint) => {+ if (!inferred) return xScale(p.line_coverage_pct ?? 0);+ const centre = p.reached ? colRight : colLeft;+ return centre + (hash01(p.file_path) * 2 - 1) * swarm;+ };return {W,H,@@ -91,14 +134,19 @@ export function RiskCoverageScatter({padR,padT,padB,+ plotW,xScale,yScale,radius,- // 60% coverage and a 7.0 score are the quadrant thresholds.- midX: xScale(60),+ xOf,+ colLeft,+ colRight,+ // 60% coverage and a 7.0 score are the quadrant thresholds. On the+ // inferred basis the vertical one is the column divider instead.+ midX: inferred ? padL + plotW * 0.5 : xScale(60),midY: yScale(7),};- }, [width, height, data]);+ }, [width, height, data, inferred]);// The expensive part, held apart from `hovered` so pointer movement does not// rebuild one element per file. React bails out of reconciling a subtree whose@@ -111,11 +159,12 @@ export function RiskCoverageScatter({key={p.file_path}data-file={p.file_path}data-i={i}- cx={geom.xScale(p.line_coverage_pct ?? 0)}+ cx={geom.xOf(p)}cy={geom.yScale(p.health_score)}r={geom.radius(p.nloc)}- className={`${bandFill(p.health_score)} ${onSelect ? "cursor-pointer" : ""}`}- fillOpacity={0.7}+ className={`${inferred ? "" : bandFill(p.health_score)} ${onSelect ? "cursor-pointer" : ""}`}+ {...(inferred ? { fill: reachedFill(p.reached) } : {})}+ fillOpacity={0.75}/>))}</g>@@ -126,14 +175,16 @@ export function RiskCoverageScatter({if (data.length === 0) {return (<p className="text-sm text-[var(--color-text-tertiary)]">- No file carries both a health score and a coverage figure yet, so there is- nothing to plot.+ {inferred+ ? "No file carries both a health score and a place in the dependency graph yet, so there is nothing to plot."+ : "No file carries both a health score and a coverage figure yet, so there is nothing to plot."}</p>);}- const { W, H, padL, padR, padT, padB, midX, midY, xScale, yScale } = geom;+ const { W, H, padL, padR, padT, padB, midX, midY, xScale, yScale, xOf } = geom;const active = hovered != null ? data[hovered] : undefined;+ const reachedCount = inferred ? data.filter((p) => p.reached).length : 0;// Delegated: one handler on the svg rather than two props on every dot.const indexFrom = (target: EventTarget): number | null => {@@ -149,7 +200,11 @@ export function RiskCoverageScatter({width="100%"height={H}role="img"- aria-label="Health against line coverage, one dot per file"+ aria-label={+ inferred+ ? "Health against whether any test reaches the file, one dot per file"+ : "Health against line coverage, one dot per file"+ }onMouseOver={(e) => setHovered(indexFrom(e.target))}onMouseOut={() => setHovered(null)}onClick={(e) => {@@ -159,12 +214,16 @@ export function RiskCoverageScatter({if (point) onSelect(point);}}>- {/* Quadrant tinting. Faint enough to read as ground rather than as- four coloured panels the dots sit on top of. */}- <rect x={padL} y={padT} width={midX - padL} height={midY - padT} fill="currentColor" className="text-[var(--color-warning)]/5" />- <rect x={midX} y={padT} width={W - padR - midX} height={midY - padT} fill="currentColor" className="text-[var(--color-success)]/5" />- <rect x={padL} y={midY} width={midX - padL} height={H - padB - midY} fill="currentColor" className="text-[var(--color-error)]/8" />- <rect x={midX} y={midY} width={W - padR - midX} height={H - padB - midY} fill="currentColor" className="text-[var(--color-caution)]/5" />+ {inferred ? null : (+ <>+ {/* Quadrant tinting. Faint enough to read as ground rather than as+ four coloured panels the dots sit on top of. */}+ <rect x={padL} y={padT} width={midX - padL} height={midY - padT} fill="currentColor" className="text-[var(--color-warning)]/5" />+ <rect x={midX} y={padT} width={W - padR - midX} height={midY - padT} fill="currentColor" className="text-[var(--color-success)]/5" />+ <rect x={padL} y={midY} width={midX - padL} height={H - padB - midY} fill="currentColor" className="text-[var(--color-error)]/8" />+ <rect x={midX} y={midY} width={W - padR - midX} height={H - padB - midY} fill="currentColor" className="text-[var(--color-caution)]/5" />+ </>+ )}{/* Axes and the two thresholds */}<line x1={padL} y1={padT} x2={padL} y2={H - padB} stroke="currentColor" strokeOpacity={0.2} />@@ -172,29 +231,50 @@ export function RiskCoverageScatter({<line x1={midX} y1={padT} x2={midX} y2={H - padB} stroke="currentColor" strokeOpacity={0.1} strokeDasharray="3 3" /><line x1={padL} y1={midY} x2={W - padR} y2={midY} stroke="currentColor" strokeOpacity={0.1} strokeDasharray="3 3" />- {[0, 25, 50, 75, 100].map((v) => (- <text key={`x${v}`} x={xScale(v)} y={H - padB + 15} fontSize={10} textAnchor="middle" fill="currentColor" opacity={0.5}>- {v}%- </text>- ))}+ {inferred ? (+ <>+ <text x={geom.colLeft} y={H - padB + 15} fontSize={10} textAnchor="middle" fill="currentColor" opacity={0.6}>+ no test reaches it+ </text>+ <text x={geom.colRight} y={H - padB + 15} fontSize={10} textAnchor="middle" fill="currentColor" opacity={0.6}>+ a test reaches it+ </text>+ </>+ ) : (+ [0, 25, 50, 75, 100].map((v) => (+ <text key={`x${v}`} x={xScale(v)} y={H - padB + 15} fontSize={10} textAnchor="middle" fill="currentColor" opacity={0.5}>+ {v}%+ </text>+ ))+ )}{[0, 2, 4, 6, 8, 10].map((v) => (<text key={`y${v}`} x={padL - 7} y={yScale(v) + 3} fontSize={10} textAnchor="end" fill="currentColor" opacity={0.5}>{v}</text>))}- <text x={padL + (W - padL - padR) / 2} y={H - 3} fontSize={10} textAnchor="middle" fill="currentColor" opacity={0.6}>- Line coverage- </text>+ {!inferred && (+ <text x={padL + (W - padL - padR) / 2} y={H - 3} fontSize={10} textAnchor="middle" fill="currentColor" opacity={0.6}>+ Line coverage+ </text>+ )}<text x={11} y={H / 2} fontSize={10} textAnchor="middle" fill="currentColor" opacity={0.6} transform={`rotate(-90 11 ${H / 2})`}>Health score</text>- {/* Quadrant captions. These stay on the canvas because they name a- region of it; the chart's key, which does not, sits underneath. */}- <text x={padL + 8} y={padT + 14} fontSize={10} fill="currentColor" opacity={0.5}>Risky, needs tests</text>- <text x={W - padR - 8} y={padT + 14} fontSize={10} textAnchor="end" fill="currentColor" opacity={0.5}>Sweet spot</text>- <text x={padL + 8} y={H - padB - 8} fontSize={10} fill="currentColor" opacity={0.5}>Critical hotspot</text>- <text x={W - padR - 8} y={H - padB - 8} fontSize={10} textAnchor="end" fill="currentColor" opacity={0.5}>Tested but messy</text>+ {/* Region captions. These stay on the canvas because they name a part+ of it; the chart's key, which does not, sits underneath. */}+ {inferred ? (+ <text x={padL + 8} y={H - padB - 8} fontSize={10} fill="currentColor" opacity={0.55}>+ Weak, and nothing runs it+ </text>+ ) : (+ <>+ <text x={padL + 8} y={padT + 14} fontSize={10} fill="currentColor" opacity={0.5}>Risky, needs tests</text>+ <text x={W - padR - 8} y={padT + 14} fontSize={10} textAnchor="end" fill="currentColor" opacity={0.5}>Sweet spot</text>+ <text x={padL + 8} y={H - padB - 8} fontSize={10} fill="currentColor" opacity={0.5}>Critical hotspot</text>+ <text x={W - padR - 8} y={H - padB - 8} fontSize={10} textAnchor="end" fill="currentColor" opacity={0.5}>Tested but messy</text>+ </>+ )}{field}@@ -202,10 +282,11 @@ export function RiskCoverageScatter({the hovered dot, which would take the whole field with it. */}{active && (<circle- cx={xScale(active.line_coverage_pct ?? 0)}+ cx={xOf(active)}cy={yScale(active.health_score)}r={geom.radius(active.nloc) * 1.5}- className={bandFill(active.health_score)}+ className={inferred ? "" : bandFill(active.health_score)}+ {...(inferred ? { fill: reachedFill(active.reached) } : {})}fillOpacity={0.9}stroke="var(--color-text-primary)"strokeWidth={1.5}@@ -220,7 +301,7 @@ export function RiskCoverageScatter({style={{// Clamped so a dot against either edge does not push the card out// of the plot; the offset lifts it clear of its own dot.- left: Math.min(Math.max(xScale(active.line_coverage_pct ?? 0), 110), W - 110),+ left: Math.min(Math.max(xOf(active), 110), W - 110),top: yScale(active.health_score) - 10,}}>@@ -229,20 +310,44 @@ export function RiskCoverageScatter({</span><span className="tabular-nums text-[var(--color-text-tertiary)]">{active.health_score.toFixed(1)} health ·{" "}- {active.line_coverage_pct?.toFixed(0)}% covered · {active.nloc} lines+ {inferred+ ? active.reached+ ? "a test reaches it"+ : "no test reaches it"+ : `${active.line_coverage_pct?.toFixed(0)}% covered`}{" "}+ · {active.nloc} lines</span></div>)}</div><p className="border-t border-[var(--color-border-default)] pt-2 font-mono text-[10px] uppercase tracking-[0.12em] tabular-nums text-[var(--color-text-tertiary)]">- {data.length.toLocaleString()} files · dot size = lines of code · thresholds- at 60% coverage and 7.0 health+ {inferred+ ? `${data.length.toLocaleString()} files · ${reachedCount.toLocaleString()} reached by a test · colour repeats the column · dot size = lines of code · height is the health score · horizontal spread carries no meaning`+ : `${data.length.toLocaleString()} files · dot size = lines of code · thresholds at 60% coverage and 7.0 health`}</p></div>);}+/**+ * Fill by which column the file sits in, on the inferred basis.+ *+ * The sunset pair, and deliberately not the health ramp. Green/amber/red carry a+ * band, so spending them here would dress a static reading as a measurement -+ * and it would be redundant besides, because the Y axis already *is* the health+ * score. Hue is the only thing left to carry the split, which is the one fact+ * this chart exists to show.+ *+ * Tried first as a 6% wash behind the dots, which failed twice over: plum at+ * that opacity is indistinguishable from grey on a light ground, and the+ * health-banded dots on top took the whole visual budget to re-say what their+ * own vertical position already said.+ */+function reachedFill(reached: boolean | undefined): string {+ return reached ? "var(--color-accent-fill)" : "var(--color-accent-secondary)";+}+/** Fill by health band. The bands are the same ones the rest of health uses. */function bandFill(score: number): string {if (score < 4) return "fill-[var(--color-error)]";@@ -250,3 +355,20 @@ function bandFill(score: number): string {if (score < 8) return "fill-[var(--color-caution)]";return "fill-[var(--color-success)]";}++/**+ * A stable number in [0, 1) from a file path, for the beeswarm offset.+ *+ * FNV-1a, which is a few lines and has no dependency. The requirement is only+ * that it spreads evenly and returns the same value for the same path every+ * render; the offset is decoration, so nothing rests on its distribution beyond+ * looking unclustered.+ */+function hash01(path: string): number {+ let h = 0x811c9dc5;+ for (let i = 0; i < path.length; i++) {+ h ^= path.charCodeAt(i);+ h = Math.imul(h, 0x01000193);+ }+ return ((h >>> 0) % 100000) / 100000;+}diff --git a/packages/ui/src/health/tests-reaching-list.tsx b/packages/ui/src/health/tests-reaching-list.tsxnew file mode 100644index 000000000..755133041--- /dev/null+++ b/packages/ui/src/health/tests-reaching-list.tsx@@ -0,0 +1,131 @@+"use client";++import useSWR from "swr";+import type { ReachedVia, TestsReachingFile } from "@repowise-dev/types/health";++import { Skeleton } from "../ui/skeleton";++export interface TestsReachingListProps {+ filePath: string;+ /**+ * Fetches the answer for one file. Optional so a host that has not wired the+ * endpoint renders nothing rather than an error.+ */+ fetcher?: (filePath: string) => Promise<TestsReachingFile>;+ /** Namespaces the SWR key so two repos never share a cached answer. */+ cacheKey: string;+ /** Opens a test file. Omitted where there is nowhere to go. */+ onSelect?: (path: string) => void;+ /**+ * Renders the heading and the framing sentence. The file page wants them; the+ * drill-down under the chart already sits beneath a heading that says it.+ */+ heading?: boolean;+}++/**+ * The tests that reach one file, per the dependency graph.+ *+ * This is a *relationship*, and it is stated as one: "6 tests run this file",+ * naming them. It is deliberately never a score with a bar beside it. Reaching+ * has no line attribution behind it, so a number on a scale would be a coverage+ * figure the data cannot support, and the moment it becomes one we have rebuilt+ * the confusion the core spent its whole design avoiding.+ *+ * `via` is carried through rather than flattened because the two tiers are+ * different claims. A test whose calls run into the file is strong evidence; a+ * test that merely imports it is real but much cruder, and a reader deciding+ * whether this file is guarded needs to know which one they have.+ */+export function TestsReachingList({+ filePath,+ fetcher,+ cacheKey,+ onSelect,+ heading = true,+}: TestsReachingListProps) {+ const { data, isLoading } = useSWR<TestsReachingFile | null>(+ fetcher ? `tests-reaching:${cacheKey}:${filePath}` : null,+ () => fetcher!(filePath).catch(() => null),+ { revalidateOnFocus: false },+ );++ if (!fetcher) return null;+ if (isLoading) return <Skeleton className="h-16 w-full max-w-[52ch] rounded-md" />;++ // A file nothing reaches is the honest answer, not an error, and it is the+ // one the reader most needs: it is the whole left column of the chart.+ if (!data || !data.reached || data.tests.length === 0) {+ return (+ <div className="flex flex-col gap-1.5">+ {heading ? <Heading>Tests reaching this file</Heading> : null}+ <p className="max-w-[62ch] text-[13px] leading-relaxed text-[var(--color-text-secondary)] [text-wrap:pretty]">+ No test in the repository calls into this file, and none imports it.+ That is a static reading of the dependency graph, so a test that+ reaches it only through a framework hook or a name looked up at run+ time would not show up here.+ </p>+ </div>+ );+ }++ const count = data.tests.length;++ return (+ <div className="flex flex-col gap-2">+ {heading ? <Heading>Tests reaching this file</Heading> : null}+ <p className="max-w-[62ch] text-[13px] leading-relaxed text-[var(--color-text-secondary)] [text-wrap:pretty]">+ <strong className="font-semibold text-[var(--color-text-primary)]">+ {count} {count === 1 ? "test file" : "test files"}+ </strong>{" "}+ {viaSentence(data.via)}+ </p>+ <ul className="flex flex-col">+ {data.tests.map((t) => (+ <li key={t} className="border-t border-[var(--color-border-default)]">+ {onSelect ? (+ <button+ type="button"+ onClick={() => onSelect(t)}+ className="w-full truncate py-1.5 text-left font-mono text-xs text-[var(--color-text-secondary)] transition-colors hover:text-[var(--color-accent-primary)]"+ title={t}+ >+ {t}+ </button>+ ) : (+ <span+ className="block truncate py-1.5 font-mono text-xs text-[var(--color-text-secondary)]"+ title={t}+ >+ {t}+ </span>+ )}+ </li>+ ))}+ </ul>+ <p className="border-t border-[var(--color-border-default)] pt-2 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">+ {data.via === "call-graph" ? "call graph" : "import graph"} · no report+ needed+ </p>+ </div>+ );+}++function Heading({ children }: { children: React.ReactNode }) {+ return (+ <h3 className="text-[13px] font-semibold text-[var(--color-text-primary)]">+ {children}+ </h3>+ );+}++/**+ * Names the claim rather than the tier. "Reached via call-graph" is our word for+ * it; "runs into this file" is what it means to the person reading.+ */+function viaSentence(via: ReachedVia | null): string {+ if (via === "import-graph") {+ return "import this file. Nothing calls into it, so they load it without necessarily running any of it.";+ }+ return "run into this file: their calls reach code defined here, within three hops.";+}diff --git a/packages/web/src/app/repos/[id]/code-health/page.tsx b/packages/web/src/app/repos/[id]/code-health/page.tsxindex 1908202cb..4fe5a1434 100644--- a/packages/web/src/app/repos/[id]/code-health/page.tsx+++ b/packages/web/src/app/repos/[id]/code-health/page.tsx@@ -59,7 +59,7 @@ type TabId = (typeof TABS)[number];const TAB_LABELS: Record<TabId, string> = {triage: "Overview",findings: "Findings",- coverage: "Coverage",+ coverage: "Tests","dead-code": "Dead code",security: "Security",impact: "Blast radius",@@ -211,7 +211,15 @@ export default function CodeHealthPage() {// to anyone who asks for it.const { data: coverage } = useSWR<HealthCoverageResponse>(`code-health-coverage-summary:${repoId}`,- () => getHealthCoverage(repoId, { limit: 1, module_limit: 0 }),+ () =>+ getHealthCoverage(repoId, {+ limit: 1,+ module_limit: 0,+ // And declines the graph fallback, which would read every call edge in+ // the repo to answer a question this badge cannot render anyway: the+ // inferred basis has no percentage to show.+ include_inferred: false,+ }),{ revalidateOnFocus: false },);const coveragePct = coverage?.summary.line_coverage_pct;diff --git a/packages/web/src/app/repos/[id]/files/[...path]/page.tsx b/packages/web/src/app/repos/[id]/files/[...path]/page.tsxindex 6d4eff861..3e071f353 100644--- a/packages/web/src/app/repos/[id]/files/[...path]/page.tsx+++ b/packages/web/src/app/repos/[id]/files/[...path]/page.tsx@@ -18,6 +18,7 @@ import {type FilePageTab,} from "@repowise-dev/ui/files";import { FilePageHost } from "@/components/files/file-page-host";+import { FileTestsPanel } from "@/components/files/file-tests-panel";import { FileHealthPanel } from "@/components/files/file-health-panel";import type { FileDetailResponse } from "@repowise-dev/types/files";@@ -187,6 +188,7 @@ export default async function FileEntityPage({ params, searchParams }: Props) {functionBlame={detail.function_blame}/>),+ testsPanel: <FileTestsPanel repoId={id} filePath={detail.file_path} />,LinkComponent: Link,});diff --git a/packages/web/src/components/code-health/coverage-tab.tsx b/packages/web/src/components/code-health/coverage-tab.tsxindex af9322602..122e1cba7 100644--- a/packages/web/src/components/code-health/coverage-tab.tsx+++ b/packages/web/src/components/code-health/coverage-tab.tsx@@ -11,6 +11,7 @@ import { CoverageView, type CodeHealthAdapter } from "@repowise-dev/ui/health";import { fileEntityPath } from "@repowise-dev/ui/shared/entity";import {getHealthCoverage,+ getTestsReaching,getHealthOverview,getRefactoringTargets,listHealthFiles,@@ -31,6 +32,7 @@ export function CoverageTab({ repoId: id }: { repoId: string }) {updateFindingStatus: (findingId, status) =>updateFindingStatus(id, findingId, status),getCoverage: (opts) => getHealthCoverage(id, opts),+ getTestsReaching: (path) => getTestsReaching(id, path),fileHref: (path) => fileEntityPath(prefix, path),navigate: (href) => router.push(href),renderFileDrawer: () => null,diff --git a/packages/web/src/components/files/file-tests-panel.tsx b/packages/web/src/components/files/file-tests-panel.tsxnew file mode 100644index 000000000..fdcebb751--- /dev/null+++ b/packages/web/src/components/files/file-tests-panel.tsx@@ -0,0 +1,28 @@+"use client";++/**+ * The Tests tab's graph-inferred test list, bound to web's `/api` client.+ *+ * Client-side for the same reason `FileHealthPanel` is: `TestsReachingList`+ * fetches, and a fetcher cannot be handed to a server-rendered tab body as a+ * prop. The server page composes this element and passes it down as a node.+ */++import { TestsReachingList } from "@repowise-dev/ui/health";+import { getTestsReaching } from "@/lib/api/code-health";++export function FileTestsPanel({+ repoId,+ filePath,+}: {+ repoId: string;+ filePath: string;+}) {+ return (+ <TestsReachingList+ filePath={filePath}+ cacheKey={repoId}+ fetcher={(p) => getTestsReaching(repoId, p)}+ />+ );+}diff --git a/packages/web/src/components/layout/repo-breadcrumb-label.ts b/packages/web/src/components/layout/repo-breadcrumb-label.tsindex caf0c3d0c..51a15168e 100644--- a/packages/web/src/components/layout/repo-breadcrumb-label.ts+++ b/packages/web/src/components/layout/repo-breadcrumb-label.ts@@ -4,7 +4,7 @@ const SEGMENT_LABELS: Record<string, string> = {chat: "Chat",architecture: "Architecture","code-health": "Code Health",- coverage: "Coverage",+ coverage: "Tests","refactoring-targets": "Refactoring Targets",trend: "Trend",search: "Search",diff --git a/tests/unit/server/test_health_coverage_basis.py b/tests/unit/server/test_health_coverage_basis.pyindex 993e0e0a4..1b6b1328e 100644--- a/tests/unit/server/test_health_coverage_basis.py+++ b/tests/unit/server/test_health_coverage_basis.py@@ -169,6 +169,37 @@ async def test_a_repo_with_no_tests_at_all_says_none_not_inferred(assert "inferred" not in body+async def test_a_caller_can_decline_the_graph_fallback(client, session, tmp_path):+ """The tab badge asks for one row and no modules because it wants one number.++ The fallback costs a read of every call edge plus every health metric, which+ is the right price for the tab and the wrong one for the badge above it. A+ declined response omits ``basis`` rather than claiming ``none``: the graph+ was not consulted, which is not the same as the graph having nothing to say.+ """+ repo = await create_test_repo(client, tmp_path)+ await save_health_metrics(session, repo["id"], [_metric("src/a.py")])+ await _seed_graph(+ session,+ repo["id"],+ nodes={"tests/test_a.py": True, "src/a.py": False},+ edges=_calls("tests/test_a.py", "src/a.py"),+ )+ await session.commit()++ body = await _get(+ client, repo["id"], limit=1, module_limit=0, include_inferred="false"+ )++ assert "inferred" not in body+ assert "basis" not in body+ assert body["summary"]["file_count"] == 0++ # And the same repo answers in full when the tab asks.+ full = await _get(client, repo["id"])+ assert full["basis"] == "inferred"++# ------------------------------------------------------------------ ## The two bases never share a field# ------------------------------------------------------------------ #