Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(files): let the map lead, and give it a key it cannot drift from (#1152)

Raghav Chamadiya6e11dbe1b6a4
diff --git a/packages/server/src/repowise/server/routers/files.py b/packages/server/src/repowise/server/routers/files.py
index 64edd174c..1ef43092e 100644
--- a/packages/server/src/repowise/server/routers/files.py
+++ b/packages/server/src/repowise/server/routers/files.py
@@ -20,6 +20,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.analysis.health.signals import file_signals
from repowise.core.analysis.health.trends import file_trend
+from repowise.core.ids import is_external
from repowise.core.persistence import crud
from repowise.core.persistence.decision_graph import get_governing_decisions
from repowise.core.persistence.models import DeadCodeFinding, Page, WikiSymbol
@@ -109,14 +110,21 @@ async def files_index(
One row per indexed file node, joined in-memory from four batch reads
(graph nodes, materialized degree metrics, health metrics, git metadata).
- Percentiles for importance (pagerank) and churn are computed once over the
- full set so the client can rank without refetching.
+ Third-party and framework nodes are excluded — they share the table with
+ real files but have no path to open. Percentiles for pagerank and churn are
+ computed once over the full set so the client can rank without refetching.
"""
repo = await crud.get_repository(session, repo_id)
if repo is None:
raise HTTPException(status_code=404, detail="Repository not found")
- nodes = await crud.get_all_file_metrics(session, repo_id)
+ # Third-party and framework nodes live in the same table as real files, and
+ # they are not files: `external:react` has no path, no LOC, no health and no
+ # page behind it, so its row rendered as a wall of em-dashes linking to a
+ # 404. Dropped before the percentile is taken, so ranking a file against a
+ # node the reader can never open cannot skew where it lands.
+ all_nodes = await crud.get_all_file_metrics(session, repo_id)
+ nodes = [n for n in all_nodes if not is_external(n.node_id)]
degrees = await crud.get_graph_metrics(session, repo_id)
metrics_by_path = {m.file_path: m for m in await crud.get_health_metrics(session, repo_id)}
git_by_path = await crud.get_all_git_metadata(session, repo_id)
diff --git a/packages/ui/__tests__/files/files-index.test.tsx b/packages/ui/__tests__/files/files-index.test.tsx
new file mode 100644
index 000000000..49326fd99
--- /dev/null
+++ b/packages/ui/__tests__/files/files-index.test.tsx
@@ -0,0 +1,202 @@
+import { beforeAll, describe, it, expect, vi } from "vitest";
+import { fireEvent, render, screen, within } from "@testing-library/react";
+import { FilesIndex } from "../../src/files/files-index.js";
+import type { FileLanguageCount, FileRow } from "@repowise-dev/types/files";
+
+// jsdom has no layout engine → stub ResizeObserver so the treemap can size
+// itself. Same shape as the code-health map's stub.
+beforeAll(() => {
+ class RO {
+ cb: ResizeObserverCallback;
+ constructor(cb: ResizeObserverCallback) {
+ this.cb = cb;
+ }
+ observe() {
+ this.cb(
+ [{ contentRect: { width: 800, height: 400 } } as ResizeObserverEntry],
+ this as unknown as ResizeObserver,
+ );
+ }
+ unobserve() {}
+ disconnect() {}
+ }
+ vi.stubGlobal("ResizeObserver", RO);
+});
+
+function row(overrides: Partial<FileRow> = {}): FileRow {
+ return {
+ file_path: "src/foo.ts",
+ language: "typescript",
+ loc: 100,
+ symbol_count: 4,
+ pagerank_pct: 50,
+ in_degree: 2,
+ out_degree: 3,
+ defect_score: 9,
+ maintainability_score: 9,
+ performance_score: 9,
+ churn_pct: 20,
+ commit_count: 10,
+ last_commit_at: null,
+ coverage_pct: 80,
+ is_test: false,
+ is_entry_point: false,
+ community_id: 0,
+ ...overrides,
+ };
+}
+
+const LANGS: FileLanguageCount[] = [
+ { language: "typescript", count: 2 },
+ { language: "python", count: 1 },
+];
+
+function renderIndex(files: FileRow[], languages: FileLanguageCount[] = LANGS) {
+ return render(<FilesIndex files={files} languages={languages} fileHref={(p) => `/f/${p}`} />);
+}
+
+/** The table's half of the page, for names the map also uses. */
+function tableSection(): HTMLElement {
+ return screen.getByRole("heading", { name: "Every file" }).closest("section")!;
+}
+
+/** The map's key row: swatches on the left, what area means on the right. */
+function keyRow(): HTMLElement {
+ return screen.getByText(/^Area is/).parentElement!;
+}
+
+/**
+ * The sentence under a heading, as one string.
+ *
+ * `getByText` matches a node's *direct* text children, so any sentence with a
+ * figure spanned inside it is invisible to it — which is every sentence on this
+ * page, since the figures are marked up rather than plain.
+ */
+function sentenceUnder(heading: string): HTMLElement {
+ return screen.getByRole("heading", { name: heading }).nextElementSibling as HTMLElement;
+}
+
+describe("FilesIndex", () => {
+ it("leads with the map, not a figure strip", () => {
+ renderIndex([row()]);
+
+ // The two section headings, in the order the page renders them. The map
+ // has to be first: a hero figure above a canvas answers a question the
+ // reader did not arrive with.
+ const headings = screen.getAllByRole("heading", { level: 2 });
+ expect(headings.map((h) => h.textContent)).toEqual(["Repository map", "Every file"]);
+ });
+
+ it("reports the healthy share against the number that carries a score", () => {
+ renderIndex([
+ row({ file_path: "a.ts", defect_score: 9 }),
+ row({ file_path: "b.ts", defect_score: 7.5 }),
+ row({ file_path: "c.ts", defect_score: null }),
+ ]);
+
+ // 2 of 3 files are scored, and only the 9 is Healthy — 7.5 sits in the
+ // Warning band. A local `>= 7` threshold would call this 100%, disagreeing
+ // with the amber tile the map paints for the same file.
+ expect(screen.getByText(/50%/)).toBeInTheDocument();
+ expect(screen.getByText(/carrying a health score are healthy/)).toBeInTheDocument();
+ });
+
+ it("names the active sort rather than claiming a fixed order", () => {
+ renderIndex([row({ file_path: "a.ts" }), row({ file_path: "b.ts" })]);
+
+ expect(screen.getByText(/sorted by dependents/)).toBeInTheDocument();
+
+ // The map's colour control also offers "Health", so reach for the one
+ // inside the table's section.
+ fireEvent.click(within(tableSection()).getByRole("button", { name: "Health" }));
+ expect(screen.getByText(/sorted by health/)).toBeInTheDocument();
+ });
+
+ it("keeps distinct percentiles distinct in the dependents column", () => {
+ // Both round to 100. The column printed `Math.round(pagerank_pct)`, so the
+ // rows that sort first were exactly the rows whose figures collapsed into
+ // one another.
+ renderIndex([
+ row({ file_path: "a.ts", pagerank_pct: 100 }),
+ row({ file_path: "b.ts", pagerank_pct: 99.6 }),
+ ]);
+
+ expect(screen.getByText("100.0")).toBeInTheDocument();
+ expect(screen.getByText("99.6")).toBeInTheDocument();
+ });
+
+ it("filters the table without disturbing the map's own scope", () => {
+ renderIndex([
+ row({ file_path: "src/app.ts" }),
+ row({ file_path: "tests/app_test.ts", is_test: true }),
+ ]);
+
+ expect(sentenceUnder("Every file")).toHaveTextContent("2 files, sorted by dependents");
+
+ fireEvent.click(screen.getByRole("button", { name: "Tests" }));
+ expect(sentenceUnder("Every file")).toHaveTextContent("1 file, sorted by dependents");
+ // The map still draws both: the toolbar scopes the table, not the canvas.
+ expect(keyRow()).toHaveTextContent("2 items at the repository root");
+ });
+});
+
+describe("FilesTreemap key row", () => {
+ it("names every health band, and the thresholds that define them", () => {
+ renderIndex([row({ defect_score: 9 })]);
+
+ // All three even though this level only carries one: a fixed scale showing
+ // two steps reads as a scale that has two.
+ for (const band of ["Healthy", "Warning", "Alert"]) {
+ expect(screen.getByText(band)).toBeInTheDocument();
+ }
+ expect(screen.getByText("8+")).toBeInTheDocument();
+ expect(screen.getByText("4–8")).toBeInTheDocument();
+ expect(screen.getByText("< 4")).toBeInTheDocument();
+ });
+
+ it("marks unscored tiles only when there are some", () => {
+ const { unmount } = renderIndex([row({ defect_score: 9 })]);
+ expect(screen.queryByText("Not scored")).not.toBeInTheDocument();
+ unmount();
+
+ renderIndex([row({ defect_score: null })]);
+ expect(screen.getByText("Not scored")).toBeInTheDocument();
+ });
+
+ it("keys the languages actually on screen when colouring by language", () => {
+ renderIndex([
+ row({ file_path: "a.ts", language: "typescript" }),
+ row({ file_path: "b.py", language: "python" }),
+ ]);
+
+ fireEvent.click(screen.getByRole("button", { name: "Language" }));
+
+ const key = screen.getByText(/^Area is/).parentElement!;
+ expect(within(key).getByText("typescript")).toBeInTheDocument();
+ expect(within(key).getByText("python")).toBeInTheDocument();
+ // Health bands belong to the other mode and must not linger.
+ expect(within(key).queryByText("Healthy")).not.toBeInTheDocument();
+ });
+
+ it("says what area means, and it follows the control", () => {
+ renderIndex([row()]);
+
+ expect(
+ screen.getByText(/Area is how much the rest of the codebase depends on it/),
+ ).toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole("button", { name: "Lines" }));
+ expect(screen.getByText(/Area is lines of code/)).toBeInTheDocument();
+ });
+
+ it("counts what is drawn, from the array the tiles are drawn from", () => {
+ // Three files under one root folder is one tile, not three.
+ renderIndex([
+ row({ file_path: "src/a.ts" }),
+ row({ file_path: "src/b.ts" }),
+ row({ file_path: "src/c.ts" }),
+ ]);
+
+ expect(keyRow()).toHaveTextContent("1 item at the repository root");
+ });
+});
diff --git a/packages/ui/src/files/files-index.tsx b/packages/ui/src/files/files-index.tsx
index ae8acc304..c787e6a11 100644
--- a/packages/ui/src/files/files-index.tsx
+++ b/packages/ui/src/files/files-index.tsx
@@ -1,8 +1,9 @@
"use client";
-import { useMemo, useState } from "react";
+import { useMemo, useState, type ReactNode } from "react";
import { Search } from "lucide-react";
import type { FileLanguageCount, FileRow } from "@repowise-dev/types/files";
+import { bandForScore } from "@repowise-dev/types/health";
import { cn } from "../lib/cn";
import { formatLOC, formatNumber } from "../lib/format";
import { FilesTreemap, type TreemapColor, type TreemapSize } from "./files-treemap";
@@ -17,8 +18,19 @@ interface FilesIndexProps {
type TestFilter = "all" | "code" | "tests";
+/** How the active sort reads in the section's sentence. Named so the copy can
+ * never claim an order the table is not in. */
+const SORT_LABEL: Record<SortKey, string> = {
+ dependents: "dependents",
+ health: "health",
+ churn: "churn",
+ loc: "lines",
+ coverage: "coverage",
+ name: "path",
+};
+
const SORT_DEFAULT_DIR: Record<SortKey, "asc" | "desc"> = {
- importance: "desc",
+ dependents: "desc",
health: "asc", // lowest (worst) health first is the interesting end
churn: "desc",
loc: "desc",
@@ -26,16 +38,27 @@ const SORT_DEFAULT_DIR: Record<SortKey, "asc" | "desc"> = {
name: "asc",
};
+/**
+ * A segmented control, optionally named.
+ *
+ * The `label` is not decoration on the map's two controls. They steer different
+ * axes and sat unlabelled side by side, so `Importance | Size` next to
+ * `Health | Language` gave the reader four pills and no statement of which pair
+ * did what. One axis, one control, and the control says which axis. The
+ * toolbar's `All | Code | Tests` needs no such help and passes nothing.
+ */
function Segmented<T extends string>({
+ label,
options,
value,
onChange,
}: {
+ label?: string;
options: { value: T; label: string }[];
value: T;
onChange: (v: T) => void;
}) {
- return (
+ const control = (
<div className="inline-flex rounded-md border border-[var(--color-border-default)] p-0.5">
{options.map((o) => (
<button
@@ -53,30 +76,34 @@ function Segmented<T extends string>({
))}
</div>
);
-}
-
-function Kpi({ label, value }: { label: string; value: string }) {
+ if (!label) return control;
return (
- <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-3 py-2">
- <p className="text-lg font-semibold tabular-nums text-[var(--color-text-primary)]">{value}</p>
- <p className="text-[11px] uppercase tracking-wide text-[var(--color-text-tertiary)]">
+ <div className="inline-flex items-center gap-2">
+ <span className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
{label}
- </p>
+ </span>
+ {control}
</div>
);
}
+/** A figure inside the lede sentence. No `tabular-nums`: it is not in a column
+ * and cannot change in place, which is where that rule applies. */
+function Fig({ children }: { children: ReactNode }) {
+ return <span className="font-medium text-[var(--color-text-primary)]">{children}</span>;
+}
+
export function FilesIndex({ files, languages, fileHref }: FilesIndexProps) {
const [query, setQuery] = useState("");
- const [sortKey, setSortKey] = useState<SortKey>("importance");
+ const [sortKey, setSortKey] = useState<SortKey>("dependents");
const [sortDir, setSortDir] = useState<"asc" | "desc">("desc");
const [langFilter, setLangFilter] = useState<string>("");
const [testFilter, setTestFilter] = useState<TestFilter>("all");
- const [sizeBy, setSizeBy] = useState<TreemapSize>("importance");
+ const [sizeBy, setSizeBy] = useState<TreemapSize>("dependents");
const [colorBy, setColorBy] = useState<TreemapColor>("health");
const [prefix, setPrefix] = useState<string[]>([]);
- // KPI strip — cheap aggregate over the full set (memoized).
+ // The figures the lede sentence spends — one pass over the full set.
const kpis = useMemo(() => {
let loc = 0;
let scored = 0;
@@ -85,13 +112,18 @@ export function FilesIndex({ files, languages, fileHref }: FilesIndexProps) {
loc += f.loc ?? 0;
if (f.defect_score != null) {
scored++;
- if (f.defect_score >= 7) healthy++;
+ // `bandForScore`, not a local `>= 7`. The threshold here was 7 while
+ // every band this page paints starts Healthy at 8, so the strip was
+ // reporting a share of files as healthy that the map beside it was
+ // colouring amber.
+ if (bandForScore(f.defect_score) === "healthy") healthy++;
}
}
return {
total: files.length,
loc,
langCount: languages.length,
+ scored,
healthyPct: scored > 0 ? Math.round((healthy / scored) * 100) : null,
};
}, [files, languages]);
@@ -124,7 +156,7 @@ export function FilesIndex({ files, languages, fileHref }: FilesIndexProps) {
filtered.sort((a, b) => {
let cmp = 0;
switch (sortKey) {
- case "importance":
+ case "dependents":
cmp = a.pagerank_pct - b.pagerank_pct;
break;
case "health":
@@ -150,31 +182,49 @@ export function FilesIndex({ files, languages, fileHref }: FilesIndexProps) {
}, [files, prefix, query, testFilter, langFilter, sortKey, sortDir]);
return (
- <div className="space-y-4">
- {/* KPI strip */}
- <div className="grid grid-cols-2 gap-2 sm:grid-cols-4">
- <Kpi label="Files" value={formatNumber(kpis.total)} />
- <Kpi label="Lines" value={formatLOC(kpis.loc)} />
- <Kpi label="Languages" value={String(kpis.langCount)} />
- <Kpi label="Healthy" value={kpis.healthyPct != null ? `${kpis.healthyPct}%` : "—"} />
- </div>
-
- {/* Treemap hero */}
- <div className="rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3 sm:p-4">
- <div className="mb-3 flex flex-wrap items-center justify-between gap-2">
- <h2 className="text-sm font-semibold text-[var(--color-text-primary)]">
- Repository map
- </h2>
- <div className="flex flex-wrap items-center gap-2">
+ <div>
+ {/*
+ The map leads, and nothing figure-shaped sits above it.
+ `PageLede` is the house opening for a surface whose subject is a number
+ — code health, coverage, dead code — and it is the wrong shape here: a
+ 52px figure at the top of a page whose subject is a canvas pushes the
+ canvas toward the fold to answer a question nobody arrived with. The
+ Knowledge Graph and Architecture ports settled this: where the canvas is
+ the page, it gets a header row, the base plane and a key row, and the
+ figures ride along in the sentence rather than in four boxes above it.
+ */}
+ <section className="space-y-3">
+ <div className="flex flex-wrap items-end justify-between gap-x-6 gap-y-3">
+ <div className="min-w-0">
+ <h2 className="text-lg font-semibold text-[var(--color-text-primary)]">
+ Repository map
+ </h2>
+ <p className="mt-1 max-w-prose text-sm text-[var(--color-text-secondary)]">
+ <Fig>{formatNumber(kpis.total)}</Fig> files across <Fig>{formatLOC(kpis.loc)}</Fig>{" "}
+ lines in <Fig>{kpis.langCount}</Fig> {kpis.langCount === 1 ? "language" : "languages"}
+ .{" "}
+ {kpis.healthyPct != null ? (
+ <>
+ <Fig>{kpis.healthyPct}%</Fig> of the <Fig>{formatNumber(kpis.scored)}</Fig>{" "}
+ carrying a health score are healthy.
+ </>
+ ) : (
+ "None carry a health score yet."
+ )}
+ </p>
+ </div>
+ <div className="flex flex-wrap items-center gap-x-5 gap-y-2">
<Segmented<TreemapSize>
+ label="Area"
value={sizeBy}
onChange={setSizeBy}
options={[
- { value: "importance", label: "Importance" },
- { value: "loc", label: "Size" },
+ { value: "dependents", label: "Dependents" },
+ { value: "loc", label: "Lines" },
]}
/>
<Segmented<TreemapColor>
+ label="Colour"
value={colorBy}
onChange={setColorBy}
options={[
@@ -184,6 +234,9 @@ export function FilesIndex({ files, languages, fileHref }: FilesIndexProps) {
/>
</div>
</div>
+ {/* No card. The thing you came for sits on the base plane, and chrome
+ goes around a canvas rather than on it — the header above and the
+ key row `FilesTreemap` renders underneath are that chrome. */}
<FilesTreemap
files={files}
fileHref={fileHref}
@@ -192,57 +245,69 @@ export function FilesIndex({ files, languages, fileHref }: FilesIndexProps) {
prefix={prefix}
onPrefixChange={setPrefix}
/>
- </div>
-
- {/* Toolbar */}
- <div className="flex flex-wrap items-center gap-2">
- <div className="relative min-w-0 flex-1">
- <Search className="pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-[var(--color-text-tertiary)]" />
- <input
- value={query}
- onChange={(e) => setQuery(e.target.value)}
- placeholder="Filter files by path…"
- className="h-9 w-full rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] pl-8 pr-3 text-sm text-[var(--color-text-primary)] outline-none placeholder:text-[var(--color-text-tertiary)] focus:border-[var(--color-accent-primary)]"
+ </section>
+
+ {/* The table is a section, not a loose stack under the map: a hairline
+ and vertical rhythm are the grouping device, not a border box. */}
+ <section className="mt-12 space-y-3 border-t border-[var(--color-border-default)] pt-8">
+ <div className="min-w-0">
+ <h2 className="text-lg font-semibold text-[var(--color-text-primary)]">Every file</h2>
+ <p className="mt-1 text-sm text-[var(--color-text-secondary)]">
+ <Fig>{formatNumber(tableFiles.length)}</Fig>{" "}
+ {tableFiles.length === 1 ? "file" : "files"}
+ {prefix.length > 0 && (
+ <>
+ {" "}
+ in <Fig>{prefix.join("/")}/</Fig>
+ </>
+ )}
+ , sorted by {SORT_LABEL[sortKey]}. Any column header re-sorts.
+ </p>
+ </div>
+
+ <div className="flex flex-wrap items-center gap-2">
+ <div className="relative min-w-0 flex-1">
+ <Search className="pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-[var(--color-text-tertiary)]" />
+ <input
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ placeholder="Filter files by path…"
+ className="h-9 w-full rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] pl-8 pr-3 text-sm text-[var(--color-text-primary)] outline-none placeholder:text-[var(--color-text-tertiary)] focus:border-[var(--color-accent-primary)]"
+ />
+ </div>
+ <Segmented<TestFilter>
+ value={testFilter}
+ onChange={setTestFilter}
+ options={[
+ { value: "all", label: "All" },
+ { value: "code", label: "Code" },
+ { value: "tests", label: "Tests" },
+ ]}
/>
+ {languages.length > 1 && (
+ <select
+ value={langFilter}
+ onChange={(e) => setLangFilter(e.target.value)}
+ className="h-9 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-2 text-sm text-[var(--color-text-secondary)] outline-none focus:border-[var(--color-accent-primary)]"
+ >
+ <option value="">All languages</option>
+ {languages.map((l) => (
+ <option key={l.language} value={l.language}>
+ {l.language} ({l.count})
+ </option>
+ ))}
+ </select>
+ )}
</div>
- <Segmented<TestFilter>
- value={testFilter}
- onChange={setTestFilter}
- options={[
- { value: "all", label: "All" },
- { value: "code", label: "Code" },
- { value: "tests", label: "Tests" },
- ]}
+
+ <FilesTable
+ files={tableFiles}
+ fileHref={fileHref}
+ sortKey={sortKey}
+ sortDir={sortDir}
+ onSort={handleSort}
/>
- {languages.length > 1 && (
- <select
- value={langFilter}
- onChange={(e) => setLangFilter(e.target.value)}
- className="h-9 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-2 text-sm text-[var(--color-text-secondary)] outline-none focus:border-[var(--color-accent-primary)]"
- >
- <option value="">All languages</option>
- {languages.map((l) => (
- <option key={l.language} value={l.language}>
- {l.language} ({l.count})
- </option>
- ))}
- </select>
- )}
- </div>
-
- <p className="text-xs text-[var(--color-text-tertiary)]">
- {formatNumber(tableFiles.length)}
- {tableFiles.length === 1 ? " file" : " files"}
- {prefix.length > 0 && ` in ${prefix.join("/")}/`}
- </p>
-
- <FilesTable
- files={tableFiles}
- fileHref={fileHref}
- sortKey={sortKey}
- sortDir={sortDir}
- onSort={handleSort}
- />
+ </section>
</div>
);
}
diff --git a/packages/ui/src/files/files-table.tsx b/packages/ui/src/files/files-table.tsx
index ae048898a..8d5830c42 100644
--- a/packages/ui/src/files/files-table.tsx
+++ b/packages/ui/src/files/files-table.tsx
@@ -5,9 +5,10 @@ import { ArrowDown, ArrowUp, FlaskConical, LogIn } from "lucide-react";
import type { FileRow } from "@repowise-dev/types/files";
import { cn } from "../lib/cn";
import { formatLOC, truncatePath } from "../lib/format";
+import { healthInk } from "../health/tokens";
export type SortKey =
- | "importance"
+ | "dependents"
| "health"
| "churn"
| "loc"
@@ -26,11 +27,17 @@ interface FilesTableProps {
const ROW_HEIGHT = 44;
const OVERSCAN = 8;
-function scoreClass(score: number | null): string {
- if (score == null) return "text-[var(--color-text-tertiary)]";
- if (score < 4) return "text-[var(--color-risk-high)]";
- if (score < 7) return "text-[var(--color-risk-medium)]";
- return "text-[var(--color-risk-low)]";
+/**
+ * The health figure's colour, from the same function the treemap tiles use.
+ *
+ * This banded at 7 while `healthInk` bands at 8, so the 7.x files — and there
+ * are a lot of them — read green in this column, green in the map's tooltip and
+ * amber on the tile the tooltip was attached to. Three vocabularies for one
+ * number on one page. Match the mark you sit next to; every other mark on this
+ * page is on the canonical bands.
+ */
+function scoreInk(score: number | null): string {
+ return score == null ? "var(--color-text-tertiary)" : healthInk(score);
}
function SortHeader({
@@ -40,6 +47,7 @@ function SortHeader({
sortDir,
onSort,
className,
+ title,
}: {
label: string;
col: SortKey;
@@ -47,11 +55,14 @@ function SortHeader({
sortDir: "asc" | "desc";
onSort: (key: SortKey) => void;
className?: string;
+ /** What the column measures, for a header whose name is not self-evident. */
+ title?: string;
}) {
const active = sortKey === col;
return (
<button
onClick={() => onSort(col)}
+ title={title}
className={cn(
"flex items-center gap-1 text-left transition-colors hover:text-[var(--color-text-primary)]",
active ? "text-[var(--color-text-primary)]" : "text-[var(--color-text-tertiary)]",
@@ -77,7 +88,7 @@ function SortHeader({
// the cells' `hidden …:flex` visibility so the grid never mis-aligns or
// overflows — the first column is always `minmax(0,1fr)` so paths truncate.
const GRID =
- "grid grid-cols-[minmax(0,1fr)_auto_56px] sm:grid-cols-[minmax(0,1fr)_64px_64px_64px] md:grid-cols-[minmax(0,1fr)_72px_84px_72px_64px_72px] items-center gap-2 px-3 sm:px-4";
+ "grid grid-cols-[minmax(0,1fr)_auto_56px] sm:grid-cols-[minmax(0,1fr)_92px_64px_64px] md:grid-cols-[minmax(0,1fr)_100px_84px_72px_64px_72px] items-center gap-2 px-3 sm:px-4";
export function FilesTable({ files, fileHref, sortKey, sortDir, onSort }: FilesTableProps) {
const scrollRef = useRef<HTMLDivElement>(null);
@@ -100,8 +111,9 @@ export function FilesTable({ files, fileHref, sortKey, sortDir, onSort }: FilesT
>
<SortHeader label="File" col="name" sortKey={sortKey} sortDir={sortDir} onSort={onSort} />
<SortHeader
- label="Imp."
- col="importance"
+ label="Dependents"
+ col="dependents"
+ title="PageRank percentile over the import graph: how much of the codebase reaches this file, directly or through others."
sortKey={sortKey}
sortDir={sortDir}
onSort={onSort}
@@ -188,21 +200,24 @@ export function FilesTable({ files, fileHref, sortKey, sortDir, onSort }: FilesT
</span>
</span>
- {/* Importance */}
+ {/* Dependents. One decimal, not `Math.round`: the server
+ rounds the percentile to 0.1 and rounding again to a
+ whole number printed "100" on every row above the
+ 99.5th, so a repo of 5,000 files led with ~25 rows
+ showing one identical figure for 25 different values —
+ a sort you could not see the basis of. */}
<span className="flex items-center justify-end gap-1.5 tabular-nums text-[var(--color-text-secondary)]">
<span
className="hidden h-1.5 rounded-full bg-[var(--color-accent-primary)] sm:inline-block"
style={{ width: `${Math.max(2, (f.pagerank_pct / 100) * 28)}px` }}
/>
- {Math.round(f.pagerank_pct)}
+ {f.pagerank_pct.toFixed(1)}
</span>
{/* Health */}
<span
- className={cn(
- "flex justify-end tabular-nums",
- scoreClass(f.defect_score),
- )}
+ className="flex justify-end tabular-nums"
+ style={{ color: scoreInk(f.defect_score) }}
>
{f.defect_score != null ? f.defect_score.toFixed(1) : "—"}
</span>
diff --git a/packages/ui/src/files/files-treemap.tsx b/packages/ui/src/files/files-treemap.tsx
index 5940e34a7..13ae4e6cd 100644
--- a/packages/ui/src/files/files-treemap.tsx
+++ b/packages/ui/src/files/files-treemap.tsx
@@ -3,11 +3,24 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { hierarchy, treemap, treemapSquarify, type HierarchyRectangularNode } from "d3-hierarchy";
import type { FileRow } from "@repowise-dev/types/files";
+import {
+ ALERT_MAX,
+ bandForScore,
+ HEALTH_BAND_LABEL,
+ HEALTHY_MIN,
+ type HealthBand,
+} from "@repowise-dev/types/health";
import { ChevronRight, FolderOpen } from "lucide-react";
-import { cn } from "../lib/cn";
-import { healthInk } from "../health/tokens";
+import { healthBandInk, healthInk } from "../health/tokens";
-export type TreemapSize = "importance" | "loc";
+/**
+ * `dependents` is the PageRank percentile over the import graph. It is named
+ * for what it measures rather than "importance", which is a judgement the
+ * number does not make: the files it ranks highest are the ones everything
+ * imports — `conftest.py`, `models.py`, `cn.ts` — and calling that importance
+ * invites the reader to treat a leaf utility as the thing to go read first.
+ */
+export type TreemapSize = "dependents" | "loc";
export type TreemapColor = "health" | "language";
interface FilesTreemapProps {
@@ -35,31 +48,56 @@ interface LevelChild {
language: string;
}
-const LANG_COLORS: Record<string, string> = {
- python: "var(--color-info)",
- typescript: "var(--color-accent-secondary)",
- javascript: "var(--color-warning)",
- tsx: "var(--color-accent-secondary)",
- go: "var(--color-edge-co-change)",
- rust: "var(--color-risk-medium)",
- java: "var(--color-plum-400)",
- ruby: "var(--color-risk-high)",
-};
-const LANG_FALLBACK = "var(--color-text-tertiary)";
+/** How many languages get their own step before the rest fall into "Other". */
+const LANG_RANKED = 5;
-function langColor(lang: string): string {
- return LANG_COLORS[lang.toLowerCase()] ?? LANG_FALLBACK;
+const LANG_OTHER_INK = "var(--color-bg-inset)";
+const NO_SCORE_INK = "var(--color-text-tertiary)";
+
+/**
+ * Language → fill, as one accent stepped down by how much of the repo each
+ * language holds.
+ *
+ * What this replaces was eight hand-picked hues, two of which were
+ * `--color-risk-medium` and `--color-risk-high` — the same tokens the health
+ * mode paints on these same tiles. An amber square therefore meant "middling
+ * health" in one mode and "Rust" in the other, on a canvas that carried no key
+ * in either. Two unlabelled marks sharing a colour vocabulary is worse than one
+ * unlabelled mark: a gap the reader can leave open becomes a trap, because
+ * whoever correctly infers one mode has been taught a rule that makes them
+ * confidently wrong about the other.
+ *
+ * Stepping one accent leaves the traffic lights to the mode that actually
+ * carries a band, and it is the same ramp `LanguageBar` uses for the same
+ * reason — proportion is the message, and naming each language is the key's
+ * job. Ranks come from the whole repo rather than the drilled level so a
+ * language does not change colour as you walk into a folder.
+ */
+function langRanks(files: FileRow[]): Map<string, number> {
+ const tally = new Map<string, number>();
+ for (const f of files) {
+ if (f.language) tally.set(f.language, (tally.get(f.language) ?? 0) + 1);
+ }
+ const ordered = [...tally.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
+ return new Map(ordered.slice(0, LANG_RANKED).map(([lang], i) => [lang, i]));
+}
+
+function langInk(rank: number | undefined): string {
+ if (rank == null) return LANG_OTHER_INK;
+ if (rank === 0) return "var(--color-accent-fill)";
+ return `color-mix(in srgb, var(--color-accent-fill) ${Math.max(12, 70 - rank * 16)}%, var(--color-bg-inset))`;
}
-/** Health score (0-10) → traffic-light fill. Null reads neutral. */
+/** Health score (0-10) → the canonical band ink. Null reads neutral. */
function healthColor(score: number | null): string {
- if (score == null) return "var(--color-text-tertiary)";
+ if (score == null) return NO_SCORE_INK;
return healthInk(score);
}
function sizeValue(row: FileRow, sizeBy: TreemapSize): number {
if (sizeBy === "loc") return Math.max(row.loc ?? 1, 1);
- // Importance: pagerank percentile, floored so trivial files still get a sliver.
+ // PageRank percentile, floored so a file nothing imports still gets a sliver
+ // rather than collapsing to a zero-area tile you cannot click.
return Math.max(row.pagerank_pct, 1);
}
@@ -126,6 +164,111 @@ function levelChildren(files: FileRow[], prefix: string[], sizeBy: TreemapSize):
return out;
}
+interface KeySwatch {
+ key: string;
+ label: string;
+ /** The band's range, or blank where the label is the whole story. */
+ hint: string;
+ ink: string;
+}
+
+/**
+ * The canvas key, plus what area means and how much is on screen.
+ *
+ * Rendered by `FilesTreemap` rather than placed by the page. Both halves of
+ * that are deliberate: chrome belongs *around* a canvas rather than floating on
+ * it, and a caption has to come from the same source as the thing it captions —
+ * a key assembled from its own second pass over the data is how you end up with
+ * a sentence that no longer describes the picture above it. This one reads the
+ * same `level` array the tiles are drawn from and the same functions that fill
+ * them.
+ *
+ * The map shipped with no key at all in either colour mode, which is what let
+ * the language palette quietly borrow the health tokens for a year.
+ */
+function KeyRow({
+ level,
+ ranks,
+ colorBy,
+ sizeBy,
+ prefix,
+}: {
+ level: LevelChild[];
+ ranks: Map<string, number>;
+ colorBy: TreemapColor;
+ sizeBy: TreemapSize;
+ prefix: string[];
+}) {
+ const swatches = useMemo<KeySwatch[]>(() => {
+ if (colorBy === "health") {
+ // All three bands always, even where one is absent from this level: a
+ // fixed scale showing two steps reads as a scale that has two.
+ const out: KeySwatch[] = (["healthy", "warning", "alert"] as HealthBand[]).map((band) => ({
+ key: band,
+ label: HEALTH_BAND_LABEL[band],
+ hint:
+ band === "healthy"
+ ? `${HEALTHY_MIN}+`
+ : band === "alert"
+ ? `< ${ALERT_MAX}`
+ : `${ALERT_MAX}–${HEALTHY_MIN}`,
+ ink: healthBandInk(band),
+ }));
+ if (level.some((c) => c.avgScore == null)) {
+ out.push({
+ key: "none",
+ label: "Not scored",
+ hint: "",
+ ink: NO_SCORE_INK,
+ });
+ }
+ return out;
+ }
+ // Languages are the opposite case: list the ones actually on screen, since
+ // a key naming a language no tile carries is a key you have to ignore.
+ const present = [...new Set(level.map((c) => c.language).filter(Boolean))];
+ const out: KeySwatch[] = present
+ .filter((lang) => ranks.has(lang))
+ .sort((a, b) => ranks.get(a)! - ranks.get(b)!)
+ .map((lang) => ({
+ key: lang,
+ label: lang,
+ hint: "",
+ ink: langInk(ranks.get(lang)),
+ }));
+ if (level.some((c) => !c.language || !ranks.has(c.language))) {
+ out.push({ key: "other", label: "Other", hint: "", ink: LANG_OTHER_INK });
+ }
+ return out;
+ }, [colorBy, level, ranks]);
+
+ return (
+ <div className="mt-3 flex flex-wrap items-center justify-between gap-x-6 gap-y-2 border-t border-[var(--color-border-default)] pt-3">
+ <div className="flex flex-wrap items-center gap-x-4 gap-y-1.5 font-mono text-[10px] text-[var(--color-text-tertiary)]">
+ {swatches.map((s) => (
+ <span key={s.key} className="inline-flex items-center">
+ <span
+ aria-hidden
+ className="mr-1.5 inline-block h-2 w-2 rounded-sm"
+ style={{ background: s.ink }}
+ />
+ {s.label}
+ {s.hint && (
+ <span className="ml-1 tabular-nums text-[var(--color-text-secondary)]">{s.hint}</span>
+ )}
+ </span>
+ ))}
+ </div>
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ Area is{" "}
+ {sizeBy === "loc" ? "lines of code" : "how much the rest of the codebase depends on it"}.{" "}
+ <span className="tabular-nums">{level.length}</span> {level.length === 1 ? "item" : "items"}{" "}
+ {prefix.length > 0 ? `in ${prefix.join("/")}/` : "at the repository root"}.
+ </p>
+ </div>
+ );
+}
+
/** Treemap node datum: the root carries `children`, each leaf a `child`. */
interface TreeDatum {
children?: TreeDatum[];
@@ -190,9 +333,14 @@ export function FilesTreemap({
setTip({ x: e.clientX - rect.left, y: e.clientY - rect.top, child });
}, []);
+ // Ranked over every file, not the drilled level, so a language keeps its
+ // step as you walk into a folder.
+ const ranks = useMemo(() => langRanks(files), [files]);
+
const fill = useCallback(
- (c: LevelChild) => (colorBy === "language" ? langColor(c.language) : healthColor(c.avgScore)),
- [colorBy],
+ (c: LevelChild) =>
+ colorBy === "language" ? langInk(ranks.get(c.language)) : healthColor(c.avgScore),
+ [colorBy, ranks],
);
if (children.length === 0) {
@@ -324,21 +472,22 @@ export function FilesTreemap({
</p>
{tip.child.avgScore != null && (
<p
- className={cn(
- "mt-0.5 font-medium",
- tip.child.avgScore < 4
- ? "text-[var(--color-risk-high)]"
- : tip.child.avgScore < 7
- ? "text-[var(--color-risk-medium)]"
- : "text-[var(--color-risk-low)]",
- )}
+ className="mt-0.5 font-medium tabular-nums"
+ // Painted by the same function as the tile underneath the
+ // pointer. It was not: this line banded at 7 while `healthInk`
+ // bands at 8, so every file scoring 7.x was an amber tile with
+ // a green score written on top of it.
+ style={{ color: healthColor(tip.child.avgScore) }}
>
- health {tip.child.avgScore.toFixed(1)}
+ {HEALTH_BAND_LABEL[bandForScore(tip.child.avgScore)]} ·{" "}
+ {tip.child.avgScore.toFixed(1)}
</p>
)}
</div>
)}
</div>
+
+ <KeyRow level={children} ranks={ranks} colorBy={colorBy} sizeBy={sizeBy} prefix={prefix} />
</div>
);
}
diff --git a/packages/ui/src/health/tokens.ts b/packages/ui/src/health/tokens.ts
index 143d24057..b420208be 100644
--- a/packages/ui/src/health/tokens.ts
+++ b/packages/ui/src/health/tokens.ts
@@ -135,13 +135,23 @@ const HEALTH_BAND_INK: Record<HealthBand, string> = {
healthy: "var(--color-success)",
};
+/**
+ * A canonical band as an ink color, for a key or legend that has a band but no
+ * score to derive it from. Exported so an off-canvas key paints from the same
+ * table the fills do — a legend with its own copy of the colours is a legend
+ * that can describe a canvas it no longer matches.
+ */
+export function healthBandInk(band: HealthBand): string {
+ return HEALTH_BAND_INK[band];
+}
+
/**
* Canonical banding for a higher-is-better health score on the 0-10 scale,
* as an ink color usable in `style`/SVG attributes. Thresholds come from the
* shared `bandForScore` mirror so every surface agrees on what counts as red.
*/
export function healthInk(score10: number): string {
- return HEALTH_BAND_INK[bandForScore(score10)];
+ return healthBandInk(bandForScore(score10));
}
/** `healthInk` for scores expressed on a 0-100 scale. */
diff --git a/packages/web/src/app/repos/[id]/files/page.tsx b/packages/web/src/app/repos/[id]/files/page.tsx
index 5c686ba7b..2fc17260c 100644
--- a/packages/web/src/app/repos/[id]/files/page.tsx
+++ b/packages/web/src/app/repos/[id]/files/page.tsx
@@ -17,7 +17,7 @@ export default async function FilesIndexPage({
maxWidth="wide"
icon={<Files className="h-5 w-5 text-[var(--color-accent-primary)]" />}
title="Files"
- description="Every indexed file, ranked by importance and browsable by folder. Drill into the map or filter the table to jump straight to a file."
+ description="Drill the map to see how the tree is shaped and where health is thin, then filter the table to find a specific file."
>
<FilesExplorer repoId={id} />
</PageShell>
diff --git a/packages/web/src/components/files/files-explorer.tsx b/packages/web/src/components/files/files-explorer.tsx
index 61754a487..b8ce0dc37 100644
--- a/packages/web/src/components/files/files-explorer.tsx
+++ b/packages/web/src/components/files/files-explorer.tsx
@@ -22,15 +22,29 @@ export function FilesExplorer({ repoId }: { repoId: string }) {
if (isLoading) {
return (
- <div className="space-y-4">
- <div className="grid grid-cols-2 gap-2 sm:grid-cols-4">
- {Array.from({ length: 4 }).map((_, i) => (
- <Skeleton key={i} className="h-14 w-full" />
- ))}
+ // Shapes match the real layout: header + sentence, the map, its key row,
+ // then the table section. A skeleton that draws something the page no
+ // longer has reflows when content lands, which reads as slower than
+ // showing nothing at all.
+ <div>
+ <div className="space-y-3">
+ <div className="flex flex-wrap items-end justify-between gap-x-6 gap-y-3">
+ <div className="space-y-2">
+ <Skeleton className="h-6 w-44" />
+ <Skeleton className="h-4 w-80 max-w-full" />
+ </div>
+ <Skeleton className="h-8 w-64" />
+ </div>
+ <Skeleton className="h-5 w-40" />
+ <Skeleton className="h-80 w-full" />
+ <Skeleton className="h-9 w-full" />
+ </div>
+ <div className="mt-12 space-y-3 border-t border-[var(--color-border-default)] pt-8">
+ <Skeleton className="h-6 w-32" />
+ <Skeleton className="h-4 w-72 max-w-full" />
+ <Skeleton className="h-9 w-full" />
+ <Skeleton className="h-96 w-full" />
</div>
- <Skeleton className="h-80 w-full" />
- <Skeleton className="h-9 w-full" />
- <Skeleton className="h-96 w-full" />
</div>
);
}
diff --git a/tests/unit/server/test_files_index.py b/tests/unit/server/test_files_index.py
new file mode 100644
index 000000000..c452de0b1
--- /dev/null
+++ b/tests/unit/server/test_files_index.py
@@ -0,0 +1,79 @@
+"""Tests for GET /api/repos/{id}/files — the browsable Files index."""
+
+from __future__ import annotations
+
+import pytest
+from httpx import AsyncClient
+
+from repowise.core.persistence.database import get_session
+from repowise.core.persistence.models import GraphNode
+from tests.unit.server.conftest import create_test_repo
+
+
+async def _insert_nodes(session_factory, repo_id: str, nodes: list[dict]) -> None:
+ async with get_session(session_factory) as session:
+ for spec in nodes:
+ session.add(
+ GraphNode(
+ repository_id=repo_id,
+ node_type="file",
+ language=spec.get("language", "python"),
+ pagerank=spec.get("pagerank", 0.0),
+ node_id=spec["node_id"],
+ )
+ )
+
+
+async def test_index_excludes_third_party_nodes(client: AsyncClient, app) -> None:
+ """`external:` and `framework:` nodes are not files and must not be rows.
+
+ They share `node_type == "file"` with real files, so they arrived in the
+ index with no path, no LOC, no health and no coverage — a row of em-dashes
+ whose only link 404s.
+ """
+ repo = await create_test_repo(client)
+ await _insert_nodes(
+ app.state.session_factory,
+ repo["id"],
+ [
+ {"node_id": "src/main.py", "pagerank": 0.5},
+ {"node_id": "external:react", "pagerank": 0.9},
+ {"node_id": "framework:django", "pagerank": 0.8},
+ ],
+ )
+
+ resp = await client.get(f"/api/repos/{repo['id']}/files")
+ assert resp.status_code == 200
+ payload = resp.json()
+
+ assert [f["file_path"] for f in payload["files"]] == ["src/main.py"]
+ assert payload["total"] == 1
+
+
+async def test_percentiles_rank_against_files_only(client: AsyncClient, app) -> None:
+ """The excluded nodes must not skew where a real file lands.
+
+ Filtering after the percentile would leave the top file ranked against
+ imports the reader can never open — `external:react` outranks most of any
+ repo, so every real file would report a percentile lower than its standing
+ among files.
+ """
+ repo = await create_test_repo(client)
+ await _insert_nodes(
+ app.state.session_factory,
+ repo["id"],
+ [
+ {"node_id": "src/low.py", "pagerank": 0.1},
+ {"node_id": "src/high.py", "pagerank": 0.5},
+ {"node_id": "external:react", "pagerank": 9.0},
+ ],
+ )
+
+ resp = await client.get(f"/api/repos/{repo['id']}/files")
+ by_path = {f["file_path"]: f for f in resp.json()["files"]}
+
+ # Two files, so the ranking is the full 0-100 span rather than 0-50.
+ assert by_path["src/low.py"]["pagerank_pct"] == 0.0
+ assert by_path["src/high.py"]["pagerank_pct"] == 100.0